hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b11749b46733621b8a1da6e4fecb58a4fb627fda
| 11,629
|
cpp
|
C++
|
ACW Project Framework/System.cpp
|
Lentono/PhysicsSimulationACW
|
a73d22571a0742fd960740f04689f6ee095c3986
|
[
"MIT"
] | 1
|
2021-06-06T10:29:12.000Z
|
2021-06-06T10:29:12.000Z
|
ACW Project Framework/System.cpp
|
Lentono/PhysicsSimulationACW
|
a73d22571a0742fd960740f04689f6ee095c3986
|
[
"MIT"
] | null | null | null |
ACW Project Framework/System.cpp
|
Lentono/PhysicsSimulationACW
|
a73d22571a0742fd960740f04689f6ee095c3986
|
[
"MIT"
] | null | null | null |
#include "System.h"
#include <winuser.h>
#include <iostream>
#include <fstream>
System::System() : m_initializationFailed(false), m_applicationName(nullptr), m_hInstance(nullptr), m_hwnd(nullptr), m_input(nullptr), m_graphics(nullptr) {
auto screenWidth = 0;
auto screenHeight = 0;
//Initialize the Windows API
InitializeWindows(screenWidth, screenHeight);
//Create our input object for reading keyboard inputs
m_input = new InputManager();
if (!m_input)
{
m_initializationFailed = true;
return;
}
//Create our graphics object for handling the rendering of all the graphics
m_graphics = new GraphicsRenderer(screenWidth, screenHeight, m_hwnd);
if (m_graphics->GetInitializationState())
{
m_initializationFailed = true;
}
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;
};
// We don't need a copy/ move constructor for this class but it's best to have it defined so the compiler doesn't generate it for us
System::System(const System& other) = default;
System::System(System&& other) noexcept = default;
System::~System()
{
//Release graphics object
if (m_graphics)
{
delete m_graphics;
m_graphics = nullptr;
}
if (m_input)
{
delete m_input;
m_input = nullptr;
}
// Shutdown window
ShutdownWindows();
}
System& System::operator=(const System& other) = default;
System& System::operator=(System&& other) noexcept = default;
//This is the main application loop where we do all the application processing through the frame function until we quit. The frame function is called each loop.
void System::Run() {
MSG message;
auto done = false;
//Initialize message structure by filling a block of memory with zeros
ZeroMemory(&message, sizeof(message));
//Loop until we get a quit message from the window or the user
while (!done)
{
//Handle windows messages
if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&message);
DispatchMessage(&message);
}
//If windows ends the application then we exit out
if (message.message == WM_QUIT)
{
done = true;
}
else
{
//Else we do the frame processing
auto const result = Frame();
if (!result)
{
done = true;
}
}
}
}
bool System::GetInitializationState() const
{
return m_initializationFailed;
}
//This is where all the application processing happens, we check to see if the user wants to quit the application, if not then we call the graphics objects frame function which will render the graphics.
//More code will be added here as we add more functionality to the framework/ application.
bool System::Frame() {
//Check if user wants to quit the application
if (m_input->IsKeyDown(VK_ESCAPE))
{
return false;
}
if (m_input->IsKeyUp(0x31) && m_input->IsKeyUp(0x32) && m_input->IsKeyUp(0x52) && m_input->IsKeyUp(0x50) && m_input->IsKeyUp(0x55) && m_input->IsKeyUp(0x4A) && m_input->IsKeyUp(0x49) && m_input->IsKeyUp(0x4B) &&
m_input->IsKeyUp(0x4F) && m_input->IsKeyUp(0x4C) && m_input->IsKeyUp(0x54) && m_input->IsKeyUp(0x42) && m_input->IsKeyUp(VK_SPACE))
{
m_input->ToggleDoOnce(true);
}
//Add Balls
if (m_input->IsKeyDown(0x31) && m_input->DoOnce())
{
m_graphics->AddNumberOfSpheres(m_hwnd);
m_input->ToggleDoOnce(false);
}
//Add Cube
if (m_input->IsKeyDown(0x32) && m_input->DoOnce())
{
m_graphics->AddCube(m_hwnd);
m_input->ToggleDoOnce(false);
}
//Reset System
if (m_input->IsKeyDown(0x52) && m_input->DoOnce())
{
m_graphics->ClearMoveableGameObjects();
m_input->ToggleDoOnce(false);
}
//Pause Simulation
if (m_input->IsKeyDown(0x50) && m_input->DoOnce())
{
m_graphics->TogglePauseSimulation();
m_input->ToggleDoOnce(false);
}
//Increase/Decrease TimeScale
if (m_input->IsKeyDown(0x55) && m_input->DoOnce())
{
m_graphics->AddTimeScale(1);
m_input->ToggleDoOnce(false);
}
if (m_input->IsKeyDown(0x4A) && m_input->DoOnce())
{
m_graphics->AddTimeScale(-1);
m_input->ToggleDoOnce(false);
}
//Increase/Decrease Friction
if (m_input->IsKeyDown(0x49) && m_input->DoOnce())
{
m_graphics->AddFriction(0.1f);
m_input->ToggleDoOnce(false);
}
if (m_input->IsKeyDown(0x4B) && m_input->DoOnce())
{
m_graphics->AddFriction(-0.1f);
m_input->ToggleDoOnce(false);
}
//Increase/Decrease Restitution
if (m_input->IsKeyDown(0x4F) && m_input->DoOnce())
{
m_graphics->AddRestitution(0.1f);
m_input->ToggleDoOnce(false);
}
if (m_input->IsKeyDown(0x4C) && m_input->DoOnce())
{
m_graphics->AddRestitution(-0.1f);
m_input->ToggleDoOnce(false);
}
//Increase/Decrease Sphere Diameter
if (m_input->IsKeyDown(0x54) && m_input->DoOnce())
{
m_graphics->AddSphereDiameter(0.1f);
m_input->ToggleDoOnce(false);
}
if (m_input->IsKeyDown(0x42) && m_input->DoOnce())
{
m_graphics->AddSphereDiameter(-0.1f);
m_input->ToggleDoOnce(false);
}
//Increase/Decrease Number Of Spheres
if (m_input->IsKeyDown(VK_OEM_6))
{
m_graphics->AddNumberOfSpheres(1);
}
if (m_input->IsKeyDown(VK_OEM_4))
{
m_graphics->AddNumberOfSpheres(-1);
}
//Toggle Random Texture
if (m_input->IsKeyDown(VK_SPACE) && m_input->DoOnce())
{
m_graphics->ToggleRandomTexture();
m_input->ToggleDoOnce(false);
}
//Camera Controls
if (m_input->IsKeyDown(0x57))
{
m_graphics->GetCamera()->AddPositionY(1.0f);
}
if (m_input->IsKeyDown(0x53))
{
m_graphics->GetCamera()->AddPositionY(-1.0f);
}
if (m_input->IsKeyDown(0x44))
{
m_graphics->GetCamera()->AddPositionX(1.0f);
}
if (m_input->IsKeyDown(0x41))
{
m_graphics->GetCamera()->AddPositionX(-1.0f);
}
if (m_input->IsKeyDown(VK_UP))
{
m_graphics->GetCamera()->AddPositionZ(1.0f);
}
if (m_input->IsKeyDown(VK_DOWN))
{
m_graphics->GetCamera()->AddPositionZ(-1.0f);
}
//Call graphics objects frame processing function
auto const result = m_graphics->Frame();
return result;
}
//Our MessageHandler where we direct the windows system messages into. With this we can listen for certain information.
//For now we just read key presses and key releases and notifiy our input object, all other information we just pass back to the default windows message handler.
LRESULT CALLBACK System::MessageHandler(HWND hwnd, UINT const umsg, WPARAM const wparam, LPARAM const lparam) {
switch(umsg)
{
//Check if a key has been pressed
case WM_KEYDOWN:
{
// If a key is pressed then send it to our input object
m_input->KeyDown(static_cast<unsigned int>(wparam));
return 0;
}
//Check if a key has been released
case WM_KEYUP:
{
//If a key is released then send it to our input object
m_input->KeyUp(static_cast<unsigned int>(wparam));
return 0;
}
//Send any other messages back to the default windows message handler
default:
{
return DefWindowProc(hwnd, umsg, wparam, lparam);
}
}
}
//This is where we build the window we are rendering to. We start by initializing a default window which can be full screen or a set size, depending on the global variable FULL_SCREEN in the GraphicsClass.h
void System::InitializeWindows(int& screenWidth, int& screenHeight) {
//The windows class structure where we define the window information and register it
WNDCLASSEX windowClass;
//The device mode structure about the initialization and environment of our display device
DEVMODE deviceEnvironment;
int positionX;
int positionY;
//Get an external pointer to our object
applicationHandle = this;
//Get the instance of our application
m_hInstance = GetModuleHandle(nullptr);
//Name our application
m_applicationName = "Real Time Graphics FrameWork ACW";
//Define our windows class with default settings
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; //To do with redrawing the window if a movement or size adjustment occurs (CS_OWNDC allocates a unique device context)
windowClass.lpfnWndProc = WndProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = m_hInstance;
windowClass.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
windowClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
windowClass.hbrBackground = static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH));
windowClass.lpszMenuName = nullptr;
windowClass.lpszClassName = m_applicationName;
windowClass.hIconSm = windowClass.hIcon;
//Register our windows class
RegisterClassEx(&windowClass);
//Get the resolution of the users screen
screenWidth = GetSystemMetrics(SM_CXSCREEN);
screenHeight = GetSystemMetrics(SM_CYSCREEN);
//Setup the display device depending on whether we are in full screen mode or windowed, if it's fullscreen we set the screen to the max size and 32bit, else to a defined resolution
if (FULL_SCREEN)
{
//Can we just do ZeroMemory?
//Initialize device structure by filling a block of memory with zeros
ZeroMemory(&deviceEnvironment, sizeof(deviceEnvironment));
//memset(&deviceEnvironment, 0, sizeof(deviceEnvironment));
deviceEnvironment.dmSize = sizeof(deviceEnvironment);
deviceEnvironment.dmPelsWidth = static_cast<unsigned long>(screenWidth);
deviceEnvironment.dmPelsHeight = static_cast<unsigned long>(screenHeight);
deviceEnvironment.dmBitsPerPel = 32;
deviceEnvironment.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
//Change display settings to fullscreen using device environment
ChangeDisplaySettings(&deviceEnvironment, CDS_FULLSCREEN);
//Set the position of the window to the top left corner
positionX = 0;
positionY = 0;
}
else
{
screenWidth = 1360;
screenHeight = 720;
//Place window in the centre of the screen
positionX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2;
positionY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2;
}
//Create the window with the screen settings and get the handle to it
m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, positionX, positionY, screenWidth, screenHeight, nullptr, nullptr, m_hInstance, nullptr);
//Show the window and bring it to the front of the applications
ShowWindow(m_hwnd, SW_SHOW);
SetForegroundWindow(m_hwnd);
SetFocus(m_hwnd);
//Hide the cursor
ShowCursor(false);
}
//Reverts the screen settings and releases the window class and any handles associated with it
void System::ShutdownWindows() {
//Show the cursor
ShowCursor(true);
//Fix display settings if we're in full screen mode
if (FULL_SCREEN)
{
ChangeDisplaySettings(nullptr, 0);
}
//Remove the window
DestroyWindow(m_hwnd);
m_hwnd = nullptr;
//Remove the application instance by un-registering our window class
UnregisterClass(m_applicationName, m_hInstance);
m_hInstance = nullptr;
//Release the pointer to this object
applicationHandle = nullptr;
}
//This is where windows will sends its message to for us to intercept and use with our message handler, if we can't use it then we just return it back to the main windows message handler inside the MessageHandler function
//We intercept this by giving this prototype function to the window procedure when we defined the window class structure for our window class (WNDCLASSEX), this way we hook into the messaging functionality and intercept messages
LRESULT CALLBACK WndProc(HWND hwnd, UINT const umsg, WPARAM const wparam, LPARAM const lparam) {
switch(umsg)
{
//Check if the window is being destroyed
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
//Check if the window is being closed
case WM_CLOSE:
{
PostQuitMessage(0);
return 0;
}
//All other messages pass to our message handler
default:
{
return applicationHandle->MessageHandler(hwnd, umsg, wparam, lparam);
}
}
}
| 27.491726
| 228
| 0.736177
|
Lentono
|
b11bbfb1c3b7aba8c6b64e42fa8a46265c859a34
| 3,353
|
cpp
|
C++
|
2017-05-24-practice/J.cpp
|
tangjz/Three-Investigators
|
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
|
[
"MIT"
] | 3
|
2018-04-02T06:00:51.000Z
|
2018-05-29T04:46:29.000Z
|
2017-05-24-practice/J.cpp
|
tangjz/Three-Investigators
|
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
|
[
"MIT"
] | 2
|
2018-03-31T17:54:30.000Z
|
2018-05-02T11:31:06.000Z
|
2017-05-24-practice/J.cpp
|
tangjz/Three-Investigators
|
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
|
[
"MIT"
] | 2
|
2018-10-07T00:08:06.000Z
|
2021-06-28T11:02:59.000Z
|
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef long double DB;
const int maxn = 201, maxm = maxn * maxn, maxs = 13;
const DB eps = 1e-8, INF = 1e4;
inline int sgn(DB x) {
assert(!std::isnan(x));
return (x > eps) - (x < -eps);
}
inline DB readDB() {
static char buf[maxs];
scanf("%s", buf);
LL ret = 0, base = 1;
char *pat = buf;
for( ; *pat && *pat != '.'; ++pat)
ret = (ret << 3) + (ret << 1) + (*pat - '0');
if(*pat == '.')
for(++pat; *pat; ++pat) {
ret = (ret << 3) + (ret << 1) + (*pat - '0');
base = (base << 3) + (base << 1);
}
for( ; !(ret & 1) && !(base & 1); ret >>= 1, base >>= 1);
for( ; !(ret % 5) && !(base % 5); ret /= 5, base /= 5);
return (DB)ret / base;
}
inline void writeDB(DB x, char endc = '\0') {
printf("%.20f", (double)x);
endc && putchar(endc);
}
int N, M, S, T, lev[maxn], lnk[maxn], cur[maxn];
struct Edge {
int nxt, v;
DB w;
} e[maxm << 2 | 1];
void addEdge(int u, int v, DB w) {
e[M] = (Edge){lnk[u], v, w};
lnk[u] = M++;
e[M] = (Edge){lnk[v], u, 0};
lnk[v] = M++;
}
bool bfs() {
int L = 0, R = 0;
static int que[maxn];
memset(lev, -1, N * sizeof(int));
lev[S] = 0;
que[R++] = S;
while(L < R)
for(int u = que[L++], it = lnk[u]; it != -1; it = e[it].nxt)
if(sgn(e[it].w) > 0 && lev[e[it].v] == -1) {
lev[e[it].v] = lev[u] + 1;
que[R++] = e[it].v;
}
return lev[T] != -1;
}
DB dfs(int u, DB upp) {
if(u == T)
return upp;
DB ret = 0, tmp;
for(int &it = cur[u]; ~it; it = e[it].nxt)
if(lev[e[it].v] == lev[u] + 1 && sgn(e[it].w) > 0
&& sgn(tmp = dfs(e[it].v, min(upp - ret, e[it].w))) > 0) {
e[it].w -= tmp;
e[it ^ 1].w += tmp;
if(sgn((ret += tmp) - upp) >= 0)
break;
}
if(!sgn(ret))
lev[u] = -1;
return ret;
}
DB dinic(int s, int t, DB lim = INF) {
DB flow = 0, tmp;
for(S = s, T = t; bfs() && sgn(lim - flow) > 0; )
for(memcpy(cur, lnk, N * sizeof(int)); sgn(lim - flow) > 0 && sgn(tmp = dfs(S, lim - flow)) > 0; flow += tmp);
return flow;
}
int n, m;
DB v, a, fmx, wmx, zmx, cap[2][maxm], ans;
int main() {
scanf("%d%d", &n, &m);
v = readDB();
a = readDB();
N = n;
M = 0;
memset(lnk, -1, N * sizeof(int));
for(int i = 0; i < m; ++i) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
--u;
--v;
addEdge(u, v, w);
addEdge(v, u, w);
} // M = 4 m
fmx = dinic(0, 2);
zmx = fmx + dinic(1, 2);
for(int i = 0; i < M; i += 2) {
if((i >> 1) & 1)
cap[0][i >> 2] -= e[i ^ 1].w;
else
cap[0][i >> 2] += e[i ^ 1].w;
e[i].w += e[i ^ 1].w;
e[i ^ 1].w = 0;
}
wmx = dinic(1, 2, zmx);
dinic(0, 2, zmx - wmx);
for(int i = 0; i < M; i += 2) {
if((i >> 1) & 1)
cap[1][i >> 2] -= e[i ^ 1].w;
else
cap[1][i >> 2] += e[i ^ 1].w;
e[i].w += e[i ^ 1].w;
e[i ^ 1].w = 0;
}
ans = min(max((1 - a) * zmx, zmx - fmx), wmx);
DB dt = sgn(fmx + wmx - zmx) > 0 ? (wmx - ans) / (fmx + wmx - zmx) : 0;
for(int i = 0; i < m; ++i) {
DB cc = dt * cap[0][i] + (1 - dt) * cap[1][i];
e[i << 2].w = sgn(cc) > 0 ? cc : 0;
e[i << 2 | 2].w = sgn(cc) < 0 ? -cc : 0;
}
dinic(1, 2, ans);
for(int i = 0; i < m; ++i) {
DB cc = dt * cap[0][i] + (1 - dt) * cap[1][i], ww = e[i << 2 | 1].w - e[i << 2 | 3].w;
writeDB((cc - ww) / v, ' ');
writeDB(ww, '\n');
}
writeDB(pow((zmx - ans) / v, a) * pow(ans, 1 - a), '\n');
return 0;
}
| 24.837037
| 112
| 0.454817
|
tangjz
|
b11e6767c676a711884031bddd27416a1bcc3ee4
| 8,468
|
cpp
|
C++
|
gui/qt/toolwidgets/pinwidget.cpp
|
hein09/vipster
|
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
|
[
"BSD-2-Clause"
] | 6
|
2015-12-02T15:33:27.000Z
|
2017-07-28T17:46:51.000Z
|
gui/qt/toolwidgets/pinwidget.cpp
|
hein09/vipster
|
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
|
[
"BSD-2-Clause"
] | 3
|
2018-02-04T16:11:19.000Z
|
2018-03-16T16:23:29.000Z
|
gui/qt/toolwidgets/pinwidget.cpp
|
hein09/vipster
|
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
|
[
"BSD-2-Clause"
] | 1
|
2017-07-05T11:44:55.000Z
|
2017-07-05T11:44:55.000Z
|
#include "../mainwindow.h"
#include "pinwidget.h"
#include "ui_pinwidget.h"
#include <QMessageBox>
using namespace Vipster;
PinWidget::PinWidget(QWidget *parent) :
BaseWidget(parent),
ui(new Ui::PinWidget)
{
ui->setupUi(this);
}
PinWidget::~PinWidget()
{
delete ui;
}
void PinWidget::updateWidget(GUI::change_t change)
{
if(change & (GUI::Change::atoms | GUI::Change::trajec |
GUI::Change::cell | GUI::Change::settings)){
// set gui-state
on_stepList_currentRowChanged(ui->stepList->currentRow());
// update GPU data
for(auto &dat: pinnedSteps){
const auto& settings = master->settings;
dat->update(dat->curStep, settings.atRadVdW.val,
settings.atRadFac.val, settings.bondRad.val);
}
}
if((change & GUI::stepChanged) == GUI::stepChanged){
// disable add-button when already pinned
for(auto &dat: pinnedSteps){
if(dat->curStep == master->curStep){
ui->addStep->setDisabled(true);
return;
}
}
ui->addStep->setEnabled(true);
}
}
PinWidget::PinnedStep::PinnedStep(Step *step, const std::string& name,
GUI::PBCVec mult)
: GUI::StepData{step},
name{name},
mult{mult}
{}
void PinWidget::PinnedStep::draw(const Vec &off,
const GUI::PBCVec &m,
const Mat &cv, bool drawCell, void *context)
{
Vec off_loc = off + this->offset;
Mat cv_loc = curStep->getCellVec() * curStep->getCellDim(AtomFmt::Bohr);
auto mult_loc = curStep->hasCell() ? mult : GUI::PBCVec{{1,1,1}};
if(repeat){
for(int x=0; x<m[0]; ++x){
for(int y=0; y<m[1]; ++y){
for(int z=0; z<m[2]; ++z){
StepData::draw(off_loc + x*cv[0] + y*cv[1] + z*cv[2],
mult_loc, cv_loc, drawCell & this->cell, context);
}
}
}
}else{
StepData::draw(off_loc, mult_loc, cv_loc, drawCell & this->cell, context);
}
}
void PinWidget::setMult(int i)
{
if (!curPin) return;
auto &mult = curPin->mult;
if(sender() == ui->xMultBox){
mult[0] = static_cast<uint8_t>(i);
}else if(sender() == ui->yMultBox){
mult[1] = static_cast<uint8_t>(i);
}else if(sender() == ui->zMultBox){
mult[2] = static_cast<uint8_t>(i);
}
triggerUpdate(GUI::Change::extra);
}
void PinWidget::setOffset(double d)
{
if (!curPin) return;
auto &off = curPin->offset;
if(sender() == ui->xOffset){
off[0] = d;
}else if(sender() == ui->yOffset){
off[1] = d;
}else if(sender() == ui->zOffset){
off[2] = d;
}
triggerUpdate(GUI::Change::extra);
}
void PinWidget::on_showCell_toggled(bool checked)
{
if (!curPin) return;
curPin->cell = checked;
triggerUpdate(GUI::Change::extra);
}
void PinWidget::on_repeatStep_toggled(bool checked)
{
if (!curPin) return;
curPin->repeat = checked;
triggerUpdate(GUI::Change::extra);
}
void PinWidget::on_delStep_clicked()
{
// remove local infos
ui->insertStep->setDisabled(true);
if(curPin->curStep == master->curStep){
ui->addStep->setEnabled(true);
}
auto pos2 = std::find(pinnedSteps.begin(), pinnedSteps.end(), curPin);
pinnedSteps.erase(pos2);
delete ui->stepList->takeItem(ui->stepList->currentRow());
triggerUpdate(GUI::Change::extra);
}
void PinWidget::on_addStep_clicked()
{
ui->addStep->setDisabled(true);
// add to list of steps
pinnedSteps.push_back(std::make_shared<PinnedStep>(master->curStep,
master->curMol->name + " (Step "
+ std::to_string(master->curVP->moldata[master->curMol].curStep) + ')',
GUI::PBCVec{1,1,1}));
pinnedSteps.back()->update(pinnedSteps.back()->curStep,
master->settings.atRadVdW.val, master->settings.atRadFac.val,
master->settings.bondRad.val);
ui->stepList->addItem(QString::fromStdString(pinnedSteps.back()->name));
// enable in current viewport
master->curVP->addExtraData(pinnedSteps.back(), true);
triggerUpdate(GUI::Change::extra);
}
void PinWidget::on_stepList_currentRowChanged(int currentRow)
{
curPin = currentRow < 0 ? nullptr : pinnedSteps[currentRow];
auto hasPin = static_cast<bool>(curPin);
auto hasCell = hasPin ? curPin->curStep->hasCell() : false;
ui->insertStep->setEnabled(hasPin ? curPin->curStep != master->curStep : false);
ui->delStep->setEnabled(hasPin);
ui->showStep->setEnabled(hasPin);
ui->repeatStep->setEnabled(hasPin);
ui->xOffset->setEnabled(hasPin);
ui->yOffset->setEnabled(hasPin);
ui->zOffset->setEnabled(hasPin);
ui->showCell->setEnabled(hasCell);
ui->xMultBox->setEnabled(hasCell);
ui->yMultBox->setEnabled(hasCell);
ui->zMultBox->setEnabled(hasCell);
ui->xFit->setEnabled(hasCell);
ui->yFit->setEnabled(hasCell);
ui->zFit->setEnabled(hasCell);
if(hasPin){
QSignalBlocker block{ui->showStep};
ui->showStep->setChecked(master->curVP->hasExtraData(curPin, true));
QSignalBlocker block1{ui->showCell};
ui->showCell->setChecked(curPin->cell);
QSignalBlocker block2{ui->repeatStep};
ui->repeatStep->setChecked(curPin->repeat);
QSignalBlocker blockx{ui->xMultBox};
ui->xMultBox->setValue(curPin->mult[0]);
QSignalBlocker blocky{ui->yMultBox};
ui->yMultBox->setValue(curPin->mult[1]);
QSignalBlocker blockz{ui->zMultBox};
ui->zMultBox->setValue(curPin->mult[2]);
QSignalBlocker blockox{ui->xOffset};
ui->xOffset->setValue(curPin->offset[0]);
QSignalBlocker blockoy{ui->yOffset};
ui->yOffset->setValue(curPin->offset[1]);
QSignalBlocker blockoz{ui->zOffset};
ui->zOffset->setValue(curPin->offset[2]);
}
}
void PinWidget::on_insertStep_clicked()
{
if (!curPin || (curPin->curStep == master->curStep)) return;
Step s = *curPin->curStep;
s.asFmt(AtomFmt::Bohr).modShift(curPin->offset);
std::array<bool,3> fit = {ui->xFit->isChecked(),
ui->yFit->isChecked(),
ui->zFit->isChecked()};
if (s.hasCell() && (curPin->mult != GUI::PBCVec{{1,1,1}})) {
const auto &m = curPin->mult;
s.modMultiply(m[0], m[1], m[2]);
}
if (s.hasCell() && (fit != std::array<bool,3>{{false, false, false}})){
auto fac = master->curStep->getCellDim(AtomFmt::Bohr) /
s.getCellDim(AtomFmt::Bohr);
auto cell = s.getCellVec();
const auto& target = master->curStep->getCellVec();
if (fit[0]) cell[0] = target[0] * fac;
if (fit[1]) cell[1] = target[1] * fac;
if (fit[2]) cell[2] = target[2] * fac;
s.setCellVec(cell, true);
}
master->curStep->newAtoms(s);
// immediately hide pinned step
master->curVP->delExtraData(curPin, true);
triggerUpdate(GUI::Change::atoms);
}
void PinWidget::on_showStep_toggled(bool checked)
{
if (!curPin) return;
if (checked) {
// insert into viewports extras
master->curVP->addExtraData(curPin, true);
}else{
// remove from viewports extras
master->curVP->delExtraData(curPin, true);
}
triggerUpdate(GUI::Change::extra);
}
void PinWidget::on_helpButton_clicked()
{
QMessageBox::information(this, QString("About pinning"),
"Pinned Steps are drawn along the currently active Step.\n\n"
"\"Repeating\" a Step means it is drawn in periodic repetitions "
"of the active Step, i.e. with the periodicity of the active Step.\n"
"Contrarily, specifying the multipliers for the pinned Step "
"itself draws it with its own periodicity.\n"
"Specifying the offset allows the pinned Step to be shifted against the active Step "
"without having to modify its structure.\n\n"
"Inserting a Step takes both offset and multipliers into account, "
"and additionally performs cell vector fitting if requested.\n\n"
"Cell vector fitting can be used e.g. to create commensurable super cells. "
"If fitting is enabled for a direction, "
"the lattice will be shrunken or stretched to "
"match this dimension in the active Step."
);
}
| 34.563265
| 93
| 0.604393
|
hein09
|
b12134d6db01c00384a15b06f234d4968cc887cb
| 312
|
cpp
|
C++
|
ClientEngine/game/engine/Stage/UnitPart/UnitEvent/UnitEventOperator.cpp
|
twesd/editor
|
10ea9f535115dadab5694fecdb0c499d0013ac1b
|
[
"MIT"
] | null | null | null |
ClientEngine/game/engine/Stage/UnitPart/UnitEvent/UnitEventOperator.cpp
|
twesd/editor
|
10ea9f535115dadab5694fecdb0c499d0013ac1b
|
[
"MIT"
] | null | null | null |
ClientEngine/game/engine/Stage/UnitPart/UnitEvent/UnitEventOperator.cpp
|
twesd/editor
|
10ea9f535115dadab5694fecdb0c499d0013ac1b
|
[
"MIT"
] | null | null | null |
#include "UnitEventOperator.h"
#include "../UnitBehavior.h"
UnitEventOperator::UnitEventOperator(SharedParams_t params) : UnitEventBase(params)
{
}
UnitEventOperator::~UnitEventOperator(void)
{
}
// Выполняется ли условие
bool UnitEventOperator::IsApprove( core::array<Event_t*>& events )
{
return true;
}
| 17.333333
| 83
| 0.762821
|
twesd
|
b122c0b8fc656809dc785c8d77afb2530c5e284f
| 4,159
|
cpp
|
C++
|
src/surrogate/benchmark/dtlz.cpp
|
lucasmpavelski/elmoead
|
35286d7b5407c7b7a72f13cedbdedd9ba27ae22d
|
[
"MIT"
] | 1
|
2020-09-24T09:36:52.000Z
|
2020-09-24T09:36:52.000Z
|
src/surrogate/benchmark/dtlz.cpp
|
lucasmpavelski/elmoead
|
35286d7b5407c7b7a72f13cedbdedd9ba27ae22d
|
[
"MIT"
] | null | null | null |
src/surrogate/benchmark/dtlz.cpp
|
lucasmpavelski/elmoead
|
35286d7b5407c7b7a72f13cedbdedd9ba27ae22d
|
[
"MIT"
] | null | null | null |
#include "dtlz.h"
namespace dtlz
{
#define PI 3.1415926535897932384626433832795
void DTLZ1(const double *x, double* f, const unsigned no_vars, const unsigned no_objs)
{
int i = 0;
int j = 0;
int n = no_vars;
int k = n - no_objs + 1;
double g = 0;
for (i = n - k + 1; i <= n; i++)
{
g += pow(x[i-1]-0.5,2) - cos(20 * PI * (x[i-1]-0.5));
}
g = 100 * (k + g);
for (i = 1; i <= no_objs; i++)
{
double fi = 0.5 * (1 + g);
for (j = no_objs - i; j >= 1; j--)
{
fi *= x[j-1];
}
if (i > 1)
{
fi *= 1 - x[(no_objs - i + 1) - 1];
}
f[i-1] = fi;
}
}
void DTLZ2(const double *x, double* f, const unsigned no_vars, const unsigned no_objs)
{
int i = 0;
int j = 0;
int n = no_vars;
int k = n - no_objs + 1;
double g = 0;
for (i = n - k + 1; i <= n; i++)
{
g += pow(x[i-1]-0.5,2);
}
for (i = 1; i <= no_objs; i++)
{
double fi = (1 + g);
for (j = no_objs - i; j >= 1; j--)
{
fi *= cos(x[j-1] * PI / 2);
}
if (i > 1)
{
fi *= sin(x[(no_objs - i + 1) - 1] * PI / 2);
}
f[i-1] = fi;
}
}
void DTLZ3(const double *x, double* f, const unsigned no_vars, const unsigned no_objs)
{
int i = 0;
int j = 0;
int n = no_vars;
int k = n - no_objs + 1;
double g = 0;
for (i = n - k + 1; i <= n; i++)
{
g += pow(x[i-1]-0.5,2) - cos(20 * PI * (x[i-1]-0.5));
}
g = 100 * (k + g);
for (i = 1; i <= no_objs; i++)
{
double fi = (1 + g);
for (j = no_objs - i; j >= 1; j--)
{
fi *= cos(x[j-1] * PI / 2);
}
if (i > 1)
{
fi *= sin(x[(no_objs - i + 1) - 1] * PI / 2);
}
f[i-1] = fi;
}
}
void DTLZ4(const double *x, double* f, const unsigned no_vars, const unsigned no_objs)
{
int i = 0;
int j = 0;
double alpha = 100;
int n = no_vars;
int k = n - no_objs + 1;
double g = 0;
for (i = n - k + 1; i <= n; i++)
{
g += pow(x[i-1]-0.5,2);
}
for (i = 1; i <= no_objs; i++)
{
double fi = (1 + g);
for (j = no_objs - i; j >= 1; j--)
{
fi *= cos(pow(x[j-1],alpha) * PI / 2);
}
if (i > 1)
{
fi *= sin(pow(x[(no_objs - i + 1) - 1],alpha) * PI / 2);
}
f[i-1] = fi;
}
}
void DTLZ5(const double *x, double* f, const unsigned no_vars, const unsigned no_objs)
{
int i = 0;
int j = 0;
int n = no_vars;
int k = n - no_objs + 1;
double *theta = new double[no_objs];
double t = 0;
double g = 0;
for (i = n - k + 1; i <= n; i++)
{
g += pow(x[i-1] - 0.5, 2);
}
t = PI / (4 * (1 + g));
theta[0] = x[0] * PI / 2;
for (i = 2; i <= no_objs - 1; i++)
{
theta[i-1] = t * (1 + 2 * g * x[i-1]);
}
for (i = 1; i <= no_objs; i++)
{
double fi = (1 + g);
for (j = no_objs - i; j >= 1; j--)
{
fi *= cos(theta[j-1]);
}
if (i > 1)
{
fi *= sin(theta[(no_objs - i + 1) - 1]);
}
f[i-1] = fi;
}
delete theta;
}
void DTLZ6(const double *x, double* f, const unsigned no_vars, const unsigned no_objs)
{
int i = 0;
int j = 0;
int n = no_vars;
int k = n - no_objs + 1;
double *theta = new double[no_objs];
double t = 0;
double g = 0;
for (i = n - k + 1; i <= n; i++)
{
g += pow(x[i-1], 0.1);
}
t = PI / (4 * (1 + g));
theta[0] = x[0] * PI / 2;
for (i = 2; i <= no_objs - 1; i++)
{
theta[i-1] = t * (1 + 2 * g * x[i-1]);
}
for (i = 1; i <= no_objs; i++)
{
double fi = (1 + g);
for (j = no_objs - i; j >= 1; j--)
{
fi *= cos(theta[j-1]);
}
if (i > 1)
{
fi *= sin(theta[(no_objs - i + 1) - 1]);
}
f[i-1] = fi;
}
delete theta;
}
void DTLZ7(const double *x, double* f, const unsigned no_vars, const unsigned no_objs)
{
int i = 0;
int j = 0;
int n = no_vars;
int k = n - no_objs + 1;
double g = 0;
double h = 0;
for (i = n - k + 1; i <= n; i++)
{
g += x[i-1];
}
g = 1 + 9 * g / k;
for (i = 1; i <= no_objs - 1; i++)
{
f[i-1] = x[i-1];
}
for (j = 1; j <= no_objs - 1; j++)
{
h += x[j-1] / (1 + g) * (1 + sin(3 * PI * x[j-1]));
}
h = no_objs - h;
f[no_objs - 1] = (1 + g) * h;
}
} /* dtlz */
| 17.47479
| 86
| 0.425824
|
lucasmpavelski
|
b1254b1b4a4235059ad51cd479eb73ceb4aa9240
| 14,579
|
cxx
|
C++
|
TRD/TRDsim/AliTRDptrgFEB.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 52
|
2016-12-11T13:04:01.000Z
|
2022-03-11T11:49:35.000Z
|
TRD/TRDsim/AliTRDptrgFEB.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 1,388
|
2016-11-01T10:27:36.000Z
|
2022-03-30T15:26:09.000Z
|
TRD/TRDsim/AliTRDptrgFEB.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 275
|
2016-06-21T20:24:05.000Z
|
2022-03-31T13:06:19.000Z
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
////////////////////////////////////////////////////////////////////////////
//
// Pre-Trigger simulation
//
// Authors: F. Reidt (Felix.Reidt@cern.ch)
//
// This class is used to simulate the front end box behavior of the
// pretrigger system. Digits of T0 and V0 are used as input. A threshold
// discrimination, masking and first processing with look up tables is
// done during the simulation process
//
////////////////////////////////////////////////////////////////////////////
#include <TClonesArray.h>
#include <TTree.h>
#include "AliRunLoader.h"
#include "AliLoader.h"
#include "AliLog.h"
#include "AliVZEROdigit.h"
#include "AliVZEROCalibData.h"
#include "AliT0digit.h"
#include "AliTRDptrgParam.h"
#include "AliTRDptrgLUT.h"
#include "AliTRDptrgFEB.h"
ClassImp(AliTRDptrgFEB)
//______________________________________________________________________________
AliTRDptrgFEB::AliTRDptrgFEB(AliRunLoader *rl)
: TObject(),
fRunLoader(rl),
fParam(0),
fLUTArray(0),
fType(AliTRDptrgParam::kUndefined),
fOperatingMode(AliTRDptrgParam::kDigits),
fInputChannelCount(0),
fPosition(AliTRDptrgParam::kUnknown),
fID(0),
fThreshold(0)
{
// default constructor
AliError("default ctor - not recommended");
}
//______________________________________________________________________________
AliTRDptrgFEB::AliTRDptrgFEB(AliRunLoader *rl, AliTRDptrgParam::AliTRDptrgFEBType_t febType,
AliTRDptrgParam::AliTRDptrgOperatingMode_t operatingMode,
AliTRDptrgParam::AliTRDptrgFEBPosition_t position, Int_t id,
AliTRDptrgParam *param)
: TObject(),
fRunLoader(rl),
fParam(param),
fLUTArray(0),
fType(febType),
fOperatingMode(operatingMode),
fInputChannelCount(0),
fPosition(position),
fID(id),
fThreshold(0x0)
{
// prefered constructor
this->LoadParams(); // load configuration parameters
}
//______________________________________________________________________________
AliTRDptrgFEB::~AliTRDptrgFEB()
{
// destructor
if (this->fParam == 0x0) {
if (this->fThreshold != 0x0) {
delete[] this->fThreshold;
this->fThreshold = 0x0;
}
}
// delete LUTArray
this->fLUTArray.Delete();
}
//______________________________________________________________________________
Int_t AliTRDptrgFEB::LoadDigits()
{
// loads T0 or V0 digits and discriminates them automatically
if (this->fType == AliTRDptrgParam::kVZERO) {
// load V0's digits --------------------------------------------------------
// behavior adapted for AliVZERODigitizer.cxx 40613 2010-04-22 09:57:15Z
// get V0 run loader
AliLoader* loader = this->fRunLoader->GetLoader( "VZEROLoader" );
if (!loader) {
AliError("Cannot get VZERO loader");
return -1;
}
loader->LoadDigits("READ");
TTree* vzeroDigitsTree = loader->TreeD();
if (!vzeroDigitsTree) {
AliError("Cannot get the VZERO digit tree");
return -1;
}
TClonesArray* vzeroDigits = NULL;
TBranch* digitBranch = vzeroDigitsTree->GetBranch("VZERODigit");
digitBranch->SetAddress(&vzeroDigits);
vzeroDigitsTree->GetEvent(0);
Int_t nDigits = vzeroDigits->GetEntriesFast(); // get digit count
AliDebug(5, Form("Found a whole of %d digits", nDigits));
Int_t inputVector = 0x0; // Vector which is feed into the LUT
for (Int_t iDigit=0; iDigit<nDigits; iDigit++) {
// loop over all digits
AliDebug(5, "Looping over digit");
AliVZEROdigit* digit = (AliVZEROdigit*)vzeroDigits->At(iDigit);
Int_t pmNumber = digit->PMNumber();
// Int_t board = pmNumber / 8; // changed in Version 40613
Int_t feeBoard = AliVZEROCalibData::GetBoardNumber(pmNumber);
Int_t board = feeBoard % 4; // feeBoard V0-A: 1-4; V0-C: 5-8 => board: 1-4
Int_t channel = pmNumber % 8;
Int_t position = -1;
if ((pmNumber >= 32) && (pmNumber <= 63)) { // V0-A (matched v40613)
position = 1; // AliTRDptrgParam::kA
}
else if ((pmNumber >= 0) && (pmNumber <= 31)) { // V0-C (matched v40613)
position = 2; // kB
}
AliDebug(5,
Form("pmNumber: %d; feeBoard: %d; board: %d; channel: %d; position %d",
pmNumber, feeBoard, board, channel, position));
if (position == -1) {
AliError("Wrong VZERO pmt position found");
loader->UnloadDigits();
return -1;
}
// check whether the digits belongs to the current FEB, otherwise omit it
if ((position == this->fPosition) && (board == this->fID)) {
AliDebug(5, "Found an digit corresponding to the current FEB");
Float_t value = digit->ADC();
AliDebug(5, Form("ADC value: %f\n", value));
Int_t channelBitMask = 0x01;
// channel0 => 0x01; channel1=> 0x02; 2^(channel number)
channelBitMask <<= channel;
if (value >= this->fThreshold[channel]) {
inputVector |= channelBitMask;
AliDebug(5,
Form("Threshold exceeded in channel %d, new inputVector 0x%x",
channel, inputVector));
}
}
}
AliDebug(5, Form("inputVector: 0x%x", inputVector));
loader->UnloadDigits();
return inputVector;
}
else if (this->fType == AliTRDptrgParam::kTZERO) {
// load T0's digits --------------------------------------------------------
AliLoader * fT0Loader = this->fRunLoader->GetLoader("T0Loader");
// AliT0digit *fDigits;
if (!fT0Loader) {
AliError("Cannot get T0 loader");
return -1;
}
fT0Loader->LoadDigits("READ");
// Creating T0 data container
TTree* treeD = fT0Loader->TreeD();
if (!treeD) {
AliError("no digits tree");
return -1;
}
AliT0digit* digits = new AliT0digit();
TBranch *brDigits = treeD->GetBranch("T0");
if (brDigits) {
brDigits->SetAddress(&digits);
}
else {
AliError("Branch T0 DIGIT not found");
return -1;
}
brDigits->GetEntry(0);
TArrayI qtc0(24); // Array must have 24 entries!
TArrayI qtc1(24); // Array must have 24 entries!
digits->GetQT0(qtc0); // baseline (reference level)
digits->GetQT1(qtc1); // measurement value
Int_t inputVector = 0x0; // vector to be fed into the look up table
// PMT Positions
// C: 0 to 11
// A: 12 to 23
// positions according to AliT0Digitizer.cxx Revision 37491
Int_t nStart = 0;
if (this->fPosition == AliTRDptrgParam::kC) { // C
nStart = 0;
}
else if (this->fPosition == AliTRDptrgParam::kA) { // A
nStart = 12;
}
Int_t channelBitMask = 0x01;
for (Int_t i = 0 + nStart; i < nStart + 12; i++) {
//Int_t channelBitMask = 0x01;
AliDebug(5, Form("channel: %d", i));
Int_t value = qtc1[i] - qtc0[i]; // calculate correct measurement value
if (value > (Int_t)this->fThreshold[i - nStart]) {
inputVector |= channelBitMask; // Add bit
AliDebug(5, Form("Threshold exceeded in channel %d,", i));
AliDebug(5, Form("new inputVector 0x%x", inputVector));
AliDebug(5, Form("channelBitMask 0x%x", channelBitMask));
}
channelBitMask <<= 1; // go on to the next channel
}
delete digits;
return inputVector;
}
return -1;
}
//______________________________________________________________________________
Int_t AliTRDptrgFEB::LoadAndProcessHits()
{
// loads TO or VO hits and converts them to digits optimized for ptrg
// afterwards the digits will be discriminated
AliError("LoadAndProcessHits() - not yet implemented!\n");
if (this->fType == AliTRDptrgParam::kVZERO) {
return 0;
}
else if (this->fType == AliTRDptrgParam::kTZERO) {
return 0;
}
return -1;
}
//______________________________________________________________________________
Bool_t AliTRDptrgFEB::LoadParams()
{
// Load Parameters
if (this->fParam == 0x0) {
AliWarning("No paramater object specified - start loading defaults\n");
if (this->fType == AliTRDptrgParam::kVZERO) {
// initialize threshold
this->fThreshold = new UInt_t[8];
for (Int_t i = 0; i < 8; i++) {
this->fThreshold[i] = 10;
}
// initialize LUTsoutputWidth=<value optimized out>
AliTRDptrgLUT* lut = new AliTRDptrgLUT();
this->fLUTArray.AddLast(lut);
lut = new AliTRDptrgLUT();
this->fLUTArray.AddLast(lut);
// the following lines are only needed for test reasons
Int_t* initData = new Int_t[256]; // 2^8
lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(0));
if (lut) {
for (Int_t i = 0; i < 256; i++ ) {
initData[i] = i;
}
lut->InitTable(8, 8, initData, kTRUE); // make copy of initData
}
lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(1));
if (lut) {
for (Int_t i = 255; i >= 0; i--) {
initData[255 - i] = i; // inverse ramp
}
lut->InitTable(8, 8, initData, kTRUE);
}
delete [] initData;
}
else {
// initialize threshold
this->fThreshold = new UInt_t[12];
for (Int_t i = 0; i < 12; i++) {
this->fThreshold[i] = 10;
}
// initialize LUTsoutputWidth=<value optimized out>
AliTRDptrgLUT* lut = new AliTRDptrgLUT();
this->fLUTArray.AddLast(lut);
lut = new AliTRDptrgLUT(); // this->fRunLoader
this->fLUTArray.AddLast(lut);
// the following lines are only needed for test reasons
lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(0));
Int_t* initData = new Int_t[4096]; // 2^12
if (lut) {
for (Int_t i = 0; i < 4096; i++ ) {
initData[i] = i;
}
lut->InitTable(12, 12, initData, kTRUE); // make a copy of the table
}
lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(1));
if (lut) {
//for (Int_t i = 4095; i >= 0; i--) {
for (Int_t i = 4096; i > 0; i--) {
initData[4096 - i] = i; // inverse ramp
}
lut->InitTable(12, 12, initData, kTRUE); // make a copy of the table
}
delete [] initData;
}
return false;
}
else {
// load parameters from object
if (this->fType == AliTRDptrgParam::kVZERO) {
// threshold
this->fThreshold =
this->fParam->GetFEBV0Thresholds(this->fPosition, (this->fID - 1));
// look up tables
// 1
AliTRDptrgLUT* LUT = new AliTRDptrgLUT();
LUT->InitTable(8, 8, this->fParam->GetFEBV0LUT(this->fPosition,
(this->fID - 1),
0), kFALSE);
// do not make a copy of the table due to performance reasons
this->fLUTArray.AddLast(LUT);
// 2
LUT = new AliTRDptrgLUT();
LUT->InitTable(8, 8, this->fParam->GetFEBV0LUT(this->fPosition,
(this->fID - 1),
1), kFALSE);
// do not make a copy of the table due to performance reasons
this->fLUTArray.AddLast(LUT);
}
else {
// threshold
this->fThreshold =
this->fParam->GetFEBT0Thresholds(this->fPosition);
// look up tables
// 1
AliTRDptrgLUT* LUT = new AliTRDptrgLUT();
LUT->InitTable(12, 12, fParam->GetFEBT0LUT(this->fPosition, 0), kFALSE);
// do not make a copy of the table due to performance reasosn
this->fLUTArray.AddLast(LUT);
// 2
LUT = new AliTRDptrgLUT();
LUT->InitTable(12, 12, fParam->GetFEBT0LUT(this->fPosition, 1), kFALSE);
// do not make a copy of the table due to performance reasosn
this->fLUTArray.AddLast(LUT);
}
return true;
}
return false;
}
//______________________________________________________________________________
Int_t* AliTRDptrgFEB::Simulate()
{
// simulates the FEB behavior and returns a 2 bit ouput
// (least significant bits)
Int_t *result = new Int_t;
(*result) = -1;
if (this->fOperatingMode == AliTRDptrgParam::kDigits) {
Int_t inputVector = this->LoadDigits();
delete result; // delete error return value
// perform look up
Int_t nLUTs = this->fLUTArray.GetEntriesFast(); // get LUT count
result = new Int_t[nLUTs + 1]; // generate new return array
result[0] = nLUTs; // storage array length in the first array value
for (Int_t iLUT = 0; iLUT < nLUTs; iLUT++) {
// process the return value for each LUT and store the result in the array
AliDebug(4, Form("FEB: (pos=%d,id=%d,lut=%d,vector=0x%x)",
this->fPosition, this->fID, iLUT, inputVector));
AliTRDptrgLUT *lutTmp = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray[iLUT]);
if (lutTmp) {
result[iLUT + 1] = lutTmp->LookUp(inputVector);
}
AliDebug(4, Form("FEB result[%d] = 0x%x",(iLUT + 1),result[iLUT + 1]));
}
}
else if (this->fOperatingMode == AliTRDptrgParam::kHits) {
return result;
}
return result;
}
| 34.223005
| 93
| 0.576651
|
AllaMaevskaya
|
b127350b502f277660f655415e9d6b020c14c583
| 3,482
|
cpp
|
C++
|
source/MaterialXTest/Document.cpp
|
lvxejay/MaterialX
|
d367fe00ad6dca5ba56370e8c97249779a6bcf71
|
[
"BSL-1.0"
] | null | null | null |
source/MaterialXTest/Document.cpp
|
lvxejay/MaterialX
|
d367fe00ad6dca5ba56370e8c97249779a6bcf71
|
[
"BSL-1.0"
] | null | null | null |
source/MaterialXTest/Document.cpp
|
lvxejay/MaterialX
|
d367fe00ad6dca5ba56370e8c97249779a6bcf71
|
[
"BSL-1.0"
] | 1
|
2021-09-11T08:01:25.000Z
|
2021-09-11T08:01:25.000Z
|
//
// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include <MaterialXTest/Catch/catch.hpp>
#include <MaterialXCore/Document.h>
namespace mx = MaterialX;
TEST_CASE("Document", "[document]")
{
// Create a document.
mx::DocumentPtr doc = mx::createDocument();
// Create a node graph with a constant color output.
mx::NodeGraphPtr nodeGraph = doc->addNodeGraph();
mx::NodePtr constant = nodeGraph->addNode("constant");
constant->setParameterValue("value", mx::Color3(0.5f, 0.5f, 0.5f));
mx::OutputPtr output = nodeGraph->addOutput();
output->setConnectedNode(constant);
REQUIRE(doc->validate());
// Create and test a type mismatch.
output->setType("float");
REQUIRE(!doc->validate());
output->setType("color3");
REQUIRE(doc->validate());
// Test hierarchical name paths.
REQUIRE(constant->getNamePath() == "nodegraph1/node1");
REQUIRE(constant->getNamePath(nodeGraph) == "node1");
// Create a simple shader interface.
mx::NodeDefPtr shader = doc->addNodeDef("", "surfaceshader", "simpleSrf");
mx::InputPtr diffColor = shader->addInput("diffColor", "color3");
mx::InputPtr specColor = shader->addInput("specColor", "color3");
mx::ParameterPtr roughness = shader->addParameter("roughness", "float");
// Create a material that instantiates the shader.
mx::MaterialPtr material = doc->addMaterial();
mx::ShaderRefPtr shaderRef = material->addShaderRef("", "simpleSrf");
// Bind the diffuse color input to the constant color output.
mx::BindInputPtr bindInput = shaderRef->addBindInput("diffColor");
bindInput->setConnectedOutput(output);
REQUIRE(diffColor->getUpstreamElement(material) == output);
// Create a collection
mx::CollectionPtr collection = doc->addCollection();
REQUIRE(doc->getCollections().size() == 1);
REQUIRE(doc->getCollection(collection->getName()));
doc->removeCollection(collection->getName());
REQUIRE(doc->getCollections().size() == 0);
// Create a property set
mx::PropertySetPtr propertySet = doc->addPropertySet();
REQUIRE(doc->getPropertySets().size() == 1);
REQUIRE(doc->getPropertySet(propertySet->getName()) != nullptr);
doc->removePropertySet(propertySet->getName());
REQUIRE(doc->getPropertySets().size() == 0);
// Generate and verify require string.
doc->generateRequireString();
REQUIRE(doc->getRequireString().find(mx::Document::REQUIRE_STRING_MATNODEGRAPH) != std::string::npos);
// Validate the document.
REQUIRE(doc->validate());
// Copy and reorder the document.
mx::DocumentPtr doc2 = doc->copy();
REQUIRE(*doc2 == *doc);
int origIndex = doc2->getChildIndex(shader->getName());
doc2->setChildIndex(shader->getName(), origIndex + 1);
REQUIRE(*doc2 != *doc);
doc2->setChildIndex(shader->getName(), origIndex);
REQUIRE(*doc2 == *doc);
REQUIRE_THROWS_AS(doc2->setChildIndex(shader->getName(), 100), mx::Exception);
// Create and test an orphaned element.
mx::ElementPtr orphan;
{
mx::DocumentPtr doc3 = doc->copy();
for (mx::ElementPtr elem : doc3->traverseTree())
{
if (elem->isA<mx::Node>("constant"))
{
orphan = elem;
}
}
REQUIRE(orphan);
}
REQUIRE_THROWS_AS(orphan->getDocument(), mx::ExceptionOrphanedElement);
}
| 36.270833
| 106
| 0.660827
|
lvxejay
|
b12dc07fbd8023ba7e19db7eddedc097b3076b8d
| 149
|
hpp
|
C++
|
source/GcLib/directx/DxConstant.hpp
|
Mugenri/Touhou-Danmakufu-ph3sx-2
|
4ab7e40682341ff41d7467b83bb64c9a669a6064
|
[
"MIT"
] | null | null | null |
source/GcLib/directx/DxConstant.hpp
|
Mugenri/Touhou-Danmakufu-ph3sx-2
|
4ab7e40682341ff41d7467b83bb64c9a669a6064
|
[
"MIT"
] | null | null | null |
source/GcLib/directx/DxConstant.hpp
|
Mugenri/Touhou-Danmakufu-ph3sx-2
|
4ab7e40682341ff41d7467b83bb64c9a669a6064
|
[
"MIT"
] | null | null | null |
#pragma once
#include "../pch.h"
#include "../gstd/GstdLib.hpp"
#include "DxTypes.hpp"
#if defined(DNH_PROJ_EXECUTOR)
#include "Vertex.hpp"
#endif
| 14.9
| 30
| 0.711409
|
Mugenri
|
b1325f3e14933c34ac5c16dba6e10221ff2415eb
| 18,257
|
cpp
|
C++
|
tests/record/test_array_fcall_method.cpp
|
hachetman/systemc-compiler
|
0cc81ace03336d752c0146340ff5763a20e3cefd
|
[
"Apache-2.0"
] | 86
|
2020-10-23T15:59:47.000Z
|
2022-03-28T18:51:19.000Z
|
tests/record/test_array_fcall_method.cpp
|
hachetman/systemc-compiler
|
0cc81ace03336d752c0146340ff5763a20e3cefd
|
[
"Apache-2.0"
] | 18
|
2020-12-14T13:11:26.000Z
|
2022-03-14T05:34:20.000Z
|
tests/record/test_array_fcall_method.cpp
|
hachetman/systemc-compiler
|
0cc81ace03336d752c0146340ff5763a20e3cefd
|
[
"Apache-2.0"
] | 17
|
2020-10-29T16:19:43.000Z
|
2022-03-11T09:51:05.000Z
|
/******************************************************************************
* Copyright (c) 2020, Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception.
*
*****************************************************************************/
#include "sct_assert.h"
#include "systemc.h"
#include <iostream>
using namespace sc_core;
// Record array elements as function parameters
class A : public sc_module {
public:
sc_in<sc_uint<2>> a{"a"};
sc_signal<sc_uint<2>> as{"as"};
sc_in<sc_int<2>> as_i{"as_i"};
sc_signal<int> s{"s"};
SC_CTOR(A)
{
for (int i = 0; i < 3; i++) {
spp[i] = new sc_signal<int>("");
}
SC_METHOD(rec_arr_elem_func_param_val);
sensitive << s;
SC_METHOD(rec_arr_elem_func_param_val2);
sensitive << s;
SC_METHOD(rec_arr_elem_func_param_val3);
sensitive << s;
SC_METHOD(rec_arr_elem_func_param_ref);
sensitive << s;
SC_METHOD(rec_arr_elem_func_param_ref2);
sensitive << s;
SC_METHOD(rec_arr_elem_func_param_ref3);
sensitive << s;
SC_METHOD(arr_elem_in_index);
sensitive << s << srr[0] << *spp[0];
// TODO: Fix me, #99
//SC_METHOD(rec_arr_elem_in_index);
//sensitive << s;
/*SC_METHOD(record_var_if);
sensitive << a << as << as_i << s;
SC_METHOD(record_var_if_bitwise);
sensitive << a << as << as_i << s;
SC_METHOD(record_var_if_arith);
sensitive << a << as << as_i << s;*/
}
//---------------------------------------------------------------------------
struct MyRec {
sc_int<2> a;
sc_uint<4> b;
};
void f1(MyRec par) {
int k = par.b;
}
int f1_two(MyRec par1, MyRec par2) {
return (par1.b + par2.b);
}
// Record array element as function parameter by value
void rec_arr_elem_func_param_val()
{
MyRec sr;
f1(sr);
MyRec sra[3];
f1(sra[1]);
int i = s.read();
f1(sra[i]);
}
// Two record array elements as function parameters by value
void rec_arr_elem_func_param_val2()
{
MyRec xr, yr;
f1_two(xr, yr);
MyRec xra[3]; MyRec yra[2];
f1_two(xra[2], yra[1]);
f1_two(xra[2], xra[1]);
f1_two(xra[2], xra[2]);
f1_two(xra[2], yr);
int i = f1_two(yr, xra[1]);
}
// Record array element at unknown index as function parameters by value
void rec_arr_elem_func_param_val3()
{
int i = s.read();
MyRec qr;
MyRec qra[3];
f1_two(qra[i], qra[i]);
f1_two(qr, qra[i+1]);
if (i) {
f1_two(qra[i-1], qr);
} else {
if (i == 1) f1(qra[i]);
}
}
//-----------------------------------------------------------------------------
void f2(MyRec& par) {
int k = par.b;
}
void f2_two(MyRec& par1, MyRec& par2) {
int k = par1.b + par2.b;
}
int f2_two_cond(MyRec& par1, bool a, MyRec& par2) {
return (a ? par1.b : par2.b);
}
// Record array element as function parameter by reference
void rec_arr_elem_func_param_ref()
{
MyRec vr[3];
f2(vr[1]);
int i = s.read();
f2(vr[i]);
}
// Two record array elements as function parameters by reference
void rec_arr_elem_func_param_ref2()
{
MyRec er[3];
MyRec fr;
f2_two(fr, er[2]);
f2_two(er[1], er[2]);
f2_two(er[1], er[1]);
bool a;
int i = s.read();
a = f2_two_cond(er[i], true, fr);
f2_two_cond(er[i+1], a, er[i+1]);
}
int f3_val(sc_uint<4> par) {
return (par+1);
}
int f3_ref(sc_uint<4>& par) {
par++;
return par;
}
// Record array elements as function parameters in IF, passed by reference
void rec_arr_elem_func_param_ref3()
{
MyRec err[3];
MyRec frr;
int i = s.read();
frr.a = f3_val(err[i].b);
frr.a = f3_ref(err[i+1].b);
f2_two(err[i], err[frr.a]);
}
// Use record array element as index for the same array
sc_signal<int> srr[3];
sc_signal<int>* spp[3];
void arr_elem_in_index()
{
int i = s.read();
int irr[3];
irr[irr[1]] = 1;
irr[irr[i]] = irr[i+1];
srr[srr[1]] = 1;
srr[srr[i]] = srr[srr[i+1]+1];
*spp[spp[1]->read()] = 1;
*spp[*spp[1]] = 1;
*spp[*spp[i]] = *spp[i+*spp[i+1]];
}
void rec_arr_elem_in_index()
{
MyRec err[3];
err[err[1].b].a = 1;
}
//-----------------------------------------------------------------------------
// Function with records
struct Simple {
int a;
sc_uint<2> b;
Simple(): a(1){
}
int geta(){
return a;
}
void seta(int bval){
a = bval;
}
};
struct Simple_arith {
sc_uint<32> a;
sc_uint<16> b;
Simple_arith(): a(30), b(15){
}
sc_uint<32> geta(){
return a;
}
sc_uint<32> getaplusb(){
return a + b;
}
sc_uint<32> getaminusb(){
return a - b;
}
sc_uint<32> getamultb(){
return a * b;
}
sc_uint<32> getadivb(){
return a / b;
}
sc_uint<32> getamodb(){
return a % b;
}
void seta(sc_uint<32> aval){
a = aval;
}
void setb(sc_uint<16> bval){
b = bval;
}
};
struct Simple_bitwise {
sc_uint<32> a;
sc_uint<16> b;
Simple_bitwise(): a(30), b(15){
}
sc_uint<32> geta(){
return a;
}
void seta(sc_uint<32> aval){
a = aval;
}
void setb(sc_uint<16> bval){
b = bval;
}
sc_uint<32> getaorb(){
return a | b;
}
sc_uint<32> getaandb(){
return a & b;
}
sc_uint<32> getnota(){
return !a;
}
sc_uint<32> getaxorb(){
return a ^ b;
}
sc_uint<32> getalorb(){
return a || b;
}
sc_uint<32> getalandb(){
return a && b;
}
};
Simple rec[16];
Simple_arith reca[16];
Simple_bitwise recb[16];
void record_var_if()
{
int num1 = 0;
int num2 = 1;
int val1 = 0;
if (num1==0) {
rec[num1].seta(val1);
} else {
rec[num1].seta(1);
}
if (num2!=1) {
rec[num2].seta(0);
} else {
rec[num2].seta(1);
}
//cout << "rec[0] = "<< rec[0].a << endl;
//cout << "rec[1] = "<< rec[1].a << endl;
sct_assert_const(rec[0].geta()==0);
sct_assert_const(rec[1].geta()==1);
if (as_i.read()==0) {
rec[as_i.read()].seta(35);
rec[s.read()].seta(45);
} else {
rec[as_i.read()].seta(25);
rec[s.read()].seta(50);
}
}
void record_var_if_arith()
{
reca[0].seta(16);
reca[0].setb(5);
sct_assert_const(reca[0].getaplusb()== 21);
sct_assert_const(reca[0].getaminusb()== 11);
sct_assert_const(reca[0].getamultb()== 80);
sct_assert_const(reca[0].getadivb()== 3);
sct_assert_const(reca[0].getamodb()== 1);
for(int i=0; i<17; i++) {
reca[i].seta(i*3);
reca[i].setb(i*2+2);
//cout << "sc_assert (reca[" << i << "].getaplusb() == " << reca[i].getaplusb() << ");" << endl;
//cout << "sc_assert (reca[" << i << "].getaminusb() == " << reca[i].getaminusb() << ");" << endl;
//cout << "sc_assert (reca[" << i << "].getamultb() == " << reca[i].getamultb() << ");" << endl;
//cout << "sc_assert (reca[" << i << "].getadivb() == " << reca[i].getadivb() << ");" << endl;
//cout << "sc_assert (reca[" << i << "].getamodb() == " << reca[i].getamodb() << ");" << endl;
}
sc_assert (reca[0].getaplusb() == 2);
sc_assert (reca[0].getaminusb() == 4294967294);
sc_assert (reca[0].getamultb() == 0);
sc_assert (reca[0].getadivb() == 0);
sc_assert (reca[0].getamodb() == 0);
sc_assert (reca[1].getaplusb() == 7);
sc_assert (reca[1].getaminusb() == 4294967295);
sc_assert (reca[1].getamultb() == 12);
sc_assert (reca[1].getadivb() == 0);
sc_assert (reca[1].getamodb() == 3);
sc_assert (reca[2].getaplusb() == 12);
sc_assert (reca[2].getaminusb() == 0);
sc_assert (reca[2].getamultb() == 36);
sc_assert (reca[2].getadivb() == 1);
sc_assert (reca[2].getamodb() == 0);
sc_assert (reca[3].getaplusb() == 17);
sc_assert (reca[3].getaminusb() == 1);
sc_assert (reca[3].getamultb() == 72);
sc_assert (reca[3].getadivb() == 1);
sc_assert (reca[3].getamodb() == 1);
sc_assert (reca[4].getaplusb() == 22);
sc_assert (reca[4].getaminusb() == 2);
sc_assert (reca[4].getamultb() == 120);
sc_assert (reca[4].getadivb() == 1);
sc_assert (reca[4].getamodb() == 2);
sc_assert (reca[5].getaplusb() == 27);
sc_assert (reca[5].getaminusb() == 3);
sc_assert (reca[5].getamultb() == 180);
sc_assert (reca[5].getadivb() == 1);
sc_assert (reca[5].getamodb() == 3);
sc_assert (reca[6].getaplusb() == 32);
sc_assert (reca[6].getaminusb() == 4);
sc_assert (reca[6].getamultb() == 252);
sc_assert (reca[6].getadivb() == 1);
sc_assert (reca[6].getamodb() == 4);
sc_assert (reca[7].getaplusb() == 37);
sc_assert (reca[7].getaminusb() == 5);
sc_assert (reca[7].getamultb() == 336);
sc_assert (reca[7].getadivb() == 1);
sc_assert (reca[7].getamodb() == 5);
sc_assert (reca[8].getaplusb() == 42);
sc_assert (reca[8].getaminusb() == 6);
sc_assert (reca[8].getamultb() == 432);
sc_assert (reca[8].getadivb() == 1);
sc_assert (reca[8].getamodb() == 6);
sc_assert (reca[9].getaplusb() == 47);
sc_assert (reca[9].getaminusb() == 7);
sc_assert (reca[9].getamultb() == 540);
sc_assert (reca[9].getadivb() == 1);
sc_assert (reca[9].getamodb() == 7);
sc_assert (reca[10].getaplusb() == 52);
sc_assert (reca[10].getaminusb() == 8);
sc_assert (reca[10].getamultb() == 660);
sc_assert (reca[10].getadivb() == 1);
sc_assert (reca[10].getamodb() == 8);
sc_assert (reca[11].getaplusb() == 57);
sc_assert (reca[11].getaminusb() == 9);
sc_assert (reca[11].getamultb() == 792);
sc_assert (reca[11].getadivb() == 1);
sc_assert (reca[11].getamodb() == 9);
sc_assert (reca[12].getaplusb() == 62);
sc_assert (reca[12].getaminusb() == 10);
sc_assert (reca[12].getamultb() == 936);
sc_assert (reca[12].getadivb() == 1);
sc_assert (reca[12].getamodb() == 10);
sc_assert (reca[13].getaplusb() == 67);
sc_assert (reca[13].getaminusb() == 11);
sc_assert (reca[13].getamultb() == 1092);
sc_assert (reca[13].getadivb() == 1);
sc_assert (reca[13].getamodb() == 11);
sc_assert (reca[14].getaplusb() == 72);
sc_assert (reca[14].getaminusb() == 12);
sc_assert (reca[14].getamultb() == 1260);
sc_assert (reca[14].getadivb() == 1);
sc_assert (reca[14].getamodb() == 12);
sc_assert (reca[15].getaplusb() == 77);
sc_assert (reca[15].getaminusb() == 13);
sc_assert (reca[15].getamultb() == 1440);
sc_assert (reca[15].getadivb() == 1);
sc_assert (reca[15].getamodb() == 13);
sc_assert (reca[16].getaplusb() == 82);
sc_assert (reca[16].getaminusb() == 14);
sc_assert (reca[16].getamultb() == 1632);
sc_assert (reca[16].getadivb() == 1);
sc_assert (reca[16].getamodb() == 14);
}
void record_var_if_bitwise()
{
for(int i=0; i<17; i++) {
recb[i].seta(i*3);
recb[i].setb(i*2+2);
//cout << "sc_assert (recb[" << i << "].getaorb() == " << recb[i].getaorb() << ");" << endl;
//cout << "sc_assert (recb[" << i << "].getaandb() == " << recb[i].getaandb() << ");" << endl;
//cout << "sc_assert (recb[" << i << "].getnota() == " << recb[i].getnota() << ");" << endl;
//cout << "sc_assert (recb[" << i << "].getaxorb() == " << recb[i].getaxorb() << ");" << endl;
//cout << "sc_assert (recb[" << i << "].getalorb() == " << recb[i].getalorb() << ");" << endl;
//cout << "sc_assert (recb[" << i << "].getalandb() == " << recb[i].getalandb() << ");" << endl;
}
sc_assert (recb[0].getaorb() == 2);
sc_assert (recb[0].getaandb() == 0);
sc_assert (recb[0].getnota() == 1);
sc_assert (recb[0].getaxorb() == 2);
sc_assert (recb[0].getalorb() == 1);
sc_assert (recb[0].getalandb() == 0);
sc_assert (recb[1].getaorb() == 7);
sc_assert (recb[1].getaandb() == 0);
sc_assert (recb[1].getnota() == 0);
sc_assert (recb[1].getaxorb() == 7);
sc_assert (recb[1].getalorb() == 1);
sc_assert (recb[1].getalandb() == 1);
sc_assert (recb[2].getaorb() == 6);
sc_assert (recb[2].getaandb() == 6);
sc_assert (recb[2].getnota() == 0);
sc_assert (recb[2].getaxorb() == 0);
sc_assert (recb[2].getalorb() == 1);
sc_assert (recb[2].getalandb() == 1);
sc_assert (recb[3].getaorb() == 9);
sc_assert (recb[3].getaandb() == 8);
sc_assert (recb[3].getnota() == 0);
sc_assert (recb[3].getaxorb() == 1);
sc_assert (recb[3].getalorb() == 1);
sc_assert (recb[3].getalandb() == 1);
sc_assert (recb[4].getaorb() == 14);
sc_assert (recb[4].getaandb() == 8);
sc_assert (recb[4].getnota() == 0);
sc_assert (recb[4].getaxorb() == 6);
sc_assert (recb[4].getalorb() == 1);
sc_assert (recb[4].getalandb() == 1);
sc_assert (recb[5].getaorb() == 15);
sc_assert (recb[5].getaandb() == 12);
sc_assert (recb[5].getnota() == 0);
sc_assert (recb[5].getaxorb() == 3);
sc_assert (recb[5].getalorb() == 1);
sc_assert (recb[5].getalandb() == 1);
sc_assert (recb[6].getaorb() == 30);
sc_assert (recb[6].getaandb() == 2);
sc_assert (recb[6].getnota() == 0);
sc_assert (recb[6].getaxorb() == 28);
sc_assert (recb[6].getalorb() == 1);
sc_assert (recb[6].getalandb() == 1);
sc_assert (recb[7].getaorb() == 21);
sc_assert (recb[7].getaandb() == 16);
sc_assert (recb[7].getnota() == 0);
sc_assert (recb[7].getaxorb() == 5);
sc_assert (recb[7].getalorb() == 1);
sc_assert (recb[7].getalandb() == 1);
sc_assert (recb[8].getaorb() == 26);
sc_assert (recb[8].getaandb() == 16);
sc_assert (recb[8].getnota() == 0);
sc_assert (recb[8].getaxorb() == 10);
sc_assert (recb[8].getalorb() == 1);
sc_assert (recb[8].getalandb() == 1);
sc_assert (recb[9].getaorb() == 31);
sc_assert (recb[9].getaandb() == 16);
sc_assert (recb[9].getnota() == 0);
sc_assert (recb[9].getaxorb() == 15);
sc_assert (recb[9].getalorb() == 1);
sc_assert (recb[9].getalandb() == 1);
sc_assert (recb[10].getaorb() == 30);
sc_assert (recb[10].getaandb() == 22);
sc_assert (recb[10].getnota() == 0);
sc_assert (recb[10].getaxorb() == 8);
sc_assert (recb[10].getalorb() == 1);
sc_assert (recb[10].getalandb() == 1);
sc_assert (recb[11].getaorb() == 57);
sc_assert (recb[11].getaandb() == 0);
sc_assert (recb[11].getnota() == 0);
sc_assert (recb[11].getaxorb() == 57);
sc_assert (recb[11].getalorb() == 1);
sc_assert (recb[11].getalandb() == 1);
sc_assert (recb[12].getaorb() == 62);
sc_assert (recb[12].getaandb() == 0);
sc_assert (recb[12].getnota() == 0);
sc_assert (recb[12].getaxorb() == 62);
sc_assert (recb[12].getalorb() == 1);
sc_assert (recb[12].getalandb() == 1);
sc_assert (recb[13].getaorb() == 63);
sc_assert (recb[13].getaandb() == 4);
sc_assert (recb[13].getnota() == 0);
sc_assert (recb[13].getaxorb() == 59);
sc_assert (recb[13].getalorb() == 1);
sc_assert (recb[13].getalandb() == 1);
sc_assert (recb[14].getaorb() == 62);
sc_assert (recb[14].getaandb() == 10);
sc_assert (recb[14].getnota() == 0);
sc_assert (recb[14].getaxorb() == 52);
sc_assert (recb[14].getalorb() == 1);
sc_assert (recb[14].getalandb() == 1);
sc_assert (recb[15].getaorb() == 45);
sc_assert (recb[15].getaandb() == 32);
sc_assert (recb[15].getnota() == 0);
sc_assert (recb[15].getaxorb() == 13);
sc_assert (recb[15].getalorb() == 1);
sc_assert (recb[15].getalandb() == 1);
sc_assert (recb[16].getaorb() == 50);
sc_assert (recb[16].getaandb() == 32);
sc_assert (recb[16].getnota() == 0);
sc_assert (recb[16].getaxorb() == 18);
sc_assert (recb[16].getalorb() == 1);
sc_assert (recb[16].getalandb() == 1);
}
};
class B_top : public sc_module {
public:
sc_signal<sc_uint<2>> a{"a"};
sc_signal<sc_uint<2>> as{"as"};
sc_signal<sc_int<2>> as_i{"as_i"};
A a_mod{"a_mod"};
SC_CTOR(B_top) {
a_mod.a(a);
a_mod.as_i(as_i);
}
};
int sc_main(int argc, char *argv[]) {
B_top b_mod{"b_mod"};
sc_start();
return 0;
}
| 31.208547
| 110
| 0.47872
|
hachetman
|
b136570926f748f7c9fc27a0a1d4efb792bc26ee
| 3,191
|
hpp
|
C++
|
hpp/Folder.impl.hpp
|
Ivy233/simple_diff
|
970bf8a0a624fc89b9c016fab44a87162feb2465
|
[
"MIT"
] | 1
|
2021-11-30T07:47:52.000Z
|
2021-11-30T07:47:52.000Z
|
hpp/Folder.impl.hpp
|
Ivy233/simple_diff
|
970bf8a0a624fc89b9c016fab44a87162feb2465
|
[
"MIT"
] | null | null | null |
hpp/Folder.impl.hpp
|
Ivy233/simple_diff
|
970bf8a0a624fc89b9c016fab44a87162feb2465
|
[
"MIT"
] | null | null | null |
/*
* File name: Folder.impl.hpp
* Description: 文件夹类,用于捕捉所有文件夹下的非隐藏文件
* Author: 王锦润
* Version: 2
* Date: 2019.6.11
* History: 此程序被纳入git,可以直接使用git查询。
*/
//防卫式声明,必须要有
//就算没有重复包含也建议有,这是代码习惯
#ifndef _FOLDER_IMPL_HPP_
#define _FOLDER_IMPL_HPP_
#include "Folder.hpp"
#include <algorithm>
#include <iostream>
using std::cout;
using std::endl;
/*
* Function: 构造函数
* Description: 构建文件夹,并搜索所有在文件夹下的文件
* Input: 文件路径
* Calls: _M_update_base, _M_update_ext
*/
Folder::Folder(const string &filedir)
{
_M_only_file = 0; //首先清空唯一文件属性
_M_update_base(filedir); //然后尝试更新文件夹路径
if (_M_only_file == 0 && _M_base_dir.size()) //如果更新成功,更新所有文件
_M_update_ext("");
//此处排序复杂度接近于线性,主要原因在于操作系统给出的文件句柄顺序
std::sort(_M_ext_dirs.begin(), _M_ext_dirs.end()); //排序使得有集合性质,方便调用差集,交集等集合运算
}
/*
* Function: print_everything
* Description: 打印所有的文件路径
*/
void Folder::print_everything()
{
cout << _M_only_file << endl;
cout << _M_base_dir << endl;
for (string ext_dir : _M_ext_dirs)
cout << ext_dir << endl;
}
/*
* Function: _M_update_base
* Description: 检验文件/文件夹,如果为单个文件则同时更新basedir和extdir,如果不是则只更新basedir
* Input: 文件路径filedir
*/
void Folder::_M_update_base(const string &filedir)
{
//首先清空文件属性
_M_base_dir.clear();
_M_ext_dirs.clear();
_finddata_t fileinfo; //C的结构体,用于访问文件系统
long hfile = 0; //文件句柄
if ((hfile = _findfirst(filedir.c_str(), &fileinfo)) != -1) //如果文件存在
{
//如果是文件
if (fileinfo.attrib & _A_ARCH)
{
size_t pos = std::max(filedir.find_last_of('/') + 1, filedir.find_last_of('\\') + 1);
_M_base_dir = filedir.substr(0, pos); //basedir更新
_M_ext_dirs.push_back(filedir.substr(pos)); //更新extdir
_M_only_file = 1;
}
else if (fileinfo.attrib & _A_SUBDIR)
{
_M_base_dir = filedir; //更新文件夹
if (_M_base_dir.back() != '/' && _M_base_dir.back() != '\\')
_M_base_dir.push_back('\\'); //如果没有则自动补全
}
}
//如果访问不到则啥都不做
else
cout << "Wrong file or folder" << endl;
}
/*
* Function: _M_update_base
* Description: 检验文件/文件夹,如果为单个文件则同时更新basedir和extdir,如果不是则只更新basedir
* Input: 文件路径filedir
*/
void Folder::_M_update_ext(const string &dir)
{
_finddata_t fileinfo;
long hfile = 0;
string p;
if ((hfile = _findfirst(p.assign(_M_base_dir).append(dir).append("*").c_str(), &fileinfo)) != -1) //如果找到内容
{
//按照文件更新
do
{
//如果是非隐藏文件夹则递归更新
if ((fileinfo.attrib & _A_SUBDIR) && (fileinfo.attrib & _A_HIDDEN) == 0)
{
//.和..是两个必备文件夹,..会递归到上层,需要避开
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
_M_update_ext(p.assign(dir).append(fileinfo.name).append("\\"));
}
//如果是文件则加入文件
else if ((fileinfo.attrib & _A_HIDDEN) == 0)
_M_ext_dirs.push_back(p.assign(dir).append(fileinfo.name));
} while (_findnext(hfile, &fileinfo) == 0); //句柄的用处
}
}
#endif
| 30.390476
| 110
| 0.581636
|
Ivy233
|
b137e61bee75558bc1d3d25813a51c4b1b82a236
| 667
|
cpp
|
C++
|
Projects/PBINFO/Problema 4/main.cpp
|
Bengo923/Visual-Studio
|
863a273644b291c311d299bd5c7c4faf9db2d30e
|
[
"MIT"
] | 1
|
2019-11-05T17:56:19.000Z
|
2019-11-05T17:56:19.000Z
|
Projects/PBINFO/Problema 4/main.cpp
|
Bengo923/PBINFO
|
863a273644b291c311d299bd5c7c4faf9db2d30e
|
[
"MIT"
] | null | null | null |
Projects/PBINFO/Problema 4/main.cpp
|
Bengo923/PBINFO
|
863a273644b291c311d299bd5c7c4faf9db2d30e
|
[
"MIT"
] | null | null | null |
// Problema 18 - Fisa Gradinariu (TEMA)
#include "pch.h"
#include "fstream"
#include "iostream"
using namespace std;
// ifstream fin("date.in");
// ofstream fout("date.out");
int index = 1, v[101], suma1, suma2, aux1, aux2;
int main()
{
int x;
cin >> x;
while (x != 0) {
v[index] = x;
index++;
cin >> x;
}
for (int i = 1; i < index; i++) {
suma1 = 0;
suma2 = 0;
aux1 = v[i];
aux2 = v[i + 1];
while (aux1) {
suma1 = suma1 + aux1 % 10;
aux1 = aux1 / 10;
}
while (aux2) {
suma2 = suma2 + aux2 % 10;
aux2 = aux2 / 10;
}
if (suma1 % 2 == 0 && suma2 % 2 == 1) {
cout << v[i] << " " << v[i + 1] << endl;
}
}
return 0;
}
| 15.511628
| 48
| 0.503748
|
Bengo923
|
b139cd6dfa8267237cb80df9cc1f4f060750af3e
| 8,727
|
cpp
|
C++
|
translit_handler.cpp
|
EzerIT/ETCBC4BibleOL
|
06bef9600a42dc17d8f0b2210492c8bce8bed558
|
[
"MIT"
] | null | null | null |
translit_handler.cpp
|
EzerIT/ETCBC4BibleOL
|
06bef9600a42dc17d8f0b2210492c8bce8bed558
|
[
"MIT"
] | null | null | null |
translit_handler.cpp
|
EzerIT/ETCBC4BibleOL
|
06bef9600a42dc17d8f0b2210492c8bce8bed558
|
[
"MIT"
] | null | null | null |
/* Copyright © 2017 Ezer IT Consulting.
* Released under an MIT License.
*/
#include <deque>
#include <map>
#include <string>
#include <iostream>
#include "util.hpp"
#include "translit_handler.hpp"
#include "hebrew_transliterator.hpp"
using namespace std;
struct translit_strings {
string g_word_translit;
string g_word_nopunct_translit;
string g_suffix_translit;
string g_lex_translit;
string g_prs_translit;
string g_vbs_translit;
string g_pfm_translit;
string g_vbe_translit;
string g_nme_translit;
string g_uvf_translit;
string g_voc_lex_translit;
string qere_translit;
};
class translit_handler : public handler {
public:
translit_handler();
virtual void list_features(set<string>&) override;
virtual void prepare_object(map<string,string>&) override;
virtual void finish_prepare() override;
virtual string define_features() override;
virtual string update_object(const map<string,string>&) override;
private:
// Transliteration context. We need five words (two before and two after the current one)
deque<map<string,string>> words;
map<int, translit_strings> transliterations; // Indexed by self
void chk_o(const map<string,string> * fmapp);
};
shared_ptr<handler> make_translit_handler()
{
return shared_ptr<handler>{new translit_handler};
}
translit_handler::translit_handler()
{
// Start by providing two empty words of context
words.emplace_back(map<string,string>{{"g_word_utf8",""},{"g_suffix_utf8",""}});
words.emplace_back(map<string,string>{{"g_word_utf8",""},{"g_suffix_utf8",""}});
}
void translit_handler::list_features(set<string>& req)
{
initialize_translit_rules();
initialize_translit_verbrules();
req.insert({"g_prs_utf8", "g_vbs_utf8", "g_pfm_utf8", "g_vbe_utf8", "g_nme_utf8",
"g_uvf_utf8", "g_word", "g_suffix_utf8", "g_word_utf8", "g_voc_lex_utf8",
"qere_utf8", "lex", "sp", "ps", "gn",
"nu", "vs", "vt"});
}
void translit_handler::chk_o(const map<string,string> * fmapp)
{
if (!fmapp)
// Running from finish_prepare(). Add final empty word of context
words.emplace_back(map<string,string>{{"g_word_utf8",""},{"g_suffix_utf8",""}});
else
words.emplace_back(*fmapp);
if (words.size()==5) {
// Now we can transliterate the middle word
bool ketiv = !words[2].at("qere_utf8").empty();
translit_strings translits;
translits.g_suffix_translit = suffix_transliterate(words[2].at("g_suffix_utf8"));
words[2]["g_suffix_translit"] = translits.g_suffix_translit; // used by transliterate()
translits.g_word_translit = transliterate(words[0].at("g_word_utf8")+words[0].at("g_suffix_utf8")+
words[1].at("g_word_utf8")+words[1].at("g_suffix_utf8"),
words[2].at(ketiv ? "g_word_cons_utf8" : "g_word_utf8"),
words[2].at("g_suffix_utf8")+
words[3].at("g_word_utf8")+words[3].at("g_suffix_utf8")+
words[4].at("g_word_utf8")+words[4].at("g_suffix_utf8"),
words[2],
ketiv, true, true);
translits.g_prs_translit = transliterate("", words[2].at("g_prs_utf8"), "", words[2], false, false, false);
translits.g_vbs_translit = transliterate("", words[2].at("g_vbs_utf8"), "", words[2], false, false, false);
translits.g_pfm_translit = transliterate("", words[2].at("g_pfm_utf8"), "", words[2], false, false, false);
translits.g_vbe_translit = transliterate("", words[2].at("g_vbe_utf8"), "", words[2], false, false, false);
translits.g_nme_translit = transliterate("", words[2].at("g_nme_utf8"), "", words[2], false, false, false);
translits.g_uvf_translit = transliterate("", words[2].at("g_uvf_utf8"), "", words[2], false, false, false);
if (words[2].at("sp")=="verb")
translits.g_voc_lex_translit = transliterate_verb_lex(words[2].at("g_voc_lex_utf8"));
else
translits.g_voc_lex_translit = transliterate("", words[2].at("g_voc_lex_utf8"), "", words[2], false, false, false);
// No words have both a g_vbe_utf8 and a g_nme_utf8.
// g_nme_utf8 always starts with a GERESH ("\u059c" or "\xd6\x9c")
if (!words[2].at("g_vbe_utf8").empty())
translits.g_lex_translit = transliterate("", words[2].at("g_lex_utf8"), words[2].at("g_vbe_utf8") + words[2].at("g_uvf_utf8"), words[2], false, false, false);
else if (!words[2].at("g_nme_utf8").empty()) {
string nm = words[2]["g_nme_utf8"];
if (nm[0]!='\xd6' || nm[1]!='\x9c')
cerr << "self=" << words[2].at("self") << " g_nme_utf8 does not start with GERES\n";
else
translits.g_lex_translit = transliterate("", words[2].at("g_lex_utf8"), nm.substr(2) + words[2].at("g_uvf_utf8"), words[2], false, false, false);
}
else
translits.g_lex_translit = transliterate("", words[2].at("g_lex_utf8"), words[2].at("g_uvf_utf8"), words[2], false, false, false);
if (!words[2].at("qere_utf8").empty())
translits.qere_translit = transliterate("", words[2].at("qere_utf8"), "", words[2], false, false, false);
char last_char = translits.g_word_translit.back();
string last_2_char = translits.g_word_translit.length()>=2 ? translits.g_word_translit.substr(translits.g_word_translit.length()-2) : "" ;
if (last_char=='|' || last_char=='-' || last_char==' ')
translits.g_word_nopunct_translit = translits.g_word_translit.substr(0, translits.g_word_translit.length()-1);
else if (last_2_char=="\u05be")
translits.g_word_nopunct_translit = translits.g_word_translit.substr(0, translits.g_word_translit.length()-2);
else
translits.g_word_nopunct_translit = translits.g_word_translit;
if (translits.g_word_nopunct_translit == "HÎʔ")
translits.g_word_nopunct_translit = "hîʔ";
transliterations[stol(words[2].at("self"))] = translits;
words.pop_front();
}
}
void translit_handler::prepare_object(map<string,string>& fmap)
{
chk_o(&fmap);
}
void translit_handler::finish_prepare()
{
chk_o(nullptr);
chk_o(nullptr);
}
string translit_handler::define_features()
{
return
" ADD g_word_translit : string DEFAULT \"\";\n"
" ADD g_word_nopunct_translit : string DEFAULT \"\";\n"
" ADD g_suffix_translit : string DEFAULT \"\";\n"
" ADD g_lex_translit : string DEFAULT \"\";\n"
" ADD g_prs_translit : string DEFAULT \"\";\n"
" ADD g_vbs_translit : string DEFAULT \"\";\n"
" ADD g_pfm_translit : string DEFAULT \"\";\n"
" ADD g_vbe_translit : string DEFAULT \"\";\n"
" ADD g_nme_translit : string DEFAULT \"\";\n"
" ADD g_uvf_translit : string DEFAULT \"\";\n"
" ADD g_voc_lex_translit : string DEFAULT \"\";\n"
" ADD qere_translit : string DEFAULT \"\";\n";
}
string translit_handler::update_object(const map<string,string>& fmap)
{
const translit_strings& translits = transliterations.at(stoi(fmap.at("self")));
return
" g_word_translit := \"" + translits.g_word_translit + "\";\n"
" g_word_nopunct_translit := \"" + translits.g_word_nopunct_translit + "\";\n"
" g_suffix_translit := \"" + translits.g_suffix_translit + "\";\n"
" g_lex_translit := \"" + translits.g_lex_translit + "\";\n"
" g_prs_translit := \"" + translits.g_prs_translit + "\";\n"
" g_vbs_translit := \"" + translits.g_vbs_translit + "\";\n"
" g_pfm_translit := \"" + translits.g_pfm_translit + "\";\n"
" g_vbe_translit := \"" + translits.g_vbe_translit + "\";\n"
" g_nme_translit := \"" + translits.g_nme_translit + "\";\n"
" g_uvf_translit := \"" + translits.g_uvf_translit + "\";\n"
" g_voc_lex_translit := \"" + translits.g_voc_lex_translit + "\";\n"
" qere_translit := \"" + translits.qere_translit + "\";\n";
}
| 41.557143
| 170
| 0.588289
|
EzerIT
|
b139f85d86021b527fb4f534e28d0217a1fb71f3
| 2,888
|
cpp
|
C++
|
aws-cpp-sdk-servicecatalog/source/model/PortfolioShareType.cpp
|
ploki/aws-sdk-cpp
|
17074e3e48c7411f81294e2ee9b1550c4dde842c
|
[
"Apache-2.0"
] | null | null | null |
aws-cpp-sdk-servicecatalog/source/model/PortfolioShareType.cpp
|
ploki/aws-sdk-cpp
|
17074e3e48c7411f81294e2ee9b1550c4dde842c
|
[
"Apache-2.0"
] | null | null | null |
aws-cpp-sdk-servicecatalog/source/model/PortfolioShareType.cpp
|
ploki/aws-sdk-cpp
|
17074e3e48c7411f81294e2ee9b1550c4dde842c
|
[
"Apache-2.0"
] | 1
|
2019-01-18T13:03:55.000Z
|
2019-01-18T13:03:55.000Z
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/servicecatalog/model/PortfolioShareType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace ServiceCatalog
{
namespace Model
{
namespace PortfolioShareTypeMapper
{
static const int IMPORTED_HASH = HashingUtils::HashString("IMPORTED");
static const int AWS_SERVICECATALOG_HASH = HashingUtils::HashString("AWS_SERVICECATALOG");
static const int AWS_ORGANIZATIONS_HASH = HashingUtils::HashString("AWS_ORGANIZATIONS");
PortfolioShareType GetPortfolioShareTypeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == IMPORTED_HASH)
{
return PortfolioShareType::IMPORTED;
}
else if (hashCode == AWS_SERVICECATALOG_HASH)
{
return PortfolioShareType::AWS_SERVICECATALOG;
}
else if (hashCode == AWS_ORGANIZATIONS_HASH)
{
return PortfolioShareType::AWS_ORGANIZATIONS;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<PortfolioShareType>(hashCode);
}
return PortfolioShareType::NOT_SET;
}
Aws::String GetNameForPortfolioShareType(PortfolioShareType enumValue)
{
switch(enumValue)
{
case PortfolioShareType::IMPORTED:
return "IMPORTED";
case PortfolioShareType::AWS_SERVICECATALOG:
return "AWS_SERVICECATALOG";
case PortfolioShareType::AWS_ORGANIZATIONS:
return "AWS_ORGANIZATIONS";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return "";
}
}
} // namespace PortfolioShareTypeMapper
} // namespace Model
} // namespace ServiceCatalog
} // namespace Aws
| 32.818182
| 98
| 0.660319
|
ploki
|
b13a972dfcdd32b01fbcab2c3dcd4bde042ee1a8
| 255
|
cpp
|
C++
|
pbdata/saf/AlnGroup.cpp
|
ggraham/blasr_libcpp
|
4abef36585bbb677ebc4acb9d4e44e82331d59f7
|
[
"RSA-MD"
] | 4
|
2015-07-03T11:59:54.000Z
|
2018-05-17T00:03:22.000Z
|
pbdata/saf/AlnGroup.cpp
|
ggraham/blasr_libcpp
|
4abef36585bbb677ebc4acb9d4e44e82331d59f7
|
[
"RSA-MD"
] | 79
|
2015-06-29T18:07:21.000Z
|
2018-09-19T13:38:39.000Z
|
pbdata/saf/AlnGroup.cpp
|
ggraham/blasr_libcpp
|
4abef36585bbb677ebc4acb9d4e44e82331d59f7
|
[
"RSA-MD"
] | 19
|
2015-06-23T08:43:29.000Z
|
2021-04-28T18:37:47.000Z
|
#include <pbdata/saf/AlnGroup.hpp>
int AlnGroup::FindPath(unsigned int idKey, std::string &val)
{
for (size_t i = 0; i < id.size(); i++) {
if (idKey == id[i]) {
val = path[i];
return 1;
}
}
return 0;
}
| 19.615385
| 60
| 0.490196
|
ggraham
|
b13c791bf3ca14b21d43409fe63b3a10840666f8
| 2,433
|
cpp
|
C++
|
mqtt/client.cpp
|
dkesler-execom/WolkSDK-Cpp
|
fd353d34affa5c252f5a1022c9fc1b6ae9a285a5
|
[
"Apache-2.0"
] | null | null | null |
mqtt/client.cpp
|
dkesler-execom/WolkSDK-Cpp
|
fd353d34affa5c252f5a1022c9fc1b6ae9a285a5
|
[
"Apache-2.0"
] | null | null | null |
mqtt/client.cpp
|
dkesler-execom/WolkSDK-Cpp
|
fd353d34affa5c252f5a1022c9fc1b6ae9a285a5
|
[
"Apache-2.0"
] | null | null | null |
// client.cpp
// Implementation of the client class for the mqtt C++ client library.
/*******************************************************************************
* Copyright (c) 2013-2017 Frank Pagliughi <fpagliughi@mindspring.com>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Frank Pagliughi - initial implementation and documentation
*******************************************************************************/
#include "client.h"
#include <memory>
#include <iostream>
namespace mqtt {
const std::chrono::minutes client::DFLT_TIMEOUT = std::chrono::minutes(5);
constexpr int client::DFLT_QOS;
/////////////////////////////////////////////////////////////////////////////
client::client(const string& serverURI, const string& clientId,
iclient_persistence* persistence /*=nullptr*/)
: cli_(serverURI, clientId, persistence),
timeout_(DFLT_TIMEOUT), userCallback_(nullptr)
{
}
client::client(const string& serverURI, const string& clientId,
const string& persistDir)
: cli_(serverURI, clientId, persistDir),
timeout_(DFLT_TIMEOUT), userCallback_(nullptr)
{
}
client::client(const string& serverURI, const string& clientId,
int maxBufferedMessages, iclient_persistence* persistence /*=nullptr*/)
: cli_(serverURI, clientId, maxBufferedMessages, persistence),
timeout_(DFLT_TIMEOUT), userCallback_(nullptr)
{
}
client::client(const string& serverURI, const string& clientId,
int maxBufferedMessages, const string& persistDir)
: cli_(serverURI, clientId, maxBufferedMessages, persistDir),
timeout_(DFLT_TIMEOUT), userCallback_(nullptr)
{
}
void client::set_callback(callback& cb)
{
userCallback_ = &cb;
cli_.set_callback(*this);
}
void client::subscribe(const string_collection& topicFilters)
{
qos_collection qos;
for (size_t i=0; i<topicFilters.size(); ++i)
qos.push_back(DFLT_QOS);
cli_.subscribe(ptr(topicFilters), qos)->wait_for(timeout_);
}
/////////////////////////////////////////////////////////////////////////////
// end namespace mqtt
}
| 30.037037
| 81
| 0.649404
|
dkesler-execom
|
b13de41571636040a9341e59272578a3a9d6b082
| 4,484
|
cpp
|
C++
|
tests/VkUploadPixelsTests.cpp
|
avaer/skia
|
b211ebc328e9df69f95fc58e7363775ec2d0c14d
|
[
"BSD-3-Clause"
] | 3
|
2018-10-28T09:55:58.000Z
|
2018-12-09T05:09:38.000Z
|
tests/VkUploadPixelsTests.cpp
|
BensonDu/skia
|
b211ebc328e9df69f95fc58e7363775ec2d0c14d
|
[
"BSD-3-Clause"
] | 1
|
2018-10-21T04:53:25.000Z
|
2018-10-21T04:53:25.000Z
|
tests/VkUploadPixelsTests.cpp
|
BensonDu/skia
|
b211ebc328e9df69f95fc58e7363775ec2d0c14d
|
[
"BSD-3-Clause"
] | 4
|
2018-08-10T03:09:14.000Z
|
2018-10-21T00:04:47.000Z
|
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This is a GPU-backend specific test. It relies on static intializers to work
#include "SkTypes.h"
#if defined(SK_VULKAN)
#include "GrContextFactory.h"
#include "GrContextPriv.h"
#include "GrSurfaceProxy.h"
#include "GrTest.h"
#include "ProxyUtils.h"
#include "SkGr.h"
#include "Test.h"
#include "TestUtils.h"
#include "vk/GrVkGpu.h"
using sk_gpu_test::GrContextFactory;
void basic_texture_test(skiatest::Reporter* reporter, GrContext* context, SkColorType ct,
bool renderTarget) {
const int kWidth = 16;
const int kHeight = 16;
SkAutoTMalloc<GrColor> srcBuffer(kWidth*kHeight);
SkAutoTMalloc<GrColor> dstBuffer(kWidth*kHeight);
fill_pixel_data(kWidth, kHeight, srcBuffer.get());
auto proxy = sk_gpu_test::MakeTextureProxyFromData(context, renderTarget, kWidth, kHeight, ct,
kTopLeft_GrSurfaceOrigin, srcBuffer, 0);
REPORTER_ASSERT(reporter, proxy);
if (proxy) {
sk_sp<GrSurfaceContext> sContext = context->contextPriv().makeWrappedSurfaceContext(proxy);
SkImageInfo dstInfo = SkImageInfo::Make(kWidth, kHeight, ct, kPremul_SkAlphaType);
bool result = sContext->readPixels(dstInfo, dstBuffer, 0, 0, 0);
REPORTER_ASSERT(reporter, result);
REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer,
dstBuffer,
kWidth,
kHeight));
dstInfo = SkImageInfo::Make(10, 2, ct, kPremul_SkAlphaType);
result = sContext->writePixels(dstInfo, srcBuffer, 0, 2, 10);
REPORTER_ASSERT(reporter, result);
memset(dstBuffer, 0, kWidth*kHeight*sizeof(GrColor));
result = sContext->readPixels(dstInfo, dstBuffer, 0, 2, 10);
REPORTER_ASSERT(reporter, result);
REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer,
dstBuffer,
10,
2));
}
proxy = sk_gpu_test::MakeTextureProxyFromData(context, renderTarget, kWidth, kHeight, ct,
kBottomLeft_GrSurfaceOrigin, srcBuffer, 0);
REPORTER_ASSERT(reporter, proxy);
if (proxy) {
sk_sp<GrSurfaceContext> sContext = context->contextPriv().makeWrappedSurfaceContext(proxy);
SkImageInfo dstInfo = SkImageInfo::Make(kWidth, kHeight, ct, kPremul_SkAlphaType);
bool result = sContext->readPixels(dstInfo, dstBuffer, 0, 0, 0);
REPORTER_ASSERT(reporter, result);
REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer,
dstBuffer,
kWidth,
kHeight));
dstInfo = SkImageInfo::Make(4, 5, ct, kPremul_SkAlphaType);
result = sContext->writePixels(dstInfo, srcBuffer, 0, 5, 4);
REPORTER_ASSERT(reporter, result);
memset(dstBuffer, 0, kWidth*kHeight*sizeof(GrColor));
result = sContext->readPixels(dstInfo, dstBuffer, 0, 5, 4);
REPORTER_ASSERT(reporter, result);
REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer,
dstBuffer,
4,
5));
}
}
DEF_GPUTEST_FOR_VULKAN_CONTEXT(VkUploadPixelsTests, reporter, ctxInfo) {
// RGBA
basic_texture_test(reporter, ctxInfo.grContext(), kRGBA_8888_SkColorType, false);
basic_texture_test(reporter, ctxInfo.grContext(), kRGBA_8888_SkColorType, true);
// BGRA
basic_texture_test(reporter, ctxInfo.grContext(), kBGRA_8888_SkColorType, false);
basic_texture_test(reporter, ctxInfo.grContext(), kBGRA_8888_SkColorType, true);
}
#endif
| 41.518519
| 99
| 0.564005
|
avaer
|
b140520194ff200a3a995ad3e1562425ee0b55d1
| 8,952
|
cpp
|
C++
|
src/chrono_vehicle/cosim/mbs/ChVehicleCosimVehicleNode.cpp
|
aluaces/chrono
|
675ff6c1105814973dd7f844bd19385d9760f90c
|
[
"BSD-3-Clause"
] | 1,383
|
2015-02-04T14:17:40.000Z
|
2022-03-30T04:58:16.000Z
|
src/chrono_vehicle/cosim/mbs/ChVehicleCosimVehicleNode.cpp
|
pchaoWT/chrono
|
fd68d37d1d4ee75230dc1eea78ceff91cca7ac32
|
[
"BSD-3-Clause"
] | 245
|
2015-01-11T15:30:51.000Z
|
2022-03-30T21:28:54.000Z
|
src/chrono_vehicle/cosim/mbs/ChVehicleCosimVehicleNode.cpp
|
pchaoWT/chrono
|
fd68d37d1d4ee75230dc1eea78ceff91cca7ac32
|
[
"BSD-3-Clause"
] | 351
|
2015-02-04T14:17:47.000Z
|
2022-03-30T04:42:52.000Z
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2020 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Wheeled vehicle system co-simulated with tire nodes and a terrain node.
//
// The global reference frame has Z up, X towards the front of the vehicle, and
// Y pointing to the left.
//
// =============================================================================
#include <fstream>
#include <algorithm>
#include <set>
#include <vector>
#include "chrono/ChConfig.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/utils/ChUtilsJSON.h"
#include "chrono_vehicle/wheeled_vehicle/vehicle/WheeledVehicle.h"
#include "chrono_vehicle/cosim/mbs/ChVehicleCosimVehicleNode.h"
using std::cout;
using std::endl;
namespace chrono {
namespace vehicle {
// -----------------------------------------------------------------------------
class WheeledVehicleDBPDriver : public ChDriver {
public:
WheeledVehicleDBPDriver(std::shared_ptr<ChWheeledVehicle> vehicle, std::shared_ptr<ChFunction> dbp_mot_func)
: ChDriver(*vehicle),
m_wheeled_vehicle(vehicle),
m_func(dbp_mot_func) {}
virtual void Synchronize(double time) override {
m_steering = 0;
m_braking = 0;
double ang_speed = m_func->Get_y(time);
for (auto& axle : m_wheeled_vehicle->GetAxles()) {
axle->m_suspension->GetAxle(VehicleSide::LEFT)->SetPos_dt(ang_speed);
axle->m_suspension->GetAxle(VehicleSide::RIGHT)->SetPos_dt(ang_speed);
}
}
std::shared_ptr<ChWheeledVehicle> m_wheeled_vehicle;
std::shared_ptr<ChFunction> m_func;
};
// -----------------------------------------------------------------------------
ChVehicleCosimVehicleNode::ChVehicleCosimVehicleNode(const std::string& vehicle_json,
const std::string& powertrain_json)
: ChVehicleCosimMBSNode(), m_num_spindles(0) {
m_vehicle = chrono_types::make_shared<WheeledVehicle>(m_system, vehicle_json);
m_powertrain = ReadPowertrainJSON(powertrain_json);
m_terrain = chrono_types::make_shared<ChTerrain>();
}
ChVehicleCosimVehicleNode::~ChVehicleCosimVehicleNode() {}
// -----------------------------------------------------------------------------
void ChVehicleCosimVehicleNode::InitializeMBS(const std::vector<ChVector<>>& tire_info,
const ChVector2<>& terrain_size,
double terrain_height) {
// Initialize vehicle
ChCoordsys<> init_pos(m_init_loc + ChVector<>(0, 0, terrain_height), Q_from_AngZ(m_init_yaw));
m_vehicle->Initialize(init_pos);
m_vehicle->SetChassisVisualizationType(VisualizationType::MESH);
m_vehicle->SetSuspensionVisualizationType(VisualizationType::PRIMITIVES);
m_vehicle->SetSteeringVisualizationType(VisualizationType::PRIMITIVES);
m_vehicle->SetWheelVisualizationType(VisualizationType::MESH);
// Initialize powertrain
m_vehicle->InitializePowertrain(m_powertrain);
// Create and initialize the dummy tires
int itire = 0;
for (auto& axle : m_vehicle->GetAxles()) {
for (auto& wheel : axle->GetWheels()) {
auto tire = chrono_types::make_shared<DummyTire>(itire, tire_info[itire].x(), tire_info[itire].y(),
tire_info[itire].z());
m_vehicle->InitializeTire(tire, wheel, VisualizationType::NONE);
m_tires.push_back(tire);
itire++;
}
}
// Extract and cache spindle bodies
auto num_axles = m_vehicle->GetNumberAxles();
m_num_spindles = 2 * num_axles;
assert(m_num_spindles == (int)m_num_tire_nodes);
auto total_mass = m_vehicle->GetVehicleMass();
for (int is = 0; is < m_num_spindles; is++) {
auto tire_mass = tire_info[is].x();
m_spindle_loads.push_back(tire_mass + total_mass / m_num_spindles);
}
}
// -----------------------------------------------------------------------------
int ChVehicleCosimVehicleNode::GetNumSpindles() const {
return m_num_spindles;
}
std::shared_ptr<ChBody> ChVehicleCosimVehicleNode::GetSpindleBody(unsigned int i) const {
VehicleSide side = (i % 2 == 0) ? VehicleSide::LEFT : VehicleSide::RIGHT;
return m_vehicle->GetWheel(i / 2, side)->GetSpindle();
}
double ChVehicleCosimVehicleNode::GetSpindleLoad(unsigned int i) const {
return m_spindle_loads[i];
}
BodyState ChVehicleCosimVehicleNode::GetSpindleState(unsigned int i) const {
VehicleSide side = (i % 2 == 0) ? VehicleSide::LEFT : VehicleSide::RIGHT;
auto spindle_body = m_vehicle->GetWheel(i / 2, side)->GetSpindle();
BodyState state;
state.pos = spindle_body->GetPos();
state.rot = spindle_body->GetRot();
state.lin_vel = spindle_body->GetPos_dt();
state.ang_vel = spindle_body->GetWvel_par();
return state;
}
std::shared_ptr<ChBody> ChVehicleCosimVehicleNode::GetChassisBody() const {
return m_vehicle->GetChassisBody();
}
void ChVehicleCosimVehicleNode::OnInitializeDBPRig(std::shared_ptr<ChFunction> func) {
// Disconnect the driveline
m_vehicle->DisconnectDriveline();
// Overwrite any driver attached to the vehicle with a custom driver which imposes zero steering and braking and
// directly sets the angular speed of the vehicle axleshafts as returned by the provided motor function.
SetDriver(chrono_types::make_shared<WheeledVehicleDBPDriver>(m_vehicle, func));
}
// -----------------------------------------------------------------------------
void ChVehicleCosimVehicleNode::PreAdvance() {
// Synchronize vehicle systems
double time = m_vehicle->GetChTime();
ChDriver::Inputs driver_inputs;
if (m_driver) {
driver_inputs = m_driver->GetInputs();
m_driver->Synchronize(time);
} else {
driver_inputs.m_steering = 0;
driver_inputs.m_throttle = 0.5;
driver_inputs.m_braking = 0;
}
m_vehicle->Synchronize(time, driver_inputs, *m_terrain);
}
void ChVehicleCosimVehicleNode::ApplySpindleForce(unsigned int i, const TerrainForce& spindle_force) {
// Cache the spindle force on the corresponding dummy tire. This force will be applied to the associated ChWheel on
// synchronization of the vehicle system (in PreAdvance)
m_tires[i]->m_force = spindle_force;
}
// -----------------------------------------------------------------------------
void ChVehicleCosimVehicleNode::OnOutputData(int frame) {
// Append to results output file
if (m_outf.is_open()) {
std::string del(" ");
const ChVector<>& pos = m_vehicle->GetVehiclePos();
m_outf << m_system->GetChTime() << del;
// Body states
m_outf << pos.x() << del << pos.y() << del << pos.z() << del;
// Solver statistics (for last integration step)
m_outf << m_system->GetTimerStep() << del << m_system->GetTimerLSsetup() << del << m_system->GetTimerLSsolve()
<< del << m_system->GetTimerUpdate() << del;
if (m_int_type == ChTimestepper::Type::HHT) {
m_outf << m_integrator->GetNumIterations() << del << m_integrator->GetNumSetupCalls() << del
<< m_integrator->GetNumSolveCalls() << del;
}
m_outf << endl;
}
// Create and write frame output file.
utils::CSV_writer csv(" ");
csv << m_system->GetChTime() << endl; // current time
WriteBodyInformation(csv); // vehicle body states
std::string filename = OutputFilename(m_node_out_dir + "/simulation", "data", "dat", frame + 1, 5);
csv.write_to_file(filename);
if (m_verbose)
cout << "[Vehicle node] write output file ==> " << filename << endl;
}
void ChVehicleCosimVehicleNode::WriteBodyInformation(utils::CSV_writer& csv) {
// Write number of bodies
csv << 1 + m_num_spindles << endl;
// Write body state information
auto chassis = m_vehicle->GetChassisBody();
csv << chassis->GetPos() << chassis->GetRot() << chassis->GetPos_dt() << chassis->GetRot_dt() << endl;
for (auto& axle : m_vehicle->GetAxles()) {
for (auto& wheel : axle->GetWheels()) {
auto spindle_body = wheel->GetSpindle();
csv << spindle_body->GetPos() << spindle_body->GetRot() << spindle_body->GetPos_dt()
<< spindle_body->GetRot_dt() << endl;
}
}
}
} // end namespace vehicle
} // end namespace chrono
| 38.093617
| 119
| 0.610813
|
aluaces
|
b14921bbd501308fc83cac6141b2bdb1cc90a6e0
| 1,431
|
inl
|
C++
|
unit_tests/api/cl_retain_release_sampler_tests.inl
|
FelipeMLopez/compute-runtime
|
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
|
[
"MIT"
] | 3
|
2019-09-20T23:26:36.000Z
|
2019-10-03T17:44:12.000Z
|
unit_tests/api/cl_retain_release_sampler_tests.inl
|
FelipeMLopez/compute-runtime
|
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
|
[
"MIT"
] | null | null | null |
unit_tests/api/cl_retain_release_sampler_tests.inl
|
FelipeMLopez/compute-runtime
|
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
|
[
"MIT"
] | 3
|
2019-05-16T07:22:51.000Z
|
2019-11-11T03:05:32.000Z
|
/*
* Copyright (C) 2017-2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "runtime/context/context.h"
#include "cl_api_tests.h"
using namespace NEO;
typedef api_tests clRetainReleaseSamplerTests;
namespace ULT {
TEST_F(clRetainReleaseSamplerTests, GivenValidSamplerWhenRetainingThenSamplerReferenceCountIsIncremented) {
cl_int retVal = CL_SUCCESS;
auto sampler = clCreateSampler(pContext, CL_TRUE, CL_ADDRESS_CLAMP,
CL_FILTER_NEAREST, &retVal);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_NE(nullptr, sampler);
cl_uint theRef;
retVal = clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT,
sizeof(cl_uint), &theRef, NULL);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, theRef);
retVal = clRetainSampler(sampler);
EXPECT_EQ(CL_SUCCESS, retVal);
retVal = clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT,
sizeof(cl_uint), &theRef, NULL);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(2u, theRef);
retVal = clReleaseSampler(sampler);
EXPECT_EQ(CL_SUCCESS, retVal);
retVal = clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT,
sizeof(cl_uint), &theRef, NULL);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, theRef);
retVal = clReleaseSampler(sampler);
EXPECT_EQ(CL_SUCCESS, retVal);
}
} // namespace ULT
| 29.8125
| 107
| 0.682041
|
FelipeMLopez
|
b14bc9a0f231be280762b19cb00aebf2e5c55308
| 5,199
|
cpp
|
C++
|
src/Apps/RtcClient/RtcClient.cpp
|
miseri/rtp_plus_plus
|
244ddd86f40f15247dd39ae7f9283114c2ef03a2
|
[
"BSD-3-Clause"
] | 1
|
2021-07-14T08:15:05.000Z
|
2021-07-14T08:15:05.000Z
|
src/Apps/RtcClient/RtcClient.cpp
|
7956968/rtp_plus_plus
|
244ddd86f40f15247dd39ae7f9283114c2ef03a2
|
[
"BSD-3-Clause"
] | null | null | null |
src/Apps/RtcClient/RtcClient.cpp
|
7956968/rtp_plus_plus
|
244ddd86f40f15247dd39ae7f9283114c2ef03a2
|
[
"BSD-3-Clause"
] | 2
|
2021-07-14T08:15:02.000Z
|
2021-07-14T08:56:10.000Z
|
#include "RtcClientPch.h"
#include "RtcClient.h"
#include <grpc++/channel_interface.h>
#include <grpc++/client_context.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
using grpc::CompletionQueue;
using grpc::ChannelInterface;
using grpc::ClientContext;
using grpc::ClientReader;
using grpc::ClientReaderWriter;
using grpc::ClientWriter;
using grpc::Status;
RtcClient::RtcClient(std::shared_ptr<ChannelInterface> channel)
:stub_(peer_connection::PeerConnectionApi::NewStub(channel))
{
}
boost::optional<std::string> RtcClient::createOffer(const std::string& sContentType)
{
ClientContext context;
peer_connection::OfferDescriptor desc;
desc.set_content_type(sContentType);
peer_connection::CreateSessionDescriptionResponse response;
Status status = stub_->createOffer(&context, desc, &response);
if (status.IsOk())
{
LOG(INFO) << "RPC createOffer success";
if (response.response_code() == 200)
{
return boost::optional<std::string>(response.session_description().session_description());
}
else
{
LOG(WARNING) << "Server returned error: " << response.response_code() << " " << response.response_description();
return boost::optional<std::string>();
}
}
else
{
LOG(WARNING) << "RPC createOffer failed";
return boost::optional<std::string>();
}
}
boost::optional<std::string> RtcClient::createAnswer(const std::string& sSessionDescription, const std::string& sContentType)
{
ClientContext context;
peer_connection::AnswerDescriptor desc;
peer_connection::SessionDescription* pOffer = new peer_connection::SessionDescription();
pOffer->set_content_type(sContentType);
pOffer->set_session_description(sSessionDescription);
desc.set_allocated_session_description(pOffer);
peer_connection::CreateSessionDescriptionResponse response;
Status status = stub_->createAnswer(&context, desc, &response);
if (status.IsOk())
{
LOG(INFO) << "RPC createAnswer success";
if (response.response_code() == 200)
{
return boost::optional<std::string>(response.session_description().session_description());
}
else
{
LOG(WARNING) << "Server returned error: " << response.response_code() << " " << response.response_description();
return boost::optional<std::string>();
}
}
else
{
LOG(WARNING) << "RPC createAnswer failed";
return boost::optional<std::string>();
}
}
bool RtcClient::setRemoteDescription(const std::string& sSessionDescription, const std::string& sContentType)
{
ClientContext context;
peer_connection::SessionDescription remoteSdp;
remoteSdp.set_content_type(sContentType);
remoteSdp.set_session_description(sSessionDescription);
peer_connection::SetSessionDescriptionResponse response;
Status status = stub_->setRemoteDescription (&context, remoteSdp, &response);
if (status.IsOk())
{
LOG(INFO) << "RPC setRemoteDescription success";
if (response.response_code() == 200)
{
return true;
}
else
{
LOG(WARNING) << "Server returned error: " << response.response_code() << " " << response.response_description();
return false;
}
}
else
{
LOG(WARNING) << "RPC setRemoteDescription failed";
return false;
}
}
bool RtcClient::startStreaming()
{
ClientContext context;
peer_connection::StartStreamingRequest request;
peer_connection::StartStreamingResponse response;
Status status = stub_->startStreaming(&context, request, &response);
if (status.IsOk())
{
LOG(INFO) << "RPC startStreaming success";
if (response.response_code() == 200)
{
return true;
}
else
{
LOG(WARNING) << "startStreaming: Server returned error: " << response.response_code() << " " << response.response_description();
return false;
}
}
else
{
LOG(WARNING) << "RPC startStreaming failed";
return false;
}
}
bool RtcClient::stopStreaming()
{
ClientContext context;
peer_connection::StopStreamingRequest request;
peer_connection::StopStreamingResponse response;
Status status = stub_->stopStreaming(&context, request, &response);
if (status.IsOk())
{
LOG(INFO) << "RPC stopStreaming success";
if (response.response_code() == 200)
{
return true;
}
else
{
LOG(WARNING) << "stopStreaming: Server returned error: " << response.response_code() << " " << response.response_description();
return false;
}
}
else
{
LOG(WARNING) << "RPC stopStreaming failed";
return false;
}
}
bool RtcClient::shutdownRemoteRtcServer()
{
ClientContext context;
peer_connection::ShutdownRequest request;
peer_connection::ShutdownResponse response;
Status status = stub_->shutdown(&context, request, &response);
if (status.IsOk())
{
LOG(INFO) << "RPC shutdown success";
if (response.response_code() == 200)
{
return true;
}
else
{
LOG(WARNING) << "shutdown: Server returned error: " << response.response_code() << " " << response.response_description();
return false;
}
}
else
{
LOG(WARNING) << "RPC shutdown failed";
return false;
}
}
void RtcClient::reset()
{
stub_.reset();
}
| 25.737624
| 134
| 0.688017
|
miseri
|
b14cce1384a48e80692e55e175a6423c5fd03243
| 1,392
|
cpp
|
C++
|
Calculator/src/main/View/CalcScreen.cpp
|
Songtech-0912/InstantCalc
|
2b36a3a7c47a7ae358eea36a4e2d7f120456dc86
|
[
"MIT"
] | 1
|
2020-09-27T12:55:41.000Z
|
2020-09-27T12:55:41.000Z
|
Calculator/src/main/View/CalcScreen.cpp
|
Songtech-0912/InstantCalc
|
2b36a3a7c47a7ae358eea36a4e2d7f120456dc86
|
[
"MIT"
] | 177
|
2020-05-04T09:14:05.000Z
|
2022-03-25T00:02:12.000Z
|
Calculator/src/main/View/CalcScreen.cpp
|
Songtech-0912/InstantCalc
|
2b36a3a7c47a7ae358eea36a4e2d7f120456dc86
|
[
"MIT"
] | 1
|
2021-10-31T04:42:41.000Z
|
2021-10-31T04:42:41.000Z
|
#ifndef TEST
#include "CalcScreen.h"
#include "../Any/View.h"
#include <SDL.h>
#include "../Any/Enums.h"
#include "../Struct/Pair.h"
#include "../Struct/Message.h"
#include "../Struct/Rect.h"
#include "../Struct/Point.h"
#include "../Struct/Size.h"
namespace ii887522::Calculator
{
CalcScreen::CalcScreen(SDL_Renderer*const renderer, const Rect& rect) : View{ renderer },
viewModel{ Rect{ Point{ rect.position.x, rect.position.y + 26 }, Size{ rect.size.w, rect.size.h - 26 } } }, rect{ rect } { }
Action CalcScreen::reactMouseMotion(const SDL_MouseMotionEvent& motionEvent)
{
viewModel.reactMouseMotion(Point{ motionEvent.x, motionEvent.y });
return Action::NONE;
}
Action CalcScreen::reactRightMouseButtonDown(const SDL_MouseButtonEvent&)
{
viewModel.reactRightMouseButtonDown();
return Action::NONE;
}
Pair<Action, Message> CalcScreen::reactRightMouseButtonUp(const SDL_MouseButtonEvent&)
{
viewModel.reactRightMouseButtonUp();
return Pair{ Action::NONE, viewModel.getMessage() };
}
Action CalcScreen::reactMouseLeaveWindow(const SDL_WindowEvent&)
{
viewModel.reactMouseLeaveWindow();
return Action::NONE;
}
void CalcScreen::render()
{
SDL_SetRenderDrawColor(getRenderer(), 192u, 192u, 192u, 255u);
const SDL_Rect sdl_rect{ rect.position.x, rect.position.y, rect.size.w, rect.size.h };
SDL_RenderFillRect(getRenderer(), &sdl_rect);
}
}
#endif
| 27.84
| 126
| 0.731322
|
Songtech-0912
|
b151a8d6e3b44fa6faebb6e4c111070d0dd085d1
| 1,950
|
hpp
|
C++
|
AirLib/include/physics/PhysicsEngineBase.hpp
|
whatseven/AirSim
|
fe7e4e7c782cf1077594c1ee6cc1bbfec3f66bd1
|
[
"MIT"
] | 7
|
2020-05-22T18:00:19.000Z
|
2021-01-07T08:31:19.000Z
|
AirLib/include/physics/PhysicsEngineBase.hpp
|
Abdulkadir-Muhendis/AirSim
|
c6f0729006ecd6d792a750edc7e27021469c5649
|
[
"MIT"
] | 4
|
2020-08-21T07:48:06.000Z
|
2021-03-14T21:06:41.000Z
|
AirLib/include/physics/PhysicsEngineBase.hpp
|
Abdulkadir-Muhendis/AirSim
|
c6f0729006ecd6d792a750edc7e27021469c5649
|
[
"MIT"
] | 7
|
2020-05-22T20:08:22.000Z
|
2021-01-22T09:39:17.000Z
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef airsim_core_PhysicsEngineBase_hpp
#define airsim_core_PhysicsEngineBase_hpp
#include "common/UpdatableContainer.hpp"
#include "common/Common.hpp"
#include "PhysicsBody.hpp"
namespace msr { namespace airlib {
class PhysicsEngineBase : public UpdatableObject {
public:
virtual void update() override
{
UpdatableObject::update();
}
virtual void reportState(StateReporter& reporter) override
{
unused(reporter);
//default nothing to report for physics engine
}
//TODO: reduce copy-past from UpdatableContainer which has same code
/********************** Container interface **********************/
typedef PhysicsBody* TUpdatableObjectPtr;
typedef vector<TUpdatableObjectPtr> MembersContainer;
typedef typename MembersContainer::iterator iterator;
typedef typename MembersContainer::const_iterator const_iterator;
typedef typename MembersContainer::value_type value_type;
iterator begin() { return members_.begin(); }
iterator end() { return members_.end(); }
const_iterator begin() const { return members_.begin(); }
const_iterator end() const { return members_.end(); }
uint size() const { return static_cast<uint>(members_.size()); }
const TUpdatableObjectPtr &at(uint index) const { return members_.at(index); }
TUpdatableObjectPtr &at(uint index) { return members_.at(index); }
//allow to override membership modifications
virtual void clear() { members_.clear(); }
virtual void insert(TUpdatableObjectPtr member) { members_.push_back(member); }
virtual void erase_remove(TUpdatableObjectPtr obj) {
members_.erase(std::remove(members_.begin(), members_.end(), obj), members_.end()); }
private:
MembersContainer members_;
};
}} //namespace
#endif
| 36.111111
| 94
| 0.692821
|
whatseven
|
b1524e07f8eaa10642fa8ed49eaac42a1b87935b
| 1,526
|
cpp
|
C++
|
toolsets/test/clang_test.cpp
|
lukka/evoke
|
793a067e2d70c4c5da77f75c7aadc734d633068d
|
[
"Apache-2.0"
] | null | null | null |
toolsets/test/clang_test.cpp
|
lukka/evoke
|
793a067e2d70c4c5da77f75c7aadc734d633068d
|
[
"Apache-2.0"
] | null | null | null |
toolsets/test/clang_test.cpp
|
lukka/evoke
|
793a067e2d70c4c5da77f75c7aadc734d633068d
|
[
"Apache-2.0"
] | null | null | null |
#include "dotted.h"
#include "Component.h"
#include "File.h"
#include "Toolset.h"
#include "Project.h"
#include <algorithm>
#include <set>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(clang_compile)
{
Component c("hello", true);
Project p("./");
File *input = p.CreateFile(c, "hello/src/gretting.cpp");
const std::set<std::string> includes {"hello/include"};
ClangToolset clang;
auto cmd = clang.getCompileCommand("clang++", "-std=c++17", "obj/hello/src/gretting.cpp.obj", input, includes, false);
BOOST_TEST(cmd == "clang++ -c -std=c++17 -o obj/hello/src/gretting.cpp.obj hello/src/gretting.cpp -Ihello/include");
}
BOOST_AUTO_TEST_CASE(clang_archive)
{
Component c("mylib", true);
Project p("./");
File *input = p.CreateFile(c, "obj/mylib/src/mylib.cpp.obj");
ClangToolset clang;
auto cmd = clang.getArchiverCommand("ar", "lib/libmylib.lib", {input});
BOOST_TEST(cmd == "ar rcs lib/libmylib.lib obj/mylib/src/mylib.cpp.obj");
}
BOOST_AUTO_TEST_CASE(clang_link)
{
Component c("mylib", true);
c.type = "library";
c.buildSuccess = true;
Project p("./");
File *input1 = p.CreateFile(c, "obj/hello/src/gretting.cpp.obj");
File *input2 = p.CreateFile(c, "obj/hello/src/main.cpp.obj");
ClangToolset clang;
auto cmd = clang.getLinkerCommand("clang++", "bin/hello.exe", {input1, input2}, {{&c}});
BOOST_TEST(cmd == "clang++ -o bin/hello.exe obj/hello/src/gretting.cpp.obj obj/hello/src/main.cpp.obj -Lbuild/clang/lib -lmylib");
}
| 35.488372
| 134
| 0.669069
|
lukka
|
b1559583e47919e0a837b5fcd0bb97833b43ecc6
| 1,459
|
hpp
|
C++
|
libraries/plugins/witness/include/steem/plugins/witness/witness_plugin_objects.hpp
|
DunnCreativeSS/ccd
|
83531f2c902a7e8bea351c86c4ca0e4b03820d5b
|
[
"MIT"
] | 1
|
2021-09-02T16:09:26.000Z
|
2021-09-02T16:09:26.000Z
|
libraries/plugins/witness/include/steem/plugins/witness/witness_plugin_objects.hpp
|
DunnCreativeSS/ccd
|
83531f2c902a7e8bea351c86c4ca0e4b03820d5b
|
[
"MIT"
] | null | null | null |
libraries/plugins/witness/include/steem/plugins/witness/witness_plugin_objects.hpp
|
DunnCreativeSS/ccd
|
83531f2c902a7e8bea351c86c4ca0e4b03820d5b
|
[
"MIT"
] | null | null | null |
#pragma once
#include <CreateCoin/chain/CreateCoin_object_types.hpp>
#ifndef CreateCoin_WITNESS_SPACE_ID
#define CreateCoin_WITNESS_SPACE_ID 19
#endif
namespace CreateCoin { namespace chain {
struct by_account;
} }
namespace CreateCoin { namespace plugins { namespace witness {
using namespace CreateCoin::chain;
enum witness_object_types
{
witness_custom_op_object_type = ( CreateCoin_WITNESS_SPACE_ID << 8 )
};
class witness_custom_op_object : public object< witness_custom_op_object_type, witness_custom_op_object >
{
public:
template< typename Constructor, typename Allocator >
witness_custom_op_object( Constructor&& c, allocator< Allocator > a )
{
c( *this );
}
id_type id;
account_name_type account;
};
typedef multi_index_container<
witness_custom_op_object,
indexed_by<
ordered_unique< tag< by_id >, member< witness_custom_op_object, witness_custom_op_object::id_type, &witness_custom_op_object::id > >,
ordered_unique< tag< by_account >, member< witness_custom_op_object, account_name_type, &witness_custom_op_object::account > >
>,
allocator< witness_custom_op_object >
> witness_custom_op_index;
} } }
FC_REFLECT( CreateCoin::plugins::witness::witness_custom_op_object,
(id)
(account)
)
CHAINBASE_SET_INDEX_TYPE( CreateCoin::plugins::witness::witness_custom_op_object, CreateCoin::plugins::witness::witness_custom_op_index )
| 28.607843
| 139
| 0.751199
|
DunnCreativeSS
|
b15717f205bad2b2ea5706d07b6808061cd79de4
| 2,734
|
hpp
|
C++
|
cpp/include/raft/linalg/detail/eltwise.hpp
|
akifcorduk/raft
|
5de31e04f03ed457ec1cb1148be54ff1cf9888cd
|
[
"Apache-2.0"
] | null | null | null |
cpp/include/raft/linalg/detail/eltwise.hpp
|
akifcorduk/raft
|
5de31e04f03ed457ec1cb1148be54ff1cf9888cd
|
[
"Apache-2.0"
] | null | null | null |
cpp/include/raft/linalg/detail/eltwise.hpp
|
akifcorduk/raft
|
5de31e04f03ed457ec1cb1148be54ff1cf9888cd
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2022, 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.
*/
#pragma once
#include "functional.cuh"
#include <raft/linalg/binary_op.hpp>
#include <raft/linalg/unary_op.hpp>
namespace raft {
namespace linalg {
namespace detail {
template <typename InType, typename IdxType, typename OutType = InType>
void scalarAdd(OutType* out, const InType* in, InType scalar, IdxType len, cudaStream_t stream)
{
raft::linalg::unaryOp(out, in, len, adds_scalar<InType, OutType>(scalar), stream);
}
template <typename InType, typename IdxType, typename OutType = InType>
void scalarMultiply(OutType* out, const InType* in, InType scalar, IdxType len, cudaStream_t stream)
{
raft::linalg::unaryOp(out, in, len, multiplies_scalar<InType, OutType>(scalar), stream);
}
template <typename InType, typename IdxType, typename OutType = InType>
void eltwiseAdd(
OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream)
{
raft::linalg::binaryOp(out, in1, in2, len, thrust::plus<InType>(), stream);
}
template <typename InType, typename IdxType, typename OutType = InType>
void eltwiseSub(
OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream)
{
raft::linalg::binaryOp(out, in1, in2, len, thrust::minus<InType>(), stream);
}
template <typename InType, typename IdxType, typename OutType = InType>
void eltwiseMultiply(
OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream)
{
raft::linalg::binaryOp(out, in1, in2, len, thrust::multiplies<InType>(), stream);
}
template <typename InType, typename IdxType, typename OutType = InType>
void eltwiseDivide(
OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream)
{
raft::linalg::binaryOp(out, in1, in2, len, thrust::divides<InType>(), stream);
}
template <typename InType, typename IdxType, typename OutType = InType>
void eltwiseDivideCheckZero(
OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream)
{
raft::linalg::binaryOp(out, in1, in2, len, divides_check_zero<InType, OutType>(), stream);
}
}; // end namespace detail
}; // end namespace linalg
}; // end namespace raft
| 35.051282
| 100
| 0.740673
|
akifcorduk
|
b15ac9a062f21c3f2e67b4623c02db1fdbbf981a
| 77
|
cxx
|
C++
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+double.4-.cxx
|
rdsouza10/ITK
|
07cb23f9866768b5f4ee48ebec8766b6e19efc69
|
[
"Apache-2.0"
] | 3
|
2019-11-19T09:47:25.000Z
|
2022-02-24T00:32:31.000Z
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+double.4-.cxx
|
rdsouza10/ITK
|
07cb23f9866768b5f4ee48ebec8766b6e19efc69
|
[
"Apache-2.0"
] | 1
|
2019-03-18T14:19:49.000Z
|
2020-01-11T13:54:33.000Z
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+double.4-.cxx
|
rdsouza10/ITK
|
07cb23f9866768b5f4ee48ebec8766b6e19efc69
|
[
"Apache-2.0"
] | 1
|
2022-02-24T00:32:36.000Z
|
2022-02-24T00:32:36.000Z
|
#include <vnl/vnl_vector_fixed.hxx>
VNL_VECTOR_FIXED_INSTANTIATE(double,4);
| 19.25
| 39
| 0.831169
|
rdsouza10
|
b15bcd81aeaf9e3b64c09ca41e58b7b830d861fb
| 7,790
|
cc
|
C++
|
src/Core/Datatypes/Mesh/Tests/LatticeVolumeMeshTests.cc
|
kimjohn1/SCIRun
|
62ae6cb632100371831530c755ef0b133fb5c978
|
[
"MIT"
] | 92
|
2015-02-09T22:42:11.000Z
|
2022-03-25T09:14:50.000Z
|
src/Core/Datatypes/Mesh/Tests/LatticeVolumeMeshTests.cc
|
kimjohn1/SCIRun
|
62ae6cb632100371831530c755ef0b133fb5c978
|
[
"MIT"
] | 1,618
|
2015-01-05T19:39:13.000Z
|
2022-03-27T20:28:45.000Z
|
src/Core/Datatypes/Mesh/Tests/LatticeVolumeMeshTests.cc
|
kimjohn1/SCIRun
|
62ae6cb632100371831530c755ef0b133fb5c978
|
[
"MIT"
] | 64
|
2015-02-20T17:51:23.000Z
|
2021-11-19T07:08:08.000Z
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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 <gtest/gtest.h>
#include <gmock/gmock.h>
#include <boost/assign.hpp>
//#include <Core/Datatypes/Mesh/MeshFactory.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Legacy/Field/LatVolMesh.h>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using ::testing::_;
using ::testing::NiceMock;
using ::testing::DefaultValue;
using ::testing::Return;
using namespace boost::assign;
class LatticeVolumeMeshTests : public ::testing::Test
{
protected:
void SetUp() override
{
int basisOrder = 1;
FieldInformation lfi("LatVolMesh", basisOrder, "double");
int sizex,sizey,sizez;
sizex = sizey = sizez = 2;
Point minb(0,0,0);
Point maxb(1,1,1);
mesh_ = CreateMesh(lfi, sizex, sizey, sizez, minb, maxb);
}
MeshHandle mesh_;
};
namespace
{
template <typename T>
std::string join(const T& list)
{
std::ostringstream oss;
const int SIZE = list.size();
for (int i = 0; i < SIZE; ++i)
{
oss << list[i];
if (i < SIZE - 1)
oss << ", ";
}
return oss.str();
}
}
TEST_F(LatticeVolumeMeshTests, BasicCubeTest)
{
ASSERT_TRUE(mesh_.get() != nullptr);
auto latVolVMesh = mesh_->vmesh();
ASSERT_TRUE(latVolVMesh != nullptr);
VMesh::dimension_type dims;
latVolVMesh->get_dimensions(dims);
VMesh::dimension_type expectedDims;
expectedDims += 2,2,2;
EXPECT_EQ(expectedDims, dims);
EXPECT_EQ(8, latVolVMesh->num_nodes());
EXPECT_EQ(12, latVolVMesh->num_edges());
EXPECT_EQ(6, latVolVMesh->num_faces());
EXPECT_EQ(1, latVolVMesh->num_elems());
#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER
ASSERT_TRUE(latVolVMesh->is_linearmesh());
ASSERT_FALSE(latVolVMesh->has_normals());
#endif
}
TEST_F(LatticeVolumeMeshTests, CubeIterationTest)
{
auto latVolVMesh = mesh_->vmesh();
{
VMesh::Edge::iterator meshEdgeIter;
VMesh::Edge::iterator meshEdgeEnd;
VMesh::Node::array_type nodesFromEdge(2);
latVolVMesh->end(meshEdgeEnd);
std::ostringstream ostr;
for (latVolVMesh->begin(meshEdgeIter); meshEdgeIter != meshEdgeEnd; ++meshEdgeIter)
{
// get nodes from edge
VMesh::Edge::index_type edgeID = *meshEdgeIter;
latVolVMesh->get_nodes(nodesFromEdge, edgeID);
Point p0, p1;
latVolVMesh->get_point(p0, nodesFromEdge[0]);
latVolVMesh->get_point(p1, nodesFromEdge[1]);
ostr << "Edge " << edgeID << " nodes=[" << nodesFromEdge[0] << " point=" << p0.get_string()
<< ", " << nodesFromEdge[1] << " point=" << p1.get_string() << "]" << std::endl;
}
EXPECT_EQ(
"Edge 0 nodes=[0 point=[0, 0, 0], 1 point=[1, 0, 0]]\n"
"Edge 1 nodes=[2 point=[0, 1, 0], 3 point=[1, 1, 0]]\n"
"Edge 2 nodes=[4 point=[0, 0, 1], 5 point=[1, 0, 1]]\n"
"Edge 3 nodes=[6 point=[0, 1, 1], 7 point=[1, 1, 1]]\n"
"Edge 4 nodes=[0 point=[0, 0, 0], 2 point=[0, 1, 0]]\n"
"Edge 5 nodes=[4 point=[0, 0, 1], 6 point=[0, 1, 1]]\n"
"Edge 6 nodes=[1 point=[1, 0, 0], 3 point=[1, 1, 0]]\n"
"Edge 7 nodes=[5 point=[1, 0, 1], 7 point=[1, 1, 1]]\n"
"Edge 8 nodes=[0 point=[0, 0, 0], 4 point=[0, 0, 1]]\n"
"Edge 9 nodes=[1 point=[1, 0, 0], 5 point=[1, 0, 1]]\n"
"Edge 10 nodes=[2 point=[0, 1, 0], 6 point=[0, 1, 1]]\n"
"Edge 11 nodes=[3 point=[1, 1, 0], 7 point=[1, 1, 1]]\n"
, ostr.str());
}
{
VMesh::Face::iterator meshFaceIter;
VMesh::Face::iterator meshFaceEnd;
VMesh::Edge::array_type edgesFromFace(4);
VMesh::Node::array_type nodesFromFace(4);
latVolVMesh->end(meshFaceEnd);
std::ostringstream ostr;
for (latVolVMesh->begin(meshFaceIter); meshFaceIter != meshFaceEnd; ++meshFaceIter)
{
// get edges and nodes from face
VMesh::Face::index_type faceID = *meshFaceIter;
latVolVMesh->get_edges(edgesFromFace, faceID);
ostr << "Face " << faceID << " edges=[" << join(edgesFromFace) << "]" << std::endl;
latVolVMesh->get_nodes(nodesFromFace, faceID);
ostr << "Face " << faceID << " nodes=[" << join(nodesFromFace) << "]" << std::endl;
}
EXPECT_EQ("Face 0 edges=[0, 1, 4, 6]\n"
"Face 0 nodes=[0, 1, 3, 2]\n"
"Face 1 edges=[2, 3, 5, 7]\n"
"Face 1 nodes=[4, 6, 7, 5]\n"
"Face 2 edges=[4, 5, 8, 10]\n"
"Face 2 nodes=[0, 2, 6, 4]\n"
"Face 3 edges=[6, 7, 9, 11]\n"
"Face 3 nodes=[1, 5, 7, 3]\n"
"Face 4 edges=[0, 2, 8, 9]\n"
"Face 4 nodes=[0, 4, 5, 1]\n"
"Face 5 edges=[1, 3, 10, 11]\n"
"Face 5 nodes=[2, 3, 7, 6]\n"
,ostr.str());
}
{
VMesh::Cell::iterator meshCellIter;
VMesh::Cell::iterator meshCellEnd;
VMesh::Edge::array_type edgesFromCell(12);
VMesh::Node::array_type nodesFromCell(8);
latVolVMesh->end(meshCellEnd);
std::ostringstream ostr;
for (latVolVMesh->begin(meshCellIter); meshCellIter != meshCellEnd; ++meshCellIter)
{
// get edges and nodes from mesh element
VMesh::Cell::index_type elemID = *meshCellIter;
latVolVMesh->get_edges(edgesFromCell, elemID);
ostr << "Cell " << elemID << " edges=[" << join(edgesFromCell) << "]" << std::endl;
latVolVMesh->get_nodes(nodesFromCell, elemID);
ostr << "Cell " << elemID << " nodes=["<< join(nodesFromCell) << "]" << std::endl;
}
EXPECT_EQ(
"Cell 0 edges=[0, 1, 2, 3, 4, 6, 5, 7, 8, 9, 10, 11]\n"
"Cell 0 nodes=[0, 1, 3, 2, 4, 5, 7, 6]\n",
ostr.str());
}
{
VMesh::Node::iterator meshNodeIter;
VMesh::Node::iterator meshNodeEnd;
VMesh::Edge::array_type edgesFromNode(3);
latVolVMesh->end(meshNodeEnd);
std::ostringstream ostr;
for (latVolVMesh->begin(meshNodeIter); meshNodeIter != meshNodeEnd; ++meshNodeIter)
{
// get edges and point from mesh node
VMesh::Node::index_type nodeID = *meshNodeIter;
Point p;
latVolVMesh->get_point(p, nodeID);
ostr << "Node " << nodeID << " point=" << p.get_string();
latVolVMesh->get_edges(edgesFromNode, nodeID);
ostr << " edges=[" << join(edgesFromNode) << "]" << std::endl;
}
EXPECT_EQ("Node 0 point=[0, 0, 0] edges=[0, 4, 8]\n"
"Node 1 point=[1, 0, 0] edges=[0, 6, 9]\n"
"Node 2 point=[0, 1, 0] edges=[1, 6, 10]\n"
"Node 3 point=[1, 1, 0] edges=[1, 8, 11]\n"
"Node 4 point=[0, 0, 1] edges=[2, 5, 9]\n"
"Node 5 point=[1, 0, 1] edges=[2, 7, 10]\n"
"Node 6 point=[0, 1, 1] edges=[3, 7, 11]\n"
"Node 7 point=[1, 1, 1] edges=[3, 9, 12]\n",
ostr.str());
}
}
| 31.92623
| 97
| 0.62362
|
kimjohn1
|
b15c0cbad4bfe40d6b175643ae4ef05aadad32a0
| 439
|
hpp
|
C++
|
library/ATF/tagNMTOOLBARA.hpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
library/ATF/tagNMTOOLBARA.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
library/ATF/tagNMTOOLBARA.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_TBBUTTON.hpp>
#include <tagNMHDR.hpp>
#include <tagRECT.hpp>
START_ATF_NAMESPACE
struct tagNMTOOLBARA
{
tagNMHDR hdr;
int iItem;
_TBBUTTON tbButton;
int cchText;
char *pszText;
tagRECT rcButton;
};
END_ATF_NAMESPACE
| 20.904762
| 108
| 0.67426
|
lemkova
|
b15d0d237ff0e7cce48d10ccabdcdcd397e7ad51
| 3,594
|
hxx
|
C++
|
src/tst/reporter.hxx
|
igagis/testy
|
a38281336816bec1651d818fa7aad89ecade17b2
|
[
"MIT"
] | 8
|
2021-04-16T13:17:20.000Z
|
2022-01-05T09:14:03.000Z
|
src/tst/reporter.hxx
|
igagis/testy
|
a38281336816bec1651d818fa7aad89ecade17b2
|
[
"MIT"
] | 16
|
2021-04-19T07:59:52.000Z
|
2022-02-07T11:14:55.000Z
|
src/tst/reporter.hxx
|
igagis/testy
|
a38281336816bec1651d818fa7aad89ecade17b2
|
[
"MIT"
] | 3
|
2021-04-17T02:33:46.000Z
|
2022-02-21T15:37:55.000Z
|
/*
MIT License
Copyright (c) 2021 Ivan Gagis
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.
*/
/* ================ LICENSE END ================ */
#pragma once
#include <string>
#include <mutex>
#include "suite.hpp"
#include "application.hpp"
#include "util.hxx"
namespace tst{
class reporter{
private:
std::mutex mutex;
const application& app;
const size_t num_tests;
size_t num_failed = 0;
size_t num_passed = 0;
size_t num_disabled = 0;
size_t num_errors = 0;
// thread safe
void report(
const full_id& id,
suite::status result,
uint32_t dt,
std::string&& message = std::string()
);
public:
uint32_t time_ms = 0;
reporter(const application& app) :
app(app),
num_tests(app.num_tests())
{}
// thread safe
void report_pass(const full_id& id, uint32_t dt)
{
this->report(id, suite::status::passed, dt);
}
// thread safe
void report_failure(
const full_id& id,
uint32_t dt,
std::string&& message
)
{
this->report(id, suite::status::failed, dt, std::move(message));
}
// thread safe
void report_error(
const full_id& id,
uint32_t dt,
std::string&& message
)
{
this->report(id, suite::status::errored, dt, std::move(message));
}
// thread safe
void report_skipped(
const full_id& id,
std::string&& message
)
{
this->report(id, suite::status::not_run, 0, std::move(message));
}
// thread safe
void report_disabled_test(const full_id& id){
this->report(id, suite::status::disabled, 0);
}
size_t num_unsuccessful()const noexcept{
return this->num_failed + this->num_errors;
}
size_t num_not_run()const noexcept{
return this->num_disabled + this->num_skipped();
}
size_t num_ran()const noexcept{
return this->num_unsuccessful() + this->num_passed + this->num_disabled;
}
size_t num_skipped()const noexcept{
ASSERT(this->num_tests >= this->num_ran())
return this->num_tests - this->num_ran();
}
void print_num_tests_run(std::ostream& o)const;
void print_num_tests_about_to_run(std::ostream& o)const;
void print_num_tests_passed(std::ostream& o)const;
void print_num_tests_disabled(std::ostream& o)const;
void print_num_tests_failed(std::ostream& o)const;
void print_num_tests_skipped(std::ostream& o)const;
void print_num_warnings(std::ostream& o)const;
void print_outcome(std::ostream& o)const;
bool is_failed()const noexcept{
return this->num_failed != 0 || this->num_errors != 0;
}
bool is_semi_passed()const noexcept{
return !this->is_failed() && this->num_skipped() == 0 && this->num_not_run() == 0;
}
void write_junit_report(const std::string& file_name)const;
};
}
| 25.132867
| 84
| 0.720367
|
igagis
|
b163203adc5166a3a5947d9ed649f545a90789d3
| 3,625
|
cpp
|
C++
|
mcg/src/aux/mex_cands2masks.cpp
|
mouthwater/rgb
|
3fafca24ecc133910923182581a2133b8568bf77
|
[
"BSD-2-Clause"
] | 392
|
2015-01-14T13:19:40.000Z
|
2022-02-12T08:47:33.000Z
|
mcg/src/aux/mex_cands2masks.cpp
|
mouthwater/rgb
|
3fafca24ecc133910923182581a2133b8568bf77
|
[
"BSD-2-Clause"
] | 45
|
2015-02-03T12:16:10.000Z
|
2022-03-07T00:25:09.000Z
|
mcg/src/aux/mex_cands2masks.cpp
|
mouthwater/rgb
|
3fafca24ecc133910923182581a2133b8568bf77
|
[
"BSD-2-Clause"
] | 168
|
2015-01-05T02:29:53.000Z
|
2022-02-22T04:32:04.000Z
|
// ------------------------------------------------------------------------
// Copyright (C)
// Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain
// University of California Berkeley (UCB) - USA
//
// Jordi Pont-Tuset <jordi.pont@upc.edu>
// Pablo Arbelaez <arbelaez@berkeley.edu>
// June 2014
// ------------------------------------------------------------------------
// This file is part of the MCG package presented in:
// Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,
// "Multiscale Combinatorial Grouping,"
// Computer Vision and Pattern Recognition (CVPR) 2014.
// Please consider citing the paper if you use this code.
// ------------------------------------------------------------------------
#include "mex.h"
#include <iostream>
#include <set>
#include <map>
#include <list>
#include "matlab_multiarray.hpp"
using namespace std;
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray*prhs[] )
{
/* Check for proper number of arguments */
if (nrhs != 3) {
mexErrMsgTxt("Three input arguments required.");
} else if (nlhs > 3) {
mexErrMsgTxt("Too many output arguments.");
}
/* Input as a Multiarray */
ConstMatlabMultiArray<double> lp(prhs[0]); /* Leaves partition */
ConstMatlabMultiArray<double> ms(prhs[1]); /* Merging sequence */
ConstMatlabMultiArray<double> cands(prhs[2]); /* Candidates */
/* Input sizes and checks */
size_t sm = lp.shape()[0];
size_t sn = lp.shape()[1];
size_t n_sons_max= ms.shape()[1]-1;
size_t n_merges = ms.shape()[0];
size_t n_leaves = ms[0][n_sons_max]-1; // n_merges+1; --> Not valid for non-binary trees
size_t n_regs = n_leaves+n_merges;
size_t n_cands = cands.shape()[0];
size_t n_regs_max= cands.shape()[1];
/* Create the list of activated pixels in each leave region */
vector<list<size_t> > x_coords(n_regs);
vector<list<size_t> > y_coords(n_regs);
for (size_t xx=0; xx<sm; ++xx)
{
for (size_t yy=0; yy<sn; ++yy)
{
size_t curr_leave = lp[xx][yy]-1;
x_coords[curr_leave].push_back(xx);
y_coords[curr_leave].push_back(yy);
}
}
/* Bottom-up expansion of the lists of pixels */
for (size_t ii=0; ii<n_merges; ++ii)
{
for (size_t jj=0; jj<n_sons_max; ++jj)
{
if (ms[ii][jj]==0)
break;
x_coords[n_leaves+ii].insert(x_coords[n_leaves+ii].end(),
x_coords[ms[ii][jj]-1].begin(),
x_coords[ms[ii][jj]-1].end());
y_coords[n_leaves+ii].insert(y_coords[n_leaves+ii].end(),
y_coords[ms[ii][jj]-1].begin(),
y_coords[ms[ii][jj]-1].end());
}
}
/* Allocate out masks */
size_t ndim = 3;
mwSize dims[3];
dims[0] = sm; dims[1] = sn; dims[2] = n_cands;
plhs[0] = mxCreateLogicalArray(3, dims);
MatlabMultiArray3<bool> out_masks(plhs[0]);
for (size_t ii=0; ii<n_cands; ++ii)
{
for (size_t jj=0; jj<n_regs_max; ++jj)
{
if (cands[ii][jj]==0)
break;
list<size_t>::iterator itx = x_coords[cands[ii][jj]-1].begin();
list<size_t>::iterator ity = y_coords[cands[ii][jj]-1].begin();
for( ; itx!=x_coords[cands[ii][jj]-1].end(); ++itx, ++ity)
{
out_masks[*itx][*ity][ii] = true;
}
}
}
}
| 34.52381
| 94
| 0.516966
|
mouthwater
|
b163e11e45e58be069f09fea1e0a569225bb8217
| 283
|
cpp
|
C++
|
main.cpp
|
ipeperko/ivo_sandbox
|
92054b242c55d58432291b70b7874c253fc3474a
|
[
"MIT"
] | null | null | null |
main.cpp
|
ipeperko/ivo_sandbox
|
92054b242c55d58432291b70b7874c253fc3474a
|
[
"MIT"
] | null | null | null |
main.cpp
|
ipeperko/ivo_sandbox
|
92054b242c55d58432291b70b7874c253fc3474a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "mysql/mysql.h"
int main()
{
MYSQL* mysql = mysql_init(nullptr);
mysql_close(mysql);
#ifdef TEST_OPTION
std::cout << "[ok] Test option enabled\n";
return 0;
#else
std::cout << "[error] Test option disabled\n";
return 1;
#endif
}
| 17.6875
| 50
| 0.636042
|
ipeperko
|
b16748b573c6346e09a61f774b1ccd5309d61bfb
| 1,051
|
cc
|
C++
|
HTTP/src/HttpError.cc
|
frankencode/CoreComponents
|
4c66d7ff9fc5be19222906ba89ba0e98951179de
|
[
"Zlib"
] | 1
|
2019-07-29T04:07:29.000Z
|
2019-07-29T04:07:29.000Z
|
HTTP/src/HttpError.cc
|
frankencode/CoreComponents
|
4c66d7ff9fc5be19222906ba89ba0e98951179de
|
[
"Zlib"
] | null | null | null |
HTTP/src/HttpError.cc
|
frankencode/CoreComponents
|
4c66d7ff9fc5be19222906ba89ba0e98951179de
|
[
"Zlib"
] | 1
|
2020-03-04T17:13:04.000Z
|
2020-03-04T17:13:04.000Z
|
/*
* Copyright (C) 2021 Frank Mertens.
*
* Distribution and use is allowed under the terms of the zlib license
* (see cc/LICENSE-zlib).
*
*/
#include <cc/HttpError>
namespace cc {
HttpBadRequest::HttpBadRequest():
HttpError{HttpStatus::BadRequest, "Bad Request"}
{}
HttpForbidden::HttpForbidden():
HttpError{HttpStatus::Forbidden, "Forbidden"}
{}
HttpNotFound::HttpNotFound():
HttpError{HttpStatus::NotFound, "Not Found"}
{}
HttpRequestTimeout::HttpRequestTimeout():
HttpError{HttpStatus::RequestTimeout, "Request Timeout"}
{}
HttpPayloadTooLarge::HttpPayloadTooLarge():
HttpError{HttpStatus::PayloadTooLarge, "Payload Too Large"}
{}
HttpInternalServerError::HttpInternalServerError():
HttpError{HttpStatus::InternalServerError, "Internal Server Error"}
{}
HttpUnsupportedVersion::HttpUnsupportedVersion():
HttpError{HttpStatus::UnsupportedVersion, "HTTP Version Not Supported"}
{}
HttpNotImplemented::HttpNotImplemented():
HttpError{HttpStatus::NotImplemented, "Not Implemented"}
{}
} // namespace cc
| 22.847826
| 75
| 0.748811
|
frankencode
|
b16a73d1932d69161cef21a71f386e6aa9590ffa
| 1,691
|
cpp
|
C++
|
tree/leetcode_tree/113_path_sum_3.cpp
|
Hadleyhzy/data_structure_and_algorithm
|
0e610ba78dcb216323d9434a0f182756780ce5c0
|
[
"MIT"
] | 1
|
2020-10-12T19:18:19.000Z
|
2020-10-12T19:18:19.000Z
|
tree/leetcode_tree/113_path_sum_3.cpp
|
Hadleyhzy/data_structure_and_algorithm
|
0e610ba78dcb216323d9434a0f182756780ce5c0
|
[
"MIT"
] | null | null | null |
tree/leetcode_tree/113_path_sum_3.cpp
|
Hadleyhzy/data_structure_and_algorithm
|
0e610ba78dcb216323d9434a0f182756780ce5c0
|
[
"MIT"
] | null | null | null |
//
// 113_path_sum_3.cpp
// leetcode_tree
//
// Created by Hadley on 11.07.20.
// Copyright © 2020 Hadley. All rights reserved.
//
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <stack>
#include <cstring>
#include <queue>
#include <functional>
#include <numeric>
using namespace std;
/**
* Definition for a binary tree node.*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
//better solution//
//*https://leetcode.com/problems/path-sum-ii/discuss/723689/C%2B%2B-96-Faster-Easytounderstand-With-Explanation*//
class Solution {
public:
vector<vector<int>> path(TreeNode* root){
if(!root)return{};
if(!root->left&&!root->right)
return {{root->val}};
vector<vector<int>> a=path(root->left);
for(auto &x:a)
x.push_back(root->val);
vector<vector<int>> b=path(root->right);
for(auto &x:b)
x.push_back(root->val);
a.insert(a.end(), b.begin(),b.end());
return a;
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
for(auto &x:path(root)){
int s=0;
for(auto &y:x){
s+=y;
}
if(s==sum){
reverse(x.begin(), x.end());
res.push_back(x);
}
}
return res;
}
};
| 23.816901
| 114
| 0.556475
|
Hadleyhzy
|
b16b38aec1e015785c877a49a58f439d06f3dbcf
| 6,884
|
hpp
|
C++
|
VSDataReduction/VSLaserData.hpp
|
sfegan/ChiLA
|
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
|
[
"BSD-3-Clause"
] | 1
|
2018-04-17T14:03:36.000Z
|
2018-04-17T14:03:36.000Z
|
VSDataReduction/VSLaserData.hpp
|
sfegan/ChiLA
|
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
|
[
"BSD-3-Clause"
] | null | null | null |
VSDataReduction/VSLaserData.hpp
|
sfegan/ChiLA
|
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
|
[
"BSD-3-Clause"
] | null | null | null |
//-*-mode:c++; mode:font-lock;-*-
/*! \file VSLaserData.hpp
Simple pedestal data
\author Stephen Fegan \n
UCLA \n
sfegan@astro.ucla.edu \n
\version 1.0
\date 05/18/2005
$Id: VSLaserData.hpp,v 3.8 2009/11/24 01:11:45 matthew Exp $
*/
#ifndef VSLASERDATA_HPP
#define VSLASERDATA_HPP
#include<string>
#include<vector>
#include<VSOctaveIO.hpp>
#include<VSSimpleHist.hpp>
namespace VERITAS
{
class VSLaserData
{
public:
struct CrateData
{
CrateData():
l2chan(), l2time(), cratetime_mean(), cratetime_dev() {}
// Data -----------------------------------------------------------------
unsigned l2chan; // L2 channel
double l2time; // L2 arrival time
double cratetime_mean; // Crate arrival time - L2 time
double cratetime_dev; // Crate arrival time dev
static void _compose(VSOctaveH5CompositeDefinition& c)
{
H5_ADDMEMBER(c,CrateData,l2chan);
H5_ADDMEMBER(c,CrateData,l2time);
H5_ADDMEMBER(c,CrateData,cratetime_mean);
H5_ADDMEMBER(c,CrateData,cratetime_dev);
}
};
struct ChanData
{
ChanData():
nflash(), l2chan(), crate(),
uncalibrated(), excluded(), chantime(), cratetime(), l2time(),
gain(), gain_err(), absgain(), absgain_err(), eff(), eff_err(),
signal_mean(), signal_dev(), signal_corr_mean(), signal_corr_dev(),
signal_hist(0) { }
// Data -----------------------------------------------------------------
unsigned nflash; // Number of flashes recorded
unsigned l2chan; // L2 channel
unsigned crate; // Crate number
bool uncalibrated; // Has less than required # of laser flashes
bool excluded; // Excluded from mean/median calculations
double chantime; // Channel arrival time - L2 time
double cratetime; // Crate arrival time - L2 time
double l2time; // L2 arrival time for crate
double gain; // Total gain relative to median
double gain_err;
double absgain; // Absolute single PE gain in DC
double absgain_err;
double eff; // Efficiency relative to median
double eff_err;
double signal_mean; // Laser amplitude mean
double signal_dev; // Laser amplitude dev
double signal_corr_mean; // Corrected laser amplitude mean
double signal_corr_dev; // Corrected laser amplitude dev
// Histograms -----------------------------------------------------------
VSSimpleHist<double> signal_hist; // Histogram of signal_mean
static void _compose(VSOctaveH5CompositeDefinition& c)
{
H5_ADDMEMBER(c,ChanData,nflash);
H5_ADDMEMBER(c,ChanData,l2chan);
H5_ADDMEMBER(c,ChanData,crate);
H5_ADDMEMBER(c,ChanData,uncalibrated);
H5_ADDMEMBER(c,ChanData,excluded);
H5_ADDMEMBER(c,ChanData,chantime);
H5_ADDMEMBER(c,ChanData,cratetime);
H5_ADDMEMBER(c,ChanData,l2time);
H5_ADDMEMBER(c,ChanData,gain);
H5_ADDMEMBER(c,ChanData,gain_err);
H5_ADDMEMBER(c,ChanData,absgain);
H5_ADDMEMBER(c,ChanData,absgain_err);
H5_ADDMEMBER(c,ChanData,eff);
H5_ADDMEMBER(c,ChanData,eff_err);
H5_ADDMEMBER(c,ChanData,signal_mean);
H5_ADDMEMBER(c,ChanData,signal_dev);
H5_ADDMEMBER(c,ChanData,signal_corr_mean);
H5_ADDMEMBER(c,ChanData,signal_corr_dev);
}
};
struct ScopeData
{
ScopeData():
runno(), nchan(0), nevents(0), nflash(0),
absgain_mean(), absgain_median(), npe_mean(), npe_median(),
nchan_mean(), nchan_dev(), signal_mean(), signal_dev(),
signal_hist(0), nchan_flash_hist(0),
nchan_logain_hist(0), nchan_higain_hist(0),
chan(), crate() {}
// Data -----------------------------------------------------------------
unsigned runno;
unsigned nchan; // Number channels in this telescope
unsigned nevents; // Number events in laser run
unsigned nflash; // Number events passing laser criteria
double absgain_mean; // Mean absolute gain
double absgain_median; // Median absolute gain
double npe_mean; // Mean number of PEs per pixel
double npe_median; // Median number of PEs per pixel
double nchan_mean; // Number of channels in each flash mean
double nchan_dev; // Number of channels in each flash dev
double signal_mean; // Average telescope laser amplitude mean
double signal_dev; // Average telescope laser amplitude dev
// Histograms -----------------------------------------------------------
VSSimpleHist<double> signal_hist;
VSSimpleHist<unsigned> nchan_flash_hist;
VSSimpleHist<unsigned> nchan_logain_hist;
VSSimpleHist<unsigned> nchan_higain_hist;
// Vectors of structures ------------------------------------------------
std::vector<ChanData> chan;
std::vector<CrateData> crate;
static void _compose(VSOctaveH5CompositeDefinition& c)
{
H5_ADDMEMBER(c,ScopeData,runno);
H5_ADDMEMBER(c,ScopeData,nchan);
H5_ADDMEMBER(c,ScopeData,nevents);
H5_ADDMEMBER(c,ScopeData,nflash);
H5_ADDMEMBER(c,ScopeData,absgain_mean);
H5_ADDMEMBER(c,ScopeData,absgain_median);
H5_ADDMEMBER(c,ScopeData,npe_mean);
H5_ADDMEMBER(c,ScopeData,npe_median);
H5_ADDMEMBER(c,ScopeData,nchan_mean);
H5_ADDMEMBER(c,ScopeData,nchan_dev);
H5_ADDMEMBER(c,ScopeData,signal_mean);
H5_ADDMEMBER(c,ScopeData,signal_dev);
}
};
// Data -------------------------------------------------------------------
unsigned m_runno;
// Settings ---------------------------------------------------------------
unsigned m_threshold_nchan;
double m_threshold_dc;
double m_singlepe_dev;
// Vectors of structures --------------------------------------------------
std::vector<ScopeData> scope;
VSLaserData(): m_runno(), m_threshold_nchan(), m_threshold_dc(),
m_singlepe_dev(), scope()
{ /* nothing to see here */ }
bool load(const std::string& filename);
void suppress(const double lo, const double hi);
void clear();
void load(VSOctaveH5ReaderStruct* reader);
bool load(unsigned iscope,VSOctaveH5ReaderStruct* reader);
void save(VSOctaveH5WriterStruct* writer) const;
static void _compose(VSOctaveH5CompositeDefinition& c)
{
H5_ADDMEMBER(c,VSLaserData,m_runno);
H5_ADDMEMBER(c,VSLaserData,m_threshold_nchan);
H5_ADDMEMBER(c,VSLaserData,m_threshold_dc);
H5_ADDMEMBER(c,VSLaserData,m_singlepe_dev);
}
private:
VSLaserData(const VSLaserData&);
VSLaserData& operator= (const VSLaserData&);
};
};
#endif // VSLASERDATA_HPP
| 34.767677
| 79
| 0.601249
|
sfegan
|
b16dfa4c3eda784ca4228a393b0a8fcc1b88b2b3
| 1,405
|
cpp
|
C++
|
cf/Div2/B/Little Elephant and Magic Square/main.cpp
|
wdjpng/soi
|
dd565587ae30985676f7f374093ec0687436b881
|
[
"MIT"
] | null | null | null |
cf/Div2/B/Little Elephant and Magic Square/main.cpp
|
wdjpng/soi
|
dd565587ae30985676f7f374093ec0687436b881
|
[
"MIT"
] | null | null | null |
cf/Div2/B/Little Elephant and Magic Square/main.cpp
|
wdjpng/soi
|
dd565587ae30985676f7f374093ec0687436b881
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define int long long
#define double long double
using namespace std;
// Easy O(1) solution, who needs general solutions anyways
bool isPrim(int n){
return n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n == 17 || n == 19 || n == 23;
}
signed main() {
// Turn off synchronization between cin/cout and scanf/printf
ios_base::sync_with_stdio(false);
// Disable automatic flush of cout when reading from cin cin.tie(0);
cin.tie(0);
int counter = 0;
vector<int>perm(9);
for (int i = 0; i < 9; ++i) {
cin >> perm[i];
}
for (int i = 1; i < 100001; ++i) {
perm[0]=i;
perm[4]=perm[0]+perm[1]+perm[2]-perm[3]-perm[5];
perm[8]=perm[0]+perm[1]+perm[2]-perm[6]-perm[7];
int sum=perm[0]+perm[1]+perm[2];
vector<int>sums;
for (int j = 0; j < 3; ++j) {
sums.push_back(perm[3*j]+perm[3*j+1]+perm[3*j+2]);
sums.push_back(perm[j]+perm[j+3]+perm[j+6]);
}
sums.push_back(perm[0]+perm[4]+perm[8]);
sums.push_back(perm[2]+perm[4]+perm[6]);
if(sums.size() == count(sums.begin(), sums.end(), sum)){
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 3; ++k) {
cout << perm[j*3+k] << " ";
}
cout << "\n";
}
break;
}
}
}
| 31.222222
| 103
| 0.479715
|
wdjpng
|
b17b6df61d569fbbc8c492038015124942f98545
| 1,368
|
cpp
|
C++
|
Codeforces 412E.cpp
|
Jvillegasd/Codeforces
|
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
|
[
"MIT"
] | null | null | null |
Codeforces 412E.cpp
|
Jvillegasd/Codeforces
|
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
|
[
"MIT"
] | null | null | null |
Codeforces 412E.cpp
|
Jvillegasd/Codeforces
|
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
bool isLetter(char l){
return (l>='a'&&l<='z') || (l>='A'&&l<='Z');
}
int main(){
string input;
cin >> input;
long long ans = 0;
for(int i = 0; i < input.size(); i++){
if(input[i] == '@'){
long long before = 0, after = 0;
for(int j = i - 1; j >= 0; j--){
if(input[j] == '@' || input[j] == '.') break;
if(isLetter(input[j])) before++;
}
for(int j = i + 1; j < input.size(); j++){
if(input[j] == '@' || input[j] == '_'){
i = j - 1;
break;
}
if(input[j] == '.'){
if(j == i + 1) break;
for(int k = j + 1; k < input.size(); k++){
if(!isLetter(input[k])) {
i = k - 1;
break;
}
i = k - 1;
after++;
}
break;
}
}
/*
Multiplicar para obtener las multiples parejas (mini emails) que se forman con esos caracteres
consecutivos.
*/
ans+=before*after;
}
}
cout << ans << endl;
return 0;
}
| 29.106383
| 110
| 0.324561
|
Jvillegasd
|
b17fd74666d6aed009e12f75c955ea10bebe8e65
| 4,161
|
cpp
|
C++
|
float4d.cpp
|
shtty/cppcnn
|
8dff95e8bb539b1762e3a25e3eb1f0b0cd30473e
|
[
"MIT"
] | 6
|
2017-08-31T23:25:06.000Z
|
2019-09-30T06:39:33.000Z
|
float4d.cpp
|
shtty/cppcnn
|
8dff95e8bb539b1762e3a25e3eb1f0b0cd30473e
|
[
"MIT"
] | null | null | null |
float4d.cpp
|
shtty/cppcnn
|
8dff95e8bb539b1762e3a25e3eb1f0b0cd30473e
|
[
"MIT"
] | 1
|
2018-12-05T07:09:38.000Z
|
2018-12-05T07:09:38.000Z
|
////////////////////////////////////////////////////////////////////////////////////
//// This code is written by Ho Yub Jung ////
////////////////////////////////////////////////////////////////////////////////////
#include "float4d.h"
std::mt19937 float4d::n_random_seed = std::mt19937(0);
void float4d::set(float min, float max, float cmin, float cmax, float multi, float add) {
float4d r;
r.resize(n_size);
if (cmin >= cmax) {
cmax = *max_element(p_v.begin(), p_v.end());
cmin = *min_element(p_v.begin(), p_v.end());
}
for (int n = 0; n < n_size.n; n++) {
for (int c = 0; c < n_size.c; c++) {
for (int h = 0; h < n_size.h; h++) {
for (int w = 0; w < n_size.w; w++) {
float v = this->operator()(n, c, h, w);
r(n, c, h, w) = ((v / (cmax - cmin))*(max - min) + min)*multi + add;
}
}
}
}
*this = r;
}
void float4d::set(string init_method, std::mt19937 &rng) {
if (init_method == "xavier" || init_method == "Xavier") {
////http://deepdish.io/2015/02/24/network-initialization/
//// X.Glorot and Y.Bengio, “Understanding the difficulty of training deep feedforward neural networks, ” in International conference on artificial intelligence and statistics, 2010, pp. 249–256.
//// Xavier initialization
float d = sqrt(12 / double(chw())) / 2;
float max = d;
float min = -d;
set(min, max,rng);
}
else if (init_method == "pass") {
set("xavier");
int ch = n_size.h / 2;
int cw = n_size.w / 2;
set(0, 0);
this->operator()(0, 0, ch, cw) = 1;
}
}
void float4d::set_borders(int border_width, float border_value) {
for (int n = 0; n < n_size.n; n++) {
for (int c = 0; c < n_size.c; c++) {
for (int h = 0; h < n_size.h; h++) {
for (int w = 0; w < n_size.w; w++) {
if (h < border_width || h >= n_size.h - border_width ||
w < border_width || w >= n_size.w - border_width) {
this->operator()(n, c, h, w) = border_value;
}
}
}
}
}
}
void float4d::print(bool print_values) {
cout << "size_NCHW " << n_size.n << " " << n_size.c << " " << n_size.h << " " << n_size.w << endl;
if (print_values) {
for (int ps = 0; ps < n_size.n; ps++) { // per each image
for (int pc = 0; pc < n_size.c; pc++) { // per each channel
for (int py = 0; py < n_size.h; py++) { // per each y
for (int px = 0; px < n_size.w; px++) { // per each x
cout << setw(4) << at(ps, pc, py, px) << " ";
//if (at(ps, pc, py, px) >= 0) { cout << " "; }
}
cout << endl;
}
cout << endl;
}
}
}
}
void float4d::rotate(int cy, int cx, int angle_degree, float out_bound_value) {
float cosangle = std::cos(float(-angle_degree * PI / 180.0));
float sinangle = std::sin(float(-angle_degree * PI / 180.0));
float4d r;
r.resize(this->size());
r.set(out_bound_value);
for (int ps = 0; ps < n_size.n; ps++) { // per each image
for (int pc = 0; pc < n_size.c; pc++) { // per each channel
for (int py = 0; py < n_size.h; py++) { // per each y
for (int px = 0; px < n_size.w; px++) { // per each x
float y, x, ry, rx;
y = cy - py;
x = px - cx;
rx = cosangle*x - sinangle*y;
ry = sinangle*x + cosangle*y;
int rpy, rpx;
rpy = int(cy - ry + 0.5f);
rpx = int(rx + cx + 0.5f);
if (rpy >= 0 && rpy < n_size.h && rpx >= 0 && rpx < n_size.w) {
r(ps, pc, py, px) = this->p_v[nchw2idx(ps, pc, rpy, rpx)];
}
}
}
}
}
this->p_v = r.p_v;
}
void float4d::translate(int th, int tw, float out_bound_value ) {
float4d r;
r.resize(this->size());
r.set(out_bound_value);
for (int ps = 0; ps < n_size.n; ps++) { // per each image
for (int pc = 0; pc < n_size.c; pc++) { // per each channel
for (int py = 0; py < n_size.h; py++) { // per each y
for (int px = 0; px < n_size.w; px++) { // per each x
int ny, nx;
ny = py + th;
nx = px + tw;
if (ny >= 0 && nx >= 0 && ny < n_size.h && nx < n_size.w) {
r(ps, pc, py, px) = this->p_v[nchw2idx(ps, pc, ny, nx)];
}
}
}
}
}
this->p_v = r.p_v;
}
| 33.02381
| 198
| 0.495554
|
shtty
|
b17fd7823ea89d912ffaf350ebd8b7e5092e959e
| 6,029
|
cpp
|
C++
|
src/Leddar/LdBoolProperty.cpp
|
deucedrone/LeddarSDK
|
c1deb6621e8ad845341e0185763c4a7706ecb788
|
[
"BSD-3-Clause"
] | null | null | null |
src/Leddar/LdBoolProperty.cpp
|
deucedrone/LeddarSDK
|
c1deb6621e8ad845341e0185763c4a7706ecb788
|
[
"BSD-3-Clause"
] | null | null | null |
src/Leddar/LdBoolProperty.cpp
|
deucedrone/LeddarSDK
|
c1deb6621e8ad845341e0185763c4a7706ecb788
|
[
"BSD-3-Clause"
] | 1
|
2020-06-01T17:40:08.000Z
|
2020-06-01T17:40:08.000Z
|
// *****************************************************************************
// Module..: Leddar
//
/// \file LdBoolProperty.cpp
///
/// \brief Definition of LdBoolProperty class.
///
/// \author Patrick Boulay
///
/// \since January 2016
//
// Copyright (c) 2016 LeddarTech Inc. All rights reserved.
// *****************************************************************************
#include "LdBoolProperty.h"
#include "LtStringUtils.h"
#include "LtScope.h"
#include <string>
// *****************************************************************************
// Function: LdBoolProperty::LdBoolProperty
//
/// \brief Constructor.
///
/// \param aCategory See LdProperty.
/// \param aFeatures See LdProperty.
/// \param aId See LdProperty.
/// \param aDeviceId See LdProperty.
/// \param aDescription See LdProperty.
///
/// \author Patrick Boulay
///
/// \since January 2016
// *****************************************************************************
LeddarCore::LdBoolProperty::LdBoolProperty( LdProperty::eCategories aCategory, uint32_t aFeatures, uint32_t aId, uint16_t aDeviceId, const std::string &aDescription ) :
LdProperty( LdProperty::TYPE_BOOL, aCategory, aFeatures, aId, aDeviceId, sizeof( bool ), sizeof( bool ), aDescription )
{
}
// *****************************************************************************
// Function: LdBoolProperty::SetValue
//
/// \brief Change the value at the given index.
///
/// \param aIndex Index in array of value to change.
/// \param aValue New value to write.
///
/// \author Patrick Boulay
///
/// \since January 2016
// *****************************************************************************
void
LeddarCore::LdBoolProperty::SetValue( size_t aIndex, bool aValue )
{
CanEdit();
// Initialize the count to 1 on the fist SetValue if not done before.
if( Count() == 0 && aIndex == 0 )
{
SetCount( 1 );
}
if( aIndex >= Count() )
{
throw std::out_of_range( "Index not valid, verify property count. Property id: " + LeddarUtils::LtStringUtils::IntToString( GetId(), 16 ) );
}
bool *lValues = reinterpret_cast<bool *>( Storage() );
if( !IsInitialized() || lValues[ aIndex ] != aValue )
{
SetInitialized( true );
lValues[ aIndex ] = aValue;
EmitSignal( LdObject::VALUE_CHANGED );
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarCore::LdBoolProperty::ForceValue( size_t aIndex, bool aValue )
///
/// \brief Force value
///
/// \param aIndex Index in array of value to change.
/// \param aValue New value to write.
///
/// \author David Levy
/// \date March 2019
////////////////////////////////////////////////////////////////////////////////////////////////////
void
LeddarCore::LdBoolProperty::ForceValue( size_t aIndex, bool aValue )
{
LeddarUtils::LtScope<bool> lForceEdit( &mCheckEditable, true );
mCheckEditable = false;
SetValue( aIndex, aValue );
}
// *****************************************************************************
// Function: LdBoolProperty::GetStringValue
//
/// \brief Display the value in string format
///
/// \author Patrick Boulay
///
/// \since January 2016
// *****************************************************************************
std::string
LeddarCore::LdBoolProperty::GetStringValue( size_t aIndex ) const
{
return ( Value( aIndex ) == true ? "true" : "false" );
}
// *****************************************************************************
// Function: LdBoolProperty::SetStringValue
//
/// \brief Property writer for the value as text. Possible value: true and false (lower case)
///
/// \param aIndex Index of value to write.
/// \param aValue The new value.
///
/// \exception std::invalid_argument If the string is not valid.
///
/// \author Patrick Boulay
///
/// \since January 2016
// *****************************************************************************
void
LeddarCore::LdBoolProperty::SetStringValue( size_t aIndex, const std::string &aValue )
{
bool lNewValue = false;
if( LeddarUtils::LtStringUtils::ToLower( aValue ) == "true" )
{
lNewValue = true;
}
else if( LeddarUtils::LtStringUtils::ToLower( aValue ) == "false" )
{
lNewValue = false;
}
else
{
throw( std::invalid_argument( "Invalid string value (use \"true\" or \"false\"." ) );
}
SetValue( aIndex, lNewValue );
return;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarCore::LdBoolProperty::ForceStringValue( size_t aIndex, const std::string &aValue )
///
/// \brief Force the value
///
/// \param aIndex Index of value to write.
/// \param aValue The new value.
///
/// \author David Levy
/// \date March 2019
////////////////////////////////////////////////////////////////////////////////////////////////////
void
LeddarCore::LdBoolProperty::ForceStringValue( size_t aIndex, const std::string &aValue )
{
LeddarUtils::LtScope<bool> lForceEdit( &mCheckEditable, true );
mCheckEditable = false;
SetStringValue( aIndex, aValue );
}
// *****************************************************************************
// Function: LdBoolProperty::Value
//
/// \brief Return the property value
///
/// \param aIndex Index of value.
///
/// \exception std::out_of_range Value out of range ( from std::stoi )
///
/// \author Patrick Boulay
///
/// \since January 2016
// *****************************************************************************
bool
LeddarCore::LdBoolProperty::Value( size_t aIndex ) const
{
VerifyInitialization();
if( aIndex >= Count() )
{
throw std::out_of_range( "Index not valid, verify property count. Property id: " + LeddarUtils::LtStringUtils::IntToString( GetId(), 16 ) );
}
return reinterpret_cast<const bool *>( CStorage() )[ aIndex ];
}
| 30.296482
| 168
| 0.502405
|
deucedrone
|
b181efefb66df7109b9f875b56e654ff92a672cd
| 4,659
|
cpp
|
C++
|
Units.Reflection.Test/DynamicReflectQuantityTests.cpp
|
dnv-opensource/Reflection
|
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
|
[
"BSL-1.0"
] | null | null | null |
Units.Reflection.Test/DynamicReflectQuantityTests.cpp
|
dnv-opensource/Reflection
|
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
|
[
"BSL-1.0"
] | null | null | null |
Units.Reflection.Test/DynamicReflectQuantityTests.cpp
|
dnv-opensource/Reflection
|
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2021 DNV AS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include "gtest/gtest.h"
#include "Units/Runtime/DynamicQuantity.h"
#include "Units/Runtime/Unit.h"
#include "Units/Length.h"
#include "Units/Mass.h"
#include "Units/ForAllDimensions.h"
#include "Units/Reflection/ReflectQuantities.h"
#include "Reflection/Classes/Class.h"
#include "Reflection/TypeLibraries/TypeLibraryFactory.h"
#include "Reflection/Objects/Object.h"
#include "Units/Reflection/Details/ReflectLength.h"
using namespace DNVS::MoFa::Reflection::Classes;
using namespace DNVS::MoFa::Reflection::Objects;
using namespace DNVS::MoFa::Reflection::TypeLibraries;
using namespace DNVS::MoFa::Reflection::TypeConversions;
using namespace DNVS::MoFa::Reflection;
using namespace DNVS::MoFa::Units;
using namespace DNVS::MoFa::Units::Runtime;
struct ConverterFromDynamicQuantityToStaticQuantity
{
public:
ConverterFromDynamicQuantityToStaticQuantity(const Variants::Variant& dynamicQuantity)
: m_dynamicQuantity(Variants::VariantService::Unreflect<DynamicQuantity>(dynamicQuantity))
, m_staticQuantity(dynamicQuantity)
{
}
template<typename DimensionT>
void Apply()
{
typedef Quantity<DimensionT> StaticQuantity;
if(DynamicDimension(DimensionT()) == m_dynamicQuantity.GetSimplifiedUnit().GetDimension())
m_staticQuantity = Variants::VariantService::Reflect<StaticQuantity>(StaticQuantity(m_dynamicQuantity.GetNeutralValue()));
}
Variants::Variant GetStaticQuantity() const
{
return m_staticQuantity;
}
private:
Variants::Variant m_staticQuantity;
DynamicQuantity m_dynamicQuantity;
};
struct FallbackUnitConverter : public IConversion
{
virtual Variants::Variant Convert(const Variants::Variant& other)
{
ConverterFromDynamicQuantityToStaticQuantity converter(other);
ForAllUsedDimensions(converter);
return converter.GetStaticQuantity();
}
virtual void IntrusiveConvert( Variants::Variant& variable )
{
ConverterFromDynamicQuantityToStaticQuantity converter(variable);
ForAllUsedDimensions(converter);
variable = converter.GetStaticQuantity();
}
};
TEST(DynamicReflectQuantityTests, ReflectDynamicQuantities_AddLengths)
{
ConversionGraphPointer conversionGraph(
TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph());
TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph));
Reflection::ReflectDynamicQuantities(typeLibrary);
Reflection::ReflectLength(typeLibrary);
Object a(typeLibrary, DynamicQuantity(5.2, _m));
Object b(typeLibrary, DynamicQuantity(4.2, _m));
Object c = a + b;
EXPECT_EQ(DynamicQuantity(5.2 + 4.2, _m), c.As<DynamicQuantity>());
}
TEST(DynamicReflectQuantityTests, ReflectDynamicQuantities_ConvertToLength)
{
ConversionGraphPointer conversionGraph(
TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph());
TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph));
Reflection::ReflectDynamicQuantities(typeLibrary);
Reflection::ReflectLength(typeLibrary);
Object a(typeLibrary, DynamicQuantity(5.2, _m));
Object b(typeLibrary, DynamicQuantity(4.2, _m));
Object c = a + b;
EXPECT_EQ(Length(5.2 + 4.2), c.As<Length>());
EXPECT_THROW(c.As<Mass>(), std::runtime_error);
}
TEST(DynamicReflectQuantityTests, TestInvalidConversionFromDynamicQuantity_NoCrash)
{
ConversionGraphPointer conversionGraph(
TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph());
TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph));
Reflection::ReflectDynamicQuantities(typeLibrary);
Reflection::ReflectLength(typeLibrary);
Object a(typeLibrary, DynamicQuantity(5.2, Unit("DummyUnit", 1.0, DynamicDimension(4, 4, 4, 4, 4))));
EXPECT_NO_FATAL_FAILURE(
EXPECT_THROW(a.As<Length>(), std::runtime_error)
);
}
TEST(DynamicReflectQuantityTests, TestConversionOfNonDimensionalToDouble)
{
ConversionGraphPointer conversionGraph(
TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph());
TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph));
Reflection::ReflectDynamicQuantities(typeLibrary);
Object a(typeLibrary, DynamicQuantity(5.2, Unit("DummyUnit", 1.0, DynamicDimension(0, 0, 0, 0, 0))));
EXPECT_DOUBLE_EQ(5.2, a.As<double>());
}
| 38.188525
| 134
| 0.75059
|
dnv-opensource
|
b1837ebd6ad25f4a9ddd8e856c43d7c54184fd20
| 16,075
|
cpp
|
C++
|
Tudat/Astrodynamics/StateDerivativeModels/UnitTests/unitTestOrbitalStateDerivativeModel.cpp
|
JPelamatti/ThesisTUDAT
|
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
|
[
"BSD-3-Clause"
] | null | null | null |
Tudat/Astrodynamics/StateDerivativeModels/UnitTests/unitTestOrbitalStateDerivativeModel.cpp
|
JPelamatti/ThesisTUDAT
|
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
|
[
"BSD-3-Clause"
] | null | null | null |
Tudat/Astrodynamics/StateDerivativeModels/UnitTests/unitTestOrbitalStateDerivativeModel.cpp
|
JPelamatti/ThesisTUDAT
|
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
|
[
"BSD-3-Clause"
] | 1
|
2019-05-30T03:42:22.000Z
|
2019-05-30T03:42:22.000Z
|
/* Copyright (c) 2010-2015, Delft University of Technology
* 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 Delft University of Technology nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Changelog
* YYMMDD Author Comment
* 140106 J. Geul File creatad, copied from unitTestOrbitalStateDerivativeModel.
*
*
* References
*
* Notes:
* Test tolerance was set at 5.0e-15 instead of epsilon due to rounding errors in Eigen types
* with entries over a number of orders of magnitude, presumably causing the observed larger
* than epsilon relative differences between expected and computed values.
*
*/
#define BOOST_TEST_MAIN
#include <boost/assign/list_of.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "Tudat/Basics/testMacros.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/testAccelerationModels.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/testBody.h"
#include "Tudat/Astrodynamics/StateDerivativeModels/orbitalStateDerivativeModel.h"
#include "Tudat/Mathematics/BasicMathematics/linearAlgebraTypes.h"
namespace tudat
{
namespace unit_tests
{
using boost::assign::list_of;
using basic_mathematics::Vector6d;
//! Rotate vector over arbitrary angles.
/*!
* This function computes a composite rotation of the input vector over arbitrary angles about the
* unit x-, y-, and z-axes. This is used in conjunction with rotateOverOtherArbitraryAngles() to
* test the frame transformation features provided by the orbitalStateDerivativeModel.
* \param inputVector Input vector before rotation.
* \return Rotated vector.
* \sa orbitalStateDerivativeModel, rotateOverOtherArbitraryAngles().
*/
Eigen::Vector3d rotateOverArbitraryAngles( const Eigen::Vector3d& inputVector )
{
// Declare rotation matrix.
Eigen::Matrix3d rotationMatrix;
rotationMatrix = Eigen::AngleAxisd( -1.15, Eigen::Vector3d::UnitX( ) )
* Eigen::AngleAxisd( 0.23, Eigen::Vector3d::UnitY( ) )
* Eigen::AngleAxisd( 2.56, Eigen::Vector3d::UnitZ( ) );
// Compute rotated matrix and return.
return rotationMatrix * inputVector;
}
//! Rotate vector over other arbitrary angles.
/*!
* This function computes another composite rotation of the input vector over different arbitrary
* angles (compared to the rotateOverArbitraryAngles() function) about the unit x-, y-, and z-axes.
* This is used in conjunction with rotateOverArbitraryAngles() to test the frame transformation
* features provided by the OrbitalStateDerivativeModel.
* \param inputVector Input vector before rotation.
* \return Rotated vector.
* \sa orbitalStateDerivativeModel, rotateOverArbitraryAngles().
*/
Eigen::Vector3d rotateOverOtherArbitraryAngles( const Eigen::Vector3d& inputVector )
{
// Declare rotation matrix.
Eigen::Matrix3d rotationMatrix;
rotationMatrix = Eigen::AngleAxisd( 0.24, Eigen::Vector3d::UnitX( ) )
* Eigen::AngleAxisd( -1.55, Eigen::Vector3d::UnitY( ) )
* Eigen::AngleAxisd( 2.13, Eigen::Vector3d::UnitZ( ) );
// Compute rotated matrix and return.
return rotationMatrix * inputVector;
}
//! Perform Mapping from Acceleration to Cartesian State Derivative
/*!
* This function is implemented in order to not use any external
* mapping functions. The function was build completely from pieces of
* code of the old cartesianStateDerivativeModel in order to use
* completely different, but also verified methods of constructing a
* stateDerivative from the total accelerations.
* \param currentState The current state.
* \param accelerations Total sum of accelerations.
* \return stateDerivative
*/
Vector6d mapCartesian( const Vector6d& cartesianState, const Eigen::Vector3d& acceleration )
{
// {{{ Snippets from cartesianStateDerivativeModel.h
typedef Vector6d CartesianStateDerivativeType;
// Declare Cartesian state derivative size.
unsigned int stateDerivativeSize = cartesianState.rows( );
// Declare Cartesian state derivative of the same size as Cartesian state.
CartesianStateDerivativeType cartesianStateDerivative
= CartesianStateDerivativeType::Zero( stateDerivativeSize );
// Set derivative of position components to current Cartesian velocity.
cartesianStateDerivative.segment( 0, stateDerivativeSize / 2 )
= cartesianState.segment( stateDerivativeSize / 2, stateDerivativeSize / 2 );
// Add transformed acceleration to state derivative.
cartesianStateDerivative.segment( stateDerivativeSize / 2, stateDerivativeSize / 2 )
+= acceleration;
// Return assembled state derivative.
return cartesianStateDerivative;
// }}} End Snippets from cartesianStateDerivativeModel.h
}
BOOST_AUTO_TEST_SUITE( test_orbital_state_derivative_model )
//! Test whether 6D Cartesian state derivative model works correctly without frame transformations.
BOOST_AUTO_TEST_CASE( test_OrbitalStateDerivativeModelWithoutFrameTransformations )
{
using basic_astrodynamics::AccelerationModel3dPointer;
using state_derivative_models::OrbitalStateDerivativeModelType;
using state_derivative_models::OrbitalStateDerivativeModelPointer;
// Shortcuts.
typedef TestBody< 3, double > TestBody3d;
typedef boost::shared_ptr< TestBody3d > TestBody3dPointer;
typedef DerivedAccelerationModel< > DerivedAccelerationModel3d;
typedef AnotherDerivedAccelerationModel< > AnotherDerivedAccelerationModel3d;
// Set current state.
const Vector6d currentState = ( basic_mathematics::Vector6d( )
<< Eigen::Vector3d( -1.1, 2.2, -3.3 ),
Eigen::Vector3d( 0.23, 1.67, -0.11 ) ).finished( );
// Set current time.
const double currentTime = 5.6;
// Set current position.
const Eigen::Vector3d currentPosition = currentState.segment( 0, 3 );
// Set current velocity.
const Eigen::Vector3d currentVelocity = currentState.segment( 3, 3 );
// Create body with zombie time and state.
TestBody3dPointer body = boost::make_shared< TestBody3d >( Eigen::VectorXd::Zero( 6 ), 0.0 );
// Create acceleration models.
AccelerationModel3dPointer firstAccelerationModel3d
= boost::make_shared< DerivedAccelerationModel3d >(
boost::bind( &TestBody3d::getCurrentPosition, body ),
boost::bind( &TestBody3d::getCurrentTime, body ) );
AccelerationModel3dPointer secondAccelerationModel3d
= boost::make_shared< AnotherDerivedAccelerationModel3d >(
boost::bind( &TestBody3d::getCurrentPosition, body ),
boost::bind( &TestBody3d::getCurrentVelocity, body ),
boost::bind( &TestBody3d::getCurrentTime, body ) );
// Create list of acceleration models to provide to state derivative model.
OrbitalStateDerivativeModelType::AccelerationModelPointerVector listOfAccelerations
= list_of( firstAccelerationModel3d )( secondAccelerationModel3d );
// Declare Cartesian state derivative model.
OrbitalStateDerivativeModelPointer cartesianStateDerivativeModel
= boost::make_shared< OrbitalStateDerivativeModelType >(
listOfAccelerations,
boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ),
boost::bind( &mapCartesian, _1, _2 ) );
// // Set Earth gravitational parameter [m^3 s^-2].
// const double earthGravitationalParameter = 3.986004415e14;
// // Declare Keplerian state derivative model.
// OrbitalStateDerivativeModelPointer keplerianStateDerivativeModel
// = boost::make_shared< OrbitalStateDerivativeModelType >(
// listOfAccelerations,
// boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ),
// boost::bind( &stateDerivativeMapKeplerian, _1, _2,
// earthGravitationalParameter ) );
// // Declare Modified Equinoctial state derivative model.
// OrbitalStateDerivativeModelPointer modifiedEquinoctialStateDerivativeModel
// = boost::make_shared< OrbitalStateDerivativeModelType >(
// listOfAccelerations,
// boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ),
// boost::bind( &stateDerivativeMapModifiedEquinoctial, _1, _2,
// earthGravitationalParameter ) );
// Set expected accelerations.
const Eigen::Vector3d expectedAccelerationFirstModel
= currentPosition / ( currentTime * currentTime );
const Eigen::Vector3d expectedAccelerationSecondModel
= 0.5 * currentPosition / ( 3.2 * ( currentTime + 3.4 ) * currentTime )
+ currentVelocity / currentTime;
// Set expected (cumulative) Cartesian state derivative.
const Vector6d expectedCartesianStateDerivative
= ( basic_mathematics::Vector6d( ) << currentVelocity,
expectedAccelerationFirstModel + expectedAccelerationSecondModel ).finished( );
// Compute Cartesian state derivative.
const Vector6d computedCartesianStateDerivative
= cartesianStateDerivativeModel->computeStateDerivative( currentTime, currentState );
// Check that computed Cartesian state derivative matches expected values.
TUDAT_CHECK_MATRIX_BASE( computedCartesianStateDerivative, expectedCartesianStateDerivative )
BOOST_CHECK_SMALL( computedCartesianStateDerivative.coeff( row, col ) -
expectedCartesianStateDerivative.coeff( row, col ),
5.0e-15 );
}
//! Test whether 6D Cartesian state derivative model works correctly with frame transformations.
BOOST_AUTO_TEST_CASE( test_OrbitalStateDerivativeModelWithFrameTransformations )
{
using basic_astrodynamics::AccelerationModel3dPointer;
using state_derivative_models::OrbitalStateDerivativeModelType;
using state_derivative_models::OrbitalStateDerivativeModelPointer;
// Shortcuts.
typedef TestBody< 3, double > TestBody3d;
typedef boost::shared_ptr< TestBody3d > TestBody3dPointer;
typedef DerivedAccelerationModel< > DerivedAccelerationModel3d;
typedef AnotherDerivedAccelerationModel< > AnotherDerivedAccelerationModel3d;
// Set current state.
const Vector6d currentState = ( basic_mathematics::Vector6d( )
<< Eigen::Vector3d( -1.1, 2.2, -3.3 ),
Eigen::Vector3d( 0.23, 1.67, -0.11 ) ).finished( );
// Set current time.
const double currentTime = 5.6;
// Set current position.
const Eigen::Vector3d currentPosition = currentState.segment( 0, 3 );
// Set current velocity.
const Eigen::Vector3d currentVelocity = currentState.segment( 3, 3 );
// Create body with zombie time and state.
TestBody3dPointer body = boost::make_shared< TestBody3d >( Eigen::VectorXd::Zero( 6 ), 0.0 );
// Create acceleration models.
AccelerationModel3dPointer firstAccelerationModel3d
= boost::make_shared< DerivedAccelerationModel3d >(
boost::bind( &TestBody3d::getCurrentPosition, body ),
boost::bind( &TestBody3d::getCurrentTime, body ) );
AccelerationModel3dPointer secondAccelerationModel3d
= boost::make_shared< AnotherDerivedAccelerationModel3d >(
boost::bind( &TestBody3d::getCurrentPosition, body ),
boost::bind( &TestBody3d::getCurrentVelocity, body ),
boost::bind( &TestBody3d::getCurrentTime, body ) );
// Create list of reference frame transformations for first acceleration model.
// NB: The order of this list is VERY important! The order of transformations executed is from
// the beginning of the vector to the end sequentially.
OrbitalStateDerivativeModelType::ListOfReferenceFrameTransformations listOfFrameTransformations
= list_of( &rotateOverArbitraryAngles )( &rotateOverOtherArbitraryAngles );
// Create list to pass to constructor of acceleration model/frame transformation list pairs.
// In this case, there are two frame transformations executed for the first acceleration model,
// and none for the second.
OrbitalStateDerivativeModelType::ListOfAccelerationFrameTransformationPairs
listOfAccelerationFrameTransformations
= list_of( std::make_pair( firstAccelerationModel3d, listOfFrameTransformations ) )
( std::make_pair( secondAccelerationModel3d,
OrbitalStateDerivativeModelType::
ListOfReferenceFrameTransformations( ) ) );
// Declare Cartesian state derivative model.
OrbitalStateDerivativeModelPointer stateDerivativeModel
= boost::make_shared< OrbitalStateDerivativeModelType >(
listOfAccelerationFrameTransformations,
boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ),
boost::bind( &mapCartesian, _1, _2 ) );
// Set expected accelerations.
const Eigen::Vector3d expectedAccelerationFirstModel
= rotateOverOtherArbitraryAngles(
rotateOverArbitraryAngles( currentPosition / ( currentTime * currentTime ) ) );
const Eigen::Vector3d expectedAccelerationSecondModel
= 0.5 * currentPosition / ( 3.2 * ( currentTime + 3.4 ) * currentTime )
+ currentVelocity / currentTime;
// Set expected (cumulative) Cartesian state derivative.
const Vector6d expectedCartesianStateDerivative
= ( basic_mathematics::Vector6d( ) << currentVelocity,
expectedAccelerationFirstModel + expectedAccelerationSecondModel ).finished( );
// Compute Cartesian state derivative.
const Vector6d computedCartesianStateDerivative
= stateDerivativeModel->computeStateDerivative( currentTime, currentState );
// Check that computed Cartesian state derivative matches expected values.
TUDAT_CHECK_MATRIX_BASE( computedCartesianStateDerivative, expectedCartesianStateDerivative )
BOOST_CHECK_CLOSE_FRACTION( computedCartesianStateDerivative.coeff( row, col ),
expectedCartesianStateDerivative.coeff( row, col ),
5.0e-15 );
}
BOOST_AUTO_TEST_SUITE_END( )
} // namespace unit_tests
} // namespace tudat
| 47.418879
| 99
| 0.71689
|
JPelamatti
|
b183cc19212e409463dc908e2e931782bbd787ca
| 2,702
|
cpp
|
C++
|
hphp/runtime/ext/vsdebug/logging.cpp
|
ActindoForks/hhvm
|
670822e2b396f2d411f4e841b4ec9ae8627ba965
|
[
"PHP-3.01",
"Zend-2.0"
] | null | null | null |
hphp/runtime/ext/vsdebug/logging.cpp
|
ActindoForks/hhvm
|
670822e2b396f2d411f4e841b4ec9ae8627ba965
|
[
"PHP-3.01",
"Zend-2.0"
] | null | null | null |
hphp/runtime/ext/vsdebug/logging.cpp
|
ActindoForks/hhvm
|
670822e2b396f2d411f4e841b4ec9ae8627ba965
|
[
"PHP-3.01",
"Zend-2.0"
] | null | null | null |
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2017-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <time.h>
#include <string>
#include "hphp/runtime/ext/vsdebug/logging.h"
namespace HPHP {
namespace VSDEBUG {
// Linkage for the log file pointer, this is a singleton for the extension.
FILE* VSDebugLogger::s_logFile {nullptr};
void VSDebugLogger::InitializeLogging(std::string& logFilePath) {
if (logFilePath.empty()) {
return;
}
// This is only expected to be invoked once, when the extension is loaded.
assert(s_logFile == nullptr);
// TODO: (Ericblue) Add logic for max file size, log file rotation, etc.
const char* path = logFilePath.c_str();
s_logFile = fopen(path, "a");
if (s_logFile == nullptr) {
return;
}
// Start with a visual delimiter so it's easy to see where
// the session started.
Log(VSDebugLogger::LogLevelInfo, "-------------------------------");
}
void VSDebugLogger::FinalizeLogging() {
if (s_logFile == nullptr) {
return;
}
Log(VSDebugLogger::LogLevelInfo, "VSDebugExtension shutting down.");
Log(VSDebugLogger::LogLevelInfo, "-------------------------------");
LogFlush();
fclose(s_logFile);
s_logFile = nullptr;
}
void VSDebugLogger::Log(const char* level, const char* fmt, ...) {
if (s_logFile == nullptr) {
return;
}
time_t t = time(NULL);
struct tm tm = *localtime(&t);
fprintf(s_logFile,
"[%d-%d-%d %d:%d:%d]",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec
);
fprintf(s_logFile, "[%s]\t", level);
va_list args;
va_start(args, fmt);
vfprintf(s_logFile, fmt, args);
va_end(args);
fprintf(s_logFile, "\n");
}
void VSDebugLogger::LogFlush() {
if (s_logFile == nullptr) {
return;
}
fflush(s_logFile);
}
}
}
| 28.145833
| 76
| 0.53849
|
ActindoForks
|
b18b765b66829e8bd0911bbaaad839d8a9f02ed6
| 26,273
|
hpp
|
C++
|
library/src/blas3/Tensile/gemm.hpp
|
pruthvistony/rocBLAS
|
9463526235e38f505caeaf29cf41bac22c1ab238
|
[
"MIT"
] | null | null | null |
library/src/blas3/Tensile/gemm.hpp
|
pruthvistony/rocBLAS
|
9463526235e38f505caeaf29cf41bac22c1ab238
|
[
"MIT"
] | null | null | null |
library/src/blas3/Tensile/gemm.hpp
|
pruthvistony/rocBLAS
|
9463526235e38f505caeaf29cf41bac22c1ab238
|
[
"MIT"
] | null | null | null |
/* ************************************************************************
* Copyright 2016-2020 Advanced Micro Devices, Inc.
* ************************************************************************ */
#pragma once
#ifndef _GEMM_HOST_HPP_
#define _GEMM_HOST_HPP_
#include "handle.hpp"
#ifdef USE_TENSILE_HOST
#include "tensile_host.hpp"
#else // USE_TENSILE_HOST
/*******************************************************************************
* Helper enumeration over different transpose combinations
******************************************************************************/
typedef enum
{
// First letter refers to A, second letter refers to B
NN,
NT,
TN,
TT,
NC,
CN,
TC,
CT,
CC,
} transpose_mode;
constexpr transpose_mode GetTransposeMode(rocblas_operation trans_a, rocblas_operation trans_b)
{
if(trans_a == rocblas_operation_none)
{
if(trans_b == rocblas_operation_none)
return NN;
if(trans_b == rocblas_operation_conjugate_transpose)
return NC;
return NT;
}
else if(trans_a == rocblas_operation_conjugate_transpose)
{
if(trans_b == rocblas_operation_none)
return CN;
if(trans_b == rocblas_operation_conjugate_transpose)
return CC;
return CT;
}
else
{
if(trans_b == rocblas_operation_none)
return TN;
if(trans_b == rocblas_operation_conjugate_transpose)
return TC;
return TT;
}
}
#include "Tensile.h"
/*******************************************************************************
* Tensile Helper Function call
******************************************************************************/
template <typename T>
rocblas_status tensile_helper(const T& alpha_h,
const T& beta_h,
const T* A,
const T* B,
T* C,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_stride strideC1,
rocblas_stride strideC2,
rocblas_stride strideA1,
rocblas_stride strideA2,
rocblas_stride strideB1,
rocblas_stride strideB2,
rocblas_int sizeI,
rocblas_int sizeJ,
rocblas_int sizeK,
rocblas_int sizeL,
rocblas_handle handle);
#define TENSILE_ARGS(T) \
(T*)C, (const T*)C, (const T*)A, (const T*)B, *((const T*)&alpha_h), *((const T*)&beta_h), \
strideC1, strideC2, strideC1, strideC2, strideA1, strideA2, strideB1, strideB2, sizeI, \
sizeJ, sizeK, sizeL, handle->rocblas_stream, 0, nullptr, nullptr, nullptr
template <>
inline rocblas_status tensile_helper(const rocblas_half& alpha_h,
const rocblas_half& beta_h,
const rocblas_half* A,
const rocblas_half* B,
rocblas_half* C,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_stride strideC1,
rocblas_stride strideC2,
rocblas_stride strideA1,
rocblas_stride strideA2,
rocblas_stride strideB1,
rocblas_stride strideB2,
rocblas_int sizeI,
rocblas_int sizeJ,
rocblas_int sizeK,
rocblas_int sizeL,
rocblas_handle handle)
{
hipError_t status = hipErrorInvalidValue;
switch(GetTransposeMode(trans_a, trans_b))
{
case NN:
status = tensile_Cijk_Ailk_Bljk_HB(TENSILE_ARGS(rocblas_half));
break;
case NT:
case NC:
status = tensile_Cijk_Ailk_Bjlk_HB(TENSILE_ARGS(rocblas_half));
break;
case TN:
case CN:
status = tensile_Cijk_Alik_Bljk_HB(TENSILE_ARGS(rocblas_half));
break;
case TT:
case TC:
case CT:
case CC:
status = tensile_Cijk_Alik_Bjlk_HB(TENSILE_ARGS(rocblas_half));
break;
}
return get_rocblas_status_for_hip_status(status);
}
template <>
inline rocblas_status tensile_helper(const float& alpha_h,
const float& beta_h,
const float* A,
const float* B,
float* C,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_stride strideC1,
rocblas_stride strideC2,
rocblas_stride strideA1,
rocblas_stride strideA2,
rocblas_stride strideB1,
rocblas_stride strideB2,
rocblas_int sizeI,
rocblas_int sizeJ,
rocblas_int sizeK,
rocblas_int sizeL,
rocblas_handle handle)
{
hipError_t status = hipErrorInvalidValue;
switch(GetTransposeMode(trans_a, trans_b))
{
case NN:
status = tensile_Cijk_Ailk_Bljk_SB(TENSILE_ARGS(float));
break;
case NT:
case NC:
status = tensile_Cijk_Ailk_Bjlk_SB(TENSILE_ARGS(float));
break;
case TN:
case CN:
status = tensile_Cijk_Alik_Bljk_SB(TENSILE_ARGS(float));
break;
case TT:
case TC:
case CT:
case CC:
status = tensile_Cijk_Alik_Bjlk_SB(TENSILE_ARGS(float));
break;
}
return get_rocblas_status_for_hip_status(status);
}
template <>
inline rocblas_status tensile_helper(const double& alpha_h,
const double& beta_h,
const double* A,
const double* B,
double* C,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_stride strideC1,
rocblas_stride strideC2,
rocblas_stride strideA1,
rocblas_stride strideA2,
rocblas_stride strideB1,
rocblas_stride strideB2,
rocblas_int sizeI,
rocblas_int sizeJ,
rocblas_int sizeK,
rocblas_int sizeL,
rocblas_handle handle)
{
hipError_t status = hipErrorInvalidValue;
switch(GetTransposeMode(trans_a, trans_b))
{
case NN:
status = tensile_Cijk_Ailk_Bljk_DB(TENSILE_ARGS(double));
break;
case NT:
case NC:
status = tensile_Cijk_Ailk_Bjlk_DB(TENSILE_ARGS(double));
break;
case TN:
case CN:
status = tensile_Cijk_Alik_Bljk_DB(TENSILE_ARGS(double));
break;
case TT:
case TC:
case CT:
case CC:
status = tensile_Cijk_Alik_Bjlk_DB(TENSILE_ARGS(double));
break;
}
return get_rocblas_status_for_hip_status(status);
}
template <>
inline rocblas_status tensile_helper(const rocblas_float_complex& alpha_h,
const rocblas_float_complex& beta_h,
const rocblas_float_complex* A,
const rocblas_float_complex* B,
rocblas_float_complex* C,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_stride strideC1,
rocblas_stride strideC2,
rocblas_stride strideA1,
rocblas_stride strideA2,
rocblas_stride strideB1,
rocblas_stride strideB2,
rocblas_int sizeI,
rocblas_int sizeJ,
rocblas_int sizeK,
rocblas_int sizeL,
rocblas_handle handle)
{
static_assert(std::is_standard_layout<TensileComplexFloat>{},
"TensileComplexFloat is not a standard layout type, and thus is "
"incompatible with C.");
static_assert(std::is_trivial<TensileComplexFloat>{},
"TensileComplexFloat is not a trivial type, and thus is "
"incompatible with C.");
static_assert(sizeof(rocblas_float_complex) == sizeof(TensileComplexFloat),
"TensileComplexFloat does not match rocblas_float_complex");
hipError_t status = hipErrorInvalidValue;
switch(GetTransposeMode(trans_a, trans_b))
{
case NN:
status = tensile_Cijk_Ailk_Bljk_CB(TENSILE_ARGS(TensileComplexFloat));
break;
case NT:
status = tensile_Cijk_Ailk_Bjlk_CB(TENSILE_ARGS(TensileComplexFloat));
break;
case TN:
status = tensile_Cijk_Alik_Bljk_CB(TENSILE_ARGS(TensileComplexFloat));
break;
case TT:
status = tensile_Cijk_Alik_Bjlk_CB(TENSILE_ARGS(TensileComplexFloat));
break;
case NC:
status = tensile_Cijk_Ailk_BjlkC_CB(TENSILE_ARGS(TensileComplexFloat));
break;
case CN:
status = tensile_Cijk_AlikC_Bljk_CB(TENSILE_ARGS(TensileComplexFloat));
break;
case TC:
status = tensile_Cijk_Alik_BjlkC_CB(TENSILE_ARGS(TensileComplexFloat));
break;
case CT:
status = tensile_Cijk_AlikC_Bjlk_CB(TENSILE_ARGS(TensileComplexFloat));
break;
case CC:
status = tensile_Cijk_AlikC_BjlkC_CB(TENSILE_ARGS(TensileComplexFloat));
break;
}
return get_rocblas_status_for_hip_status(status);
}
template <>
inline rocblas_status tensile_helper(const rocblas_double_complex& alpha_h,
const rocblas_double_complex& beta_h,
const rocblas_double_complex* A,
const rocblas_double_complex* B,
rocblas_double_complex* C,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_stride strideC1,
rocblas_stride strideC2,
rocblas_stride strideA1,
rocblas_stride strideA2,
rocblas_stride strideB1,
rocblas_stride strideB2,
rocblas_int sizeI,
rocblas_int sizeJ,
rocblas_int sizeK,
rocblas_int sizeL,
rocblas_handle handle)
{
static_assert(std::is_standard_layout<TensileComplexDouble>{},
"TensileComplexDouble is not a standard layout type, and thus is "
"incompatible with C.");
static_assert(std::is_trivial<TensileComplexDouble>{},
"TensileComplexDouble is not a trivial type, and thus is "
"incompatible with C.");
static_assert(sizeof(rocblas_double_complex) == sizeof(TensileComplexDouble),
"TensileComplexDouble does not match rocblas_double_complex");
hipError_t status = hipErrorInvalidValue;
switch(GetTransposeMode(trans_a, trans_b))
{
case NN:
status = tensile_Cijk_Ailk_Bljk_ZB(TENSILE_ARGS(TensileComplexDouble));
break;
case NT:
status = tensile_Cijk_Ailk_Bjlk_ZB(TENSILE_ARGS(TensileComplexDouble));
break;
case TN:
status = tensile_Cijk_Alik_Bljk_ZB(TENSILE_ARGS(TensileComplexDouble));
break;
case TT:
status = tensile_Cijk_Alik_Bjlk_ZB(TENSILE_ARGS(TensileComplexDouble));
break;
case NC:
status = tensile_Cijk_Ailk_BjlkC_ZB(TENSILE_ARGS(TensileComplexDouble));
break;
case CN:
status = tensile_Cijk_AlikC_Bljk_ZB(TENSILE_ARGS(TensileComplexDouble));
break;
case TC:
status = tensile_Cijk_Alik_BjlkC_ZB(TENSILE_ARGS(TensileComplexDouble));
break;
case CT:
status = tensile_Cijk_AlikC_Bjlk_ZB(TENSILE_ARGS(TensileComplexDouble));
break;
case CC:
status = tensile_Cijk_AlikC_BjlkC_ZB(TENSILE_ARGS(TensileComplexDouble));
break;
}
return get_rocblas_status_for_hip_status(status);
}
#undef TENSILE_ARGS
#endif // USE_TENSILE_HOST
/*********************************************************************************
* Right now Tensile requires alpha and beta to be passed by value on host. *
* If in device pointer mode, copy alpha and beta to host. *
* If k == 0, we set alpha = 0 instead of copying from device. *
* TODO: Make this asynchronous, putting synchronization closer to Tensile call. *
*********************************************************************************/
template <typename T, typename Tc>
rocblas_status copy_alpha_beta_to_host_if_on_device(
rocblas_handle handle, const T*& alpha, const T*& beta, Tc& alpha_h, Tc& beta_h, rocblas_int k)
{
if(handle->pointer_mode == rocblas_pointer_mode_device)
{
if(alpha)
{
if(k == 0)
alpha_h = 0;
else
RETURN_IF_HIP_ERROR(hipMemcpy(&alpha_h, alpha, sizeof(Tc), hipMemcpyDeviceToHost));
alpha = &alpha_h;
}
if(beta)
{
RETURN_IF_HIP_ERROR(hipMemcpy(&beta_h, beta, sizeof(Tc), hipMemcpyDeviceToHost));
beta = &beta_h;
}
}
return rocblas_status_success;
}
/*******************************************************************************
* Tensile Function call
******************************************************************************/
template <typename T>
inline rocblas_status call_tensile(rocblas_handle handle,
const T* alpha,
const T* beta,
const T* A,
const T* B,
T* C,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_int ld_c,
rocblas_stride stride_c,
rocblas_int ld_a,
rocblas_stride stride_a,
rocblas_int ld_b,
rocblas_stride stride_b,
rocblas_int m,
rocblas_int n,
rocblas_int k,
rocblas_int batch_count = 1)
{
#ifdef USE_TENSILE_HOST
RocblasContractionProblem<T> problem{handle,
trans_a,
trans_b,
m,
n,
k,
alpha,
A,
ld_a,
stride_a,
B,
ld_b,
stride_b,
beta,
C,
ld_c,
stride_c,
batch_count};
return runContractionProblem(problem);
#else // USE_TENSILE_HOST
return tensile_helper(*alpha,
*beta,
A,
B,
C,
trans_a,
trans_b,
ld_c,
stride_c,
ld_a,
stride_a,
ld_b,
stride_b,
m,
n,
batch_count,
k,
handle);
#endif // USE_TENSILE_HOST
}
/*******************************************************************************
* Validate Arguments
******************************************************************************/
template <typename T>
inline rocblas_status validateArgs(rocblas_handle handle,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_int m,
rocblas_int n,
rocblas_int k,
const T* alpha,
const void* a,
rocblas_int ld_a,
const void* b,
rocblas_int ld_b,
const T* beta,
const void* c,
rocblas_int ld_c,
rocblas_int batch_count = 1)
{
// handle must be valid
if(!handle)
return rocblas_status_invalid_handle;
// sizes must not be negative
if(m < 0 || n < 0 || k < 0 || batch_count < 0)
return rocblas_status_invalid_size;
rocblas_int num_rows_a = trans_a == rocblas_operation_none ? m : k;
rocblas_int num_rows_b = trans_b == rocblas_operation_none ? k : n;
rocblas_int num_rows_c = m;
// leading dimensions must be valid
if(num_rows_a > ld_a || num_rows_b > ld_b || num_rows_c > ld_c)
return rocblas_status_invalid_size;
// quick return 0 is valid in BLAS
// Note: k==0 is not a quick return, because C must still be multiplied by beta
if(!m || !n || !batch_count)
return rocblas_status_success;
if(!beta)
return rocblas_status_invalid_pointer;
if(handle->pointer_mode == rocblas_pointer_mode_host && *beta == 1)
{
if(!k)
return rocblas_status_success;
if(!alpha)
return rocblas_status_invalid_pointer;
if(!*alpha)
return rocblas_status_success;
}
// pointers must be valid
if((k && (!a || !b || !alpha)) || !c)
return rocblas_status_invalid_pointer;
return rocblas_status_continue;
}
/*
* ===========================================================================
* template interface
* ===========================================================================
*/
template <bool BATCHED, typename T, typename U, typename V>
ROCBLAS_EXPORT_NOINLINE rocblas_status rocblas_gemm_template(rocblas_handle handle,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_int m,
rocblas_int n,
rocblas_int k,
const T* alpha,
const U* A,
rocblas_int offset_a,
rocblas_int ld_a,
rocblas_stride stride_a,
const U* B,
rocblas_int offset_b,
rocblas_int ld_b,
rocblas_stride stride_b,
const T* beta,
V* C,
rocblas_int offset_c,
rocblas_int ld_c,
rocblas_stride stride_c,
rocblas_int batch_count)
{
// Early exit. Note: k==0 is not an early exit, since C still needs to be multiplied by beta.
if(m == 0 || n == 0 || batch_count == 0)
return rocblas_status_success;
// Temporarily change the thread's default device ID to the handle's device ID
auto saved_device_id = handle->push_device_id();
T alpha_h, beta_h;
RETURN_IF_ROCBLAS_ERROR(
copy_alpha_beta_to_host_if_on_device(handle, alpha, beta, alpha_h, beta_h, k));
// When beta == 1 and either k == 0 or alpha == 0, the operation is a no-op
if(*beta == 1 && (k == 0 || *alpha == 0))
return rocblas_status_success;
rocblas_status status = rocblas_status_success;
// TODO: Use C++17 constexpr if
if(BATCHED)
{
// We cannot do this with a device array, so array of pointers must be on host for now
// Host arrays of device pointers.
auto hostA = std::make_unique<T*[]>(batch_count);
auto hostB = std::make_unique<T*[]>(batch_count);
auto hostC = std::make_unique<T*[]>(batch_count);
RETURN_IF_HIP_ERROR(
hipMemcpy(&hostA[0], A, sizeof(T*) * batch_count, hipMemcpyDeviceToHost));
RETURN_IF_HIP_ERROR(
hipMemcpy(&hostB[0], B, sizeof(T*) * batch_count, hipMemcpyDeviceToHost));
RETURN_IF_HIP_ERROR(
hipMemcpy(&hostC[0], C, sizeof(T*) * batch_count, hipMemcpyDeviceToHost));
for(rocblas_int b = 0; b < batch_count; b++)
{
status = call_tensile(handle,
alpha,
beta,
hostA[b] + offset_a,
hostB[b] + offset_b,
hostC[b] + offset_c,
trans_a,
trans_b,
ld_c,
stride_c,
ld_a,
stride_a,
ld_b,
stride_b,
m,
n,
k);
if(status != rocblas_status_success)
break;
}
}
else
{
// The (T*) casts are to prevent template deduction errors when BATCHED==true and the A, B, C
// pointers are pointers to arrays of pointers. constexpr if(BATCHED) above could avoid this.
status = call_tensile(handle,
alpha,
beta,
(T*)A + offset_a,
(T*)B + offset_b,
(T*)C + offset_c,
trans_a,
trans_b,
ld_c,
stride_c,
ld_a,
stride_a,
ld_b,
stride_b,
m,
n,
k,
batch_count);
}
return status;
}
#endif // _GEMM_HOST_HPP_
| 40.670279
| 101
| 0.421954
|
pruthvistony
|
b18c662df9a7d74637ad3540d633f3a069954954
| 3,761
|
cpp
|
C++
|
plugins/dmetaphone/dmetaphone.cpp
|
miguelvazq/HPCC-Platform
|
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
|
[
"Apache-2.0"
] | 286
|
2015-01-03T12:45:17.000Z
|
2022-03-25T18:12:57.000Z
|
plugins/dmetaphone/dmetaphone.cpp
|
miguelvazq/HPCC-Platform
|
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
|
[
"Apache-2.0"
] | 9,034
|
2015-01-02T08:49:19.000Z
|
2022-03-31T20:34:44.000Z
|
plugins/dmetaphone/dmetaphone.cpp
|
cloLN/HPCC-Platform
|
42ffb763a1cdcf611d3900831973d0a68e722bbe
|
[
"Apache-2.0"
] | 208
|
2015-01-02T03:27:28.000Z
|
2022-02-11T05:54:52.000Z
|
#include "platform.h"
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include "dmetaphone.hpp"
#include "metaphone.h"
#define DMETAPHONE_VERSION "DMETAPHONE 1.1.05"
static const char * compatibleVersions[] = {
"DMETAPHONE 1.1.05 [0e64c86ec1d5771d4ce0abe488a98a2a]",
"DMETAPHONE 1.1.05",
NULL };
DMETAPHONE_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
{
if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
{
ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb;
pbx->compatibleVersions = compatibleVersions;
}
else if (pb->size != sizeof(ECLPluginDefinitionBlock))
return false;
pb->magicVersion = PLUGIN_VERSION;
pb->version = DMETAPHONE_VERSION;
pb->moduleName = "lib_metaphone";
pb->ECL = NULL; // Definition is in lib_metaphone.ecllib
pb->flags = PLUGIN_IMPLICIT_MODULE;
pb->description = "Metaphone library";
return true;
}
namespace nsDmetaphone {
IPluginContext * parentCtx = NULL;
}
using namespace nsDmetaphone;
DMETAPHONE_API void setPluginContext(IPluginContext * _ctx) { parentCtx = _ctx; }
DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone1(size32_t & __ret_len,char * & __ret_str,unsigned _len_instr,const char * instr)
{
cString metaph;
cString metaph2;
MString ms;
ms.Set(instr, _len_instr);
ms.DoubleMetaphone(metaph, metaph2);
__ret_len = strlen((char*) metaph);
__ret_str = (char *) CTXMALLOC(parentCtx, __ret_len+1);
strcpy(__ret_str, (char*) metaph);
}
DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone2(size32_t & __ret_len,char * & __ret_str,unsigned _len_instr,const char * instr)
{
cString metaph;
cString metaph2;
MString ms;
ms.Set(instr, _len_instr);
ms.DoubleMetaphone(metaph, metaph2);
__ret_len = strlen((char*) metaph2);
__ret_str = (char *) CTXMALLOC(parentCtx, __ret_len+1);
strcpy(__ret_str, (char*) metaph2);
}
DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphoneBoth(size32_t & __ret_len,char * & __ret_str,unsigned _len_instr,const char * instr)
{
cString metaph;
cString metaph2;
MString ms;
ms.Set(instr, _len_instr);
ms.DoubleMetaphone(metaph, metaph2);
__ret_len = strlen((char*) metaph) + strlen((char*) metaph2);
__ret_str = (char *) CTXMALLOC(parentCtx, __ret_len+1);
strcpy(__ret_str, (char*) metaph);
strcat(__ret_str, (char*) metaph2);
}
DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone1_20(char * __ret_str,unsigned _len_instr,const char * instr)
{
cString metaph;
cString metaph2;
MString ms;
ms.Set(instr, _len_instr);
ms.DoubleMetaphone(metaph, metaph2);
memset(__ret_str, ' ', 20);
size32_t metaph_len = strlen((char*) metaph);
strncpy(__ret_str, (char*) metaph, (metaph_len > 20)?20:metaph_len);
}
DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone2_20(char * __ret_str,unsigned _len_instr,const char * instr)
{
cString metaph;
cString metaph2;
MString ms;
ms.Set(instr, _len_instr);
ms.DoubleMetaphone(metaph, metaph2);
memset(__ret_str, ' ', 20);
size32_t metaph2_len = strlen((char*) metaph2);
strncpy(__ret_str, (char*) metaph2, (metaph2_len > 20)?20:metaph2_len);
}
DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphoneBoth_40(char * __ret_str,unsigned _len_instr,const char * instr)
{
cString metaph;
cString metaph2;
MString ms;
ms.Set(instr, _len_instr);
ms.DoubleMetaphone(metaph, metaph2);
memset(__ret_str, ' ', 40);
size32_t metaph_len = strlen((char*) metaph);
strncpy(__ret_str, (char*) metaph, (metaph_len > 20)?20:metaph_len);
size32_t metaph2_len = strlen((char*) metaph2);
strncpy(__ret_str+metaph_len, (char*) metaph2, (metaph2_len > 20)?20:metaph2_len);
}
| 31.605042
| 132
| 0.708588
|
miguelvazq
|
b18d55a2d3735b5c31fd9acc502cf9a8bdb3f5ee
| 788
|
hpp
|
C++
|
tutorial/eos-docker/contracts/asserter/asserter.abi.hpp
|
alex-public/online-smart-storage
|
3d066f8728b645d98cd786c2c2f637399669444b
|
[
"MIT"
] | null | null | null |
tutorial/eos-docker/contracts/asserter/asserter.abi.hpp
|
alex-public/online-smart-storage
|
3d066f8728b645d98cd786c2c2f637399669444b
|
[
"MIT"
] | null | null | null |
tutorial/eos-docker/contracts/asserter/asserter.abi.hpp
|
alex-public/online-smart-storage
|
3d066f8728b645d98cd786c2c2f637399669444b
|
[
"MIT"
] | 2
|
2018-11-12T21:42:44.000Z
|
2019-04-25T07:28:37.000Z
|
const char* const asserter_abi = R"=====(
{
"version": "eosio::abi/1.0",
"types": [],
"structs": [
{
"name": "assertdef",
"base": "",
"fields": [
{
"name": "condition",
"type": "int8"
},{
"name": "message",
"type": "string"
}
]
}, {
"name": "nothing",
"base": "",
"fields": []
}
],
"actions": [
{
"name": "procassert",
"type": "assertdef",
"ricardian_contract": ""
}, {
"name": "provereset",
"type": "nothing",
"ricardian_contract": ""
}
],
"tables": [],
"ricardian_clauses": [],
"abi_extensions": []
}
)=====";
| 19.7
| 41
| 0.347716
|
alex-public
|
b18d7cab6b3cb369c34fda45e9bfc0ab8c6eee57
| 1,078
|
hpp
|
C++
|
src/ast/ast_var_decl.hpp
|
Wassasin/splicpp
|
b88bf8ec18985bc6ee5a8ccb952f413f23d74c5a
|
[
"Beerware"
] | 2
|
2019-04-09T01:04:36.000Z
|
2019-05-12T06:17:03.000Z
|
src/ast/ast_var_decl.hpp
|
Wassasin/splicpp
|
b88bf8ec18985bc6ee5a8ccb952f413f23d74c5a
|
[
"Beerware"
] | null | null | null |
src/ast/ast_var_decl.hpp
|
Wassasin/splicpp
|
b88bf8ec18985bc6ee5a8ccb952f413f23d74c5a
|
[
"Beerware"
] | null | null | null |
#ifndef AST_VAR_DECL_H
#define AST_VAR_DECL_H
#include <memory>
#include "ast.hpp"
#include "../common/typedefs.hpp"
#include "../typing/substitution.hpp"
namespace splicpp
{
class ast_type;
class ast_exp;
class ast_id;
class symboltable;
class varcontext;
class typecontext;
class ltypecontext;
class sl_type;
class ir_stmt;
class ircontext;
class ast_var_decl : public ast
{
public:
const s_ptr<ast_type> t;
const s_ptr<ast_id> id;
const s_ptr<ast_exp> exp;
ast_var_decl(__decltype(t) t, __decltype(id) id, __decltype(exp) exp, const sloc sl)
: ast(sl)
, t(t)
, id(id)
, exp(exp)
{}
void assign(sid i);
std::string fetch_name() const;
sid fetch_id() const;
void assign_ids(const varcontext& c);
void register_types(symboltable& s, varcontext& c);
s_ptr<const sl_type> fetch_assigned_type(const typecontext& c) const;
substitution declare_type(ltypecontext& c) const;
s_ptr<const ir_stmt> translate(const ircontext& c) const;
virtual void pretty_print(std::ostream& s, const uint tab) const;
};
}
#endif
| 19.6
| 86
| 0.714286
|
Wassasin
|
b18d8212b9015540071f5512237d4d6356dc1bfe
| 64,921
|
cpp
|
C++
|
test/localPRG_test.cpp
|
rffrancon/pandora
|
5786548a1a1111a4990f0b8a6ec3335e4d1a5319
|
[
"MIT"
] | null | null | null |
test/localPRG_test.cpp
|
rffrancon/pandora
|
5786548a1a1111a4990f0b8a6ec3335e4d1a5319
|
[
"MIT"
] | null | null | null |
test/localPRG_test.cpp
|
rffrancon/pandora
|
5786548a1a1111a4990f0b8a6ec3335e4d1a5319
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include "test_macro.cpp"
#include "localPRG.h"
#include "minimizer.h"
#include "minirecord.h"
#include "minihit.h"
#include "interval.h"
#include "prg/path.h"
#include "localgraph.h"
#include "localnode.h"
#include "index.h"
#include "inthash.h"
#include "pangenome/pannode.h"
#include "pangenome/panread.h"
#include "utils.h"
#include "seq.h"
#include "kmergraph.h"
#include "kmernode.h"
#include <stdint.h>
#include <iostream>
using namespace std;
TEST(LocalPRGTest, create) {
LocalPRG l0(0, "empty", "");
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
uint32_t j = 0;
EXPECT_EQ(j, l0.id);
EXPECT_EQ("empty", l0.name);
EXPECT_EQ("", l0.seq);
j = 1;
EXPECT_EQ(j, l1.id);
EXPECT_EQ("simple", l1.name);
EXPECT_EQ("AGCT", l1.seq);
j = 2;
EXPECT_EQ(j, l2.id);
EXPECT_EQ("varsite", l2.name);
EXPECT_EQ("A 5 GC 6 G 5 T", l2.seq);
j = 3;
EXPECT_EQ(j, l3.id);
EXPECT_EQ("nested varsite", l3.name);
EXPECT_EQ("A 5 G 7 C 8 T 7 6 G 5 T", l3.seq);
}
TEST(LocalPRGTest, isalphaEmptyString) {
LocalPRG l0(0, "empty", "");
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
bool a0 = l0.isalpha_string("");
bool a1 = l1.isalpha_string("");
bool a2 = l2.isalpha_string("");
bool a3 = l3.isalpha_string("");
EXPECT_EQ(a0, 1) << "isalpha_string thinks the empty string is not alphabetic for l0";
EXPECT_EQ(a1, 1) << "isalpha_string thinks the empty string is not alphabetic for l1";
EXPECT_EQ(a2, 1) << "isalpha_string thinks the empty string is not alphabetic for l2";
EXPECT_EQ(a3, 1) << "isalpha_string thinks the empty string is not alphabetic for l3";
}
TEST(LocalPRGTest, isalphaSpaceString) {
LocalPRG l0(0, "empty", "");
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
bool a0 = l0.isalpha_string("AGCT T");
bool a1 = l1.isalpha_string("AGCT T");
bool a2 = l2.isalpha_string("AGCT T");
bool a3 = l3.isalpha_string("AGCT T");
EXPECT_EQ(a0, 0) << "isalpha_string thinks a string containing a space is alphabetic for l0";
EXPECT_EQ(a1, 0) << "isalpha_string thinks a string containing a space is alphabetic for l1";
EXPECT_EQ(a2, 0) << "isalpha_string thinks a string containing a space is alphabetic for l2";
EXPECT_EQ(a3, 0) << "isalpha_string thinks a string containing a space is alphabetic for l3";
}
TEST(LocalPRGTest, isalphaNumberString) {
LocalPRG l0(0, "empty", "");
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
bool a0 = l0.isalpha_string("AGCT 8 T");
bool a1 = l1.isalpha_string("AGCT 8 T");
bool a2 = l2.isalpha_string("AGCT 8 T");
bool a3 = l3.isalpha_string("AGCT 8 T");
EXPECT_EQ(a0, 0) << "isalpha_string thinks a string containing a number is alphabetic for l0";
EXPECT_EQ(a1, 0) << "isalpha_string thinks a string containing a number is alphabetic for l1";
EXPECT_EQ(a2, 0) << "isalpha_string thinks a string containing a number is alphabetic for l2";
EXPECT_EQ(a3, 0) << "isalpha_string thinks a string containing a number is alphabetic for l3";
}
TEST(LocalPRGTest, string_along_path) {
LocalPRG l0(0, "empty", "");
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
// empty interval
deque<Interval> d = {Interval(0, 0)};
Path p;
p.initialize(d);
EXPECT_EQ("", l0.string_along_path(p));
EXPECT_EQ("", l1.string_along_path(p));
EXPECT_EQ("", l2.string_along_path(p));
EXPECT_EQ("", l3.string_along_path(p));
// positive length interval
d = {Interval(1, 3)};
p.initialize(d);
EXPECT_EQ("GC", l1.string_along_path(p));
EXPECT_EQ(" 5", l2.string_along_path(p));
EXPECT_EQ(" 5", l3.string_along_path(p));
// multiple intervals
d = {Interval(0, 1), Interval(2, 3)};
p.initialize(d);
EXPECT_EQ("AC", l1.string_along_path(p));
EXPECT_EQ("A5", l2.string_along_path(p));
EXPECT_EQ("A5", l3.string_along_path(p));
// including empty interval
d = {Interval(0, 1), Interval(2, 2)};
p.initialize(d);
EXPECT_EQ("A", l1.string_along_path(p));
EXPECT_EQ("A", l2.string_along_path(p));
EXPECT_EQ("A", l3.string_along_path(p));
// forbidden paths
d = {Interval(2, 3), Interval(13, 25)};
p.initialize(d);
EXPECT_DEATH(l1.string_along_path(p), "");
EXPECT_DEATH(l1.string_along_path(p), "");
EXPECT_DEATH(l2.string_along_path(p), "");
EXPECT_DEATH(l3.string_along_path(p), "");
}
TEST(LocalPRGTest, string_along_localpath) {
LocalPRG l0(0, "empty", "");
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
// empty interval
vector<LocalNodePtr> p = {l0.prg.nodes[0]};
EXPECT_EQ("", l0.string_along_path(p));
p = {l1.prg.nodes[0]};
EXPECT_EQ("AGCT", l1.string_along_path(p));
// extract from intervals
p = {l2.prg.nodes[0], l2.prg.nodes[1]};
EXPECT_EQ("AGC", l2.string_along_path(p));
p = {l2.prg.nodes[0], l2.prg.nodes[2], l2.prg.nodes[3]};
EXPECT_EQ("AGT", l2.string_along_path(p));
}
TEST(LocalPRGTest, nodes_along_path) {
LocalPRG l0(0, "empty", "");
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
// empty interval expects no nodes along
deque<Interval> d = {Interval(0, 0)};
Path p;
p.initialize(d);
vector<LocalNodePtr> v;
//EXPECT_EQ(v, l0.nodes_along_path(p));
EXPECT_EQ(v, l1.nodes_along_path(p));
EXPECT_EQ(v, l2.nodes_along_path(p));
EXPECT_EQ(v, l3.nodes_along_path(p));
// positive length interval
d = {Interval(1, 3)};
p.initialize(d);
uint32_t j = 1;
EXPECT_EQ(j, l1.nodes_along_path(p).size());
j = 0;
EXPECT_EQ(j, l1.nodes_along_path(p)[0]->id);
EXPECT_EQ(j, l2.nodes_along_path(p).size()); // no nodes in this interval
EXPECT_EQ(j, l3.nodes_along_path(p).size());
// different interval
d = {Interval(4, 5)};
p.initialize(d);
j = 1;
EXPECT_EQ(j, l2.nodes_along_path(p).size());
EXPECT_EQ(j, l3.nodes_along_path(p).size());
EXPECT_EQ(j, l2.nodes_along_path(p)[0]->id);
EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id);
// multiple intervals
d = {Interval(0, 1), Interval(4, 5)};
p.initialize(d);
j = 1;
EXPECT_EQ(j, l1.nodes_along_path(p).size());
j = 2;
EXPECT_EQ(j, l2.nodes_along_path(p).size());
EXPECT_EQ(j, l3.nodes_along_path(p).size());
j = 0;
EXPECT_EQ(j, l1.nodes_along_path(p)[0]->id);
EXPECT_EQ(j, l2.nodes_along_path(p)[0]->id);
EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id);
j = 1;
EXPECT_EQ(j, l2.nodes_along_path(p)[1]->id);
EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id);
// including empty interval
d = {Interval(12, 13), Interval(16, 16), Interval(23, 24)};
p.initialize(d);
j = 3;
vector<LocalNodePtr> w = l3.nodes_along_path(p);
EXPECT_EQ(j, w.size());
EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id);
j = 4;
EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id);
j = 6;
EXPECT_EQ(j, l3.nodes_along_path(p)[2]->id);
// a path with an empty node at end
d = {Interval(12, 13), Interval(16, 16), Interval(23, 23)};
p.initialize(d);
j = 3;
w = l3.nodes_along_path(p);
EXPECT_EQ(j, w.size());
EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id);
j = 4;
EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id);
j = 6;
EXPECT_EQ(j, l3.nodes_along_path(p)[2]->id);
// and a path which ends on a null node
d = {Interval(12, 13), Interval(16, 16)};
p.initialize(d);
j = 2;
w = l3.nodes_along_path(p);
EXPECT_EQ(j, w.size());
j = 3;
EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id);
j = 4;
EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id);
// and a path that can't really exist still works
d = {Interval(12, 13), Interval(19, 20)};
p.initialize(d);
j = 2;
EXPECT_EQ(j, l3.nodes_along_path(p).size());
j = 3;
EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id);
j = 5;
EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id);
}
TEST(LocalPRGTest, split_by_siteNoSites) {
LocalPRG l0(0, "empty", "");
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
vector<Interval> v0, v1;
v0.push_back(Interval(0, 0));
EXPECT_ITERABLE_EQ(vector<Interval>, v0,
l0.split_by_site(Interval(0, 0)));// << "Failed to split empty string with input Interval";
v1.push_back(Interval(0, 4));
EXPECT_ITERABLE_EQ(vector<Interval>, v1,
l1.split_by_site(Interval(0, 4)));// << "Failed to split string with input Interval";
v1.clear();
v1.push_back(Interval(0, 2));
EXPECT_ITERABLE_EQ(vector<Interval>, v1,
l1.split_by_site(Interval(0, 2)));// << "Failed to split string with short input Interval";
v1.clear();
v1.push_back(Interval(1, 3));
EXPECT_ITERABLE_EQ(vector<Interval>, v1,
l1.split_by_site(Interval(1, 3)));// << "Failed to split string with middle input Interval";
}
TEST(LocalPRGTest, split_by_siteSite) {
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
vector<Interval> v2;
v2.push_back(Interval(0, 1));
l2.next_site = 5;
EXPECT_ITERABLE_EQ(vector<Interval>, v2,
l2.split_by_site(Interval(0, 1)));// << "Failed to split string in Interval" << Interval(0,1);
EXPECT_ITERABLE_EQ(vector<Interval>, v2,
l2.split_by_site(Interval(0, 2)));// << "Failed to split string in Interval" << Interval(0,2);
EXPECT_ITERABLE_EQ(vector<Interval>, v2,
l2.split_by_site(Interval(0, 3)));// << "Failed to split string in Interval" << Interval(0,3);
//EXPECT_ITERABLE_EQ( vector< Interval >,v2, l2.split_by_site(Interval(0,4)));// << "Failed to split string in Interval" << Interval(0,4);
v2.push_back(Interval(4, 6));
EXPECT_ITERABLE_EQ(vector<Interval>, v2,
l2.split_by_site(Interval(0, 6)));// << "Failed to split string in Interval" << Interval(0,6);
EXPECT_ITERABLE_EQ(vector<Interval>, v2,
l2.split_by_site(Interval(0, 7)));// << "Failed to split string in Interval" << Interval(0,7);
EXPECT_ITERABLE_EQ(vector<Interval>, v2,
l2.split_by_site(Interval(0, 8)));// << "Failed to split string in Interval" << Interval(0,8);
v2.push_back(Interval(9, 10));
EXPECT_ITERABLE_EQ(vector<Interval>, v2,
l2.split_by_site(Interval(0, 10)));// << "Failed to split string in Interval" << Interval(0,10);
EXPECT_ITERABLE_EQ(vector<Interval>, v2,
l2.split_by_site(Interval(0, 11)));// << "Failed to split string in Interval" << Interval(0,11);
EXPECT_ITERABLE_EQ(vector<Interval>, v2,
l2.split_by_site(Interval(0, 12)));// << "Failed to split string in Interval" << Interval(0,12);
v2.push_back(Interval(13, 14));
EXPECT_ITERABLE_EQ(vector<Interval>, v2,
l2.split_by_site(Interval(0, 14)));// << "Failed to split string in Interval" << Interval(0,14);
v2.clear();
v2.push_back(Interval(5, 6));
EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(
Interval(5, 8)));// << "Failed to split string in mid Interval" << Interval(5,8);
}
TEST(LocalPRGTest, split_by_siteNestedSite) {
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
LocalPRG l4(4, "nested varsite start immediately", " 5 G 7 C 8 T 7 6 G 5 ");
vector<Interval> v3;
v3.push_back(Interval(0, 1));
l3.next_site = 5;
EXPECT_ITERABLE_EQ(vector<Interval>, v3,
l3.split_by_site(Interval(0, 1)));// << "Failed to split string in Interval" << Interval(0,1);
EXPECT_ITERABLE_EQ(vector<Interval>, v3,
l3.split_by_site(Interval(0, 2)));// << "Failed to split string in Interval" << Interval(0,2);
EXPECT_ITERABLE_EQ(vector<Interval>, v3,
l3.split_by_site(Interval(0, 3)));// << "Failed to split string in Interval" << Interval(0,3);
//EXPECT_ITERABLE_EQ( vector< Interval >,v3, l3.split_by_site(Interval(0,4)));// << "Failed to split string in Interval" << Interval(0,4);
v3.push_back(Interval(4, 16));
EXPECT_ITERABLE_EQ(vector<Interval>, v3,
l3.split_by_site(Interval(0, 16)));// << "Failed to split string in Interval" << Interval(0,6);
EXPECT_ITERABLE_EQ(vector<Interval>, v3,
l3.split_by_site(Interval(0, 17)));// << "Failed to split string in Interval" << Interval(0,7);
EXPECT_ITERABLE_EQ(vector<Interval>, v3,
l3.split_by_site(Interval(0, 18)));// << "Failed to split string in Interval" << Interval(0,8);
v3.push_back(Interval(19, 20));
EXPECT_ITERABLE_EQ(vector<Interval>, v3,
l3.split_by_site(Interval(0, 20)));// << "Failed to split string in Interval" << Interval(0,10);
EXPECT_ITERABLE_EQ(vector<Interval>, v3,
l3.split_by_site(Interval(0, 21)));// << "Failed to split string in Interval" << Interval(0,11);
EXPECT_ITERABLE_EQ(vector<Interval>, v3,
l3.split_by_site(Interval(0, 22)));// << "Failed to split string in Interval" << Interval(0,12);
v3.push_back(Interval(23, 24));
EXPECT_ITERABLE_EQ(vector<Interval>, v3,
l3.split_by_site(Interval(0, 24)));// << "Failed to split string in Interval" << Interval(0,14);
l3.next_site = 7;
v3.clear();
v3.push_back(Interval(4, 5));
v3.push_back(Interval(8, 9));
v3.push_back(Interval(12, 13));
v3.push_back(Interval(16, 16));
EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(
Interval(4, 16)));// << "Failed to split string in mid Interval" << Interval(5,8);
vector<Interval> v4;
v4.push_back(Interval(0, 0));
l4.next_site = 5;
EXPECT_ITERABLE_EQ(vector<Interval>, v4,
l4.split_by_site(Interval(0, 1)));// << "Failed to split string in Interval" << Interval(0,1);
EXPECT_ITERABLE_EQ(vector<Interval>, v4,
l4.split_by_site(Interval(0, 2)));// << "Failed to split string in Interval" << Interval(0,2);
v4.push_back(Interval(3, 15));
EXPECT_ITERABLE_EQ(vector<Interval>, v4,
l4.split_by_site(Interval(0, 15)));// << "Failed to split string in Interval" << Interval(0,6);
EXPECT_ITERABLE_EQ(vector<Interval>, v4,
l4.split_by_site(Interval(0, 16)));// << "Failed to split string in Interval" << Interval(0,7);
EXPECT_ITERABLE_EQ(vector<Interval>, v4,
l4.split_by_site(Interval(0, 17)));// << "Failed to split string in Interval" << Interval(0,8);
v4.push_back(Interval(18, 19));
EXPECT_ITERABLE_EQ(vector<Interval>, v4,
l4.split_by_site(Interval(0, 19)));// << "Failed to split string in Interval" << Interval(0,10);
EXPECT_ITERABLE_EQ(vector<Interval>, v4,
l4.split_by_site(Interval(0, 20)));// << "Failed to split string in Interval" << Interval(0,11);
l4.next_site = 7;
v4.clear();
v4.push_back(Interval(0, 4));
v4.push_back(Interval(7, 8));
v4.push_back(Interval(11, 12));
v4.push_back(Interval(15, 22));
EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(
Interval(0, 22)));// << "Failed to split string in mid Interval" << Interval(5,8);
}
TEST(LocalPRGTest, build_graph) {
LocalPRG l0(0, "empty", "");
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
LocalGraph lg0;
lg0.add_node(0, "", Interval(0, 0));
EXPECT_EQ(lg0, l0.prg);
LocalGraph lg1;
lg1.add_node(0, "AGCT", Interval(0, 4));
EXPECT_EQ(lg1, l1.prg);
LocalGraph lg2;
lg2.add_node(0, "A", Interval(0, 1));
lg2.add_node(1, "GC", Interval(4, 6));
lg2.add_node(2, "G", Interval(9, 10));
lg2.add_node(3, "T", Interval(13, 14));
lg2.add_edge(0, 1);
lg2.add_edge(0, 2);
lg2.add_edge(1, 3);
lg2.add_edge(2, 3);
EXPECT_EQ(lg2, l2.prg);
LocalGraph lg3;
lg3.add_node(0, "A", Interval(0, 1));
lg3.add_node(1, "G", Interval(4, 5));
lg3.add_node(2, "C", Interval(8, 9));
lg3.add_node(3, "T", Interval(12, 13));
lg3.add_node(4, "", Interval(16, 16));
lg3.add_node(5, "G", Interval(19, 20));
lg3.add_node(6, "T", Interval(23, 24));
lg3.add_edge(0, 1);
lg3.add_edge(0, 5);
lg3.add_edge(1, 2);
lg3.add_edge(1, 3);
lg3.add_edge(2, 4);
lg3.add_edge(3, 4);
lg3.add_edge(4, 6);
lg3.add_edge(5, 6);
EXPECT_EQ(lg3, l3.prg);
}
TEST(LocalPRGTest, shift) {
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "AT 5 G 7 C 8 T 7 6 G 5 T");
//LocalPRG l4(4, "much more complex", "TCATTC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AGCTG");
LocalPRG l5(5, "one with lots of null at start and end, and a long stretch in between",
" 5 7 9 11 AGTTCTGAAACATTGCGCGTGAGATCTCTG 12 T 11 10 A 9 8 C 7 6 G 5 ");
LocalPRG l6(6, "one representing a possible deletion at end", "GATCTCTAG 5 TTATG 6 5 ");
deque<Interval> d = {Interval(0, 3)};
Path p, q;
p.initialize(d);
d = {Interval(1, 4)};
q.initialize(d);
vector<Path> v_exp = {q};
EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l1.shift(p));
v_exp.clear();
EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l1.shift(q)); // there are no shifts over end of prg
d = {Interval(0, 1), Interval(4, 6)};
p.initialize(d);
d = {Interval(4, 6), Interval(13, 14)};
q.initialize(d);
v_exp = {q};
EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l2.shift(p));
v_exp.clear();
EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l2.shift(q));
v_exp.clear();
d = {Interval(0, 2)};
p.initialize(d);
d = {Interval(1, 2), Interval(5, 6)};
q.initialize(d);
v_exp.push_back(q);
d = {Interval(1, 2), Interval(20, 21)};
q.initialize(d);
v_exp.push_back(q);
EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l3.shift(p));
v_exp.clear();
d = {Interval(1, 2), Interval(5, 6)};
p.initialize(d);
d = {Interval(5, 6), Interval(9, 10)};
q.initialize(d);
v_exp.push_back(q);
d = {Interval(5, 6), Interval(13, 14)};
q.initialize(d);
v_exp.push_back(q);
EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l3.shift(p));
v_exp.clear();
d = {Interval(0, 0), Interval(3, 3), Interval(6, 6), Interval(9, 9), Interval(13, 18)};
p.initialize(d);
d = {Interval(14, 19)};
q.initialize(d);
v_exp.push_back(q);
EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l5.shift(p));
v_exp.clear();
d = {Interval(3, 8)};
p.initialize(d);
d = {Interval(4, 9), Interval(20, 20), Interval(23, 23)};
q.initialize(d);
v_exp.push_back(q);
d = {Interval(4, 9)};
q.initialize(d);
v_exp.push_back(q);
EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l6.shift(p));
v_exp.clear();
d = {Interval(4, 9)};
p.initialize(d);
d = {Interval(5, 9), Interval(12, 13)};
q.initialize(d);
v_exp.push_back(q);
EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l6.shift(p));
}
TEST(LocalPRGTest, minimizer_sketch) {
// note this is a bad test
LocalPRG l0(0, "empty", "");
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
LocalPRG l4(4, "much more complex", "TCATTC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AGCTG");
LocalPRG l5(5, "one with lots of null at start and end, and a long stretch in between",
" 5 7 9 11 AGTTCTGAAACATTGCGCGTGAGATCTCTG 12 T 11 10 A 9 8 C 7 6 G 5 ");
Index *idx;
idx = new Index();
KmerHash hash;
l0.minimizer_sketch(idx, 1, 3);
uint32_t j = 0;
EXPECT_EQ(j, idx->minhash.size());
l1.minimizer_sketch(idx, 2, 3);
j = 1;
EXPECT_EQ(j, idx->minhash.size());
l1.minimizer_sketch(idx, 1, 3);
EXPECT_EQ(j, idx->minhash.size());
j = 2;
pair<uint64_t, uint64_t> kh = hash.kmerhash("AGC", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
idx->clear();
l2.minimizer_sketch(idx, 2, 3);
j = 1;
EXPECT_EQ(j, idx->minhash.size());
l2.minimizer_sketch(idx, 1, 3);
j = 2;
EXPECT_EQ(j, idx->minhash.size());
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
j = 1;
kh = hash.kmerhash("AGT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
idx->clear();
l3.minimizer_sketch(idx, 2, 3);
j = 2;
EXPECT_EQ(j, idx->minhash.size());
l3.minimizer_sketch(idx, 1, 3);
j = 3;
EXPECT_EQ(j, idx->minhash.size());
j = 2;
kh = hash.kmerhash("AGC", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); //AGC
kh = hash.kmerhash("AGT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); //AGTx2
j = 1;
kh = hash.kmerhash("GTT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
idx->clear();
l4.minimizer_sketch(idx, 1, 3);
j = 16;
EXPECT_EQ(j, idx->minhash.size());
j = 5;
kh = hash.kmerhash("TCA", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
j = 4;
kh = hash.kmerhash("CTA", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
j = 3;
kh = hash.kmerhash("ACT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("CAA", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("AAG", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("TCT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("AGC", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
j = 2;
kh = hash.kmerhash("TTC", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("CAC", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("CTC", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
j = 1;
kh = hash.kmerhash("CAT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("ATT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("GTC", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("GTT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("TGT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("CTG", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
idx->clear();
l4.minimizer_sketch(idx, 3, 3);
j = 10;
EXPECT_EQ(j, idx->minhash.size());
j = 4;
kh = hash.kmerhash("CTA", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
j = 3;
kh = hash.kmerhash("CTT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
j = 2;
kh = hash.kmerhash("CAC", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
j = 1;
kh = hash.kmerhash("ATT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("ACT", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("TCA", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("AAC", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("GTC", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("GAG", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
kh = hash.kmerhash("CTG", 3);
EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size());
idx->clear();
l5.minimizer_sketch(idx, 4, 5);
EXPECT_EQ((idx->minhash.size() > 2), true);
idx->clear();
delete idx;
}
struct MiniPos {
bool operator()(Minimizer lhs, Minimizer rhs) {
return (lhs.pos.start) < (rhs.pos.start);
}
};
TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw1) {
string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT";
Index *idx;
idx = new Index();
LocalPRG l(0, "prg", st);
l.minimizer_sketch(idx, 1, 15);
Seq s = Seq(0, "read", st, 1, 15);
//cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl;
EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2);
set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end());
l.kmer_prg.sort_topologically();
vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin();
lit++;
for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) {
EXPECT_EQ((*sit).pos, (*lit)->path.path[0]);
++lit;
}
}
TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw5) {
string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT";
Index *idx;
idx = new Index();
LocalPRG l(0, "prg", st);
l.minimizer_sketch(idx, 5, 15);
Seq s = Seq(0, "read", st, 5, 15);
//cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl;
EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2);
set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end());
l.kmer_prg.sort_topologically();
vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin();
lit++;
for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) {
EXPECT_EQ((*sit).pos, (*lit)->path.path[0]);
++lit;
}
}
TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw10) {
string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT";
Index *idx;
idx = new Index();
LocalPRG l(0, "prg", st);
l.minimizer_sketch(idx, 10, 15);
Seq s = Seq(0, "read", st, 10, 15);
//cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl;
EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2);
set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end());
l.kmer_prg.sort_topologically();
vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin();
lit++;
for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) {
EXPECT_EQ((*sit).pos, (*lit)->path.path[0]);
++lit;
}
}
TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw15) {
string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT";
Index *idx;
idx = new Index();
LocalPRG l(0, "prg", st);
l.minimizer_sketch(idx, 15, 15);
Seq s = Seq(0, "read", st, 15, 15);
//cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl;
EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2);
set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end());
l.kmer_prg.sort_topologically();
vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin();
lit++;
for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) {
EXPECT_EQ((*sit).pos, (*lit)->path.path[0]);
++lit;
}
}
TEST(LocalPRGTest, localnode_path_from_kmernode_path) {
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
LocalPRG l4(4, "much more complex", "TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG");
Index *idx;
idx = new Index();
KmerHash hash;
l3.minimizer_sketch(idx, 2, 3);
//vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[0], l3.kmer_prg.nodes[1], l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]};
vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]};
vector<LocalNodePtr> lmp = l3.localnode_path_from_kmernode_path(kmp);
vector<LocalNodePtr> lmp_exp = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4],
l3.prg.nodes[6]};
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp);
lmp = l3.localnode_path_from_kmernode_path(kmp, 2);
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp);
idx->clear();
l4.minimizer_sketch(idx, 3, 3);
//kmp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[1], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[7], l4.kmer_prg.nodes[9], l4.kmer_prg.nodes[11], l4.kmer_prg.nodes[13]};
kmp = {l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[7]};
lmp = l4.localnode_path_from_kmernode_path(kmp, 2);
lmp_exp = {l4.prg.nodes[0], l4.prg.nodes[1], l4.prg.nodes[3], l4.prg.nodes[4], l4.prg.nodes[6]};
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp);
lmp = l4.localnode_path_from_kmernode_path(kmp, 3);
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp);
delete idx;
}
TEST(LocalPRGTest, kmernode_path_from_localnode_path) {
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
LocalPRG l4(4, "much more complex", "TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG");
LocalPRG l5(5, "nested varsite", "A 5 G 7 C 8 T 7 T 9 CCG 10 CGG 9 6 G 5 TAT");
Index *idx;
idx = new Index();
KmerHash hash;
l3.minimizer_sketch(idx, 2, 3);
l3.kmer_prg.sort_topologically();
vector<LocalNodePtr> lmp = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6]};
vector<KmerNodePtr> kmp = l3.kmernode_path_from_localnode_path(lmp);
sort(kmp.begin(), kmp.end());
vector<KmerNodePtr> kmp_exp = {l3.kmer_prg.nodes[0], l3.kmer_prg.nodes[1], l3.kmer_prg.nodes[2],
l3.kmer_prg.nodes[4]};
sort(kmp_exp.begin(), kmp_exp.end());
EXPECT_ITERABLE_EQ(vector<KmerNodePtr>, kmp_exp, kmp);
idx->clear();
l4.minimizer_sketch(idx, 3, 3);
l4.kmer_prg.sort_topologically();
lmp = {l4.prg.nodes[0], l4.prg.nodes[1], l4.prg.nodes[3], l4.prg.nodes[4], l4.prg.nodes[6]};
kmp = l4.kmernode_path_from_localnode_path(lmp);
sort(kmp.begin(), kmp.end());
kmp_exp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[1], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[7],
l4.kmer_prg.nodes[9], l4.kmer_prg.nodes[11], l4.kmer_prg.nodes[13]};
sort(kmp_exp.begin(), kmp_exp.end());
EXPECT_ITERABLE_EQ(vector<KmerNodePtr>, kmp_exp, kmp);
// case where we don't have start and end point in localpath, so need to consider whether kmer overlaps
idx->clear();
l5.minimizer_sketch(idx, 2, 3);
l5.kmer_prg.sort_topologically();
lmp = {l5.prg.nodes[1], l5.prg.nodes[2], l5.prg.nodes[4], l5.prg.nodes[6], l5.prg.nodes[7]};
kmp = l5.kmernode_path_from_localnode_path(lmp);
sort(kmp.begin(), kmp.end());
cout << l5.kmer_prg << endl;
kmp_exp = {l5.kmer_prg.nodes[1], l5.kmer_prg.nodes[2], l5.kmer_prg.nodes[6], l5.kmer_prg.nodes[8],
l5.kmer_prg.nodes[10], l5.kmer_prg.nodes[12], l5.kmer_prg.nodes[13]};
sort(kmp_exp.begin(), kmp_exp.end());
EXPECT_ITERABLE_EQ(vector<KmerNodePtr>, kmp_exp, kmp);
delete idx;
}
TEST(LocalPRGTest, get_covgs_along_localnode_path) {
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
LocalPRG l4(4, "much more complex", "TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG");
Index *idx;
idx = new Index();
KmerHash hash;
l3.minimizer_sketch(idx, 2, 3);
vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]};
vector<LocalNodePtr> lmp = l3.localnode_path_from_kmernode_path(kmp, 2);
shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "3"));
pn3->kmer_prg = l3.kmer_prg;
for (const auto &n : pn3->kmer_prg.nodes) {
n->covg[0] += 1;
}
vector<uint> covgs = get_covgs_along_localnode_path(pn3, lmp, kmp);
vector<uint> covgs_exp = {0, 1, 1, 1};
EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs);
idx->clear();
l4.minimizer_sketch(idx, 1, 3);
kmp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[1], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[5], l4.kmer_prg.nodes[7],
l4.kmer_prg.nodes[9], l4.kmer_prg.nodes[12], l4.kmer_prg.nodes[15], l4.kmer_prg.nodes[18],
l4.kmer_prg.nodes[21], l4.kmer_prg.nodes[23], l4.kmer_prg.nodes[25], l4.kmer_prg.nodes[27],
l4.kmer_prg.nodes[29]};
lmp = l4.localnode_path_from_kmernode_path(kmp, 1);
shared_ptr<pangenome::Node> pn4(make_shared<pangenome::Node>(4, 4, "4"));
pn4->kmer_prg = l4.kmer_prg;
for (const auto &n : pn4->kmer_prg.nodes) {
n->covg[0] += 1;
}
covgs = get_covgs_along_localnode_path(pn4, lmp, kmp);
//covgs_exp = {1,2,3,3,3,3,3,3,3,3,3,3,2,1};
covgs_exp = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs);
kmp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[5], l4.kmer_prg.nodes[12],
l4.kmer_prg.nodes[15], l4.kmer_prg.nodes[18], l4.kmer_prg.nodes[25]};
lmp = l4.localnode_path_from_kmernode_path(kmp, 2);
covgs = get_covgs_along_localnode_path(pn4, lmp, kmp);
//covgs_exp = {0,1,2,2,1,1,2,3,2,1,1,1,1,0};
covgs_exp = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0};
EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs);
delete idx;
}
TEST(LocalPRGTest, write_covgs_to_file) {
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T");
Index *idx;
idx = new Index();
KmerHash hash;
l3.minimizer_sketch(idx, 2, 3);
vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]};
vector<LocalNodePtr> lmp = l3.localnode_path_from_kmernode_path(kmp, 2);
shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "3"));
pn3->kmer_prg = l3.kmer_prg;
for (const auto &n : pn3->kmer_prg.nodes) {
n->covg[0] += 1;
}
vector<uint> covgs = get_covgs_along_localnode_path(pn3, lmp, kmp);
vector<uint> covgs_exp = {0, 1, 1, 1};
EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs);
l3.write_covgs_to_file("localPRG_test.covgs", covgs);
delete idx;
}
TEST(LocalPRGTest, write_path_to_fasta) {
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT");
Index *idx;
idx = new Index();
l3.minimizer_sketch(idx, 1, 3);
vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]};
l3.write_path_to_fasta("localPRG_test.maxpath.fa", lmp3, 0.00);
delete idx;
}
TEST(LocalPRGTest, append_path_to_fasta) {
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT");
Index *idx;
idx = new Index();
l3.minimizer_sketch(idx, 1, 3);
vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]};
l3.append_path_to_fasta("localPRG_test.maxpath.fa", lmp3, 0.00);
delete idx;
}
TEST(LocalPRGTest, write_aligned_path_to_fasta) {
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT");
Index *idx;
idx = new Index();
l3.minimizer_sketch(idx, 1, 3);
vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]};
l3.write_aligned_path_to_fasta("localPRG_test.alignedpath.fa", lmp3, 0.00);
delete idx;
}
TEST(LocalPRGTest, build_vcf) {
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT");
LocalPRG l4(4, "small real PRG", "ATGACAAAACGAAGTGGAAGTAATACGCGCAGGCGGGCTATCAGTCGCCCTGTTCGTCTGACGGCAGAAGAAGACCAGG"
"AAATCAGAAAAAGGGCTGCTGAATGCGGCAAGACCGTTTC 5 T 6 C 5 GGTTTTTTACGGGCGGCAGCTCTCGGTAAGAAAGTTAA 7 TTCACTGACTGA"
"TGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG 8 CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA 7 CAGAAA"
"AAACTCTTTATCGACGGCAAGCGTGTCGGGGACAG 9 A 10 G 9 GAGTATGCGGAGGTGCTGAT 11 A 12 C 11 GCTATTACGGAGTATCACCG 13"
" G 14 T 13 GCCCTGTTATCCAGGCTTATGGCAGATTAG");
LocalPRG l5(5, "another real PRG",
"ATGACAAAGGTTACACCGT 5 C 6 T 5 TGACGTGCTACGCCTGTCAGGCCTATTCGACTCCTGCAAT 7 G 8 A 7 TATTGAATTTGCATAGTTTT 9 G 10 A 9 TAGGTCGA 11 G 12 A 11 TAAGGCGTTCACGCCGCATCCGGCGTGAACAAA 13 G 14 T 13 TACTCTTTTT 15 17 19 C 20 T 19 GCACAATCCAA 18 CGCACAAACCAA 17 16 21 CGCACAATCCAA 22 23 CGT 24 CGC 23 ACAAACCA 25 A 26 T 25 21 TATGTGCAAATTATTACTTTTTCCAGAAATCATCGAAAACGG 15 ");
VCF vcf;
l1.build_vcf(vcf, l1.prg.top_path());
uint j = 0;
EXPECT_EQ(j, vcf.records.size());
EXPECT_EQ(j, vcf.samples.size());
vcf.clear();
l2.build_vcf(vcf, l2.prg.top_path());
j = 1;
EXPECT_EQ(j, vcf.records.size());
EXPECT_EQ("varsite", vcf.records[0].chrom);
EXPECT_EQ((uint) 1, vcf.records[0].pos);
EXPECT_EQ("GC", vcf.records[0].ref);
EXPECT_EQ("G", vcf.records[0].alt[0]);
EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[0].info);
vcf.clear();
vector<LocalNodePtr> lmp = {l2.prg.nodes[0], l2.prg.nodes[2], l2.prg.nodes[3]};
l2.build_vcf(vcf, lmp);
j = 1;
EXPECT_EQ(j, vcf.records.size());
EXPECT_EQ("varsite", vcf.records[0].chrom);
EXPECT_EQ((uint) 1, vcf.records[0].pos);
EXPECT_EQ("G", vcf.records[0].ref);
EXPECT_EQ("GC", vcf.records[0].alt[0]);
EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[0].info);
vcf.clear();
l3.build_vcf(vcf, l3.prg.top_path());
vcf.sort_records();
j = 2;
EXPECT_EQ(j, vcf.records.size());
EXPECT_EQ("nested varsite", vcf.records[0].chrom);
EXPECT_EQ((uint) 1, vcf.records[0].pos);
EXPECT_EQ("GC", vcf.records[0].ref);
EXPECT_EQ("G", vcf.records[0].alt[0]);
EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=NESTED", vcf.records[0].info);
EXPECT_EQ((uint) 2, vcf.records[1].pos);
EXPECT_EQ("C", vcf.records[1].ref);
EXPECT_EQ("T", vcf.records[1].alt[0]);
EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=NESTED", vcf.records[1].info);
vcf.clear();
lmp = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]};
l3.build_vcf(vcf, lmp);
vcf.sort_records();
EXPECT_EQ(j, vcf.records.size());
EXPECT_EQ("nested varsite", vcf.records[0].chrom);
EXPECT_EQ((uint) 1, vcf.records[0].pos);
EXPECT_EQ("GT", vcf.records[0].ref);
EXPECT_EQ("G", vcf.records[0].alt[0]);
EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=NESTED", vcf.records[0].info);
EXPECT_EQ((uint) 2, vcf.records[1].pos);
EXPECT_EQ("T", vcf.records[1].ref);
EXPECT_EQ("C", vcf.records[1].alt[0]);
EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=NESTED", vcf.records[1].info);
vcf.clear();
lmp = {l3.prg.nodes[0], l3.prg.nodes[5], l3.prg.nodes[6]};
l3.build_vcf(vcf, lmp);
vcf.sort_records();
EXPECT_EQ(j, vcf.records.size());
EXPECT_EQ("nested varsite", vcf.records[0].chrom);
EXPECT_EQ((uint) 1, vcf.records[0].pos);
EXPECT_EQ("G", vcf.records[0].ref);
EXPECT_EQ("GC", vcf.records[0].alt[0]);
EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[0].info);
EXPECT_EQ((uint) 1, vcf.records[1].pos);
EXPECT_EQ("G", vcf.records[1].ref);
EXPECT_EQ("GT", vcf.records[1].alt[0]);
EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[1].info);
vcf.clear();
l4.build_vcf(vcf, l4.prg.top_path());
vcf.sort_records();
j = 5;
EXPECT_EQ(j, vcf.records.size());
EXPECT_EQ("small real PRG", vcf.records[0].chrom);
EXPECT_EQ((uint) 119, vcf.records[0].pos);
EXPECT_EQ("T", vcf.records[0].ref);
EXPECT_EQ("C", vcf.records[0].alt[0]);
EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[0].info);
EXPECT_EQ((uint) 158, vcf.records[1].pos);
EXPECT_EQ("TTCACTGACTGATGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG", vcf.records[1].ref);
EXPECT_EQ("CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA", vcf.records[1].alt[0]);
EXPECT_EQ("SVTYPE=PH_SNPs;GRAPHTYPE=SIMPLE", vcf.records[1].info);
EXPECT_EQ((uint) 251, vcf.records[2].pos);
EXPECT_EQ("A", vcf.records[2].ref);
EXPECT_EQ("G", vcf.records[2].alt[0]);
EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[2].info);
EXPECT_EQ((uint) 272, vcf.records[3].pos);
EXPECT_EQ("A", vcf.records[3].ref);
EXPECT_EQ("C", vcf.records[3].alt[0]);
EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[3].info);
EXPECT_EQ((uint) 293, vcf.records[4].pos);
EXPECT_EQ("G", vcf.records[4].ref);
EXPECT_EQ("T", vcf.records[4].alt[0]);
EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[4].info);
vcf.clear();
lmp = {l4.prg.nodes[0], l4.prg.nodes[2], l4.prg.nodes[3], l4.prg.nodes[4], l4.prg.nodes[6], l4.prg.nodes[8],
l4.prg.nodes[9], l4.prg.nodes[10], l4.prg.nodes[12], l4.prg.nodes[14], l4.prg.nodes[15]};
l4.build_vcf(vcf, lmp);
vcf.sort_records();
j = 5;
EXPECT_EQ(j, vcf.records.size());
EXPECT_EQ("small real PRG", vcf.records[0].chrom);
EXPECT_EQ((uint) 119, vcf.records[0].pos);
EXPECT_EQ("C", vcf.records[0].ref);
EXPECT_EQ("T", vcf.records[0].alt[0]);
EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[0].info);
EXPECT_EQ((uint) 158, vcf.records[1].pos);
EXPECT_EQ("TTCACTGACTGATGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG", vcf.records[1].ref);
EXPECT_EQ("CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA", vcf.records[1].alt[0]);
EXPECT_EQ("SVTYPE=PH_SNPs;GRAPHTYPE=SIMPLE", vcf.records[1].info);
EXPECT_EQ((uint) 251, vcf.records[2].pos);
EXPECT_EQ("G", vcf.records[2].ref);
EXPECT_EQ("A", vcf.records[2].alt[0]);
EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[2].info);
EXPECT_EQ((uint) 272, vcf.records[3].pos);
EXPECT_EQ("A", vcf.records[3].ref);
EXPECT_EQ("C", vcf.records[3].alt[0]);
EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[3].info);
EXPECT_EQ((uint) 293, vcf.records[4].pos);
EXPECT_EQ("T", vcf.records[4].ref);
EXPECT_EQ("G", vcf.records[4].alt[0]);
EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[4].info);
vcf.clear();
l5.build_vcf(vcf, l5.prg.top_path());
vcf.sort_records();
}
TEST(LocalPRGTest, add_sample_gt_to_vcf) {
LocalPRG l1(1, "simple", "AGCT");
LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T");
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT");
LocalPRG l4(4, "small real PRG", "ATGACAAAACGAAGTGGAAGTAATACGCGCAGGCGGGCTATCAGTCGCCCTGTTCGTCTGACGGCAGAAGAAGACCAGG"
"AAATCAGAAAAAGGGCTGCTGAATGCGGCAAGACCGTTTC 5 T 6 C 5 GGTTTTTTACGGGCGGCAGCTCTCGGTAAGAAAGTTAA 7 TTCACTGACTGA"
"TGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG 8 CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA 7 CAGAAA"
"AAACTCTTTATCGACGGCAAGCGTGTCGGGGACAG 9 A 10 G 9 GAGTATGCGGAGGTGCTGAT 11 A 12 C 11 GCTATTACGGAGTATCACCG 13"
" G 14 T 13 GCCCTGTTATCCAGGCTTATGGCAGATTAG");
LocalPRG l5(5, "another real PRG", " 5 ATGCTTATTGGCTATGT 7 9 ACGCGTA 10 TCGCGTA 10 ACGTGTG 9 TCAACAAATGACCAGAACA"
"C 11 A 12 C 11 8 ACGCGTATCAACAAATGATCAGAACACA 7 GATCTACAACGTAATGCG 6 AAGT 5 ");
VCF vcf;
vector<LocalNodePtr> lmp1 = {l1.prg.nodes[0]};
l1.build_vcf(vcf, l1.prg.top_path());
l1.add_sample_gt_to_vcf(vcf, l1.prg.top_path(), lmp1, "sample");
uint j = 1;
EXPECT_EQ(j, vcf.samples.size());
vcf.clear();
vector<LocalNodePtr> lmp2 = {l2.prg.nodes[0], l2.prg.nodes[2], l2.prg.nodes[3]};
l2.build_vcf(vcf, l2.prg.top_path());
l2.add_sample_gt_to_vcf(vcf, l2.prg.top_path(), lmp2, "sample");
j = 1;
EXPECT_EQ(j, vcf.samples.size());
EXPECT_EQ(j, vcf.records[0].samples.size());
EXPECT_EQ((uint8_t) 1, vcf.records[0].samples[0]["GT"][0]);
vcf.clear();
vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]};
l3.build_vcf(vcf, l3.prg.top_path());
vcf.sort_records();
l3.add_sample_gt_to_vcf(vcf, l3.prg.top_path(), lmp3, "sample");
EXPECT_EQ(j, vcf.samples.size());
EXPECT_EQ(j, vcf.records[0].samples.size());
EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]);
vcf.clear();
vector<LocalNodePtr> lmp4 = {l4.prg.nodes[0], l4.prg.nodes[1], l4.prg.nodes[3], l4.prg.nodes[5], l4.prg.nodes[6],
l4.prg.nodes[8], l4.prg.nodes[9], l4.prg.nodes[10], l4.prg.nodes[12], l4.prg.nodes[13],
l4.prg.nodes[15]};
l4.build_vcf(vcf, l4.prg.top_path());
vcf.sort_records();
l4.add_sample_gt_to_vcf(vcf, l4.prg.top_path(), lmp4, "sample");
EXPECT_EQ(j, vcf.samples.size());
EXPECT_EQ(j, vcf.records[0].samples.size());
EXPECT_EQ((uint8_t) 0, vcf.records[0].samples[0]["GT"][0]);
EXPECT_EQ(j, vcf.records[1].samples.size());
EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]);
EXPECT_EQ(j, vcf.records[2].samples.size());
EXPECT_EQ((uint8_t) 1, vcf.records[2].samples[0]["GT"][0]);
EXPECT_EQ(j, vcf.records[3].samples.size());
EXPECT_EQ((uint8_t) 0, vcf.records[3].samples[0]["GT"][0]);
EXPECT_EQ(j, vcf.records[4].samples.size());
EXPECT_EQ((uint8_t) 0, vcf.records[4].samples[0]["GT"][0]);
vcf.clear();
vector<LocalNodePtr> lmp5 = {l5.prg.nodes[0], l5.prg.nodes[1], l5.prg.nodes[10], l5.prg.nodes[11],
l5.prg.nodes[13]};
l5.build_vcf(vcf, l5.prg.top_path());
vcf.sort_records();
l5.add_sample_gt_to_vcf(vcf, l5.prg.top_path(), lmp5, "sample");
EXPECT_EQ(j, vcf.samples.size());
EXPECT_EQ((uint) 5, vcf.records.size());
EXPECT_EQ(j, vcf.records[0].samples.size());
EXPECT_TRUE(vcf.records[0].samples[0].find("GT") == vcf.records[0].samples[0].end());
EXPECT_EQ(j, vcf.records[1].samples.size());
EXPECT_TRUE(vcf.records[1].samples[0].find("GT") == vcf.records[1].samples[0].end());
EXPECT_EQ(j, vcf.records[2].samples.size());
EXPECT_TRUE(vcf.records[2].samples[0].find("GT") == vcf.records[2].samples[0].end());
EXPECT_EQ(j, vcf.records[3].samples.size());
EXPECT_EQ((uint8_t) 1, vcf.records[3].samples[0]["GT"][0]);
EXPECT_EQ(j, vcf.records[4].samples.size());
EXPECT_TRUE(vcf.records[4].samples[0].find("GT") == vcf.records[4].samples[0].end());
// add the ref path
l5.add_sample_gt_to_vcf(vcf, l5.prg.top_path(), l5.prg.top_path(), "sample2");
EXPECT_EQ((uint) 2, vcf.samples.size());
EXPECT_EQ((uint) 5, vcf.records.size());
EXPECT_EQ((uint) 2, vcf.records[0].samples.size());
EXPECT_EQ((uint8_t) 0, vcf.records[0].samples[1]["GT"][0]);
EXPECT_EQ((uint) 2, vcf.records[1].samples.size());
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[1]["GT"][0]);
EXPECT_EQ((uint) 2, vcf.records[2].samples.size());
EXPECT_EQ((uint8_t) 0, vcf.records[2].samples[1]["GT"][0]);
EXPECT_EQ((uint) 2, vcf.records[3].samples.size());
EXPECT_EQ((uint8_t) 0, vcf.records[3].samples[1]["GT"][0]);
EXPECT_EQ((uint) 2, vcf.records[4].samples.size());
EXPECT_EQ((uint8_t) 0, vcf.records[4].samples[1]["GT"][0]);
}
TEST(LocalPRGTest, moreupdateVCF) {
// load PRGs from file
std::vector<std::shared_ptr<LocalPRG>> prgs;
read_prg_file(prgs, "../../test/test_cases/updatevcf_test.fa");
EXPECT_EQ((uint) 3, prgs.size());
VCF vcf;
prgs[0]->build_vcf(vcf, prgs[0]->prg.top_path());
prgs[1]->build_vcf(vcf, prgs[1]->prg.top_path());
prgs[2]->build_vcf(vcf, prgs[2]->prg.top_path());
vcf.sort_records();
//for (uint i=0; i!=prgs[2]->vcf.records.size(); ++i)
//{
//cout << prgs[2]->vcf.records[i];
//}
vector<LocalNodePtr> lmp1 = {prgs[1]->prg.nodes[0], prgs[1]->prg.nodes[11], prgs[1]->prg.nodes[12],
prgs[1]->prg.nodes[17], prgs[1]->prg.nodes[65], prgs[1]->prg.nodes[67]};
//cout << "PRG 1 has " << prgs[1]->prg.nodes.size() << " nodes" << endl;
prgs[1]->add_sample_gt_to_vcf(vcf, prgs[1]->prg.top_path(), lmp1, "sample");
vector<LocalNodePtr> lmp2 = {prgs[2]->prg.nodes[0], prgs[2]->prg.nodes[1], prgs[2]->prg.nodes[3],
prgs[2]->prg.nodes[4], prgs[2]->prg.nodes[6], prgs[2]->prg.nodes[7],
prgs[2]->prg.nodes[9], prgs[2]->prg.nodes[10], prgs[2]->prg.nodes[11],
prgs[2]->prg.nodes[13], prgs[2]->prg.nodes[14], prgs[2]->prg.nodes[16],
prgs[2]->prg.nodes[17], prgs[2]->prg.nodes[19], prgs[2]->prg.nodes[44],
prgs[2]->prg.nodes[45], prgs[2]->prg.nodes[47], prgs[2]->prg.nodes[118],
prgs[2]->prg.nodes[119], prgs[2]->prg.nodes[121], prgs[2]->prg.nodes[123],
prgs[2]->prg.nodes[125], prgs[2]->prg.nodes[126], prgs[2]->prg.nodes[130],
prgs[2]->prg.nodes[131], prgs[2]->prg.nodes[133], prgs[2]->prg.nodes[135],
prgs[2]->prg.nodes[141], prgs[2]->prg.nodes[142], prgs[2]->prg.nodes[144],
prgs[2]->prg.nodes[145], prgs[2]->prg.nodes[160]};
//cout << "PRG 2 has " << prgs[2]->prg.nodes.size() << " nodes" << endl;
prgs[2]->add_sample_gt_to_vcf(vcf, prgs[2]->prg.top_path(), lmp2, "sample");
}
TEST(LocalPRGTest, find_alt_path) {
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT 9 T 10 9 ATG");
vector<LocalNodePtr> top = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6]};
vector<LocalNodePtr> middle = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]};
vector<LocalNodePtr> bottom = {l3.prg.nodes[0], l3.prg.nodes[5], l3.prg.nodes[6]};
vector<LocalNodePtr> alt_path = l3.find_alt_path(top, 2, "C", "T");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, middle, alt_path);
alt_path = l3.find_alt_path(top, 1, "GC", "G");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path);
alt_path = l3.find_alt_path(middle, 2, "T", "C");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path);
alt_path = l3.find_alt_path(top, 1, "GT", "G");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path);
alt_path = l3.find_alt_path(bottom, 1, "G", "GT");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, middle, alt_path);
alt_path = l3.find_alt_path(bottom, 1, "G", "GC");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path);
// and now for the one where the alt or ref is "."
top = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6], l3.prg.nodes[7],
l3.prg.nodes[9]};
bottom = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6], l3.prg.nodes[8],
l3.prg.nodes[9]};
alt_path = l3.find_alt_path(top, 6, "T", ".");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path);
alt_path = l3.find_alt_path(bottom, 6, ".", "T");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path);
// if the site is at the start and alt is "."
LocalPRG l3_(3, "nested varsite", " 5 G 7 C 8 T 7 6 5 TAT 9 T 10 9 ");
top = {l3_.prg.nodes[0], l3_.prg.nodes[1], l3_.prg.nodes[2], l3_.prg.nodes[4], l3_.prg.nodes[6]};
bottom = {l3_.prg.nodes[0], l3_.prg.nodes[5], l3_.prg.nodes[6]};
alt_path = l3_.find_alt_path(top, 0, "GC", ".");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path);
alt_path = l3_.find_alt_path(bottom, 0, ".", "GC");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path);
// if the site at the end has ref/alt as "."
top = {l3_.prg.nodes[0], l3_.prg.nodes[1], l3_.prg.nodes[2], l3_.prg.nodes[4],
l3_.prg.nodes[6], l3_.prg.nodes[7], l3_.prg.nodes[9]};
bottom = {l3_.prg.nodes[0], l3_.prg.nodes[1], l3_.prg.nodes[2], l3_.prg.nodes[4],
l3_.prg.nodes[6], l3_.prg.nodes[8], l3_.prg.nodes[9]};
alt_path = l3_.find_alt_path(top, 5, "T", ".");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path);
alt_path = l3_.find_alt_path(bottom, 5, ".", "T");
EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path);
}
TEST(LocalPRGTest, append_kmer_covgs_in_range) {
Index *idx;
idx = new Index();
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT");
l3.minimizer_sketch(idx, 1, 3);
l3.kmer_prg.nodes[2]->covg[0] = 4;
l3.kmer_prg.nodes[2]->covg[1] = 3;
l3.kmer_prg.nodes[5]->covg[0] = 4;
l3.kmer_prg.nodes[5]->covg[1] = 5;
l3.kmer_prg.nodes[7]->covg[0] = 2;
l3.kmer_prg.nodes[7]->covg[1] = 3;
l3.kmer_prg.nodes[8]->covg[0] = 4;
l3.kmer_prg.nodes[8]->covg[1] = 6;
for (const auto &n : l3.kmer_prg.nodes) {
cout << *n;
}
vector<LocalNodePtr> lmp = {};
vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[0], l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[5], l3.kmer_prg.nodes[8],
l3.kmer_prg.nodes[10], l3.kmer_prg.nodes[11]};
vector<uint32_t> fwd, rev, exp_fwd, exp_rev;
l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 0, fwd, rev);
exp_fwd = {};
exp_rev = {};
EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd);
EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev);
l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 1, fwd, rev);
exp_fwd = {4};
exp_rev = {3};
EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd);
EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev);
fwd.clear();
rev.clear();
l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 2, fwd, rev);
exp_fwd = {4, 4};
exp_rev = {3, 5};
EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd);
EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev);
fwd.clear();
rev.clear();
l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 3, fwd, rev);
exp_fwd = {4, 4, 4};
exp_rev = {3, 5, 6};
EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd);
EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev);
fwd.clear();
rev.clear();
l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 1, 2, fwd, rev);
exp_fwd = {4, 4};
exp_rev = {3, 5};
EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd);
EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev);
}
TEST(LocalPRGTest, add_sample_covgs_to_vcf) {
Index *idx;
idx = new Index();
vector<string> short_formats = {"GT"};
vector<string> formats = {"GT", "MEAN_FWD_COVG", "MEAN_REV_COVG",
"MED_FWD_COVG", "MED_REV_COVG",
"SUM_FWD_COVG", "SUM_REV_COVG"};
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT");
l3.minimizer_sketch(idx, 1, 3);
l3.kmer_prg.sort_topologically();
VCF vcf;
vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]};
l3.build_vcf(vcf, l3.prg.top_path());
vcf.sort_records();
l3.add_sample_gt_to_vcf(vcf, l3.prg.top_path(), lmp3, "sample");
EXPECT_EQ((uint) 1, vcf.samples.size());
EXPECT_EQ((uint) 1, vcf.records[0].samples.size());
EXPECT_ITERABLE_EQ(vector<string>, short_formats, vcf.records[0].format);
EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]);
l3.add_sample_covgs_to_vcf(vcf, l3.kmer_prg, l3.prg.top_path(), "sample");
EXPECT_EQ((uint) 1, vcf.samples.size());
EXPECT_EQ((uint) 1, vcf.records[0].samples.size());
EXPECT_ITERABLE_EQ(vector<string>, formats, vcf.records[0].format);
EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_FWD_COVG"][0]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_REV_COVG"][0]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_FWD_COVG"][1]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_REV_COVG"][1]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_FWD_COVG"][0]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_REV_COVG"][0]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_FWD_COVG"][1]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_REV_COVG"][1]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_FWD_COVG"][0]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_REV_COVG"][0]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_FWD_COVG"][1]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_REV_COVG"][1]);
// ref
l3.kmer_prg.nodes[1]->covg[0] = 1;
l3.kmer_prg.nodes[1]->covg[1] = 0;
l3.kmer_prg.nodes[4]->covg[0] = 1;
l3.kmer_prg.nodes[4]->covg[1] = 0;
l3.kmer_prg.nodes[7]->covg[0] = 1;
l3.kmer_prg.nodes[7]->covg[1] = 0;
// alt
l3.kmer_prg.nodes[2]->covg[0] = 6;
l3.kmer_prg.nodes[2]->covg[1] = 8;
l3.kmer_prg.nodes[5]->covg[0] = 5;
l3.kmer_prg.nodes[5]->covg[1] = 5;
l3.kmer_prg.nodes[8]->covg[0] = 4;
l3.kmer_prg.nodes[8]->covg[1] = 5;
l3.add_sample_covgs_to_vcf(vcf, l3.kmer_prg, l3.prg.top_path(), "sample");
EXPECT_EQ((uint) 1, vcf.samples.size());
EXPECT_EQ((uint) 1, vcf.records[0].samples.size());
EXPECT_ITERABLE_EQ(vector<string>, formats, vcf.records[0].format);
EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]);
EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["MEAN_FWD_COVG"][0]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_REV_COVG"][0]);
EXPECT_EQ((uint8_t) 5, vcf.records[1].samples[0]["MEAN_FWD_COVG"][1]);
EXPECT_EQ((uint8_t) 6, vcf.records[1].samples[0]["MEAN_REV_COVG"][1]);
EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["MED_FWD_COVG"][0]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_REV_COVG"][0]);
EXPECT_EQ((uint8_t) 5, vcf.records[1].samples[0]["MED_FWD_COVG"][1]);
EXPECT_EQ((uint8_t) 5, vcf.records[1].samples[0]["MED_REV_COVG"][1]);
EXPECT_EQ((uint8_t) 3, vcf.records[1].samples[0]["SUM_FWD_COVG"][0]);
EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_REV_COVG"][0]);
EXPECT_EQ((uint8_t) 15, vcf.records[1].samples[0]["SUM_FWD_COVG"][1]);
EXPECT_EQ((uint8_t) 18, vcf.records[1].samples[0]["SUM_REV_COVG"][1]);
delete idx;
}
TEST(LocalPRGTest, add_consensus_path_to_fastaq_bin) {
Index *idx;
idx = new Index();
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT");
l3.minimizer_sketch(idx, 1, 3);
shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "three"));
pn3->kmer_prg = l3.kmer_prg;
pn3->kmer_prg.nodes[2]->covg[0] = 4;
pn3->kmer_prg.nodes[2]->covg[1] = 3;
pn3->kmer_prg.nodes[5]->covg[0] = 4;
pn3->kmer_prg.nodes[5]->covg[0] = 5;
pn3->kmer_prg.nodes[7]->covg[0] = 2;
pn3->kmer_prg.nodes[7]->covg[1] = 3;
pn3->kmer_prg.nodes[8]->covg[0] = 4;
pn3->kmer_prg.nodes[8]->covg[0] = 6;
pn3->kmer_prg.num_reads = 6;
pn3->kmer_prg.set_p(0.0001);
shared_ptr<pangenome::Read> pr(make_shared<pangenome::Read>(0));
pn3->reads.insert(pr);
Fastaq fq(false, true);
vector<KmerNodePtr> kmp;
vector<LocalNodePtr> lmp;
l3.add_consensus_path_to_fastaq(fq, pn3, kmp, lmp, 1, true, 8);
EXPECT_EQ("AGTTAT", l3.string_along_path(lmp));
bool added_to_fq = find(fq.names.begin(), fq.names.end(), "three") != fq.names.end();
EXPECT_TRUE(added_to_fq);
bool added_to_seqs = fq.sequences.find("three") != fq.sequences.end();
EXPECT_TRUE(added_to_seqs);
bool added_to_scores = fq.scores.find("three") != fq.scores.end();
EXPECT_TRUE(added_to_scores);
bool added_to_headers = fq.headers.find("three") != fq.headers.end();
EXPECT_TRUE(added_to_headers);
EXPECT_EQ("AGTTAT", fq.sequences["three"]);
EXPECT_EQ(fq.scores["three"], "DDD\?\?!");
cout << fq << endl;
}
TEST(LocalPRGTest, add_consensus_path_to_fastaq_nbin) {
Index *idx;
idx = new Index();
LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT");
l3.minimizer_sketch(idx, 1, 3);
shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "three"));
pn3->kmer_prg = l3.kmer_prg;
pn3->kmer_prg.nodes[2]->covg[0] = 4;
pn3->kmer_prg.nodes[2]->covg[1] = 3;
pn3->kmer_prg.nodes[5]->covg[0] = 4;
pn3->kmer_prg.nodes[5]->covg[0] = 5;
pn3->kmer_prg.nodes[7]->covg[0] = 2;
pn3->kmer_prg.nodes[7]->covg[1] = 3;
pn3->kmer_prg.nodes[8]->covg[0] = 4;
pn3->kmer_prg.nodes[8]->covg[0] = 6;
pn3->kmer_prg.num_reads = 6;
pn3->kmer_prg.set_nb(0.05, 2.0);
shared_ptr<pangenome::Read> pr(make_shared<pangenome::Read>(0));
pn3->reads.insert(pr);
Fastaq fq(false, true);
vector<KmerNodePtr> kmp;
vector<LocalNodePtr> lmp;
l3.add_consensus_path_to_fastaq(fq, pn3, kmp, lmp, 1, false, 8);
EXPECT_EQ("AGTTAT", l3.string_along_path(lmp));
bool added_to_fq = find(fq.names.begin(), fq.names.end(), "three") != fq.names.end();
EXPECT_TRUE(added_to_fq);
bool added_to_seqs = fq.sequences.find("three") != fq.sequences.end();
EXPECT_TRUE(added_to_seqs);
bool added_to_scores = fq.scores.find("three") != fq.scores.end();
EXPECT_TRUE(added_to_scores);
bool added_to_headers = fq.headers.find("three") != fq.headers.end();
EXPECT_TRUE(added_to_headers);
EXPECT_EQ("AGTTAT", fq.sequences["three"]);
EXPECT_EQ(fq.scores["three"], "DDD\?\?!");
cout << fq << endl;
}
| 42.739302
| 790
| 0.636913
|
rffrancon
|
b18e06d0512c64b33691bc04dbdbad6eda9196a9
| 2,238
|
cpp
|
C++
|
BZOJ/2142/std.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
BZOJ/2142/std.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
BZOJ/2142/std.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 100010
#define mp make_pair
#define pa pair<ll,ll>
#define fi first
#define se second
using namespace std ;
typedef long long ll;
ll p,n,m,w[N];
ll prime[N],mod[N],cnt[N],a[N];
int tot;
ll quick_my(ll a,ll b,ll M)
{
ll ret=1;
while(b)
{
if(b&1)ret=(ret*a)%M;
a=(a*a)%M;
b>>=1;
}
return ret;
}
void exgcd(ll a,ll b,ll &x,ll &y,ll &gcd)
{
if(!b)
{
x=1,y=0,gcd=a;
return ;
}
exgcd(b,a%b,x,y,gcd);
ll t=y;
y=x-a/b*y;x=t;
}
void get_factor(ll x)
{
for(int i=2;i*i<=x;i++)
{
if(x%i==0)
{
prime[++tot]=i,cnt[tot]=0,mod[tot]=1;
while(x%i==0){x/=i,cnt[tot]++,mod[tot]*=i;}
}
}
if(x>1)prime[++tot]=x,cnt[tot]=1,mod[tot]=x;
}
ll inverse(ll a,ll b)
{
ll xx,yy,d;
exgcd(a,b,xx,yy,d);
return (xx+b)%b;
}
pa fact(ll k,ll n)
{
if(n==0)return mp(0,1);
int x=n/prime[k],y=n/mod[k];
ll ans=1;
if(y)
{
for(int i=2;i<mod[k];i++)
{
if(i%prime[k]!=0)ans=(ans*i)%mod[k];
}
ans=quick_my(ans,y,mod[k]);
}
for(int i=y*mod[k]+1;i<=n;i++)
{
if(i%prime[k]!=0)ans=ans*i%mod[k];
}
pa tmp=fact(k,x);
return mp(x+tmp.fi,ans*tmp.se%mod[k]);
}
ll calc(int k,ll n,ll m)
{
if(n<m)return 0;
pa a=fact(k,n),b=fact(k,m),c=fact(k,n-m);
return a.se%mod[k]*inverse(b.se,mod[k])%mod[k]*inverse(c.se,mod[k])%mod[k]*quick_my(prime[k],a.fi-b.fi-c.fi,mod[k])%mod[k];
}
ll china()
{
ll gcd,y,x=0;
for(int i=1;i<=tot;i++)
{
ll r=p/mod[i];
exgcd(mod[i],r,gcd,y,gcd);
x=(x+r*y*a[i])%p;
}
return (x+p)%p;
}
ll work(ll n,ll m)
{
for(int i=1;i<=tot;i++)
a[i]=calc(i,n,m);
return china();
}
int main()
{
freopen("code.in","r",stdin);freopen("std.out","w",stdout);
scanf("%lld%lld%lld",&p,&n,&m);
get_factor(p);
int sum=0;
for(int i=1;i<=m;i++)scanf("%lld",&w[i]),sum+=w[i];
if(sum>n){printf("Impossible\n");return 0;}
ll ans=work(n,sum)%p;
for(int i=1;i<=m;i++)
{
ans=ans*work(sum,w[i])%p;
sum-=w[i];
}
printf("%lld\n",ans);
}
| 19.631579
| 127
| 0.488382
|
sjj118
|
b18fcce746bab43b072a0679baa95fdaebf8b77d
| 10,606
|
cpp
|
C++
|
ProjectEuler+/euler-0237.cpp
|
sarvekash/HackerRank_Solutions
|
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
|
[
"Apache-2.0"
] | null | null | null |
ProjectEuler+/euler-0237.cpp
|
sarvekash/HackerRank_Solutions
|
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
|
[
"Apache-2.0"
] | null | null | null |
ProjectEuler+/euler-0237.cpp
|
sarvekash/HackerRank_Solutions
|
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
|
[
"Apache-2.0"
] | 1
|
2021-05-28T11:14:34.000Z
|
2021-05-28T11:14:34.000Z
|
// ////////////////////////////////////////////////////////
// # Title
// Tours on a 4 x n playing board
//
// # URL
// https://projecteuler.net/problem=237
// http://euler.stephan-brumme.com/237/
//
// # Problem
// Let `T(n)` be the number of tours over a `4 * n` playing board such that:
// - The tour starts in the top left corner.
// - The tour consists of moves that are up, down, left, or right one square.
// - The tour visits each square exactly once.
// - The tour ends in the bottom left corner.
//
// The diagram shows one tour over a `4 * 10` board:
//
// 
//
// `T(10)` is 2329. What is `T(10^12) mod 10^8`?
//
// # Solved by
// Stephan Brumme
// October 2017
//
// # Algorithm
// A nice problem that you can easily understand within a few seconds. But it took a few days to come up with a solution ...
//
// Of course I immediately wrote a ''bruteForce'' algorithm and it solves the `T(10)` case. Anything beyond that is impossible.
//
// The main realization was to split the whole board in its columns.
// I identified 15 different columns (A - O) which can have a unique "flow" on their left and right border.
// The term "flow" means the chronological way how a piece moves across the board.
//
// The arrows symbolize the "flow" in and out of a column while hash signs stand for "no border crossing":
//
// || 4 || 4 || 4 || 4 || 4 ||
// ||! A ++ B ++ C ++ D ++ E ||
// || ==> ==> ++ ==> ==> ++ ==> ==> ++ ==> ==> ++ ==> ## ||
// || <== <== ++ <== ## ++ ## <== ++ <== <== ++ <== ## ||
// || ==> ==> ++ ==> ## ++ ## ==> ++ ==> ## ++ ==> ==> ||
// || <== <== ++ <== <== ++ <== <== ++ <== ## ++ <== <== ||
//
// || 4 || 4 || 4 || 4 || 4 ||
// ||! F ++ G ++ H ++ I ++ J ||
// || ==> ==> ++ ## ==> ++ ==> ## ++ ## ==> ++ ==> ==> ||
// || <== <== ++ ## <== ++ ## ==> ++ ==> ## ++ <== ## ||
// || ## ==> ++ ==> ==> ++ ## <== ++ <== ## ++ ## ## ||
// || ## <== ++ <== <== ++ <== ## ++ ## <== ++ ## <== ||
//
// || 4 || 4 || 4 || 4 || 4 ||
// ||! K ++ L ++ M ++ N ++ O ||
// || ==> ## ++ ==> ==> ++ ## ==> ++ ==> ## ++ ==> ## ||
// || ## ## ++ ## <== ++ ## ## ++ <== ## ++ ## ## ||
// || ## ==> ++ ## ## ++ ==> ## ++ ==> ## ++ ## ## ||
// || <== <== ++ <== ## ++ <== <== ++ <== ## ++ <== ## ||
//
// Columns N and O can only be found at the right edge of the board.
//
// Unfortunately it's not sufficient to represent the flow by arrows because they are still ambigious:
// there are three different chronological orders how the "flow" can pass through column A.
//
// If I look at each column's left and right border then there are just 6 patterns for these borders.
// With a proper labelling of the flow's chronological order (indicated by 1,2,3,4 and a hash means "no crossing") I get 8 different borders:
//
// || 2 || 2 || 2 || 2 || 2 || 2 || 2 || 2 ||
// || 1 ++ 1 ++ 1 ++ # ++ # ++ 1 ++ 3 ++ # ||
// || # ++ 2 ++ 2 ++ 1 ++ # ++ 4 ++ 2 ++ # ||
// || # ++ # ++ 3 ++ 2 ++ 1 ++ 3 ++ 1 ++ # ||
// || 2 ++ # ++ 4 ++ # ++ 2 ++ 2 ++ 4 ++ # ||
//
// The function ''fill()'' stores the borders of each column, e.g. column C is
// ''neighbors.insert( { "1##2", "1234" } );''
// Trust me, getting all this stuff right was a lot of work: I made tons of mistakes !
//
// I wrote two algorithms: a simple one that verifies `T(10)` and a much faster one to solve `T(10^12)`.
// ''slow()'' linearly goes through all borders that are allowed on the right side of the current border and stops if it reaches the right side of the board.
// Assuming that there are about 3 borders that are compatible in such a way, the routine analyzes `3^width` combinations.
// There's no way it can solve `T(10^12)` - but I really needed this algorithm to get my borders right.
// When the output finally matched the results of ''bruteForce'' I went on to write a faster (and more complex) algorithm.
//
// ''fast()'' is a divide-and-conquer approach:
// - I treat a group of columns as a blackbox where I only knows its left and right border
// - if I cut through this blackbox at an arbitrary point then any of the 8 borders could be found
// - well, that's not quite right, since the 8th border is reserved for the right-most border of the board ==> only 7 borders "inside" the blackbox
// - then the number of combinations of a blackbox is the product of its left and right half
// - if I keep doing this until the blackbox contains only a single column then I check whether this type of column is valid
//
// This isn't much faster than what ''slow()'' does ... but when the blackbox becomes smaller, I process the same kinds of blackboxes over and over again.
// Thus memoization drastically reduced the number of __different__ blackboxes. At the end, ''cache'' contains 3417 values.
//
// # Note
// Even though the result is found within about 0.02 seconds, I felt that dividing each blackbox in the middle isn't optimal:
// if I try to divide the blackbox in such a way that at least one half's size is a power of two (that means `2^i`) then ''cache'' contains only 2031 values.
// Moreover, the program runs about 50% faster.
//
// Replacing the ''std::string'' by plain integers would be still faster but I think it would be much harder to understand the code.
//
// # Alternative
// I was blown away by the simple solutions found by others: they discovered a relationship between `T(n)` and `T(n-1)`, ..., `T(n-4)`.
// Incredible stuff - or maybe just looked up in OEIS A181688.
#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <tuple>
// assuming that the route could exceed the left border I get these states for the left-most and right-most borders:
typedef std::string Border;
const Border LeftBorder = "1##2";
const Border RightBorder = "####";
// all possible borders that can be found inside the grid
std::set<Border> borders;
// define which borders can be next to each other
std::set<std::pair<Border, Border>> neighbors;
// set up the containers "borders" and "neighbors"
void fill()
{
// the following lines are derived from my drawings above
// left right column
neighbors.insert( { "1234", "1234" } ); // A
neighbors.insert( { "1432", "1432" } ); // A
neighbors.insert( { "3214", "3214" } ); // A
neighbors.insert( { "1432", "1##2" } ); // B
neighbors.insert( { "3214", "1##2" } ); // B
neighbors.insert( { "1##2", "1234" } ); // C
neighbors.insert( { "1234", "12##" } ); // D
neighbors.insert( { "1234", "##12" } ); // E
neighbors.insert( { "12##", "1432" } ); // F
neighbors.insert( { "##12", "3214" } ); // G
neighbors.insert( { "1##2", "#12#" } ); // H
neighbors.insert( { "#12#", "1##2" } ); // I
neighbors.insert( { "12##", "1##2" } ); // J
neighbors.insert( { "1##2", "##12" } ); // K
neighbors.insert( { "1##2", "12##" } ); // L
neighbors.insert( { "##12", "1##2" } ); // M
neighbors.insert( { "1234", RightBorder } ); // N
neighbors.insert( { "1##2", RightBorder } ); // O
for (auto x : neighbors)
borders.insert(x.first);
}
// fast search in O(log n)
unsigned long long search(const Border& left, const Border& right, unsigned long long length, unsigned int modulo)
{
// reduced to a single column ?
if (length == 1)
// can these two borders be next to each other ?
return neighbors.count(std::make_pair(left, right));
// memoize
auto id = std::make_tuple(left, right, length);
// I don't add "modulo" to the key to keep it simple
static std::map<std::tuple<Border, Border, unsigned long long>, unsigned long long> cache;
auto lookup = cache.find(id);
if (lookup != cache.end())
return lookup->second;
// split region into two parts: every possible border can be at the splitting point
unsigned long long result = 0;
for (const auto& next : borders)
{
// prefer a "power of two"-splitting, causes less states than splitting 50:50
unsigned long long pow2 = 1;
while (pow2 < length / 2)
pow2 *= 2;
//pow2 = length / 2; // alternatively: less efficient 50:50 method
// process left half
auto leftHalf = search(left, next, pow2, modulo);
// process right half
auto rightHalf = search(next, right, length - pow2, modulo);
// each left half can be combined with each right half
auto combined = (leftHalf * rightHalf) % modulo;
result += combined;
}
result %= modulo;
cache[id] = result;
return result;
}
// slow search, no caching whatsoever
unsigned long long slow(const std::string& border, unsigned int length, unsigned int width, unsigned int modulo)
{
// walked across the whole board ?
if (length == width)
return (border == RightBorder) ? 1 : 0;
// proceed with each border that is compatible to the current one
unsigned long long result = 0;
for (auto x : neighbors)
if (x.first == border)
result += slow(x.second, length + 1, width, modulo);
return result % modulo;
}
// backtracking of possible paths, doesn't need the information about borders etc.
typedef std::vector<std::vector<unsigned int>> Grid;
unsigned int bruteForce(Grid& grid, unsigned int x, unsigned int y, unsigned int step)
{
// reached final position ?
if (x == 0 && y == 3)
return (step == grid.size() * grid[0].size()) ? 1 : 0;
// take a step
grid[x][y] = step;
// try to search deeper in each direction
unsigned int result = 0;
if (x > 0 && grid[x - 1][y] == 0)
result += bruteForce(grid, x - 1, y, step + 1);
if (x + 1 < grid.size() && grid[x + 1][y] == 0)
result += bruteForce(grid, x + 1, y, step + 1);
if (y > 0 && grid[x][y - 1] == 0)
result += bruteForce(grid, x, y - 1, step + 1);
if (y < 3 && grid[x][y + 1] == 0)
result += bruteForce(grid, x, y + 1, step + 1);
// undo step
grid[x][y] = 0;
return result;
}
int main()
{
// set up borders and their relationships
fill();
unsigned int modulo = 100000000;
unsigned long long limit = 1000000000000;
std::cin >> limit;
//#define BRUTEFORCE
#ifdef BRUTEFORCE
// allocate memory
Grid grid(limit);
for (auto& column : grid)
column.resize(4, 0);
// start in upper left corner (0,0), that's the first step
std::cout << bruteForce(grid, 0, 0, 1) << std::endl;
#endif
//#define SLOW
#ifdef SLOW
std::cout << slow(LeftBorder, 0, limit, modulo) << std::endl;
#endif
#define FAST
#ifdef FAST
std::cout << search(LeftBorder, RightBorder, limit, modulo) << std::endl;
#endif
return 0;
}
| 40.326996
| 157
| 0.580898
|
sarvekash
|
b19372a16d8c3d42e0619dfaa01516cce0bde149
| 74,881
|
cc
|
C++
|
src/bin/dhcp6/tests/classify_unittests.cc
|
kphf1995cm/kea
|
2f6940ef5ed697f3f683035ed7a16046253add4d
|
[
"Apache-2.0"
] | null | null | null |
src/bin/dhcp6/tests/classify_unittests.cc
|
kphf1995cm/kea
|
2f6940ef5ed697f3f683035ed7a16046253add4d
|
[
"Apache-2.0"
] | null | null | null |
src/bin/dhcp6/tests/classify_unittests.cc
|
kphf1995cm/kea
|
2f6940ef5ed697f3f683035ed7a16046253add4d
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (C) 2016-2019 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <dhcp/dhcp6.h>
#include <dhcp/option.h>
#include <dhcp/option_int.h>
#include <dhcp/option_int_array.h>
#include <dhcp/pkt6.h>
#include <dhcp/tests/iface_mgr_test_config.h>
#include <dhcp/opaque_data_tuple.h>
#include <dhcp/option_string.h>
#include <dhcp/option_vendor_class.h>
#include <dhcp/option6_addrlst.h>
#include <dhcp/tests/pkt_captures.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcp6/tests/dhcp6_test_utils.h>
#include <dhcp6/tests/dhcp6_client.h>
#include <asiolink/io_address.h>
#include <stats/stats_mgr.h>
#include <boost/pointer_cast.hpp>
#include <string>
using namespace isc;
using namespace isc::asiolink;
using namespace isc::dhcp;
using namespace isc::dhcp::test;
namespace {
/// @brief Set of JSON configurations used by the classification unit tests.
///
/// - Configuration 0:
/// - Specifies 3 classes: 'router', 'reserved-class1' and 'reserved-class2'.
/// - 'router' class is assigned when the client sends option 1234 (string)
/// equal to 'foo'.
/// - The other two classes are reserved for the client having
/// DUID '01:02:03:04'
/// - Class 'router' includes option 'ipv6-forwarding'.
/// - Class 'reserved-class1' includes option DNS servers.
/// - Class 'reserved-class2' includes option NIS servers.
/// - All three options are sent when client has reservations for the
/// 'reserved-class1', 'reserved-class2' and sends option 1234 with
/// the 'foo' value.
/// - There is one subnet specified 2001:db8:1::/48 with pool of
/// IPv6 addresses.
///
/// - Configuration 1:
/// - Used for complex membership (example taken from HA)
/// - 1 subnet: 2001:db8:1::/48
/// - 4 pools: 2001:db8:1:1::/64, 2001:db8:1:2::/64,
/// 2001:db8:1:3::/64 and 2001:db8:1:4::/64
/// - 4 classes to compose:
/// server1 and server2 for each HA server
/// option 1234 'foo' aka telephones
/// option 1234 'bar' aka computers
///
/// - Configuration 2:
/// - Used for complex membership (example taken from HA) and pd-pools
/// - 1 subnet: 2001:db8::/32
/// - 4 pd-pools: 2001:db8:1::/48, 2001:db8:2::/48,
/// 2001:db8:3::/48 and 2001:db8:4::/48
/// - 4 classes to compose:
/// server1 and server2 for each HA server
/// option 1234 'foo' aka telephones
/// option 1234 'bar' aka computers
///
/// - Configuration 3:
/// - Used for the DROP class
/// - 1 subnet: 2001:db8:1::/48
/// - 2 pool: 2001:db8:1:1::/64
/// - the following class defined: option 1234 'foo', DROP
///
const char* CONFIGS[] = {
// Configuration 0
"{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"option-def\": [ "
"{"
" \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\""
"},"
"{"
" \"name\": \"ipv6-forwarding\","
" \"code\": 2345,"
" \"type\": \"boolean\""
"} ],"
"\"client-classes\": ["
"{"
" \"name\": \"router\","
" \"test\": \"option[host-name].text == 'foo'\","
" \"option-data\": ["
" {"
" \"name\": \"ipv6-forwarding\", "
" \"data\": \"true\""
" } ]"
"},"
"{"
" \"name\": \"reserved-class1\","
" \"option-data\": ["
" {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::50\""
" }"
" ]"
"},"
"{"
" \"name\": \"reserved-class2\","
" \"option-data\": ["
" {"
" \"name\": \"nis-servers\","
" \"data\": \"2001:db8:1::100\""
" }"
" ]"
"}"
"],"
"\"subnet6\": [ "
"{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], "
" \"subnet\": \"2001:db8:1::/48\", "
" \"interface\": \"eth1\","
" \"reservations\": ["
" {"
" \"duid\": \"01:02:03:04\","
" \"client-classes\": [ \"reserved-class1\", \"reserved-class2\" ]"
" } ]"
" } ],"
"\"valid-lifetime\": 4000 }",
// Configuration 1
"{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"option-def\": [ "
"{"
" \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\""
"} ],"
"\"client-classes\": ["
"{"
" \"name\": \"server1\""
"},"
"{"
" \"name\": \"server2\""
"},"
"{"
" \"name\": \"telephones\","
" \"test\": \"option[host-name].text == 'foo'\""
"},"
"{"
" \"name\": \"computers\","
" \"test\": \"option[host-name].text == 'bar'\""
"},"
"{"
" \"name\": \"server1_and_telephones\","
" \"test\": \"member('server1') and member('telephones')\""
"},"
"{"
" \"name\": \"server1_and_computers\","
" \"test\": \"member('server1') and member('computers')\""
"},"
"{"
" \"name\": \"server2_and_telephones\","
" \"test\": \"member('server2') and member('telephones')\""
"},"
"{"
" \"name\": \"server2_and_computers\","
" \"test\": \"member('server2') and member('computers')\""
"}"
"],"
"\"subnet6\": [ "
"{ \"subnet\": \"2001:db8:1::/48\", "
" \"interface\": \"eth1\","
" \"pools\": [ "
" { \"pool\": \"2001:db8:1:1::/64\","
" \"client-class\": \"server1_and_telephones\" },"
" { \"pool\": \"2001:db8:1:2::/64\","
" \"client-class\": \"server1_and_computers\" },"
" { \"pool\": \"2001:db8:1:3::/64\","
" \"client-class\": \"server2_and_telephones\" },"
" { \"pool\": \"2001:db8:1:4::/64\","
" \"client-class\": \"server2_and_computers\" } ]"
" } ],"
"\"valid-lifetime\": 4000 }",
// Configuration 2
"{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"option-def\": [ "
"{"
" \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\""
"} ],"
"\"client-classes\": ["
"{"
" \"name\": \"server1\""
"},"
"{"
" \"name\": \"server2\""
"},"
"{"
" \"name\": \"telephones\","
" \"test\": \"option[host-name].text == 'foo'\""
"},"
"{"
" \"name\": \"computers\","
" \"test\": \"option[host-name].text == 'bar'\""
"},"
"{"
" \"name\": \"server1_and_telephones\","
" \"test\": \"member('server1') and member('telephones')\""
"},"
"{"
" \"name\": \"server1_and_computers\","
" \"test\": \"member('server1') and member('computers')\""
"},"
"{"
" \"name\": \"server2_and_telephones\","
" \"test\": \"member('server2') and member('telephones')\""
"},"
"{"
" \"name\": \"server2_and_computers\","
" \"test\": \"member('server2') and member('computers')\""
"}"
"],"
"\"subnet6\": [ "
"{ \"subnet\": \"2001:db8::/32\", "
" \"interface\": \"eth1\","
" \"pd-pools\": [ "
" { \"prefix\": \"2001:db8:1::\","
" \"prefix-len\": 48, \"delegated-len\": 64,"
" \"client-class\": \"server1_and_telephones\" },"
" { \"prefix\": \"2001:db8:2::\","
" \"prefix-len\": 48, \"delegated-len\": 64,"
" \"client-class\": \"server1_and_computers\" },"
" { \"prefix\": \"2001:db8:3::\","
" \"prefix-len\": 48, \"delegated-len\": 64,"
" \"client-class\": \"server2_and_telephones\" },"
" { \"prefix\": \"2001:db8:4::\","
" \"prefix-len\": 48, \"delegated-len\": 64,"
" \"client-class\": \"server2_and_computers\" } ]"
" } ],"
"\"valid-lifetime\": 4000 }",
// Configuration 3
"{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"option-def\": [ "
"{"
" \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\""
"},"
"{"
" \"name\": \"ipv6-forwarding\","
" \"code\": 2345,"
" \"type\": \"boolean\""
"} ],"
"\"client-classes\": ["
"{"
" \"name\": \"DROP\","
" \"test\": \"option[host-name].text == 'foo'\""
"}"
"],"
"\"subnet6\": [ "
"{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], "
" \"subnet\": \"2001:db8:1::/48\", "
" \"interface\": \"eth1\""
" } ],"
"\"valid-lifetime\": 4000 }"
};
/// @brief Test fixture class for testing client classification by the
/// DHCPv6 server.
///
/// @todo There are numerous tests not using Dhcp6Client class. They should be
/// migrated to use it one day.
class ClassifyTest : public Dhcpv6SrvTest {
public:
/// @brief Constructor.
///
/// Sets up fake interfaces.
ClassifyTest()
: Dhcpv6SrvTest(),
iface_mgr_test_config_(true) {
}
/// @brief Verify values of options returned by the server when the server
/// uses configuration with index 0.
///
/// @param config Reference to DHCP client's configuration received.
/// @param ip_forwarding Expected value of IP forwarding option. This option
/// is expected to always be present.
/// @param dns_servers String holding an address carried within DNS
/// servers option. If this value is empty, the option is expected to not
/// be included in the response.
/// @param nis_servers String holding an address carried within NIS
/// servers option. If this value is empty, the option is expected to not
/// be included in the response.
void verifyConfig0Options(const Dhcp6Client::Configuration& config,
const uint8_t ip_forwarding = 1,
const std::string& dns_servers = "",
const std::string& nis_servers = "") {
// IP forwarding option should always exist.
OptionPtr ip_forwarding_opt = config.findOption(2345);
ASSERT_TRUE(ip_forwarding_opt);
// The option comprises 2 bytes of option code, 2 bytes of option length,
// and a single 1 byte value. This makes it 5 bytes of a total length.
ASSERT_EQ(5, ip_forwarding_opt->len());
ASSERT_EQ(static_cast<int>(ip_forwarding),
static_cast<int>(ip_forwarding_opt->getUint8()));
// DNS servers.
Option6AddrLstPtr dns_servers_opt = boost::dynamic_pointer_cast<
Option6AddrLst>(config.findOption(D6O_NAME_SERVERS));
if (!dns_servers.empty()) {
ASSERT_TRUE(dns_servers_opt);
Option6AddrLst::AddressContainer addresses = dns_servers_opt->getAddresses();
// For simplicity, we expect only a single address.
ASSERT_EQ(1, addresses.size());
EXPECT_EQ(dns_servers, addresses[0].toText());
} else {
EXPECT_FALSE(dns_servers_opt);
}
// NIS servers.
Option6AddrLstPtr nis_servers_opt = boost::dynamic_pointer_cast<
Option6AddrLst>(config.findOption(D6O_NIS_SERVERS));
if (!nis_servers.empty()) {
ASSERT_TRUE(nis_servers_opt);
Option6AddrLst::AddressContainer addresses = nis_servers_opt->getAddresses();
// For simplicity, we expect only a single address.
ASSERT_EQ(1, addresses.size());
EXPECT_EQ(nis_servers, addresses[0].toText());
} else {
EXPECT_FALSE(nis_servers_opt);
}
}
/// @brief Create a solicit
Pkt6Ptr createSolicit(std::string remote_addr = "fe80::abcd") {
OptionPtr clientid = generateClientId();
Pkt6Ptr query(new Pkt6(DHCPV6_SOLICIT, 1234));
query->setRemoteAddr(IOAddress(remote_addr));
query->addOption(clientid);
query->setIface("eth1");
query->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000));
return (query);
}
/// @brief Interface Manager's fake configuration control.
IfaceMgrTestConfig iface_mgr_test_config_;
};
// Checks if DOCSIS client packets are classified properly
TEST_F(ClassifyTest, docsisClientClassification) {
NakedDhcpv6Srv srv(0);
// Let's create a relayed SOLICIT. This particular relayed SOLICIT has
// vendor-class set to docsis3.0
Pkt6Ptr sol1;
ASSERT_NO_THROW(sol1 = PktCaptures::captureDocsisRelayedSolicit());
ASSERT_NO_THROW(sol1->unpack());
srv.classifyPacket(sol1);
// It should belong to docsis3.0 class. It should not belong to eRouter1.0
EXPECT_TRUE(sol1->inClass("VENDOR_CLASS_docsis3.0"));
EXPECT_FALSE(sol1->inClass("eRouter1.0"));
// Let's get a relayed SOLICIT. This particular relayed SOLICIT has
// vendor-class set to eRouter1.0
Pkt6Ptr sol2;
ASSERT_NO_THROW(sol2 = PktCaptures::captureeRouterRelayedSolicit());
ASSERT_NO_THROW(sol2->unpack());
srv.classifyPacket(sol2);
EXPECT_TRUE(sol2->inClass(srv.VENDOR_CLASS_PREFIX + "eRouter1.0"));
EXPECT_FALSE(sol2->inClass(srv.VENDOR_CLASS_PREFIX + "docsis3.0"));
}
// Checks if client packets are classified properly using match expressions.
// Note option names and definitions are used.
TEST_F(ClassifyTest, matchClassification) {
IfaceMgrTestConfig test_config(true);
NakedDhcpv6Srv srv(0);
// The router class matches incoming packets with foo in a host-name
// option (code 1234) and sets an ipv6-forwarding option in the response.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ] }, "
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"valid-lifetime\": 4000, "
"\"option-def\": [ "
"{ \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\" },"
"{ \"name\": \"ipv6-forwarding\","
" \"code\": 2345,"
" \"type\": \"boolean\" }],"
"\"subnet6\": [ "
"{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], "
" \"subnet\": \"2001:db8:1::/48\", "
" \"interface\": \"eth1\" } ],"
"\"client-classes\": [ "
"{ \"name\": \"router\", "
" \"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"true\" } ], "
" \"test\": \"option[host-name].text == 'foo'\" } ] }";
ASSERT_NO_THROW(configure(config));
// Create packets with enough to select the subnet
Pkt6Ptr query1 = createSolicit();
Pkt6Ptr query2 = createSolicit();
Pkt6Ptr query3 = createSolicit();
// Create and add an ORO option to the first 2 queries
OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO));
ASSERT_TRUE(oro);
oro->addValue(2345);
query1->addOption(oro);
query2->addOption(oro);
// Create and add a host-name option to the first and last queries
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
ASSERT_TRUE(hostname);
query1->addOption(hostname);
query3->addOption(hostname);
// Classify packets
srv.classifyPacket(query1);
srv.classifyPacket(query2);
srv.classifyPacket(query3);
// Packets with the exception of the second should be in the router class
EXPECT_TRUE(query1->inClass("router"));
EXPECT_FALSE(query2->inClass("router"));
EXPECT_TRUE(query3->inClass("router"));
// Process queries
AllocEngine::ClientContext6 ctx1;
bool drop = false;
srv.initContext(query1, ctx1, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response1 = srv.processSolicit(ctx1);
AllocEngine::ClientContext6 ctx2;
srv.initContext(query2, ctx2, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response2 = srv.processSolicit(ctx2);
AllocEngine::ClientContext6 ctx3;
srv.initContext(query3, ctx3, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response3 = srv.processSolicit(ctx3);
// Classification processing should add an ip-forwarding option
OptionPtr opt1 = response1->getOption(2345);
EXPECT_TRUE(opt1);
// But only for the first query: second was not classified
OptionPtr opt2 = response2->getOption(2345);
EXPECT_FALSE(opt2);
// But only for the first query: third has no ORO
OptionPtr opt3 = response3->getOption(2345);
EXPECT_FALSE(opt3);
}
// Check that only-if-required classes are not evaluated by classifyPacket
TEST_F(ClassifyTest, required) {
IfaceMgrTestConfig test_config(true);
NakedDhcpv6Srv srv(0);
// The router class matches incoming packets with foo in a host-name
// option (code 1234) and sets an ipv6-forwarding option in the response.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ] }, "
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"valid-lifetime\": 4000, "
"\"option-def\": [ "
"{ \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\" },"
"{ \"name\": \"ipv6-forwarding\","
" \"code\": 2345,"
" \"type\": \"boolean\" }],"
"\"subnet6\": [ "
"{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], "
" \"subnet\": \"2001:db8:1::/48\", "
" \"interface\": \"eth1\" } ],"
"\"client-classes\": [ "
"{ \"name\": \"router\", "
" \"only-if-required\": true, "
" \"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"true\" } ], "
" \"test\": \"option[host-name].text == 'foo'\" } ] }";
ASSERT_NO_THROW(configure(config));
// Create packets with enough to select the subnet
OptionPtr clientid = generateClientId();
Pkt6Ptr query1(new Pkt6(DHCPV6_SOLICIT, 1234));
query1->setRemoteAddr(IOAddress("fe80::abcd"));
query1->addOption(clientid);
query1->setIface("eth1");
query1->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000));
Pkt6Ptr query2(new Pkt6(DHCPV6_SOLICIT, 1234));
query2->setRemoteAddr(IOAddress("fe80::abcd"));
query2->addOption(clientid);
query2->setIface("eth1");
query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000));
Pkt6Ptr query3(new Pkt6(DHCPV6_SOLICIT, 1234));
query3->setRemoteAddr(IOAddress("fe80::abcd"));
query3->addOption(clientid);
query3->setIface("eth1");
query3->addOption(generateIA(D6O_IA_NA, 345, 1500, 3000));
// Create and add an ORO option to the first 2 queries
OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO));
ASSERT_TRUE(oro);
oro->addValue(2345);
query1->addOption(oro);
query2->addOption(oro);
// Create and add a host-name option to the first and last queries
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
ASSERT_TRUE(hostname);
query1->addOption(hostname);
query3->addOption(hostname);
// Classify packets
srv.classifyPacket(query1);
srv.classifyPacket(query2);
srv.classifyPacket(query3);
// No packet is in the router class
EXPECT_FALSE(query1->inClass("router"));
EXPECT_FALSE(query2->inClass("router"));
EXPECT_FALSE(query3->inClass("router"));
// Process queries
AllocEngine::ClientContext6 ctx1;
bool drop = false;
srv.initContext(query1, ctx1, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response1 = srv.processSolicit(ctx1);
AllocEngine::ClientContext6 ctx2;
srv.initContext(query2, ctx2, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response2 = srv.processSolicit(ctx2);
AllocEngine::ClientContext6 ctx3;
srv.initContext(query3, ctx3, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response3 = srv.processSolicit(ctx3);
// Classification processing should do nothing
OptionPtr opt1 = response1->getOption(2345);
EXPECT_FALSE(opt1);
OptionPtr opt2 = response2->getOption(2345);
EXPECT_FALSE(opt2);
OptionPtr opt3 = response3->getOption(2345);
EXPECT_FALSE(opt3);
}
// Checks that when only-if-required classes are still evaluated
TEST_F(ClassifyTest, requiredClassification) {
IfaceMgrTestConfig test_config(true);
NakedDhcpv6Srv srv(0);
// The router class matches incoming packets with foo in a host-name
// option (code 1234) and sets an ipv6-forwarding option in the response.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ] }, "
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"valid-lifetime\": 4000, "
"\"option-def\": [ "
"{ \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\" },"
"{ \"name\": \"ipv6-forwarding\","
" \"code\": 2345,"
" \"type\": \"boolean\" }],"
"\"subnet6\": [ "
"{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], "
" \"subnet\": \"2001:db8:1::/48\", "
" \"require-client-classes\": [ \"router\" ], "
" \"interface\": \"eth1\" } ],"
"\"client-classes\": [ "
"{ \"name\": \"router\", "
" \"only-if-required\": true, "
" \"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"true\" } ], "
" \"test\": \"option[host-name].text == 'foo'\" } ] }";
ASSERT_NO_THROW(configure(config));
// Create packets with enough to select the subnet
OptionPtr clientid = generateClientId();
Pkt6Ptr query1(new Pkt6(DHCPV6_SOLICIT, 1234));
query1->setRemoteAddr(IOAddress("fe80::abcd"));
query1->addOption(clientid);
query1->setIface("eth1");
query1->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000));
Pkt6Ptr query2(new Pkt6(DHCPV6_SOLICIT, 1234));
query2->setRemoteAddr(IOAddress("fe80::abcd"));
query2->addOption(clientid);
query2->setIface("eth1");
query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000));
Pkt6Ptr query3(new Pkt6(DHCPV6_SOLICIT, 1234));
query3->setRemoteAddr(IOAddress("fe80::abcd"));
query3->addOption(clientid);
query3->setIface("eth1");
query3->addOption(generateIA(D6O_IA_NA, 345, 1500, 3000));
// Create and add an ORO option to the first 2 queries
OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO));
ASSERT_TRUE(oro);
oro->addValue(2345);
query1->addOption(oro);
query2->addOption(oro);
// Create and add a host-name option to the first and last queries
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
ASSERT_TRUE(hostname);
query1->addOption(hostname);
query3->addOption(hostname);
// Classify packets
srv.classifyPacket(query1);
srv.classifyPacket(query2);
srv.classifyPacket(query3);
// No packet is in the router class yet
EXPECT_FALSE(query1->inClass("router"));
EXPECT_FALSE(query2->inClass("router"));
EXPECT_FALSE(query3->inClass("router"));
// Process queries
AllocEngine::ClientContext6 ctx1;
bool drop = false;
srv.initContext(query1, ctx1, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response1 = srv.processSolicit(ctx1);
AllocEngine::ClientContext6 ctx2;
srv.initContext(query2, ctx2, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response2 = srv.processSolicit(ctx2);
AllocEngine::ClientContext6 ctx3;
srv.initContext(query3, ctx3, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response3 = srv.processSolicit(ctx3);
// Classification processing should add an ip-forwarding option
OptionPtr opt1 = response1->getOption(2345);
EXPECT_TRUE(opt1);
// But only for the first query: second was not classified
OptionPtr opt2 = response2->getOption(2345);
EXPECT_FALSE(opt2);
// But only for the first query: third has no ORO
OptionPtr opt3 = response3->getOption(2345);
EXPECT_FALSE(opt3);
}
// Checks subnet options have the priority over class options
TEST_F(ClassifyTest, subnetClassPriority) {
IfaceMgrTestConfig test_config(true);
NakedDhcpv6Srv srv(0);
// Subnet sets an ipv6-forwarding option in the response.
// The router class matches incoming packets with foo in a host-name
// option (code 1234) and sets an ipv6-forwarding option in the response.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ] }, "
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"valid-lifetime\": 4000, "
"\"option-def\": [ "
"{ \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\" },"
"{ \"name\": \"ipv6-forwarding\","
" \"code\": 2345,"
" \"type\": \"boolean\" }],"
"\"subnet6\": [ "
"{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], "
" \"subnet\": \"2001:db8:1::/48\", "
" \"interface\": \"eth1\", "
" \"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"false\" } ] } ], "
"\"client-classes\": [ "
"{ \"name\": \"router\","
" \"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"true\" } ], "
" \"test\": \"option[1234].text == 'foo'\" } ] }";
ASSERT_NO_THROW(configure(config));
// Create a packet with enough to select the subnet and go through
// the SOLICIT processing
Pkt6Ptr query = createSolicit();
// Create and add an ORO option to the query
OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO));
ASSERT_TRUE(oro);
oro->addValue(2345);
query->addOption(oro);
// Create and add a host-name option to the query
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
ASSERT_TRUE(hostname);
query->addOption(hostname);
// Classify the packet
srv.classifyPacket(query);
// The packet should be in the router class
EXPECT_TRUE(query->inClass("router"));
// Process the query
AllocEngine::ClientContext6 ctx;
bool drop = false;
srv.initContext(query, ctx, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response = srv.processSolicit(ctx);
// Processing should add an ip-forwarding option
OptionPtr opt = response->getOption(2345);
ASSERT_TRUE(opt);
ASSERT_GT(opt->len(), opt->getHeaderLen());
// Classification sets the value to true/1, subnet to false/0
// Here subnet has the priority
EXPECT_EQ(0, opt->getUint8());
}
// Checks subnet options have the priority over global options
TEST_F(ClassifyTest, subnetGlobalPriority) {
IfaceMgrTestConfig test_config(true);
NakedDhcpv6Srv srv(0);
// Subnet sets an ipv6-forwarding option in the response.
// The router class matches incoming packets with foo in a host-name
// option (code 1234) and sets an ipv6-forwarding option in the response.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ] }, "
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"valid-lifetime\": 4000, "
"\"option-def\": [ "
"{ \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\" },"
"{ \"name\": \"ipv6-forwarding\","
" \"code\": 2345,"
" \"type\": \"boolean\" }],"
"\"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"false\" } ], "
"\"subnet6\": [ "
"{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], "
" \"subnet\": \"2001:db8:1::/48\", "
" \"interface\": \"eth1\", "
" \"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"false\" } ] } ] }";
ASSERT_NO_THROW(configure(config));
// Create a packet with enough to select the subnet and go through
// the SOLICIT processing
Pkt6Ptr query = createSolicit();
// Create and add an ORO option to the query
OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO));
ASSERT_TRUE(oro);
oro->addValue(2345);
query->addOption(oro);
// Create and add a host-name option to the query
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
ASSERT_TRUE(hostname);
query->addOption(hostname);
// Process the query
AllocEngine::ClientContext6 ctx;
bool drop = false;
srv.initContext(query, ctx, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response = srv.processSolicit(ctx);
// Processing should add an ip-forwarding option
OptionPtr opt = response->getOption(2345);
ASSERT_TRUE(opt);
ASSERT_GT(opt->len(), opt->getHeaderLen());
// Global sets the value to true/1, subnet to false/0
// Here subnet has the priority
EXPECT_EQ(0, opt->getUint8());
}
// Checks class options have the priority over global options
TEST_F(ClassifyTest, classGlobalPriority) {
IfaceMgrTestConfig test_config(true);
NakedDhcpv6Srv srv(0);
// A global ipv6-forwarding option is set in the response.
// The router class matches incoming packets with foo in a host-name
// option (code 1234) and sets an ipv6-forwarding option in the response.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ] }, "
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"valid-lifetime\": 4000, "
"\"option-def\": [ "
"{ \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\" },"
"{ \"name\": \"ipv6-forwarding\","
" \"code\": 2345,"
" \"type\": \"boolean\" }],"
"\"subnet6\": [ "
"{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], "
" \"subnet\": \"2001:db8:1::/48\", "
" \"interface\": \"eth1\" } ],"
"\"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"false\" } ], "
"\"client-classes\": [ "
"{ \"name\": \"router\","
" \"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"true\" } ], "
" \"test\": \"option[1234].text == 'foo'\" } ] }";
ASSERT_NO_THROW(configure(config));
// Create a packet with enough to select the subnet and go through
// the SOLICIT processing
Pkt6Ptr query = createSolicit();
// Create and add an ORO option to the query
OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO));
ASSERT_TRUE(oro);
oro->addValue(2345);
query->addOption(oro);
// Create and add a host-name option to the query
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
ASSERT_TRUE(hostname);
query->addOption(hostname);
// Classify the packet
srv.classifyPacket(query);
// The packet should be in the router class
EXPECT_TRUE(query->inClass("router"));
// Process the query
AllocEngine::ClientContext6 ctx;
bool drop = false;
srv.initContext(query, ctx, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response = srv.processSolicit(ctx);
// Processing should add an ip-forwarding option
OptionPtr opt = response->getOption(2345);
ASSERT_TRUE(opt);
ASSERT_GT(opt->len(), opt->getHeaderLen());
// Classification sets the value to true/1, global to false/0
// Here class has the priority
EXPECT_NE(0, opt->getUint8());
}
// Checks class options have the priority over global persistent options
TEST_F(ClassifyTest, classGlobalPersistency) {
IfaceMgrTestConfig test_config(true);
NakedDhcpv6Srv srv(0);
// Subnet sets an ipv6-forwarding option in the response.
// The router class matches incoming packets with foo in a host-name
// option (code 1234) and sets an ipv6-forwarding option in the response.
// Note the persistency flag follows a "OR" semantic so to set
// it to false (or to leave the default) has no effect.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ] }, "
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"valid-lifetime\": 4000, "
"\"option-def\": [ "
"{ \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\" },"
"{ \"name\": \"ipv6-forwarding\","
" \"code\": 2345,"
" \"type\": \"boolean\" }],"
"\"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"false\", "
" \"always-send\": true } ], "
"\"subnet6\": [ "
"{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], "
" \"subnet\": \"2001:db8:1::/48\", "
" \"interface\": \"eth1\", "
" \"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"false\", "
" \"always-send\": false } ] } ] }";
ASSERT_NO_THROW(configure(config));
// Create a packet with enough to select the subnet and go through
// the SOLICIT processing
Pkt6Ptr query = createSolicit();
// Do not add an ORO.
OptionPtr oro = query->getOption(D6O_ORO);
EXPECT_FALSE(oro);
// Create and add a host-name option to the query
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
ASSERT_TRUE(hostname);
query->addOption(hostname);
// Process the query
AllocEngine::ClientContext6 ctx;
bool drop = false;
srv.initContext(query, ctx, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response = srv.processSolicit(ctx);
// Processing should add an ip-forwarding option
OptionPtr opt = response->getOption(2345);
ASSERT_TRUE(opt);
ASSERT_GT(opt->len(), opt->getHeaderLen());
// Global sets the value to true/1, subnet to false/0
// Here subnet has the priority
EXPECT_EQ(0, opt->getUint8());
}
// Checks if the client-class field is indeed used for subnet selection.
// Note that packet classification is already checked in ClassifyTest
// .*Classification above.
TEST_F(ClassifyTest, clientClassifySubnet) {
// This test configures 2 subnets. We actually only need the
// first one, but since there's still this ugly hack that picks
// the pool if there is only one, we must use more than one
// subnet. That ugly hack will be removed in #3242, currently
// under review.
// The second subnet does not play any role here. The client's
// IP address belongs to the first subnet, so only that first
// subnet is being tested.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"subnet6\": [ "
" { \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ],"
" \"subnet\": \"2001:db8:1::/48\", "
" \"client-class\": \"foo\" "
" }, "
" { \"pools\": [ { \"pool\": \"2001:db8:2::/64\" } ],"
" \"subnet\": \"2001:db8:2::/48\", "
" \"client-class\": \"xyzzy\" "
" } "
"],"
"\"valid-lifetime\": 4000 }";
ASSERT_NO_THROW(configure(config));
Pkt6Ptr sol = createSolicit("2001:db8:1::3");
// This discover does not belong to foo class, so it will not
// be serviced
bool drop = false;
EXPECT_FALSE(srv_.selectSubnet(sol, drop));
EXPECT_FALSE(drop);
// Let's add the packet to bar class and try again.
sol->addClass("bar");
// Still not supported, because it belongs to wrong class.
EXPECT_FALSE(srv_.selectSubnet(sol, drop));
EXPECT_FALSE(drop);
// Let's add it to matching class.
sol->addClass("foo");
// This time it should work
EXPECT_TRUE(srv_.selectSubnet(sol, drop));
EXPECT_FALSE(drop);
}
// Checks if the client-class field is indeed used for pool selection.
TEST_F(ClassifyTest, clientClassifyPool) {
IfaceMgrTestConfig test_config(true);
NakedDhcpv6Srv srv(0);
// This test configures 2 pools.
// The second pool does not play any role here. The client's
// IP address belongs to the first pool, so only that first
// pool is being tested.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"client-classes\": [ "
" { "
" \"name\": \"foo\" "
" }, "
" { "
" \"name\": \"bar\" "
" } "
"], "
"\"subnet6\": [ "
" { \"pools\": [ "
" { "
" \"pool\": \"2001:db8:1::/64\", "
" \"client-class\": \"foo\" "
" }, "
" { "
" \"pool\": \"2001:db8:2::/64\", "
" \"client-class\": \"xyzzy\" "
" } "
" ], "
" \"subnet\": \"2001:db8::/40\" "
" } "
"], "
"\"valid-lifetime\": 4000 }";
ASSERT_NO_THROW(configure(config));
Pkt6Ptr query1 = createSolicit("2001:db8:1::3");
Pkt6Ptr query2 = createSolicit("2001:db8:1::3");
Pkt6Ptr query3 = createSolicit("2001:db8:1::3");
// This discover does not belong to foo class, so it will not
// be serviced
srv.classifyPacket(query1);
AllocEngine::ClientContext6 ctx1;
bool drop = false;
srv.initContext(query1, ctx1, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response1 = srv.processSolicit(ctx1);
ASSERT_TRUE(response1);
OptionPtr ia_na1 = response1->getOption(D6O_IA_NA);
ASSERT_TRUE(ia_na1);
EXPECT_TRUE(ia_na1->getOption(D6O_STATUS_CODE));
EXPECT_FALSE(ia_na1->getOption(D6O_IAADDR));
// Let's add the packet to bar class and try again.
query2->addClass("bar");
// Still not supported, because it belongs to wrong class.
srv.classifyPacket(query2);
AllocEngine::ClientContext6 ctx2;
srv.initContext(query2, ctx2, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response2 = srv.processSolicit(ctx2);
ASSERT_TRUE(response2);
OptionPtr ia_na2 = response2->getOption(D6O_IA_NA);
ASSERT_TRUE(ia_na2);
EXPECT_TRUE(ia_na2->getOption(D6O_STATUS_CODE));
EXPECT_FALSE(ia_na2->getOption(D6O_IAADDR));
// Let's add it to matching class.
query3->addClass("foo");
// This time it should work
srv.classifyPacket(query3);
AllocEngine::ClientContext6 ctx3;
srv.initContext(query3, ctx3, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response3 = srv.processSolicit(ctx3);
ASSERT_TRUE(response3);
OptionPtr ia_na3 = response3->getOption(D6O_IA_NA);
ASSERT_TRUE(ia_na3);
EXPECT_FALSE(ia_na3->getOption(D6O_STATUS_CODE));
EXPECT_TRUE(ia_na3->getOption(D6O_IAADDR));
}
// Checks if the [UN]KNOWN built-in classes is indeed used for pool selection.
TEST_F(ClassifyTest, clientClassifyPoolKnown) {
IfaceMgrTestConfig test_config(true);
NakedDhcpv6Srv srv(0);
// This test configures 2 pools.
// The first one requires reservation, the second does the opposite.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"subnet6\": [ "
" { \"pools\": [ "
" { "
" \"pool\": \"2001:db8:1::/64\", "
" \"client-class\": \"KNOWN\" "
" }, "
" { "
" \"pool\": \"2001:db8:2::/64\", "
" \"client-class\": \"UNKNOWN\" "
" } "
" ], "
" \"subnet\": \"2001:db8::/40\", "
" \"reservations\": [ "
" { \"duid\": \"01:02:03:04\", \"hostname\": \"foo\" } ] "
" } "
"], "
"\"valid-lifetime\": 4000 }";
ASSERT_NO_THROW(configure(config));
OptionPtr clientid1 = generateClientId();
Pkt6Ptr query1 = Pkt6Ptr(new Pkt6(DHCPV6_SOLICIT, 1234));
query1->setRemoteAddr(IOAddress("2001:db8:1::3"));
query1->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000));
query1->addOption(clientid1);
query1->setIface("eth1");
// First pool requires reservation so the second will be used
srv.classifyPacket(query1);
AllocEngine::ClientContext6 ctx1;
bool drop = false;
srv.initContext(query1, ctx1, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response1 = srv.processSolicit(ctx1);
ASSERT_TRUE(response1);
OptionPtr ia_na1 = response1->getOption(D6O_IA_NA);
ASSERT_TRUE(ia_na1);
EXPECT_FALSE(ia_na1->getOption(D6O_STATUS_CODE));
OptionPtr iaaddr1 = ia_na1->getOption(D6O_IAADDR);
ASSERT_TRUE(iaaddr1);
boost::shared_ptr<Option6IAAddr> addr1 =
boost::dynamic_pointer_cast<Option6IAAddr>(iaaddr1);
ASSERT_TRUE(addr1);
EXPECT_EQ("2001:db8:2::", addr1->getAddress().toText());
// Try with DUID 01:02:03:04
uint8_t duid[] = { 0x01, 0x02, 0x03, 0x04 };
OptionBuffer buf(duid, duid + sizeof(duid));
OptionPtr clientid2(new Option(Option::V6, D6O_CLIENTID, buf));
Pkt6Ptr query2 = Pkt6Ptr(new Pkt6(DHCPV6_SOLICIT, 2345));
query2->setRemoteAddr(IOAddress("2001:db8:1::3"));
query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000));
query2->addOption(clientid2);
query2->setIface("eth1");
// Now the first pool will be used
srv.classifyPacket(query2);
AllocEngine::ClientContext6 ctx2;
srv.initContext(query2, ctx2, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response2 = srv.processSolicit(ctx2);
ASSERT_TRUE(response2);
OptionPtr ia_na2 = response2->getOption(D6O_IA_NA);
ASSERT_TRUE(ia_na2);
EXPECT_FALSE(ia_na2->getOption(D6O_STATUS_CODE));
OptionPtr iaaddr2 = ia_na2->getOption(D6O_IAADDR);
ASSERT_TRUE(iaaddr2);
boost::shared_ptr<Option6IAAddr> addr2 =
boost::dynamic_pointer_cast<Option6IAAddr>(iaaddr2);
ASSERT_TRUE(addr2);
EXPECT_EQ("2001:db8:1::", addr2->getAddress().toText());
}
// Tests whether a packet with custom vendor-class (not erouter or docsis)
// is classified properly.
TEST_F(ClassifyTest, vendorClientClassification2) {
NakedDhcpv6Srv srv(0);
// Let's create a SOLICIT.
Pkt6Ptr sol = Pkt6Ptr(new Pkt6(DHCPV6_SOLICIT, 1234));
sol->setRemoteAddr(IOAddress("2001:db8:1::3"));
sol->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000));
OptionPtr clientid = generateClientId();
sol->addOption(clientid);
// Now let's add a vendor-class with id=1234 and content "foo"
OptionVendorClassPtr vendor_class(new OptionVendorClass(Option::V6, 1234));
OpaqueDataTuple tuple(OpaqueDataTuple::LENGTH_2_BYTES);
tuple = "foo";
vendor_class->addTuple(tuple);
sol->addOption(vendor_class);
// Now the server classifies the packet.
srv.classifyPacket(sol);
// The packet should now belong to VENDOR_CLASS_foo.
EXPECT_TRUE(sol->inClass(srv.VENDOR_CLASS_PREFIX + "foo"));
// It should not belong to "foo"
EXPECT_FALSE(sol->inClass("foo"));
}
// Checks if relay IP address specified in the relay-info structure can be
// used together with client-classification.
TEST_F(ClassifyTest, relayOverrideAndClientClass) {
// This test configures 2 subnets. They both are on the same link, so they
// have the same relay-ip address. Furthermore, the first subnet is
// reserved for clients that belong to class "foo".
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"subnet6\": [ "
" { \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ],"
" \"subnet\": \"2001:db8:1::/48\", "
" \"client-class\": \"foo\", "
" \"relay\": { "
" \"ip-address\": \"2001:db8:3::1\""
" }"
" }, "
" { \"pools\": [ { \"pool\": \"2001:db8:2::/64\" } ],"
" \"subnet\": \"2001:db8:2::/48\", "
" \"relay\": { "
" \"ip-address\": \"2001:db8:3::1\""
" }"
" } "
"],"
"\"valid-lifetime\": 4000 }";
// Use this config to set up the server
ASSERT_NO_THROW(configure(config));
// Let's get the subnet configuration objects
const Subnet6Collection* subnets =
CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
ASSERT_EQ(2, subnets->size());
// Let's get them for easy reference
Subnet6Ptr subnet1 = (*subnets)[0];
Subnet6Ptr subnet2 = (*subnets)[1];
ASSERT_TRUE(subnet1);
ASSERT_TRUE(subnet2);
Pkt6Ptr sol = createSolicit("2001:db8:1::3");
// Now pretend the packet came via one relay.
Pkt6::RelayInfo relay;
relay.linkaddr_ = IOAddress("2001:db8:3::1");
relay.peeraddr_ = IOAddress("fe80::1");
sol->relay_info_.push_back(relay);
// This packet does not belong to class foo, so it should be rejected in
// subnet[0], even though the relay-ip matches. It should be accepted in
// subnet[1], because the subnet matches and there are no class
// requirements.
bool drop = false;
EXPECT_TRUE(subnet2 == srv_.selectSubnet(sol, drop));
EXPECT_FALSE(drop);
// Now let's add this packet to class foo and recheck. This time it should
// be accepted in the first subnet, because both class and relay-ip match.
sol->addClass("foo");
EXPECT_TRUE(subnet1 == srv_.selectSubnet(sol, drop));
EXPECT_FALSE(drop);
}
// This test checks that it is possible to specify static reservations for
// client classes.
TEST_F(ClassifyTest, clientClassesInHostReservations) {
Dhcp6Client client;
// Initially use a DUID for which there are no reservations. As a result,
// the client should be assigned a single class "router".
client.setDUID("01:02:03:05");
client.setInterface("eth1");
client.requestAddress();
// Request all options we may potentially get. Otherwise, the server will
// not return them, even when the client is assigned to the classes for
// which these options should be sent.
client.requestOption(2345);
client.requestOption(D6O_NAME_SERVERS);
client.requestOption(D6O_NIS_SERVERS);
ASSERT_NO_THROW(configure(CONFIGS[0], *client.getServer()));
// Adding this option to the client's message will cause the client to
// belong to the 'router' class.
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
client.addExtraOption(hostname);
// Send a message to the server.
ASSERT_NO_THROW(client.doSolicit(true));
// IP forwarding should be present, but DNS and NIS servers should not.
ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_));
// Modify the DUID of our client to the one for which class reservations
// have been made.
client.setDUID("01:02:03:04");
ASSERT_NO_THROW(client.doSolicit(true));
// This time, the client should obtain options from all three classes.
ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1,
"2001:db8:1::50",
"2001:db8:1::100"));
// This should also work for Request case.
ASSERT_NO_THROW(client.doSARR());
ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1,
"2001:db8:1::50",
"2001:db8:1::100"));
// Renew case.
ASSERT_NO_THROW(client.doRenew());
ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1,
"2001:db8:1::50",
"2001:db8:1::100"));
// Rebind case.
ASSERT_NO_THROW(client.doRebind());
ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1,
"2001:db8:1::50",
"2001:db8:1::100"));
// Confirm case. This must be before Information-request because the
// client must have an address to confirm from one of the transactions
// involving address assignment, i.e. Request, Renew or Rebind.
ASSERT_NO_THROW(client.doConfirm());
ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1,
"2001:db8:1::50",
"2001:db8:1::100"));
// Information-request case.
ASSERT_NO_THROW(client.doInfRequest());
ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1,
"2001:db8:1::50",
"2001:db8:1::100"));
}
// Check classification using membership expressions.
TEST_F(ClassifyTest, member) {
IfaceMgrTestConfig test_config(true);
NakedDhcpv6Srv srv(0);
// The router class matches incoming packets with foo in a host-name
// option (code 1234) and sets an ipv6-forwarding option in the response.
std::string config = "{ \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ] }, "
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000, "
"\"renew-timer\": 1000, "
"\"valid-lifetime\": 4000, "
"\"option-def\": [ "
"{ \"name\": \"host-name\","
" \"code\": 1234,"
" \"type\": \"string\" },"
"{ \"name\": \"ipv6-forwarding\","
" \"code\": 2345,"
" \"type\": \"boolean\" }],"
"\"subnet6\": [ "
"{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], "
" \"subnet\": \"2001:db8:1::/48\", "
" \"interface\": \"eth1\" } ],"
"\"client-classes\": [ "
"{ \"name\": \"not-foo\", "
" \"test\": \"not (option[host-name].text == 'foo')\""
"},"
"{ \"name\": \"foo\", "
" \"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"true\" } ], "
" \"test\": \"not member('not-foo')\""
"},"
"{ \"name\": \"bar\", "
" \"test\": \"option[host-name].text == 'bar'\""
"},"
"{ \"name\": \"baz\", "
" \"test\": \"option[host-name].text == 'baz'\""
"},"
"{ \"name\": \"barz\", "
" \"option-data\": ["
" { \"name\": \"ipv6-forwarding\", "
" \"data\": \"false\" } ], "
" \"test\": \"member('bar') or member('baz')\" } ] }";
ASSERT_NO_THROW(configure(config));
// Create packets with enough to select the subnet
OptionPtr clientid = generateClientId();
Pkt6Ptr query1(new Pkt6(DHCPV6_SOLICIT, 1234));
query1->setRemoteAddr(IOAddress("fe80::abcd"));
query1->addOption(clientid);
query1->setIface("eth1");
query1->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000));
Pkt6Ptr query2(new Pkt6(DHCPV6_SOLICIT, 1234));
query2->setRemoteAddr(IOAddress("fe80::abcd"));
query2->addOption(clientid);
query2->setIface("eth1");
query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000));
Pkt6Ptr query3(new Pkt6(DHCPV6_SOLICIT, 1234));
query3->setRemoteAddr(IOAddress("fe80::abcd"));
query3->addOption(clientid);
query3->setIface("eth1");
query3->addOption(generateIA(D6O_IA_NA, 345, 1500, 3000));
// Create and add an ORO option to queries
OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO));
ASSERT_TRUE(oro);
oro->addValue(2345);
query1->addOption(oro);
query2->addOption(oro);
query3->addOption(oro);
// Create and add a host-name option to the first and last queries
OptionStringPtr hostname1(new OptionString(Option::V6, 1234, "foo"));
ASSERT_TRUE(hostname1);
query1->addOption(hostname1);
OptionStringPtr hostname3(new OptionString(Option::V6, 1234, "baz"));
ASSERT_TRUE(hostname3);
query3->addOption(hostname3);
// Classify packets
srv.classifyPacket(query1);
srv.classifyPacket(query2);
srv.classifyPacket(query3);
// Check classes
EXPECT_FALSE(query1->inClass("not-foo"));
EXPECT_TRUE(query1->inClass("foo"));
EXPECT_FALSE(query1->inClass("bar"));
EXPECT_FALSE(query1->inClass("baz"));
EXPECT_FALSE(query1->inClass("barz"));
EXPECT_TRUE(query2->inClass("not-foo"));
EXPECT_FALSE(query2->inClass("foo"));
EXPECT_FALSE(query2->inClass("bar"));
EXPECT_FALSE(query2->inClass("baz"));
EXPECT_FALSE(query2->inClass("barz"));
EXPECT_TRUE(query3->inClass("not-foo"));
EXPECT_FALSE(query3->inClass("foo"));
EXPECT_FALSE(query3->inClass("bar"));
EXPECT_TRUE(query3->inClass("baz"));
EXPECT_TRUE(query3->inClass("barz"));
// Process queries
AllocEngine::ClientContext6 ctx1;
bool drop = false;
srv.initContext(query1, ctx1, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response1 = srv.processSolicit(ctx1);
AllocEngine::ClientContext6 ctx2;
srv.initContext(query2, ctx2, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response2 = srv.processSolicit(ctx2);
AllocEngine::ClientContext6 ctx3;
srv.initContext(query3, ctx3, drop);
ASSERT_FALSE(drop);
Pkt6Ptr response3 = srv.processSolicit(ctx3);
// Classification processing should add an ip-forwarding option
OptionPtr opt1 = response1->getOption(2345);
EXPECT_TRUE(opt1);
OptionCustomPtr ipf1 =
boost::dynamic_pointer_cast<OptionCustom>(opt1);
ASSERT_TRUE(ipf1);
EXPECT_TRUE(ipf1->readBoolean());
// But not the second query which was not classified
OptionPtr opt2 = response2->getOption(2345);
EXPECT_FALSE(opt2);
// The third has the option but with another value
OptionPtr opt3 = response3->getOption(2345);
EXPECT_TRUE(opt3);
OptionCustomPtr ipf3 =
boost::dynamic_pointer_cast<OptionCustom>(opt3);
ASSERT_TRUE(ipf3);
EXPECT_FALSE(ipf3->readBoolean());
}
// This test checks the precedence order in required evaluation.
// This order is: shared-network > subnet > pools
TEST_F(ClassifyTest, precedenceNone) {
std::string config =
"{"
"\"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"preferred-lifetime\": 3000,"
"\"rebind-timer\": 2000,"
"\"renew-timer\": 1000,"
"\"client-classes\": ["
" {"
" \"name\": \"all\","
" \"test\": \"'' == ''\""
" },"
" {"
" \"name\": \"for-pool\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::1\""
" } ]"
" },"
" {"
" \"name\": \"for-subnet\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::2\""
" } ]"
" },"
" {"
" \"name\": \"for-network\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::3\""
" } ]"
" }"
"],"
"\"shared-networks\": [ {"
" \"name\": \"frog\","
" \"interface\": \"eth1\","
" \"subnet6\": [ { "
" \"subnet\": \"2001:db8:1::/64\","
" \"id\": 1,"
" \"pools\": [ { "
" \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\""
" } ]"
" } ]"
"} ],"
"\"valid-lifetime\": 600"
"}";
// Create a client requesting dns-servers option
Dhcp6Client client;
client.setInterface("eth1");
client.requestAddress(0xabca, IOAddress("2001:db8:1::28"));
client.requestOption(D6O_NAME_SERVERS);
// Load the config and perform a SARR
configure(config, *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
EXPECT_EQ(1, client.getLeaseNum());
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// Check dns-servers option
OptionPtr opt = resp->getOption(D6O_NAME_SERVERS);
EXPECT_FALSE(opt);
}
// This test checks the precedence order in required evaluation.
// This order is: shared-network > subnet > pools
TEST_F(ClassifyTest, precedencePool) {
std::string config =
"{"
"\"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"valid-lifetime\": 600,"
"\"client-classes\": ["
" {"
" \"name\": \"all\","
" \"test\": \"'' == ''\""
" },"
" {"
" \"name\": \"for-pool\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::1\""
" } ]"
" },"
" {"
" \"name\": \"for-subnet\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::2\""
" } ]"
" },"
" {"
" \"name\": \"for-network\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::3\""
" } ]"
" }"
"],"
"\"shared-networks\": [ {"
" \"name\": \"frog\","
" \"interface\": \"eth1\","
" \"subnet6\": [ { "
" \"subnet\": \"2001:db8:1::/64\","
" \"id\": 1,"
" \"pools\": [ { "
" \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\","
" \"require-client-classes\": [ \"for-pool\" ]"
" } ]"
" } ]"
"} ],"
"\"valid-lifetime\": 600"
"}";
// Create a client requesting dns-servers option
Dhcp6Client client;
client.setInterface("eth1");
client.requestAddress(0xabca, IOAddress("2001:db8:1::28"));
client.requestOption(D6O_NAME_SERVERS);
// Load the config and perform a SARR
configure(config, *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
EXPECT_EQ(1, client.getLeaseNum());
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// Check dns-servers option
OptionPtr opt = resp->getOption(D6O_NAME_SERVERS);
ASSERT_TRUE(opt);
Option6AddrLstPtr servers =
boost::dynamic_pointer_cast<Option6AddrLst>(opt);
ASSERT_TRUE(servers);
auto addrs = servers->getAddresses();
ASSERT_EQ(1, addrs.size());
EXPECT_EQ("2001:db8:1::1", addrs[0].toText());
}
// This test checks the precedence order in required evaluation.
// This order is: shared-network > subnet > pools
TEST_F(ClassifyTest, precedenceSubnet) {
std::string config =
"{"
"\"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"valid-lifetime\": 600,"
"\"client-classes\": ["
" {"
" \"name\": \"all\","
" \"test\": \"'' == ''\""
" },"
" {"
" \"name\": \"for-pool\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::1\""
" } ]"
" },"
" {"
" \"name\": \"for-subnet\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::2\""
" } ]"
" },"
" {"
" \"name\": \"for-network\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::3\""
" } ]"
" }"
"],"
"\"shared-networks\": [ {"
" \"name\": \"frog\","
" \"interface\": \"eth1\","
" \"subnet6\": [ { "
" \"subnet\": \"2001:db8:1::/64\","
" \"id\": 1,"
" \"require-client-classes\": [ \"for-subnet\" ],"
" \"pools\": [ { "
" \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\","
" \"require-client-classes\": [ \"for-pool\" ]"
" } ]"
" } ]"
"} ],"
"\"valid-lifetime\": 600"
"}";
// Create a client requesting dns-servers option
Dhcp6Client client;
client.setInterface("eth1");
client.requestAddress(0xabca, IOAddress("2001:db8:1::28"));
client.requestOption(D6O_NAME_SERVERS);
// Load the config and perform a SARR
configure(config, *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
EXPECT_EQ(1, client.getLeaseNum());
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// Check dns-servers option
OptionPtr opt = resp->getOption(D6O_NAME_SERVERS);
ASSERT_TRUE(opt);
Option6AddrLstPtr servers =
boost::dynamic_pointer_cast<Option6AddrLst>(opt);
ASSERT_TRUE(servers);
auto addrs = servers->getAddresses();
ASSERT_EQ(1, addrs.size());
EXPECT_EQ("2001:db8:1::2", addrs[0].toText());
}
// This test checks the precedence order in required evaluation.
// This order is: shared-network > subnet > pools
TEST_F(ClassifyTest, precedenceNetwork) {
std::string config =
"{"
"\"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
"},"
"\"valid-lifetime\": 600,"
"\"client-classes\": ["
" {"
" \"name\": \"all\","
" \"test\": \"'' == ''\""
" },"
" {"
" \"name\": \"for-pool\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::1\""
" } ]"
" },"
" {"
" \"name\": \"for-subnet\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::2\""
" } ]"
" },"
" {"
" \"name\": \"for-network\","
" \"test\": \"member('all')\","
" \"only-if-required\": true,"
" \"option-data\": [ {"
" \"name\": \"dns-servers\","
" \"data\": \"2001:db8:1::3\""
" } ]"
" }"
"],"
"\"shared-networks\": [ {"
" \"name\": \"frog\","
" \"interface\": \"eth1\","
" \"require-client-classes\": [ \"for-network\" ],"
" \"subnet6\": [ { "
" \"subnet\": \"2001:db8:1::/64\","
" \"id\": 1,"
" \"require-client-classes\": [ \"for-subnet\" ],"
" \"pools\": [ { "
" \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\","
" \"require-client-classes\": [ \"for-pool\" ]"
" } ]"
" } ]"
"} ],"
"\"valid-lifetime\": 600"
"}";
// Create a client requesting dns-servers option
Dhcp6Client client;
client.setInterface("eth1");
client.requestAddress(0xabca, IOAddress("2001:db8:1::28"));
client.requestOption(D6O_NAME_SERVERS);
// Load the config and perform a SARR
configure(config, *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
EXPECT_EQ(1, client.getLeaseNum());
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// Check dns-servers option
OptionPtr opt = resp->getOption(D6O_NAME_SERVERS);
ASSERT_TRUE(opt);
Option6AddrLstPtr servers =
boost::dynamic_pointer_cast<Option6AddrLst>(opt);
ASSERT_TRUE(servers);
auto addrs = servers->getAddresses();
ASSERT_EQ(1, addrs.size());
EXPECT_EQ("2001:db8:1::3", addrs[0].toText());
}
// This test checks the complex membership from HA with server1 telephone.
TEST_F(ClassifyTest, server1Telephone) {
// Create a client.
Dhcp6Client client;
client.setInterface("eth1");
ASSERT_NO_THROW(client.requestAddress(0xabca0));
// Add option.
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
client.addExtraOption(hostname);
// Add server1
client.addClass("server1");
// Load the config and perform a SARR
configure(CONFIGS[1], *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// The address is from the first pool.
ASSERT_EQ(1, client.getLeaseNum());
Lease6 lease_client = client.getLease(0);
EXPECT_EQ("2001:db8:1:1::", lease_client.addr_.toText());
}
// This test checks the complex membership from HA with server1 computer.
TEST_F(ClassifyTest, server1Computer) {
// Create a client.
Dhcp6Client client;
client.setInterface("eth1");
ASSERT_NO_THROW(client.requestAddress(0xabca0));
// Add option.
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar"));
client.addExtraOption(hostname);
// Add server1
client.addClass("server1");
// Load the config and perform a SARR
configure(CONFIGS[1], *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// The address is from the second pool.
ASSERT_EQ(1, client.getLeaseNum());
Lease6 lease_client = client.getLease(0);
EXPECT_EQ("2001:db8:1:2::", lease_client.addr_.toText());
}
// This test checks the complex membership from HA with server2 telephone.
TEST_F(ClassifyTest, server2Telephone) {
// Create a client.
Dhcp6Client client;
client.setInterface("eth1");
ASSERT_NO_THROW(client.requestAddress(0xabca0));
// Add option.
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
client.addExtraOption(hostname);
// Add server2
client.addClass("server2");
// Load the config and perform a SARR
configure(CONFIGS[1], *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// The address is from the third pool.
ASSERT_EQ(1, client.getLeaseNum());
Lease6 lease_client = client.getLease(0);
EXPECT_EQ("2001:db8:1:3::", lease_client.addr_.toText());
}
// This test checks the complex membership from HA with server2 computer.
TEST_F(ClassifyTest, server2Computer) {
// Create a client.
Dhcp6Client client;
client.setInterface("eth1");
ASSERT_NO_THROW(client.requestAddress(0xabca0));
// Add option.
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar"));
client.addExtraOption(hostname);
// Add server2
client.addClass("server2");
// Load the config and perform a SARR
configure(CONFIGS[1], *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// The address is from the forth pool.
ASSERT_EQ(1, client.getLeaseNum());
Lease6 lease_client = client.getLease(0);
EXPECT_EQ("2001:db8:1:4::", lease_client.addr_.toText());
}
// This test checks the complex membership from HA with server1 telephone
// with prefixes.
TEST_F(ClassifyTest, pDserver1Telephone) {
// Create a client.
Dhcp6Client client;
client.setInterface("eth1");
ASSERT_NO_THROW(client.requestPrefix(0xabca0));
// Add option.
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
client.addExtraOption(hostname);
// Add server1
client.addClass("server1");
// Load the config and perform a SARR
configure(CONFIGS[2], *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// The prefix is from the first pool.
ASSERT_EQ(1, client.getLeaseNum());
Lease6 lease_client = client.getLease(0);
EXPECT_EQ("2001:db8:1::", lease_client.addr_.toText());
}
// This test checks the complex membership from HA with server1 computer
// with prefix.
TEST_F(ClassifyTest, pDserver1Computer) {
// Create a client.
Dhcp6Client client;
client.setInterface("eth1");
ASSERT_NO_THROW(client.requestPrefix(0xabca0));
// Add option.
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar"));
client.addExtraOption(hostname);
// Add server1
client.addClass("server1");
// Load the config and perform a SARR
configure(CONFIGS[2], *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// The prefix is from the second pool.
ASSERT_EQ(1, client.getLeaseNum());
Lease6 lease_client = client.getLease(0);
EXPECT_EQ("2001:db8:2::", lease_client.addr_.toText());
}
// This test checks the complex membership from HA with server2 telephone
// with prefixes.
TEST_F(ClassifyTest, pDserver2Telephone) {
// Create a client.
Dhcp6Client client;
client.setInterface("eth1");
ASSERT_NO_THROW(client.requestPrefix(0xabca0));
// Add option.
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
client.addExtraOption(hostname);
// Add server2
client.addClass("server2");
// Load the config and perform a SARR
configure(CONFIGS[2], *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// The prefix is from the third pool.
ASSERT_EQ(1, client.getLeaseNum());
Lease6 lease_client = client.getLease(0);
EXPECT_EQ("2001:db8:3::", lease_client.addr_.toText());
}
// This test checks the complex membership from HA with server2 computer
// with prefix.
TEST_F(ClassifyTest, pDserver2Computer) {
// Create a client.
Dhcp6Client client;
client.setInterface("eth1");
ASSERT_NO_THROW(client.requestPrefix(0xabca0));
// Add option.
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar"));
client.addExtraOption(hostname);
// Add server2
client.addClass("server2");
// Load the config and perform a SARR
configure(CONFIGS[2], *client.getServer());
ASSERT_NO_THROW(client.doSARR());
// Check response
Pkt6Ptr resp = client.getContext().response_;
ASSERT_TRUE(resp);
// The prefix is from the forth pool.
ASSERT_EQ(1, client.getLeaseNum());
Lease6 lease_client = client.getLease(0);
EXPECT_EQ("2001:db8:4::", lease_client.addr_.toText());
}
// This test checks the handling for the DROP special class.
TEST_F(ClassifyTest, dropClass) {
Dhcp6Client client;
client.setDUID("01:02:03:05");
client.setInterface("eth1");
client.requestAddress();
// Configure DHCP server.
ASSERT_NO_THROW(configure(CONFIGS[3], *client.getServer()));
// Send a message to the server.
ASSERT_NO_THROW(client.doSolicit(true));
// No option: no drop.
EXPECT_TRUE(client.getContext().response_);
// Retry with an option matching the DROP class.
Dhcp6Client client2;
// Add the host-name option.
OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo"));
ASSERT_TRUE(hostname);
client2.addExtraOption(hostname);
// Send a message to the server.
ASSERT_NO_THROW(client2.doSolicit(true));
// Option, dropped.
EXPECT_FALSE(client2.getContext().response_);
// There should also be pkt6-receive-drop stat bumped up.
stats::StatsMgr& mgr = stats::StatsMgr::instance();
stats::ObservationPtr drop_stat = mgr.getObservation("pkt6-receive-drop");
// This statistic must be present and must be set to 1.
ASSERT_TRUE(drop_stat);
EXPECT_EQ(1, drop_stat->getInteger().first);
}
} // end of anonymous namespace
| 35.287936
| 89
| 0.557071
|
kphf1995cm
|
b196e57f1237f15db988464f02b0ea45981686b9
| 1,842
|
cpp
|
C++
|
src/BufferedInsert.cpp
|
slate6715/GN_Utilities
|
642f8dfadef06073320e38deab614a7807e3d332
|
[
"MIT"
] | null | null | null |
src/BufferedInsert.cpp
|
slate6715/GN_Utilities
|
642f8dfadef06073320e38deab614a7807e3d332
|
[
"MIT"
] | null | null | null |
src/BufferedInsert.cpp
|
slate6715/GN_Utilities
|
642f8dfadef06073320e38deab614a7807e3d332
|
[
"MIT"
] | null | null | null |
/*
* File: BufferedInsert.cpp
* Author: root
*
* Created on October 3, 2012, 2:06 PM
*/
#ifdef _WIN32
#include "stdafx.h"
#endif
#include "BufferedInsert.h"
#include <memory>
namespace util {
BufferedInsert::BufferedInsert(DBase &conn, const char *preface, const char *postface) :
_conn(conn)
, _preface(preface)
, _postface(postface) {
buf_size = BUFFER_SIZE;
count = 0;
_buf.reserve(buf_size * 50);
_buf = preface;
}
BufferedInsert::BufferedInsert(const BufferedInsert& orig):
_conn(orig._conn)
, _preface(orig._preface)
, _postface(orig._postface)
, _buf(orig._buf)
, buf_size(orig.buf_size)
{
}
BufferedInsert::~BufferedInsert(void) {
}
bool BufferedInsert::insertValues(const char *values) {
if (count != 0)
_buf += ", ";
_buf += values;
count++;
if (count > buf_size)
flush();
return true;
}
bool BufferedInsert::insertValues(std::string &values) {
if (count != 0)
_buf += ", ";
_buf += values;
count++;
if (count > buf_size)
flush();
return true;
}
void BufferedInsert::flush() {
if (!_conn.isConnected())
throw DBException("BufferedInsert Flush: Database connection not established.");
if (count == 0)
return;
if (_postface.length() > 0)
_buf += _postface;
std::unique_ptr<util::Query> stmt = _conn.getQueryObj();
*stmt << _buf;
stmt->execUpdate();
_buf.clear();
_buf.reserve(buf_size * 50); // a guess on the size of each value string
_buf = _preface;
count = 0;
}
} // namespace util
| 22.463415
| 89
| 0.536374
|
slate6715
|
b19d8b5d5db7db1a5fe9772b7b5f697865047fbd
| 540
|
cpp
|
C++
|
templates/window.cpp
|
qaqwqaqwq-0/YGP
|
928d53aff1c8ca1327b0cf7ad6e6836d44c3447f
|
[
"MIT"
] | 5
|
2020-12-07T08:58:24.000Z
|
2021-03-22T08:21:16.000Z
|
templates/window.cpp
|
qaqwqaqwq-0/YGP
|
928d53aff1c8ca1327b0cf7ad6e6836d44c3447f
|
[
"MIT"
] | null | null | null |
templates/window.cpp
|
qaqwqaqwq-0/YGP
|
928d53aff1c8ca1327b0cf7ad6e6836d44c3447f
|
[
"MIT"
] | 2
|
2021-01-26T07:45:52.000Z
|
2021-02-14T15:54:54.000Z
|
#define YGP_DISABLE_BROOM
#define YGP_DISABLE_DEMENTOR
#define YGP_DISABLE_BROWSER
#define YGP_DISABLE_PLAYER
#include"../include/ygp.hpp"
YGP_INIT
YGP_WNDPROC
{
static window win;
YGP_BEGIN_MSG_MAP
case WM_CREATE:
{
win=hwnd;
break;
}
case WM_DESTROY:
{
PostQuitMessage(0);
break;
}
YGP_END_MSG_MAP
return 0;
}
YGP_WINMAIN
{
YGP_TRY
YGP_REGCLS("YGPWindowClass")
window win("YGPWindowClass","Caption");
messageloop();
YGP_CATCH_MSGBOX
}
| 17.419355
| 47
| 0.648148
|
qaqwqaqwq-0
|
b19eea6d8ecb650cbabc95346422e7358cabed79
| 138
|
cpp
|
C++
|
TextRPG/Source/Random.cpp
|
DanDanCool/TextRPG
|
f3404a6f1b4590909b37a4c61211527276462738
|
[
"Apache-2.0"
] | 1
|
2021-01-07T14:33:22.000Z
|
2021-01-07T14:33:22.000Z
|
TextRPG/Source/Random.cpp
|
DanDanCool/TextRPG
|
f3404a6f1b4590909b37a4c61211527276462738
|
[
"Apache-2.0"
] | 2
|
2020-05-15T22:20:54.000Z
|
2020-05-24T06:49:52.000Z
|
TextRPG/Source/Random.cpp
|
DanDanCool/TextRPG
|
f3404a6f1b4590909b37a4c61211527276462738
|
[
"Apache-2.0"
] | null | null | null |
#include "Random.h"
std::mt19937 Random::s_RandomEngine;
std::uniform_int_distribution<std::mt19937::result_type> Random::s_Distribution;
| 34.5
| 80
| 0.811594
|
DanDanCool
|
b1a1ca02efd4919326c503aedc371115c9c08ec4
| 1,675
|
cpp
|
C++
|
src/cm/cf/func/SdeFFunction.cpp
|
ukjhsa/ADEF
|
ce9e16d6a0f40558860a222b20065297f1a1c8fb
|
[
"MIT"
] | null | null | null |
src/cm/cf/func/SdeFFunction.cpp
|
ukjhsa/ADEF
|
ce9e16d6a0f40558860a222b20065297f1a1c8fb
|
[
"MIT"
] | 8
|
2015-12-03T10:21:21.000Z
|
2019-02-20T11:20:57.000Z
|
src/cm/cf/func/SdeFFunction.cpp
|
ukjhsa/ADEF
|
ce9e16d6a0f40558860a222b20065297f1a1c8fb
|
[
"MIT"
] | null | null | null |
#include <memory>
#include <vector>
#include <string>
#include <any>
#include "cm/cf/func/SdeFFunction.h"
#include "cm/ControlledObject.h"
#include "Configuration.h"
#include "PrototypeManager.h"
#include "Individual.h"
namespace adef {
void SdeFFunction::setup(const Configuration & config, const PrototypeManager & pm)
{
auto rand_config = config.get_config("rand");
auto rand = make_and_setup_type<BaseFunction>(rand_config, pm);
rand->set_function_name("rand");
add_function(rand);
parameters_.resize(config.get_uint_value("number_of_parameters"));
}
SdeFFunction::Object SdeFFunction::generate()
{
Object diff = 0;
auto size = parameters_.size();
for (decltype(size) idx = 1; idx < size; idx += 2) {
diff += parameters_.at(idx) - parameters_.at(idx + 1);
}
return parameters_.at(0) + get_function("rand")->generate() * diff;
}
bool SdeFFunction::record(const std::vector<std::any>& params, const std::string & name)
{
if (params.size() == parameters_.size()) {
for (decltype(params.size()) idx = 0; idx < params.size(); ++idx) {
parameters_.at(idx) = std::any_cast<Object>(params.at(idx));
}
}
else {
throw std::logic_error("SdeFFunction accept wrong parameters.");
}
return true;
}
bool SdeFFunction::record(const std::vector<std::any>& params, std::shared_ptr<const Individual> parent, std::shared_ptr<const Individual> offspring, const std::string & name)
{
return record(params, name);
}
void SdeFFunction::update()
{
get_function("rand")->update();
}
unsigned int SdeFFunction::number_of_parameters() const
{
return parameters_.size();
}
}
| 27.016129
| 175
| 0.677612
|
ukjhsa
|
b1a62eafc01aafb7f991ddbf2d86af8a305701f3
| 1,428
|
cpp
|
C++
|
Source/GravityGun/GravityGunCameraShake.cpp
|
jSplunk/GravityGun
|
1157d876a6a6b9843602171781c52b12e7e2dd69
|
[
"Apache-2.0"
] | null | null | null |
Source/GravityGun/GravityGunCameraShake.cpp
|
jSplunk/GravityGun
|
1157d876a6a6b9843602171781c52b12e7e2dd69
|
[
"Apache-2.0"
] | null | null | null |
Source/GravityGun/GravityGunCameraShake.cpp
|
jSplunk/GravityGun
|
1157d876a6a6b9843602171781c52b12e7e2dd69
|
[
"Apache-2.0"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "GravityGunCameraShake.h"
void UGravityGunCameraShake::SetRotPitch(float Amplitude, float Frequency)
{
//Setting new values for the roational pitch of the oscillation
RotPitch.Amplitude = Amplitude;
RotPitch.Frequency = Frequency;
RotOscillation.Pitch = RotPitch;
}
void UGravityGunCameraShake::SetRotYaw(float Amplitude, float Frequency)
{
//Setting new values for the roational yaw of the oscillation
RotYaw.Amplitude = Amplitude;
RotYaw.Frequency = Frequency;
RotOscillation.Pitch = RotYaw;
}
UGravityGunCameraShake::UGravityGunCameraShake()
{
//Default values being applied for both pitch and yaw rotational oscillation
RotPitch.Amplitude = 1.0f;
RotPitch.Frequency = FMath::RandRange(15.0f, 50.0f);
RotYaw.Amplitude = 1.0f;
RotYaw.Frequency = FMath::RandRange(15.0f, 50.0f);
RotOscillation.Pitch = RotPitch;
RotOscillation.Yaw = RotYaw;
//Setting the duration of the oscillation
OscillationDuration = .5f;
}
void UGravityGunCameraShake::PlayShake(APlayerCameraManager* Camera, float Scale, ECameraAnimPlaySpace::Type InPlaySpace, FRotator UserPlaySpaceRot)
{
Super::PlayShake(Camera, Scale, InPlaySpace, UserPlaySpaceRot);
}
void UGravityGunCameraShake::UpdateAndApplyCameraShake(float DeltaTime, float Alpha, FMinimalViewInfo& InOutPOV)
{
Super::UpdateAndApplyCameraShake(DeltaTime, Alpha, InOutPOV);
}
| 29.142857
| 148
| 0.794118
|
jSplunk
|
b1a70972281a31d591aede137638cb0761a8f267
| 1,272
|
cc
|
C++
|
cc/test-bezier-gradient.cc
|
acorg/acmacs-base
|
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
|
[
"MIT"
] | null | null | null |
cc/test-bezier-gradient.cc
|
acorg/acmacs-base
|
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
|
[
"MIT"
] | null | null | null |
cc/test-bezier-gradient.cc
|
acorg/acmacs-base
|
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
|
[
"MIT"
] | null | null | null |
#include "acmacs-base/argv.hh"
#include "acmacs-base/color-gradient.hh"
// ----------------------------------------------------------------------
using namespace acmacs::argv;
struct Options : public argv
{
Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }
argument<str> color1{*this, arg_name{"color1"}, mandatory};
argument<str> color2{*this, arg_name{"color2"}, mandatory};
argument<str> color3{*this, arg_name{"color3"}, mandatory};
argument<size_t> output_size{*this, arg_name{"output-size"}, mandatory};
};
int main(int argc, const char* argv[])
{
int exit_code = 0;
try {
Options opt(argc, argv);
const Color c1{*opt.color1}, c2{*opt.color2}, c3{*opt.color3};
const auto result = acmacs::color::bezier_gradient(c1, c2, c3, opt.output_size);
for (const auto& color : result)
fmt::print("{:X}\n", color);
}
catch (std::exception& err) {
fmt::print(stderr, "ERROR: {}\n", err);
exit_code = 1;
}
return exit_code;
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 31.8
| 129
| 0.556604
|
acorg
|
b1a74ba2798aa83b8e00fb35def02c352a7183dd
| 5,756
|
cc
|
C++
|
aslam_cv2/aslam_cv_cameras/src/distortion-fisheye.cc
|
eglrp/maplab-note
|
4f4508d5cd36345c79dd38f6621a0a55aa5b0138
|
[
"Apache-2.0"
] | 2
|
2020-12-25T07:00:18.000Z
|
2022-03-15T14:35:59.000Z
|
aslam_cv2/aslam_cv_cameras/src/distortion-fisheye.cc
|
eglrp/maplab-note
|
4f4508d5cd36345c79dd38f6621a0a55aa5b0138
|
[
"Apache-2.0"
] | null | null | null |
aslam_cv2/aslam_cv_cameras/src/distortion-fisheye.cc
|
eglrp/maplab-note
|
4f4508d5cd36345c79dd38f6621a0a55aa5b0138
|
[
"Apache-2.0"
] | 1
|
2020-06-09T04:07:33.000Z
|
2020-06-09T04:07:33.000Z
|
#include <aslam/cameras/distortion-fisheye.h>
namespace aslam {
std::ostream& operator<<(std::ostream& out, const FisheyeDistortion& distortion) {
distortion.printParameters(out, std::string(""));
return out;
}
FisheyeDistortion::FisheyeDistortion(const Eigen::VectorXd& dist_coeffs)
: Base(dist_coeffs, Distortion::Type::kFisheye) {
CHECK(distortionParametersValid(dist_coeffs)) << dist_coeffs.transpose();
}
void FisheyeDistortion::distortUsingExternalCoefficients(const Eigen::VectorXd* dist_coeffs,
Eigen::Vector2d* point,
Eigen::Matrix2d* out_jacobian) const {
CHECK_NOTNULL(point);
// Use internal params if dist_coeffs==nullptr
if(!dist_coeffs)
dist_coeffs = &distortion_coefficients_;
CHECK_EQ(dist_coeffs->size(), kNumOfParams) << "dist_coeffs: invalid size!";
const double& w = (*dist_coeffs)(0);
const double r_u = point->norm();
const double r_u_cubed = r_u * r_u * r_u;
const double tanwhalf = tan(w / 2.);
const double tanwhalfsq = tanwhalf * tanwhalf;
const double atan_wrd = atan(2. * tanwhalf * r_u);
double r_rd;
if (w * w < 1e-5) {
// Limit w > 0.
r_rd = 1.0;
} else {
if (r_u * r_u < 1e-5) {
// Limit r_u > 0.
r_rd = 2. * tanwhalf / w;
} else {
r_rd = atan_wrd / (r_u * w);
}
}
const double& u = (*point)(0);
const double& v = (*point)(1);
// If Jacobian calculation is requested.
if (out_jacobian) {
out_jacobian->resize(2, 2);
if (w * w < 1e-5) {
out_jacobian->setIdentity();
}
else if (r_u * r_u < 1e-5) {
out_jacobian->setIdentity();
// The coordinates get multiplied by an expression not depending on r_u.
*out_jacobian *= (2. * tanwhalf / w);
}
else {
const double duf_du = (atan_wrd) / (w * r_u)
- (u * u * atan_wrd) / (w * r_u_cubed)
+ (2 * u * u * tanwhalf)
/ (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1));
const double duf_dv = (2 * u * v * tanwhalf)
/ (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1))
- (u * v * atan_wrd) / (w * r_u_cubed);
const double dvf_du = (2 * u * v * tanwhalf)
/ (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1))
- (u * v * atan_wrd) / (w * r_u_cubed);
const double dvf_dv = (atan_wrd) / (w * r_u)
- (v * v * atan_wrd) / (w * r_u_cubed)
+ (2 * v * v * tanwhalf)
/ (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1));
*out_jacobian << duf_du, duf_dv,
dvf_du, dvf_dv;
}
}
*point *= r_rd;
}
void FisheyeDistortion::distortParameterJacobian(const Eigen::VectorXd* dist_coeffs,
const Eigen::Vector2d& point,
Eigen::Matrix<double, 2, Eigen::Dynamic>* out_jacobian) const {
CHECK_EQ(dist_coeffs->size(), kNumOfParams) << "dist_coeffs: invalid size!";
CHECK_NOTNULL(out_jacobian);
const double& w = (*dist_coeffs)(0);
const double tanwhalf = tan(w / 2.);
const double tanwhalfsq = tanwhalf * tanwhalf;
const double r_u = point.norm();
const double atan_wrd = atan(2. * tanwhalf * r_u);
const double& u = point(0);
const double& v = point(1);
out_jacobian->resize(2, kNumOfParams);
if (w * w < 1e-5) {
out_jacobian->setZero();
}
else if (r_u * r_u < 1e-5) {
out_jacobian->setOnes();
*out_jacobian *= (w - sin(w)) / (w * w * cos(w / 2) * cos(w / 2));
}
else {
const double dxd_d_w = (2 * u * (tanwhalfsq / 2 + 0.5))
/ (w * (4 * tanwhalfsq * r_u * r_u + 1))
- (u * atan_wrd) / (w * w * r_u);
const double dyd_d_w = (2 * v * (tanwhalfsq / 2 + 0.5))
/ (w * (4 * tanwhalfsq * r_u * r_u + 1))
- (v * atan_wrd) / (w * w * r_u);
*out_jacobian << dxd_d_w, dyd_d_w;
}
}
void FisheyeDistortion::undistortUsingExternalCoefficients(const Eigen::VectorXd& dist_coeffs,
Eigen::Vector2d* point) const {
CHECK_NOTNULL(point);
CHECK_EQ(dist_coeffs.size(), kNumOfParams) << "dist_coeffs: invalid size!";
const double& w = dist_coeffs(0);
double mul2tanwby2 = tan(w / 2.0) * 2.0;
// Calculate distance from point to center.
double r_d = point->norm();
if (mul2tanwby2 == 0 || r_d == 0) {
return;
}
// Calculate undistorted radius of point.
double r_u;
if (fabs(r_d * w) <= kMaxValidAngle) {
r_u = tan(r_d * w) / (r_d * mul2tanwby2);
} else {
return;
}
(*point) *= r_u;
}
bool FisheyeDistortion::areParametersValid(const Eigen::VectorXd& parameters)
{
// Check the vector size.
if (parameters.size() != kNumOfParams)
return false;
// Expect w to have sane magnitude.
double w = parameters(0);
bool valid = std::abs(w) < 1e-16 || (w >= kMinValidW && w <= kMaxValidW);
LOG_IF(INFO, !valid) << "Invalid w parameter: " << w << ", expected w in [" << kMinValidW
<< ", " << kMaxValidW << "].";
return valid;
}
bool FisheyeDistortion::distortionParametersValid(const Eigen::VectorXd& dist_coeffs) const {
return areParametersValid(dist_coeffs);
}
void FisheyeDistortion::printParameters(std::ostream& out, const std::string& text) const {
const Eigen::VectorXd& distortion_coefficients = getParameters();
CHECK_EQ(distortion_coefficients.size(), kNumOfParams) << "dist_coeffs: invalid size!";
out << text << std::endl;
out << "Distortion: (FisheyeDistortion) " << std::endl;
out << " w: " << distortion_coefficients(0) << std::endl;
}
} // namespace aslam
| 33.271676
| 112
| 0.567582
|
eglrp
|
b1afc8a8d08db2792989acf9ba24e88993e6c627
| 5,945
|
cpp
|
C++
|
src/imgui_glfw.cpp
|
pperehozhih/imgui_glfw
|
726549cbec2b754dbbd0afdfecc23e60c015378f
|
[
"Apache-2.0"
] | null | null | null |
src/imgui_glfw.cpp
|
pperehozhih/imgui_glfw
|
726549cbec2b754dbbd0afdfecc23e60c015378f
|
[
"Apache-2.0"
] | null | null | null |
src/imgui_glfw.cpp
|
pperehozhih/imgui_glfw
|
726549cbec2b754dbbd0afdfecc23e60c015378f
|
[
"Apache-2.0"
] | null | null | null |
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#define GL_GLEXT_PROTOTYPES
#define EGL_EGLEXT_PROTOTYPES
#else
extern "C" {
#include "examples/libs/gl3w/GL/gl3w.c"
}
#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM "examples/libs/gl3w/GL/gl3w.h"
#endif
#include "backends/imgui_impl_opengl3.cpp"
#include "backends/imgui_impl_glfw.cpp"
#include "misc/cpp/imgui_stdlib.cpp"
#include "misc/freetype/imgui_freetype.cpp"
#include "imgui.h"
#include "imgui-glfw.h"
#include <map>
namespace ImGui
{
namespace GLFW
{
int g_UnloadTextureInterval = 1;
std::map<void*, std::pair<int, ImTextureID>> g_TexturesCache;
GLuint GetNativeTexture(const GLFWimage& texture) {
auto&& found = g_TexturesCache.find(texture.pixels);
GLuint gl_texture = 0;
if (found != g_TexturesCache.end()) {
found->second.first = g_UnloadTextureInterval;
gl_texture = (GLuint)(intptr_t)found->second.second;
return gl_texture;
}
glGenTextures(1, &gl_texture);
glBindTexture(GL_TEXTURE_2D, gl_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef GL_UNPACK_ROW_LENGTH
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture.width, texture.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.pixels);
glBindTexture(GL_TEXTURE_2D, gl_texture);
g_TexturesCache[texture.pixels] = std::make_pair(g_UnloadTextureInterval, (ImTextureID)(intptr_t)gl_texture);
return gl_texture;
}
bool Init(GLFWwindow* window) {
IMGUI_CHECKVERSION();
ImGui::CreateContext();
#ifdef __EMSCRIPTEN__
const char* glsl_version = "#version 100";
#elif __APPLE__
// GL 3.2 + GLSL 150
const char* glsl_version = "#version 150";
#else
// GL 3.0 + GLSL 130
const char* glsl_version = "#version 130";
#endif
#ifdef __EMSCRIPTEN__
bool err = false;
#else
bool err = gl3wInit() != 0;
#endif
if (err)
{
fprintf(stderr, "Failed to initialize OpenGL loader!\n");
return false;
}
if (!ImGui_ImplGlfw_InitForOpenGL(window, true)) {
fprintf(stderr, "Failed to initialize imgui OpenGL!\n");
return false;
}
if (!ImGui_ImplOpenGL3_Init(glsl_version)) {
fprintf(stderr, "Failed to initialize imgui!\n");
return false;
}
return true;
}
void UpdateFontTexture() {
if (g_FontTexture) {
ImGui_ImplOpenGL3_DestroyFontsTexture();
}
ImGui_ImplOpenGL3_CreateFontsTexture();
}
void NewFrame() {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void Render(GLFWwindow* window) {
ImGui::Render();
int display_w, display_h;
glfwGetFramebufferSize(window, &display_w, &display_h);
glViewport(0, 0, display_w, display_h);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
auto&& texture = g_TexturesCache.begin();
while (texture != g_TexturesCache.end()) {
texture->second.first--;
if (texture->second.first < 0) {
GLuint gl_texture = (GLuint)(intptr_t)texture->second.second;
glDeleteTextures(1, &gl_texture);
texture = g_TexturesCache.erase(texture);
}
else {
++texture;
}
}
}
void Shutdown() {
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void SetTextureUnloadInterval(int updateCount) {
g_UnloadTextureInterval = updateCount;
}
}
// Image overloads
void Image(const GLFWimage& texture,
const glm::vec4& tintColor,
const glm::vec4& borderColor) {
Image(texture, glm::vec2(texture.width, texture.height), tintColor, borderColor);
}
void Image(const GLFWimage& texture, const glm::vec2& size,
const glm::vec4& tintColor,
const glm::vec4& borderColor) {
ImTextureID textureID =
(ImTextureID)GLFW::GetNativeTexture(texture);
ImGui::Image(textureID, size, ImVec2(0, 0), ImVec2(1, 1), tintColor,
borderColor);
}
// ImageButton overloads
bool ImageButton(const GLFWimage& texture, const int framePadding,
const glm::vec4& bgColor,
const glm::vec4& tintColor) {
return ImageButton(texture, glm::vec2(texture.width, texture.height), framePadding, bgColor, tintColor);
}
bool ImageButton(const GLFWimage& texture, const glm::vec2& size, const int framePadding,
const glm::vec4& bgColor,
const glm::vec4& tintColor) {
ImTextureID textureID =
(ImTextureID)GLFW::GetNativeTexture(texture);
return ImGui::ImageButton(textureID, size, ImVec2(0, 0), ImVec2(1, 1), framePadding, bgColor,
tintColor);
}
// Draw_list overloads. All positions are in relative coordinates (relative to top-left of the current window)
void DrawLine(const glm::vec2& a, const glm::vec2& b, const glm::vec4& col, float thickness) {
ImDrawList* draw_list = ImGui::GetWindowDrawList();
glm::vec2 pos = ImGui::GetCursorScreenPos();
draw_list->AddLine(a + pos, b + pos, ColorConvertFloat4ToU32(col),
thickness);
}
}
| 36.697531
| 129
| 0.600673
|
pperehozhih
|
b1bd5b16e7ed13b229a7b98dfd0ea1fa98e1c305
| 3,911
|
cpp
|
C++
|
Kernel/Heap.cpp
|
Archlisk/fos2
|
f6a6efcaf1d29ccabdef7d9f713cc0b80f1b6565
|
[
"MIT"
] | null | null | null |
Kernel/Heap.cpp
|
Archlisk/fos2
|
f6a6efcaf1d29ccabdef7d9f713cc0b80f1b6565
|
[
"MIT"
] | null | null | null |
Kernel/Heap.cpp
|
Archlisk/fos2
|
f6a6efcaf1d29ccabdef7d9f713cc0b80f1b6565
|
[
"MIT"
] | null | null | null |
#include <Heap.h>
#include <Memory.h>
using namespace Kernel;
Heap::Heap(void* start_addr, u64 size)
: m_start_addr(start_addr), m_size(size)
{
Header* first_header = (Header*)start_addr;
Header* last_header = (Header*)((u64)start_addr + size - sizeof(Header));
first_header->prev = nullptr;
first_header->free = true;
first_header->first = true;
first_header->last = false;
first_header->next = last_header;
last_header->prev = first_header;
last_header->free = false;
last_header->first = false;
last_header->last = true;
last_header->next = nullptr;
}
#include <TTY.h>
void* Heap::alloc(u32 bytes) {
if (!bytes)
return nullptr;
Header* c_header = (Header*)m_start_addr;
while (!c_header->last) {
if (c_header->free) {
u32 c_size = ((u64)c_header->next - (u64)c_header) - sizeof(Header);
if (c_size >= bytes && c_size <= bytes + sizeof(Header)) {
c_header->free = false;
return (void*)((u64)c_header + sizeof(Header));
}
if (c_size >= bytes + sizeof(Header)) {
Header* new_header = (Header*)((u64)c_header + bytes + sizeof(Header));
new_header->free = true;
new_header->last = false;
new_header->first = false;
new_header->prev = c_header;
new_header->next = c_header->next;
c_header->next = new_header;
c_header->free = false;
new_header->next->prev = new_header;
return (void*)((u64)c_header + sizeof(Header));
}
}
c_header = c_header->next;
}
out << "Heap is out of memory!\n";
return nullptr;
}
void* Heap::realloc(void* addr, u32 bytes) {
if (!bytes) {
free(addr);
return nullptr;
}
if (!addr)
return alloc(bytes);
Header* header = (Header*)((u64)addr - sizeof(Header));
u32 alloc_size = (u64)header->next - (u64)header - sizeof(Header);
// TODO: When the current allocated size is smaller it should create a new header instead of free()-ing and alloc()-ing.
if (bytes > alloc_size) {
void* new_addr = alloc(bytes);
FC::Memory::copy(new_addr, addr, alloc_size);
free(addr);
return new_addr;
}
if (bytes < alloc_size) {
void* new_addr = alloc(bytes);
FC::Memory::copy(new_addr, addr, bytes);
free(addr);
return new_addr;
}
return addr;
}
void Heap::free(void* addr) {
if (!addr)
return;
Header* header = (Header*)((u64)addr - sizeof(Header));
header->free = true;
if (!header->first && header->prev->free)
erase_header(header);
if (!header->next->last && header->next->free)
erase_header(header->next);
// if (check_corruption()) {
// out << "HEAP CORRUPTED!\n";
// print_headers();
// while (true) {}
// }
}
bool Heap::check_corruption() {
Header* c_header = (Header*)m_start_addr;
Header* next_header_ptr = nullptr;
Header* prev_header_ptr = nullptr;
while (!c_header->last) {
if (next_header_ptr != c_header && next_header_ptr)
return true;
if (prev_header_ptr != c_header->prev && prev_header_ptr)
return true;
next_header_ptr = c_header->next;
prev_header_ptr = c_header;
c_header = c_header->next;
}
return false;
}
void Heap::print_headers() {
Header* c_header = (Header*)m_start_addr;
Header* next_header_ptr = nullptr;
Header* prev_header_ptr = nullptr;
while (!c_header->last) {
if (next_header_ptr != c_header && next_header_ptr)
out << "HEAP CORRUPTION DETECTED!\n";
if (prev_header_ptr != c_header->prev && prev_header_ptr)
out << "HEAP CORRUPTION DETECTED!\n";
u32 c_size = (u64)c_header->next - (u64)c_header - sizeof(Header);
if (c_header->free)
out << "FREE:\t 0x" << c_header << " size=" << (u64)c_size << "B next=" << c_header->next << " prev=" << c_header->prev << "\n";
else
out << "USED:\t 0x" << c_header << " size=" << (u64)c_size << "B next=" << c_header->next << " prev=" << c_header->prev << "\n";
next_header_ptr = c_header->next;
prev_header_ptr = c_header;
c_header = c_header->next;
}
}
| 23.70303
| 131
| 0.645615
|
Archlisk
|
04df61e9469c036c18ce1d54b9672164fc18d18b
| 2,082
|
cpp
|
C++
|
addons/ofxMPMFluid/src/ofxMPMObstacle.cpp
|
eraly5555/Hub
|
e890f841f16988c642cf6390fa31c3c5ae82773d
|
[
"MIT"
] | 20
|
2015-01-13T08:14:46.000Z
|
2022-01-09T21:01:41.000Z
|
addons/ofxMPMFluid/src/ofxMPMObstacle.cpp
|
eraly5555/Hub
|
e890f841f16988c642cf6390fa31c3c5ae82773d
|
[
"MIT"
] | null | null | null |
addons/ofxMPMFluid/src/ofxMPMObstacle.cpp
|
eraly5555/Hub
|
e890f841f16988c642cf6390fa31c3c5ae82773d
|
[
"MIT"
] | 3
|
2016-07-13T08:58:33.000Z
|
2021-01-29T07:06:34.000Z
|
/**
* ofxMPMFluid.cpp
* The MIT License (MIT)
* Copyright (c) 2010 respective contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*****************************************
* MPM FLuid Simulation Demo
* OpenFrameworks version by Golan Levin
* http://www.flong.com
*
* ofxAddon created by James George (@obviousjm)
* http://www.jamesgeorge.org
*
* Original Java version:
* http://grantkot.com/MPM/Liquid.html
*
* Flash version:
* Copyright iunpin ( http://wonderfl.net/user/iunpin )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/6eu4
*
* Javascript version:
* Copyright Stephen Sinclair (radarsat1) ( http://www.music.mcgill.ca/~sinclair )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://www.music.mcgill.ca/~sinclair/blog
*/
#include "ofxMPMObstacle.h"
ofxMPMObstacle::ofxMPMObstacle ( float inx, float iny, float inr) {
cx = inx;
cy = iny;
radius = inr;
radius2 = radius * radius;
}
| 39.283019
| 82
| 0.716138
|
eraly5555
|
04e01ab7bc1d1eb226f49ea65bf13fa5ffd56fcb
| 700
|
hpp
|
C++
|
lib/hmat/hmatrix_dense_compressor.hpp
|
mdavezac/bempp
|
bc573062405bda107d1514e40b6153a8350d5ab5
|
[
"BSL-1.0"
] | null | null | null |
lib/hmat/hmatrix_dense_compressor.hpp
|
mdavezac/bempp
|
bc573062405bda107d1514e40b6153a8350d5ab5
|
[
"BSL-1.0"
] | null | null | null |
lib/hmat/hmatrix_dense_compressor.hpp
|
mdavezac/bempp
|
bc573062405bda107d1514e40b6153a8350d5ab5
|
[
"BSL-1.0"
] | null | null | null |
// vi: set et ts=4 sw=2 sts=2:
#ifndef HMAT_HMATRIX_DENSE_COMPRESSOR_HPP
#define HMAT_HMATRIX_DENSE_COMPRESSOR_HPP
#include "common.hpp"
#include "hmatrix_compressor.hpp"
#include "data_accessor.hpp"
namespace hmat {
template <typename ValueType, int N>
class HMatrixDenseCompressor : public HMatrixCompressor<ValueType, N> {
public:
HMatrixDenseCompressor(const DataAccessor<ValueType, N> &dataAccessor);
void compressBlock(const BlockClusterTreeNode<N> &blockClusterTreeNode,
shared_ptr<HMatrixData<ValueType>> &hMatrixData) const
override;
private:
const DataAccessor<ValueType, N> &m_dataAccessor;
};
}
#include "hmatrix_dense_compressor_impl.hpp"
#endif
| 24.137931
| 75
| 0.771429
|
mdavezac
|
04e4ad8aba946a547875ef09ec87454d428cfc12
| 4,139
|
cpp
|
C++
|
src/templateargumentprocessor.cpp
|
strandfield/libscript
|
5d413762ad8ce88ff887642f6947032017dd284c
|
[
"MIT"
] | 3
|
2020-12-28T01:40:45.000Z
|
2021-05-18T01:47:07.000Z
|
src/templateargumentprocessor.cpp
|
strandfield/libscript
|
5d413762ad8ce88ff887642f6947032017dd284c
|
[
"MIT"
] | 4
|
2019-06-29T12:23:11.000Z
|
2020-07-25T15:38:46.000Z
|
src/templateargumentprocessor.cpp
|
strandfield/libscript
|
5d413762ad8ce88ff887642f6947032017dd284c
|
[
"MIT"
] | 1
|
2021-11-17T01:49:42.000Z
|
2021-11-17T01:49:42.000Z
|
// Copyright (C) 2018-2020 Vincent Chambrin
// This file is part of the libscript library
// For conditions of distribution and use, see copyright notice in LICENSE
#include "script/templateargumentprocessor.h"
#include "script/class.h"
#include "script/classtemplate.h"
#include "script/classtemplateinstancebuilder.h"
#include "script/diagnosticmessage.h"
#include "script/private/template_p.h"
#include "script/compiler/compilererrors.h"
#include "script/compiler/literalprocessor.h"
#include "script/compiler/nameresolver.h"
#include "script/compiler/typeresolver.h"
#include "script/ast/node.h"
#include "script/compiler/compiler.h"
namespace script
{
TemplateArgument TemplateArgumentProcessor::argument(const Scope & scp, const std::shared_ptr<ast::Node> & arg)
{
if (arg->is<ast::Identifier>())
{
auto name = std::static_pointer_cast<ast::Identifier>(arg);
NameLookup lookup = NameLookup::resolve(name, scp);
if (lookup.resultType() == NameLookup::TypeName)
return TemplateArgument{ lookup.typeResult() };
else
throw compiler::CompilationFailure{ CompilerError::InvalidTemplateArgument };
}
else if (arg->is<ast::Literal>())
{
const ast::Literal & l = arg->as<ast::Literal>();
if (l.is<ast::BoolLiteral>())
return TemplateArgument{ l.token == parser::Token::True };
else if (l.is<ast::IntegerLiteral>())
return TemplateArgument{ compiler::LiteralProcessor::generate(std::static_pointer_cast<ast::IntegerLiteral>(arg)) };
else
throw compiler::CompilationFailure{ CompilerError::InvalidLiteralTemplateArgument };
}
else if (arg->is<ast::TypeNode>())
{
auto type = std::static_pointer_cast<ast::TypeNode>(arg);
compiler::TypeResolver r;
return TemplateArgument{ r.resolve(type->value, scp) };
}
throw compiler::CompilationFailure{ CompilerError::InvalidTemplateArgument };
}
std::vector<TemplateArgument> TemplateArgumentProcessor::arguments(const Scope & scp, const std::vector<std::shared_ptr<ast::Node>> & args)
{
std::vector<TemplateArgument> result;
result.reserve(args.size());
for (const auto & a : args)
result.push_back(argument(scp, a));
return result;
}
Class TemplateArgumentProcessor::instantiate(ClassTemplate & ct, const std::vector<TemplateArgument> & args)
{
ClassTemplateInstanceBuilder builder{ ct, std::vector<TemplateArgument>{ args} };
Class ret = ct.backend()->instantiate(builder);
ct.impl()->instances[args] = ret;
return ret;
}
Class TemplateArgumentProcessor::process(const Scope & scp, ClassTemplate & ct, const std::shared_ptr<ast::TemplateIdentifier> & tmplt)
{
try
{
std::vector<TemplateArgument> targs = arguments(scp, tmplt->arguments);
complete(ct, scp, targs);
Class c;
const bool result = ct.hasInstance(targs, &c);
if (result)
return c;
return instantiate(ct, targs);
}
catch (const compiler::CompilationFailure& ex)
{
// silently discard the error
(void)ex;
}
catch (const TemplateInstantiationError & error)
{
// silently discard the error
(void)error;
}
return Class{};
}
void TemplateArgumentProcessor::complete(const Template & t, const Scope &scp, std::vector<TemplateArgument> & args)
{
if (t.parameters().size() == args.size())
return;
for (size_t i(0); i < t.parameters().size(); ++i)
{
if (!t.parameters().at(i).hasDefaultValue())
throw compiler::CompilationFailure{ CompilerError::MissingNonDefaultedTemplateParameter };
TemplateArgument arg = argument(scp, t.parameters().at(i).defaultValue());
args.push_back(arg);
}
}
const std::vector<std::shared_ptr<ast::Node>> & TemplateArgumentProcessor::getTemplateArguments(const std::shared_ptr<ast::Identifier> & tname)
{
if (tname->is<ast::TemplateIdentifier>())
{
const auto & name = tname->as<ast::TemplateIdentifier>();
return name.arguments;
}
else if (tname->is<ast::ScopedIdentifier>())
{
return getTemplateArguments(tname->as<ast::ScopedIdentifier>().rhs);
}
throw std::runtime_error{ "Bad call to TemplateArgumentProcessor::getTemplateArguments()" };
}
} // namespace script
| 31.356061
| 143
| 0.712491
|
strandfield
|
04e63d8b01982081dba6536e567c4f7d691639ac
| 6,407
|
hh
|
C++
|
maxutils/maxbase/include/maxbase/log.hh
|
sdrik/MaxScale
|
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
|
[
"BSD-3-Clause"
] | null | null | null |
maxutils/maxbase/include/maxbase/log.hh
|
sdrik/MaxScale
|
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
|
[
"BSD-3-Clause"
] | null | null | null |
maxutils/maxbase/include/maxbase/log.hh
|
sdrik/MaxScale
|
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2018 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2026-01-04
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#pragma once
#include <maxbase/ccdefs.hh>
#include <stdexcept>
#include <maxbase/log.h>
enum mxb_log_target_t
{
MXB_LOG_TARGET_DEFAULT,
MXB_LOG_TARGET_FS, // File system
MXB_LOG_TARGET_STDOUT, // Standard output
};
/**
* Prototype for function providing additional information.
*
* If the function returns a non-zero value, that amount of characters
* will be enclosed between '(' and ')', and written first to a logged
* message.
*
* @param buffer Buffer where additional context may be written.
* @param len Length of @c buffer.
*
* @return Length of data written to buffer.
*/
using mxb_log_context_provider_t = size_t (*)(char* buffer, size_t len);
using mxb_in_memory_log_t = void (*)(const std::string& buffer);
/**
* Typedef for conditional logging callback.
*
* @param priority The syslog priority under which the message is logged.
* @return True if the message should be logged, false if it should be suppressed.
*/
using mxb_should_log_t = bool (*)(int priority);
/**
* @brief Initialize the log
*
* This function must be called before any of the log function should be
* used.
*
* @param ident The syslog ident. If NULL, then the program name is used.
* @param logdir The directory for the log file. If NULL, file output is discarded.
* @param filename The name of the log-file. If NULL, the program name will be used
* if it can be deduced, otherwise the name will be "messages.log".
* @param target Logging target
* @param context_provider Optional function for providing contextual information
* at logging time.
*
* @return true if succeed, otherwise false
*/
bool mxb_log_init(const char* ident, const char* logdir, const char* filename,
mxb_log_target_t target, mxb_log_context_provider_t context_provider,
mxb_in_memory_log_t in_memory_log, mxb_should_log_t should_log);
/**
* @brief Finalize the log
*
* A successfull call to @c max_log_init() should be followed by a call
* to this function before the process exits.
*/
void mxb_log_finish();
/**
* @brief Initialize the log
*
* This function initializes the log using
* - the program name as the syslog ident,
* - the current directory as the logdir, and
* - the default log name (program name + ".log").
*
* @param target The specified target for the logging.
*
* @return True if succeeded, false otherwise.
*/
inline bool mxb_log_init(mxb_log_target_t target = MXB_LOG_TARGET_FS)
{
return mxb_log_init(nullptr, ".", nullptr, target, nullptr, nullptr, nullptr);
}
namespace maxbase
{
/**
* @class Log
*
* A simple utility RAII class where the constructor initializes the log and
* the destructor finalizes it.
*/
class Log
{
Log(const Log&) = delete;
Log& operator=(const Log&) = delete;
public:
Log(const char* ident,
const char* logdir,
const char* filename,
mxb_log_target_t target,
mxb_log_context_provider_t context_provider,
mxb_in_memory_log_t in_memory_log,
mxb_should_log_t should_log)
{
if (!mxb_log_init(ident, logdir, filename, target, context_provider, in_memory_log, should_log))
{
throw std::runtime_error("Failed to initialize the log.");
}
}
Log(mxb_log_target_t target = MXB_LOG_TARGET_FS)
: Log(nullptr, ".", nullptr, target, nullptr, nullptr, nullptr)
{
}
~Log()
{
mxb_log_finish();
}
};
// RAII class for setting and clearing the "scope" of the log messages. Adds the given object name to log
// messages as long as the object is alive.
class LogScope
{
public:
LogScope(const LogScope&) = delete;
LogScope& operator=(const LogScope&) = delete;
explicit LogScope(const char* name)
: m_prev_scope(s_current_scope)
, m_name(name)
{
s_current_scope = this;
}
~LogScope()
{
s_current_scope = m_prev_scope;
}
static const char* current_scope()
{
return s_current_scope ? s_current_scope->m_name : nullptr;
}
private:
LogScope* m_prev_scope;
const char* m_name;
static thread_local LogScope* s_current_scope;
};
// Class for redirecting the thread-local log message stream to a different handler. Only one of these should
// be constructed in the callstack.
class LogRedirect
{
public:
LogRedirect(const LogRedirect&) = delete;
LogRedirect& operator=(const LogRedirect&) = delete;
/**
* The message handler type
*
* @param level Syslog log level of the message
* @param msg The message itself
*
* @return True if the message was consumed (i.e. it should not be logged)
*/
using Func = bool (*)(int level, const std::string& msg);
explicit LogRedirect(Func func);
~LogRedirect();
static Func current_redirect();
private:
static thread_local Func s_redirect;
};
#define MXB_STREAM_LOG_HELPER(CMXBLOGLEVEL__, mxb_msg_str__) \
do { \
if (!mxb_log_is_priority_enabled(CMXBLOGLEVEL__)) \
{ \
break; \
} \
thread_local std::ostringstream os; \
os.str(std::string()); \
os << mxb_msg_str__; \
mxb_log_message(CMXBLOGLEVEL__, MXB_MODULE_NAME, __FILE__, __LINE__, \
__func__, "%s", os.str().c_str()); \
} while (false)
#define MXB_SALERT(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_ALERT, mxb_msg_str__)
#define MXB_SERROR(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_ERR, mxb_msg_str__)
#define MXB_SWARNING(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_WARNING, mxb_msg_str__)
#define MXB_SNOTICE(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_NOTICE, mxb_msg_str__)
#define MXB_SINFO(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_INFO, mxb_msg_str__)
#if defined (SS_DEBUG)
#define MXB_SDEBUG(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_DEBUG, mxb_msg_str__)
#else
#define MXB_SDEBUG(mxb_msg_str__)
#endif
}
| 29.255708
| 109
| 0.68472
|
sdrik
|
04eb53258babfb8b10e0b47571fad57dfe9d560f
| 6,577
|
hpp
|
C++
|
src/core/util/ImageProcessing.hpp
|
ShamylZakariya/KesslerSyndrome
|
dce00108304fe2c1b528515dafc29c15011d4679
|
[
"MIT"
] | null | null | null |
src/core/util/ImageProcessing.hpp
|
ShamylZakariya/KesslerSyndrome
|
dce00108304fe2c1b528515dafc29c15011d4679
|
[
"MIT"
] | null | null | null |
src/core/util/ImageProcessing.hpp
|
ShamylZakariya/KesslerSyndrome
|
dce00108304fe2c1b528515dafc29c15011d4679
|
[
"MIT"
] | null | null | null |
//
// ImageProgressing.hpp
// Kessler Syndrome
//
// Created by Shamyl Zakariya on 11/30/17.
//
#ifndef ImageProcessing_hpp
#define ImageProcessing_hpp
#include <cinder/Channel.h>
#include <cinder/Perlin.h>
#include "core/Common.hpp"
#include "core/MathHelpers.hpp"
namespace core {
namespace util {
namespace ip {
// perform a dilation pass such that each pixel in dst image is the max of the pixels in src kernel for that pixel
void dilate(const Channel8u &src, Channel8u &dst, int radius);
// perform a dilation pass such that each pixel in dst image is the min of the pixels in src kernel for that pixel
void erode(const Channel8u &src, Channel8u &dst, int radius);
// acting on copy of `src, floodfill into `dst
void floodfill(const Channel8u &src, Channel8u &dst, ivec2 start, uint8_t targetValue, uint8_t newValue, bool copy);
// remap values in `src which are of value `targetValue to `newTargetValue; all other values are converted to `defaultValue
void remap(const Channel8u &src, Channel8u &dst, uint8_t targetValue, uint8_t newTargetValue, uint8_t defaultValue);
// perform blur of size `radius of `src into `dst
void blur(const Channel8u &src, Channel8u &dst, int radius);
// for every value in src, maxV if pixelV >= threshV else minV
void threshold(const Channel8u &src, Channel8u &dst, uint8_t threshV = 128, uint8_t maxV = 255, uint8_t minV = 0);
// apply vignette effect to src, into dst, where pixels have vignetteColor applied as pixel radius from center approaches outerRadius
void vignette(const Channel8u &src, Channel8u &dst, double innerRadius, double outerRadius, uint8_t vignetteColor = 0);
// perform a dilation pass such that each pixel in result image is the max of the pixels in the kernel
inline Channel8u dilate(const Channel8u &src, int size) {
Channel8u dst;
::core::util::ip::dilate(src, dst, size);
return dst;
}
// perform a dilation pass such that each pixel in result image is the min of the pixels in the kernel
inline Channel8u erode(const Channel8u &src, int size) {
Channel8u dst;
::core::util::ip::erode(src, dst, size);
return dst;
}
// remap values in `src which are of value `targetValue to `newTargetValue; all other values are converted to `defaultValue
inline Channel8u remap(const Channel8u &src, uint8_t targetValue, uint8_t newTargetValue, uint8_t defaultValue) {
Channel8u dst;
::core::util::ip::remap(src, dst, targetValue, newTargetValue, defaultValue);
return dst;
}
// perform blur of size `radius
inline Channel8u blur(const Channel8u &src, int radius) {
Channel8u dst;
::core::util::ip::blur(src, dst, radius);
return dst;
}
// for every value in src, maxV if pixelV >= threshV else minV
inline Channel8u threshold(const Channel8u &src, uint8_t threshV = 128, uint8_t maxV = 255, uint8_t minV = 0) {
Channel8u dst;
::core::util::ip::threshold(src, dst, threshV, maxV, minV);
return dst;
}
// apply vignette effect to src, where pixels have vignetteColor applied as pixel radius from center approaches outerRadius
inline Channel8u vignette(const Channel8u &src, double innerRadius, double outerRadius, uint8_t vignetteColor = 0) {
Channel8u dst;
::core::util::ip::vignette(src, dst, innerRadius, outerRadius, vignetteColor);
return dst;
}
namespace in_place {
// operations which can act on a single channel, in-place, safely
// fill all pixels in channel with a given value
void fill(Channel8u &channel, uint8_t value);
// fill all pixels of rect in channel with a given value
void fill(Channel8u &channel, Area rect, uint8_t value);
// fill all pixels of channel with noise at a given frequency
void perlin(Channel8u &channel, Perlin &noise, double frequency);
// add value of the perlin noise function, scaled, to each existing pixel
void perlin_add(Channel8u &channel, Perlin &noise, double frequency, double scale);
// fill all pixels of channel with noise at a given frequency, where the noise is absoluted and thresholded
void perlin_abs_thresh(Channel8u &channel, Perlin &noise, double frequency, uint8_t threshold);
// flood fill into channel starting at `start, where pixels of `targetValue are changed to `newValue - modifies `channel
inline void floodfill(Channel8u &channel, ivec2 start, uint8_t targetValue, uint8_t newValue) {
::core::util::ip::floodfill(channel, channel, start, targetValue, newValue, false);
}
// remap values in `src which are of value `targetValue to `newTargetValue; all other values are converted to `defaultValue
inline void remap(Channel8u &channel, uint8_t targetValue, uint8_t newTargetValue, uint8_t defaultValue) {
::core::util::ip::remap(channel, channel, targetValue, newTargetValue, defaultValue);
}
// for every value in src, maxV if pixelV >= threshV else minV
inline void threshold(Channel8u &channel, uint8_t threshV = 128, uint8_t maxV = 255, uint8_t minV = 0) {
::core::util::ip::threshold(channel, channel, threshV, maxV, minV);
}
// apply vignette effect to src, where pixels have vignetteColor applied as pixel radius from center approaches outerRadius
inline void vignette(Channel8u &src, double innerRadius, double outerRadius, uint8_t vignetteColor = 0) {
::core::util::ip::vignette(src, src, innerRadius, outerRadius, vignetteColor);
}
}
}
}
} // end namespace core::util::ip
#endif /* ImageProcessing_hpp */
| 49.825758
| 145
| 0.610005
|
ShamylZakariya
|
04eb66a4e3bd630eb33cd10064113df68094b628
| 510
|
hpp
|
C++
|
wxRecognize/src/cDialogConfigureDetection.hpp
|
enzo418/Recognice-CCTV-c-
|
15da07a559d6de611452df4d404a15d4551c3017
|
[
"Apache-2.0"
] | 1
|
2020-09-06T21:44:56.000Z
|
2020-09-06T21:44:56.000Z
|
wxRecognize/src/cDialogConfigureDetection.hpp
|
enzo418/Recognice-CCTV-c-
|
15da07a559d6de611452df4d404a15d4551c3017
|
[
"Apache-2.0"
] | null | null | null |
wxRecognize/src/cDialogConfigureDetection.hpp
|
enzo418/Recognice-CCTV-c-
|
15da07a559d6de611452df4d404a15d4551c3017
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "wx/dialog.h"
#include "wx/textctrl.h"
#include "wx/button.h"
class cDialogConfigureDetection : public wxDialog {
public:
cDialogConfigureDetection ( wxWindow * parent, wxWindowID id, const wxString & title,
const wxPoint & pos,
const wxSize & size,
wxString& yoloCfg, wxString& yoloWeight, wxString& yoloClasses);
~cDialogConfigureDetection();
wxTextCtrl * dialogText;
wxString GetText();
// private:
// void OnOk(wxCommandEvent & event);
};
| 23.181818
| 87
| 0.696078
|
enzo418
|
04ebc87204d0b084f35987a10fe1f9168a7d3f3a
| 2,847
|
cpp
|
C++
|
pkcs11-gui/src/importp12dialog.cpp
|
T-Bonhagen/pkcs11-gui
|
95eed0e907235af826d79a58531dca07b77cca5d
|
[
"Apache-2.0"
] | 7
|
2018-06-06T12:53:46.000Z
|
2022-02-28T16:42:09.000Z
|
pkcs11-gui/src/importp12dialog.cpp
|
n3wtron/pkcs11-gui
|
faccbaa79dd58d803d8466ae28af7098c3a8e92a
|
[
"Apache-2.0"
] | 4
|
2020-07-28T06:46:28.000Z
|
2021-01-22T09:55:13.000Z
|
pkcs11-gui/src/importp12dialog.cpp
|
n3wtron/pkcs11-gui
|
faccbaa79dd58d803d8466ae28af7098c3a8e92a
|
[
"Apache-2.0"
] | 4
|
2018-04-25T16:57:55.000Z
|
2021-01-21T19:59:11.000Z
|
/*
* Copyright 2017 Igor Maculan <n3wtron@gmail.com>
*
* 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 <importp12dialog.h>
#include <ui_importp12dialog.h>
#include <QShowEvent>
#include <QFileDialog>
#include <QMessageBox>
#include <QtConcurrent/QtConcurrent>
ImportP12Dialog::ImportP12Dialog(QWidget *parent, SmartCardReader **smartCardReader) :
QDialog(parent),
ui(new Ui::ImportP12Dialog)
{
ui->setupUi(this);
this->smartCardReader = smartCardReader;
connect(ui->browseBtn,SIGNAL(clicked()),this,SLOT(browseFile()));
connect(ui->importBtn,SIGNAL(clicked()),this,SLOT(importP12()));
connect(ui->cancelBtn,SIGNAL(clicked()),this,SLOT(close()));
}
void ImportP12Dialog::browseFile(){
QString fileName = QFileDialog::getOpenFileName(this,tr("Open PEM Private Key"));
ui->privKeyFilePathEdt->setText(fileName);
}
void ImportP12Dialog::importP12(){
this->setEnabled(false);
QApplication::setOverrideCursor(Qt::WaitCursor);
if (*(this->smartCardReader)!=nullptr){
SmartCard* smCard = (*this->smartCardReader)->getSmartCard();
if (smCard!=NULL){
if (ui->privKeyFilePathEdt->text().isEmpty()){
QMessageBox::critical(this,tr("Import Private Key"),tr("Cannot import private key without a selected file"));
this->setEnabled(true);
QApplication::restoreOverrideCursor();
return;
}
QFile privKeyFile(ui->privKeyFilePathEdt->text());
if (!privKeyFile.exists()){
QMessageBox::critical(this,tr("Import Private Key"),tr("Cannot import private key. file does not exist"));
this->setEnabled(true);
QApplication::restoreOverrideCursor();
return;
}
Either<QString, bool> result = smCard->storeP12(ui->privKeyFilePathEdt->text(),ui->passwordEdt->text(),ui->labelEdt->text(),ui->idEdt->text().toInt());
if (result.isLeft){
QMessageBox::critical(this,tr("Import Private Key"),result.leftValue);
}else{
emit(this->imported());
this->close();
}
}
}
QApplication::restoreOverrideCursor();
this->setEnabled(true);
}
ImportP12Dialog::~ImportP12Dialog()
{
delete ui;
}
| 35.148148
| 163
| 0.651212
|
T-Bonhagen
|
04ed2a8339473a505b57b7cdaa6452d583729559
| 4,822
|
cpp
|
C++
|
5. Graph Theory/Connectivity/articulationPointsAndBridges.cpp
|
eashwaranRaghu/Data-Structures-and-Algorithms
|
3aad0f1da3d95b572fbb1950c770198bd042a80f
|
[
"MIT"
] | 6
|
2020-01-29T14:05:56.000Z
|
2021-04-24T04:37:27.000Z
|
5. Graph Theory/Connectivity/articulationPointsAndBridges.cpp
|
eashwaranRaghu/Data-Structures-and-Algorithms
|
3aad0f1da3d95b572fbb1950c770198bd042a80f
|
[
"MIT"
] | null | null | null |
5. Graph Theory/Connectivity/articulationPointsAndBridges.cpp
|
eashwaranRaghu/Data-Structures-and-Algorithms
|
3aad0f1da3d95b572fbb1950c770198bd042a80f
|
[
"MIT"
] | 1
|
2020-05-22T06:37:20.000Z
|
2020-05-22T06:37:20.000Z
|
// Created on 15-07-2019 18:51:46 by necronomicon
#include <bits/stdc++.h>
using namespace std;
#define MP make_pair
#define PB push_back
#define ARR_MAX (int)1e5 //Max array length
#define INF (int)1e9 //10^9
#define EPS 1e-9 //10^-9
#define MOD 1000000007 //10^9+7
#define PI 3.1415926535897932384626433832795
typedef long int int32;
typedef unsigned long int uint32;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef pair<int, int> Pii;
typedef vector<int> Vi;
typedef vector<string> Vs;
typedef vector<Pii> VPii;
typedef vector<Vi> VVi;
typedef map<int,int> Mii;
typedef set<int> Si;
typedef multimap<int,int> MMii;
typedef multiset<int> MSi;
typedef unordered_map<int,int> UMii;
typedef unordered_set<int> USi;
typedef unordered_multimap<int,int> UMMii;
typedef unordered_multiset<int> UMSi;
typedef priority_queue<int> PQi;
typedef queue<int> Qi;
typedef deque<int> DQi;
/*
We need 3 vectors : visited, ids and low (explained below)
Slow Algo:
Run dfs and find number of Connected components
for each vertex, remove it and run dfs, see if number of Connected Components increase. If it does then its an articulation point.
for each edge remove it and see if number of Connected Components increase. If it does then its an bridge.
Faster algo takes O(n) check it in single dfs.
Doesnt count if CC increase
Algo:
call dfs with 2 params the node to visit and its parent.
increment the global id/time
assign this node's id and low with it
call all the children of this node
if the node has children as parent skip it
if the child is already visited and child has lower low than id of current node then this child is an ancestor.
else child isnt discovered
if its low is lesser than id of current then this is bridge
if its low is lesser than or equal to id of current then this is artPoint
Time Complexity: O(n)
Space Complexity: O(n)
below links have same implementations
https://cp-algorithms.com/graph/cutpoints.html
https://www.youtube.com/watch?v=aZXi1unBdJA
*/
int id;
vector<bool> visited;
Vi ids; // stores uniqueId or timestamp based on discovery of node during dfs
Vi low; // stores the minimum uniqueId reachable from that node
VPii bridges; //contains the list of bridge-edges which can break the graph into more sets
Vi articulationPoints; //contains the list of cut-points which can break the graph into more sets
void dfs(VVi Adj, int at, int parent){
visited[at] = true;
id++;
low[at] = ids[at] = id;
int children = 0;
for (int to: Adj[at])
{
if(to == parent) continue; // if backedge to parent we dont do anything
if(visited[to]){ // this is backedge to an ancestor and we need its id as our low
low[at] = min(low[at], ids[to]);
}
else{ // a child is discovered which is undiscovered and we need to update our low with its low (not its id)
dfs(Adj, to, at);
low[at] = min(low[at], low[to]);
if(ids[at] < low[to]){ // if child (to) is not linked to an ancestor above (at)
bridges.push_back({at, to});
}
if(ids[at] <= low[to] && parent != -1){ // if the child has lowest
articulationPoints.push_back(at);
}
children++; // only required for checking if the root can be an articulation point. When dfs starts from root and marks all nodes visited then this remains 1 hence not artPoint.
}
}
if(parent == -1 && children > 1){
articulationPoints.push_back(at);
}
}
void find(VVi Adj){
visited = vector<bool>(Adj.size(), false),
ids = Vi(Adj.size(), 0),
low = Vi(Adj.size(), 0),
id = -1;
bridges.clear();
articulationPoints.clear();
for(int i=0; i<Adj.size(); i++){
if(!visited[i]){
dfs(Adj, i, -1);
}
}
}
int main (int argc, char const *argv[]) {
VVi Adj; // Adjency list
Adj = {
{1,2},
{0,2},
{0,1,3,5},
{2,4},
{3},
{2,6,8},
{5,7},
{6,8},
{5,7}
};
// Adj = {
// {1},
// {2,3,4,5},
// {1},
// {1},
// {1, 5},
// {1, 4}
// };
// Adj = {
// {1,2},
// {0,2},
// {0,1}
// };
find(Adj);
std::for_each(std::begin(bridges), std::end(bridges), [](Pii p) {
cout << p.first << ' ' << p.second << endl;
});
cout << endl;
std::for_each(std::begin(articulationPoints), std::end(articulationPoints), [](int x) {
cout << x << ' ';
});
return EXIT_SUCCESS;
}
| 32.362416
| 190
| 0.597677
|
eashwaranRaghu
|
04f4016359f6f2986f2fdf3f368e5a69cd757811
| 11,727
|
cpp
|
C++
|
main/PIKern/KextDeviceNotify.cpp
|
minku1024/endpointdlp
|
931ab140eef053498907d1db74a5c055bea8ef93
|
[
"Apache-2.0"
] | 33
|
2020-11-18T09:30:13.000Z
|
2022-03-03T17:56:24.000Z
|
main/PIKern/KextDeviceNotify.cpp
|
s4ngsuk-sms/endpointdlp
|
9e87e352e23bff3b5e0701dd278756aadc8a0539
|
[
"Apache-2.0"
] | 25
|
2020-07-31T01:43:17.000Z
|
2020-11-27T12:32:09.000Z
|
main/PIKern/KextDeviceNotify.cpp
|
s4ngsuk-sms/endpointdlp
|
9e87e352e23bff3b5e0701dd278756aadc8a0539
|
[
"Apache-2.0"
] | 26
|
2020-11-18T09:30:15.000Z
|
2022-01-18T08:24:01.000Z
|
#include <stdio.h>
#include <string.h>
#ifdef LINUX
#include <stdlib.h>
#include <mntent.h>
#include <libudev.h>
#else
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h>
#import <IOKit/usb/IOUSBLib.h>
#import <IOKit/hid/IOHIDKeys.h>
#endif
#ifdef LINUX
#include "../../PISupervisor/apple/include/KernelProtocol.h"
#else
#include "../../PISupervisor/PISupervisor/apple/include/KernelProtocol.h"
#endif
#include "KextDeviceNotify.h"
#include "PISecSmartDrv.h"
#ifndef VFS_RETURNED
#define VFS_RETURNED 0
#endif
#ifdef LINUX
int EnumMountCallback(void* pMount, void* pParam);
#else
int EnumMountCallback(mount_t pMount, void* pParam);
#endif
void FetchVolumes()
{
VolCtx_Clear();
EnumMountCallback(NULL, NULL);
}
#ifdef LINUX
int get_storage_type(struct udev* udev, char* mnt_fsname)
{
int ret = BusTypeUnknown;
struct udev_enumerate* enumerate = NULL;
if (udev == NULL || mnt_fsname == NULL)
return ret;
enumerate = udev_enumerate_new(udev);
if (enumerate == NULL)
return ret;
printf("DEVNAME = %s\n", mnt_fsname);
udev_enumerate_add_match_property(enumerate, "DEVNAME", mnt_fsname);
udev_enumerate_scan_devices(enumerate);
struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
struct udev_list_entry *entry = NULL;
udev_list_entry_foreach(entry, devices)
{
const char* path = udev_list_entry_get_name(entry);
if (path == NULL)
continue;
struct udev_device* parent = udev_device_new_from_syspath(udev, path);
if (parent == NULL)
continue;
const char *id_cdrom = udev_device_get_property_value(parent, "ID_CDROM");
//printf("\tproperty [ID_CDROM][%s]\n", id_cdrom);
const char *devtype = udev_device_get_property_value(parent, "DEVTYPE");
//printf("\tproperty [DEVTYPE][%s]\n", devtype);
if (id_cdrom != NULL)
{
ret = BusTypeAtapi;
}
else if (devtype != NULL)
{
ret = BusTypeUsb;
}
break;
}
udev_enumerate_unref(enumerate);
if (ret == BusTypeUnknown)
{
#ifdef WSL
ret = BusTypeUsb;
#else
ret = BusTypeSFolder;
#endif
}
return ret;
}
int EnumMountCallback(void *pMount, void* pParam)
#else
int EnumMountCallback(mount_t pMount, void* pParam)
#endif
{
int nBusType = 0;
boolean_t bUsbStor = FALSE;
boolean_t bCDStor = FALSE;
boolean_t bSFolder = FALSE;
boolean_t bTBStor = FALSE;
#ifdef LINUX
struct mntent *ent = NULL;
FILE *aFile = NULL;
struct udev* udev = NULL;
aFile = setmntent("/proc/mounts", "r");
if (aFile == NULL)
{
printf("[DLP][%s] setmntent() failed \n", __FUNCTION__);
return -1;
}
udev = udev_new();
if (udev == NULL)
{
printf("[DLP][%s] udev_new() failed \n", __FUNCTION__);
endmntent(aFile);
return -1;
}
while (NULL != (ent = getmntent(aFile)))
{
// e.g.
// f_mntonname /media/somansa/PRIVACY-I
// f_mntfromname /dev/sdb1
//
// ent->mnt_fsname, ent->mnt_dir, ent->mnt_type, ent->mnt_opts
// /dev/sdb1 /media/somansa/PRIVACY-I vfat rw,nosuid,nodev,relatime,uid=1001,gid=1001,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,showexec,utf8,flush,errors=remount-ro
// /dev/sda3 / ext4 rw,relatime,errors=remount-ro
#ifdef WSL
if (strstr(ent->mnt_dir, "/dev/") == NULL && strstr(ent->mnt_dir, "/mnt/") == NULL)
#else
if (strstr(ent->mnt_fsname, "/dev/") == NULL && strstr(ent->mnt_fsname, "/mnt/") == NULL)
#endif
{
#ifdef WSL
if (ent->mnt_fsname[0] == '/' && ent->mnt_fsname[1] == '/')
#else
if (ent->mnt_dir[0] == '/' && ent->mnt_dir[1] == '/')
#endif
{
// //192.168.181.1/tmp
}
else
{
continue;
}
}
else
{
#ifdef WSL
#else
// /dev/sda3 /
if (ent->mnt_dir[0] == '/' && ent->mnt_dir[1] == 0)
{
continue;
}
#endif
}
#ifdef WSL
if (strlen(ent->mnt_dir) <= 1)
#else
if (strlen(ent->mnt_fsname) <= 1)
#endif
{
continue;
}
//printf("%s %s %s %s \n", ent->mnt_fsname, ent->mnt_dir, ent->mnt_type, ent->mnt_opts);
//#ifdef WSL
int type = get_storage_type(udev, ent->mnt_fsname);
//#else
// int type = get_storage_type(udev, ent->mnt_dir);
//#endif
VolCtx_Update( ent->mnt_fsname, ent->mnt_dir, type );
}
endmntent(aFile);
udev_unref(udev);
return 0;
#else
// Get all mounted path
NSArray *mounted = [[NSFileManager defaultManager] mountedVolumeURLsIncludingResourceValuesForKeys:nil options:0];
// Get mounted USB information
for(NSURL *url in mounted) {
char f_mntfromname[MAX_PATH] = {0};
char f_mntonname[MAX_PATH] = {0};
char f_fstypename[] = "";
GetMountPath([url.path UTF8String], f_mntonname, sizeof(f_mntonname), f_mntfromname, sizeof(f_mntfromname));
if (f_mntfromname[0] == 0 || f_mntonname[0] == 0)
continue;
// 1. Volume Context Search.
nBusType = VolCtx_Search_BusType( f_mntonname );
if(nBusType == BusTypeUsb ||
nBusType == BusType1394 ||
nBusType == BusTypeThunderBolt ||
nBusType == BusTypeAtapi ||
nBusType == BusTypeSFolder)
{
switch(nBusType)
{
case BusType1394:
case BusTypeUsb:
bUsbStor = TRUE;
break;
case BusTypeThunderBolt:
bTBStor = TRUE;
break;
case BusTypeAtapi:
bCDStor = TRUE;
break;
case BusTypeSFolder:
bSFolder = TRUE;
break;
default: break;
}
}
else
{ // 2. First Acess Check.
bUsbStor = IsMediaPath_UsbStor( f_mntonname );
if(bUsbStor)
{
nBusType = BusTypeUsb;
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeUsb );
}
bCDStor = IsMediaPath_CDStor( f_mntonname );
if(bCDStor)
{
nBusType = BusTypeAtapi;
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeAtapi );
}
bSFolder = IsMediaPath_SFolder( f_mntfromname, f_mntonname, f_fstypename );
if(bSFolder)
{
nBusType = BusTypeSFolder;
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeSFolder );
}
}
}
return (VFS_RETURNED); //VFS_RETURENED_DONE
#endif
}
boolean_t
IsControlDeviceType( const vnode_t pVnode, const char* pczPath )
{
boolean_t bSFolder = FALSE;
boolean_t bUsbStor = FALSE;
boolean_t bCDStor = FALSE;
boolean_t bTBStor = FALSE;
boolean_t bVoulmesDir = FALSE;
boolean_t bCups = FALSE;
//if(!pVnode) return FALSE;
if(pczPath)
{
bCups = IsCupsDirectory( pczPath );
if(TRUE == bCups) return TRUE;
}
if(pczPath)
{
bVoulmesDir = IsVolumesDirectory( pczPath );
// printf("[DLP][%s] pczPath=%s \n", __FUNCTION__, pczPath );
}
char f_mntonname[MAX_PATH] = {0};
char f_mntfromname[MAX_PATH] = {0};
char f_fstypename[] = "";
if(bVoulmesDir)
{
int nBusType = 0;
// e.g.
// f_mntonname /Volumes/새 볼륨
// f_mntfromname disk2s2
GetMountPath(pczPath, f_mntonname, sizeof(f_mntonname), f_mntfromname, sizeof(f_mntfromname));
// 1. Volume Context Search.
//nBusType = VolCtx_Search_BusType( Stat.f_mntonname );
nBusType = VolCtx_Search_BusType( f_mntonname );
if(nBusType == BusTypeUsb || nBusType == BusType1394 ||
nBusType == BusTypeThunderBolt || nBusType == BusTypeAtapi || nBusType == BusTypeSFolder)
{
return TRUE;
}
// 2. First Acess Check.
//bUsbStor = IsMediaPath_UsbStor( f_mntfromname );
bUsbStor = IsMediaPath_UsbStor( f_mntonname );
if(bUsbStor)
{
printf("[DLP][%s] UsbStor=1, fs=%s, from=%s, name=%s \n", __FUNCTION__, f_fstypename, f_mntfromname, f_mntonname );
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeUsb );
return bUsbStor;
}
//bCDStor = IsMediaPath_CDStor( f_mntfromname );
bCDStor = IsMediaPath_CDStor( f_mntonname );
if(bCDStor)
{
printf("[DLP][%s] CDStor=1, fs=%s, from=%s, name=%s \n", __FUNCTION__, f_fstypename, f_mntfromname, f_mntonname );
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeAtapi );
return bCDStor;
}
bSFolder = IsMediaPath_SFolder( f_mntfromname, f_mntonname, f_fstypename );
if(bSFolder)
{
// '/Volumes/shared2/.DS_Store' skip
printf("[DLP][%s] SFolder=1, fs=%s, from=%s, name=%s, pczPath=%s \n", __FUNCTION__, f_fstypename, f_mntfromname, f_mntonname, pczPath );
if(NULL == sms_strnstr( pczPath, "/.DS_Store", strlen("/.DS_Store") ))
{
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeSFolder );
return bSFolder;
}
else
return FALSE;
}
}
return FALSE;
}
boolean_t
IsCupsdConfigFile( const char* pczPath )
{
boolean_t bCups = FALSE;
size_t nlen = 0;
if(!pczPath)
return FALSE;
if(pczPath)
{
nlen = strlen(FILE_CUPSD_CONFIG);
if(nlen > 0 && 0 == strncasecmp( pczPath, FILE_CUPSD_CONFIG, nlen))
{
bCups = TRUE;
}
}
return bCups;
}
boolean_t
IsCupsDirectory(const char* pczPath)
{
size_t nLength = 0;
size_t nCups = 0;
if(!pczPath) return FALSE;
nLength = strlen(pczPath);
nCups = strlen(g_czCupsSpoolPath);
if(0 == nCups || nLength < nCups) return FALSE;
if(0 == strncasecmp( pczPath, g_czCupsSpoolPath, nCups ))
{
size_t nLenght = (int)strlen(pczPath);
int nAdd = ('/' == g_czCupsSpoolPath[nCups-1])?0:1;
for(size_t i=nCups+nAdd; i<nLenght; i++)
{
// is file??
if('/' == pczPath[i])
{
printf("[DLP][%s] Detected Path is not file=%s \n", __FUNCTION__, pczPath );
return FALSE;
}
}
printf("[DLP][%s] Detect Path=%s \n", __FUNCTION__, pczPath );
return TRUE;
}
return FALSE;
}
boolean_t IsVolumesDirectory(const char* path)
{
boolean_t volumesDir = FALSE;
#ifdef LINUX
volumesDir = TRUE;
#else
if (path != NULL &&
strlen(path) >= strlen("/Volumes/") &&
*(path+0) == '/' &&
*(path+1) == 'V' &&
*(path+2) == 'o' &&
*(path+3) == 'l' &&
*(path+4) == 'u' &&
*(path+5) == 'm' &&
*(path+6) == 'e' &&
*(path+7) == 's' &&
*(path+8) == '/')
{
volumesDir = TRUE;
}
#endif
return volumesDir;
}
void SetProtectUsbMobileNotify(void)
{
}
void SetProtect_Camera_UsbDeviceNotify(void)
{
}
void SetProtect_RNDIS_UsbDeviceNotify(void)
{
}
void SetProtect_RNDIS_BthDeviceNotify(void)
{
}
boolean_t
KextNotify_Init()
{
return true;
}
boolean_t
KextNotify_Uninit()
{
return true;
}
| 25.660832
| 202
| 0.560672
|
minku1024
|
04f4f85c36d483addd2997684f76e5dd9ccf0604
| 16,923
|
cpp
|
C++
|
src/tx/dexoperatortx.cpp
|
xiaoyu1998/wasm.bitcoin
|
0fbd7bdc4555382abca64b5df33e8aec7a65ff3b
|
[
"MIT"
] | 1,313
|
2018-01-09T01:49:01.000Z
|
2022-02-26T11:10:40.000Z
|
src/tx/dexoperatortx.cpp
|
linnbenton/WaykiChain
|
91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a
|
[
"MIT"
] | 32
|
2018-06-07T10:21:21.000Z
|
2021-12-07T06:53:42.000Z
|
src/tx/dexoperatortx.cpp
|
linnbenton/WaykiChain
|
91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a
|
[
"MIT"
] | 322
|
2018-02-26T03:41:36.000Z
|
2022-02-08T08:12:16.000Z
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2017-2019 The WaykiChain Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dexoperatortx.h"
#include "config/configuration.h"
#include "main.h"
#include <regex>
#include <algorithm>
////////////////////////////////////////////////////////////////////////////////
// ProcessAssetFee
static const string OPERATOR_ACTION_REGISTER = "register";
static const string OPERATOR_ACTION_UPDATE = "update";
static const uint32_t MAX_NAME_LEN = 32;
static const uint64_t MAX_MATCH_FEE_RATIO_VALUE = 50000000; // 50%
static const uint64_t ORDER_OPEN_DEXOP_LIST_SIZE_MAX = 500;
static bool ProcessDexOperatorFee(CBaseTx &tx, CTxExecuteContext& context, const string &action) {
IMPLEMENT_DEFINE_CW_STATE;
uint64_t exchangeFee = 0;
if (action == OPERATOR_ACTION_REGISTER) {
if (!cw.sysParamCache.GetParam(DEX_OPERATOR_REGISTER_FEE, exchangeFee))
return state.DoS(100, ERRORMSG("read param DEX_OPERATOR_REGISTER_FEE error"),
REJECT_INVALID, "read-sysparam-error");
} else {
assert(action == OPERATOR_ACTION_UPDATE);
if (!cw.sysParamCache.GetParam(DEX_OPERATOR_UPDATE_FEE, exchangeFee))
return state.DoS(100, ERRORMSG("read param DEX_OPERATOR_UPDATE_FEE error"),
REJECT_INVALID, "read-sysparam-error");
}
if (!tx.sp_tx_account->OperateBalance(SYMB::WICC, BalanceOpType::SUB_FREE, exchangeFee,
ReceiptType::DEX_OPERATOR_REG_UPDATE_FEE_FROM_OPERATOR, tx.receipts))
return state.DoS(100, ERRORMSG("tx account insufficient funds for operator %s fee! fee=%llu, tx_addr=%s",
action, exchangeFee, tx.sp_tx_account->keyid.ToAddress()),
UPDATE_ACCOUNT_FAIL, "insufficent-funds");
uint64_t dexOperatorRiskFeeRatio;
if(!cw.sysParamCache.GetParam(SysParamType::DEX_OPERATOR_RISK_FEE_RATIO, dexOperatorRiskFeeRatio)) {
return state.DoS(100, ERRORMSG("ProcessDexOperatorFee, get dexOperatorRiskFeeRatio error"),
READ_SYS_PARAM_FAIL, "read-db-error");
}
uint64_t riskFee = exchangeFee * dexOperatorRiskFeeRatio / RATIO_BOOST;
uint64_t minerTotalFee = exchangeFee - riskFee;
auto spFcoinAccount = tx.GetAccount(context, SysCfg().GetFcoinGenesisRegId(), "fcoin");
if (!spFcoinAccount) return false;
ReceiptType code = (action == OPERATOR_ACTION_REGISTER) ? ReceiptType::DEX_OPERATOR_REG_FEE_TO_RESERVE :
ReceiptType::DEX_OPERATOR_UPDATED_FEE_TO_RESERVE;
if (!spFcoinAccount->OperateBalance(SYMB::WICC, BalanceOpType::ADD_FREE, riskFee, code, tx.receipts)) {
return state.DoS(100, ERRORMSG("operate balance failed! add %s asset fee=%llu to risk reserve account error",
action, riskFee), UPDATE_ACCOUNT_FAIL, "update-account-failed");
}
VoteDelegateVector delegates;
if (!cw.delegateCache.GetActiveDelegates(delegates)) {
return state.DoS(100, ERRORMSG("GetActiveDelegates failed"), REJECT_INVALID, "get-delegates-failed");
}
assert(delegates.size() != 0 );
for (size_t i = 0; i < delegates.size(); i++) {
const CRegID &delegateRegid = delegates[i].regid;
auto spDelegateAccount = tx.GetAccount(context, delegateRegid, "delegate_regid");
if (!spDelegateAccount) return false;
uint64_t minerFee = minerTotalFee / delegates.size();
if (i == 0) minerFee += minerTotalFee % delegates.size(); // give the dust amount to topmost miner
ReceiptType code = (action == OPERATOR_ACTION_REGISTER) ? ReceiptType::DEX_OPERATOR_REG_FEE_TO_MINER :
ReceiptType::DEX_OPERATOR_UPDATED_FEE_TO_MINER;
if (!spDelegateAccount->OperateBalance(SYMB::WICC, BalanceOpType::ADD_FREE, minerFee, code, tx.receipts)) {
return state.DoS(100, ERRORMSG("add %s asset fee to miner failed, miner regid=%s",
action, delegateRegid.ToString()), UPDATE_ACCOUNT_FAIL, "operate-account-failed");
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
// class CDEXOperatorRegisterTx
Object CDEXOperatorRegisterTx::ToJson(CCacheWrapper &cw) const {
Object result = CBaseTx::ToJson(cw);
result.push_back(Pair("owner_uid", data.owner_uid.ToString()));
result.push_back(Pair("fee_receiver_uid", data.fee_receiver_uid.ToString()));
result.push_back(Pair("dex_name", data.name));
result.push_back(Pair("portal_url", data.portal_url));
result.push_back(Pair("maker_fee_ratio",data.maker_fee_ratio));
result.push_back(Pair("taker_fee_ratio",data.taker_fee_ratio));
result.push_back(Pair("memo",data.memo));
return result;
}
bool CDEXOperatorRegisterTx::CheckTx(CTxExecuteContext &context) {
CValidationState &state = *context.pState;
if (!data.owner_uid.is<CRegID>())
return state.DoS(100, ERRORMSG("owner_uid must be regid"), REJECT_INVALID,
"owner-uid-type-error");
if (!data.fee_receiver_uid.is<CRegID>())
return state.DoS(100, ERRORMSG("fee_receiver_uid must be regid"), REJECT_INVALID,
"match-uid-type-error");
if (data.name.size() > MAX_NAME_LEN)
return state.DoS(100, ERRORMSG("name len=%d greater than %d",
data.name.size(), MAX_NAME_LEN), REJECT_INVALID, "invalid-name");
if(data.memo.size() > MAX_COMMON_TX_MEMO_SIZE)
return state.DoS(100, ERRORMSG("memo len=%d greater than %d",
data.memo.size(), MAX_COMMON_TX_MEMO_SIZE), REJECT_INVALID, "invalid-memo");
if (data.maker_fee_ratio > MAX_MATCH_FEE_RATIO_VALUE)
return state.DoS(100, ERRORMSG("maker_fee_ratio=%d is greater than %d",
data.maker_fee_ratio, MAX_MATCH_FEE_RATIO_VALUE), REJECT_INVALID, "invalid-match-fee-ratio-type");
if (data.taker_fee_ratio > MAX_MATCH_FEE_RATIO_VALUE)
return state.DoS(100, ERRORMSG("taker_fee_ratio=%d is greater than %d",
data.taker_fee_ratio, MAX_MATCH_FEE_RATIO_VALUE), REJECT_INVALID, "invalid-match-fee-ratio-type");
if (data.order_open_dexop_list.size() > ORDER_OPEN_DEXOP_LIST_SIZE_MAX)
return state.DoS(100, ERRORMSG("size=%u of order_open_dexop_list exceed max=%u",
data.order_open_dexop_list.size(), ORDER_OPEN_DEXOP_LIST_SIZE_MAX),
REJECT_INVALID, "invalid-shared-dexop-list-size");
return true;
}
bool CDEXOperatorRegisterTx::ExecuteTx(CTxExecuteContext &context) {
CCacheWrapper &cw = *context.pCw; CValidationState &state = *context.pState;
DexOpIdValueSet dexIdSet;
for (auto &item : data.order_open_dexop_list) {
if (!cw.dexCache.HaveDexOperator(item.get())) {
return state.DoS(100, ERRORMSG("operator item=%s not exist",
db_util::ToString(item)), REJECT_INVALID, "operator-not-exist");
}
auto ret = dexIdSet.insert(item);
if (!ret.second) {
return state.DoS(100, ERRORMSG("duplicated item=%s in order_open_dexop_list",
db_util::ToString(item)), REJECT_INVALID, "duplicated-item-of-dexop-list");
}
}
shared_ptr<CAccount> spOwnerAccount;
if (sp_tx_account->IsSelfUid(data.owner_uid)) {
spOwnerAccount = sp_tx_account;
} else {
spOwnerAccount = GetAccount(context, data.owner_uid, "owner_uid");
if (!spOwnerAccount) return false;
}
shared_ptr<CAccount> pMatchAccount;
if (!sp_tx_account->IsSelfUid(data.fee_receiver_uid) && !sp_tx_account->IsSelfUid(data.fee_receiver_uid)) {
pMatchAccount = GetAccount(context, data.fee_receiver_uid, "fee_receiver_uid");
if (!pMatchAccount) return false;
}
if (cw.dexCache.HasDexOperatorByOwner(spOwnerAccount->regid))
return state.DoS(100, ERRORMSG("the owner's operator exist! owner_regid=%s",
spOwnerAccount->regid.ToString()), REJECT_INVALID, "owner-dexoperator-exist");
if (!ProcessDexOperatorFee(*this, context, OPERATOR_ACTION_REGISTER))
return false;
uint32_t new_id;
if (!cw.dexCache.IncDexID(new_id))
return state.DoS(100, ERRORMSG("increase dex id error! txUid=%s", GetHash().ToString() ),
UPDATE_ACCOUNT_FAIL, "inc_dex_id_error");
DexOperatorDetail detail = {
data.owner_uid.get<CRegID>(),
data.fee_receiver_uid.get<CRegID>(),
data.name,
data.portal_url,
data.order_open_mode,
data.maker_fee_ratio,
data.taker_fee_ratio,
dexIdSet,
data.memo
};
if (!cw.dexCache.CreateDexOperator(new_id, detail))
return state.DoS(100, ERRORMSG("save new dex operator error! new_id=%u", new_id),
UPDATE_ACCOUNT_FAIL, "save-operator-error");
return true;
}
bool CDEXOperatorUpdateData::Check(CBaseTx &tx, CCacheWrapper &cw, string& errmsg, string& errcode,const uint32_t currentHeight){
DexOperatorDetail dex;
if(!cw.dexCache.GetDexOperator(dexId,dex)) {
errmsg = strprintf("dexoperator(id=%d) not found", dexId);
errcode = "invalid-dex-id";
return false;
}
if(field == UPDATE_NONE || field > MEMO ){
errmsg = "CDEXOperatorUpdateData::check(): update field is error";
errcode= "empty-update-data";
return false;
}
if (field == FEE_RECEIVER_UID || field == OWNER_UID){
string placeholder = (field == FEE_RECEIVER_UID)? "fee_receiver": "owner";
const auto &uid = get<CUserID>();
auto spAccount = tx.GetAccount(cw, uid);
if (!spAccount) {
errmsg = strprintf("CDEXOperatorUpdateData::check(): %s_uid (%s) is not exist! ",placeholder, ValueToString());
errcode = strprintf("%s-uid-invalid", placeholder);
return false;
}
if (!spAccount->IsRegistered() || !spAccount->regid.IsMature(currentHeight)) {
errmsg = strprintf("CDEXOperatorUpdateData::check(): %s_uid (%s) not register or regid is immature ! ",placeholder, ValueToString() );
errcode = strprintf("%s-uid-invalid", placeholder);
return false;
}
}
if (field == NAME && get<string>().size() > MAX_NAME_LEN) {
errmsg = strprintf("%s, name len=%d greater than %d", __func__,get<string>().size(), MAX_NAME_LEN);
errcode = "invalid-name";
return false;
}
if (field == MEMO && get<string>().size() > MAX_COMMON_TX_MEMO_SIZE){
errmsg = strprintf("%s, memo len=%d greater than %d", __func__,get<string>().size(), MAX_COMMON_TX_MEMO_SIZE);
errcode = "invalid-memo";
return false;
}
if (field == TAKER_FEE_RATIO || field == MAKER_FEE_RATIO ){
uint64_t v = get<uint64_t>();
if( v > MAX_MATCH_FEE_RATIO_VALUE){
errmsg = strprintf("%s, fee_ratio=%d is greater than %d", __func__,
v, MAX_MATCH_FEE_RATIO_VALUE);
errcode = "invalid-match-fee-ratio-type";
return false;
}
}
if (field == OPEN_MODE) {
dex::OpenMode om = get<dex::OpenMode>();
if (om != dex::OpenMode::PRIVATE && om != dex::OpenMode::PUBLIC) {
errmsg = strprintf("dex open mode value(%d) is error", (uint8_t)om);
errcode = "invalid-open-mode";
return false;
}
if (om == dex.order_open_mode) {
errmsg = strprintf("the new dex open mode value(%d) is as same as old open mode", (uint8_t)om);
errcode = "same-open-mode";
return false;
}
}
if (field == ORDER_OPEN_DEXOP_LIST) {
const auto &dexlist = get<DexOpIdValueList>();
if (dexlist.size() > ORDER_OPEN_DEXOP_LIST_SIZE_MAX) {
errmsg = strprintf("size=%u of order_open_dexop_list exceed max=%u",
dexlist.size(), ORDER_OPEN_DEXOP_LIST_SIZE_MAX);
errcode = "invalid-shared-dexop-list-size";
return false;
}
DexOpIdValueSet dexIdSet;
for (auto dexOpId : dexlist) {
if (dexOpId.get() == dexId) {
errmsg = strprintf("dexid=%d is self", dexOpId.get());
errcode = "self-dexid-error";
return false;
}
if (!cw.dexCache.HaveDexOperator(dexOpId.get())) {
errmsg = strprintf("dex(id=%d) not exist!!", dexOpId.get());
errcode = "dexid-not-exist";
return false;
}
}
}
return true;
}
bool CDEXOperatorUpdateData::UpdateToDexOperator(DexOperatorDetail& detail,CCacheWrapper& cw) {
switch (field) {
case FEE_RECEIVER_UID:{
if(get<CUserID>().is<CRegID>()) {
detail.fee_receiver_regid = get<CUserID>().get<CRegID>();
return true;
} else{
return false;
}
}
case OWNER_UID:{
if(get<CUserID>().is<CRegID>()){
detail.owner_regid = get<CUserID>().get<CRegID>();
return true;
} else{
return false;
}
}
case NAME:
detail.name = get<string>();
break;
case PORTAL_URL:
detail.portal_url = get<string>();
break;
case TAKER_FEE_RATIO:
detail.taker_fee_ratio = get<uint64_t>();
break;
case MAKER_FEE_RATIO:
detail.maker_fee_ratio = get<uint64_t>();
break;
case MEMO:
detail.memo = get<string>();
break;
case OPEN_MODE:
detail.order_open_mode = get<dex::OpenMode>();
break;
case ORDER_OPEN_DEXOP_LIST:{
const auto &dexIdList = get<DexOpIdValueList>();
DexOpIdValueSet dexIdSet;
for (auto dexId: dexIdList) {
dexIdSet.insert(dexId);
}
detail.order_open_dexop_set = dexIdSet;
break;
}
default:
return false;
}
return true;
}
string CDEXOperatorUpdateTx::ToString(CAccountDBCache &accountCache) {
return "";
}
Object CDEXOperatorUpdateTx::ToJson(CCacheWrapper &cw) const {
Object result = CBaseTx::ToJson(cw);
result.push_back(Pair("update_field", update_data.field));
result.push_back(Pair("update_value", update_data.ValueToString()));
result.push_back(Pair("dex_id", update_data.dexId));
return result;
}
bool CDEXOperatorUpdateTx::CheckTx(CTxExecuteContext &context) {
IMPLEMENT_DEFINE_CW_STATE;
string errmsg;
string errcode;
if(!update_data.Check(*this, cw, errmsg ,errcode, context.height )){
return state.DoS(100, ERRORMSG("%s", errmsg), REJECT_INVALID, errcode);
}
if(update_data.field == CDEXOperatorUpdateData::OWNER_UID){
if(cw.dexCache.HasDexOperatorByOwner(CRegID(update_data.ValueToString())))
return state.DoS(100, ERRORMSG("the owner already has a dex operator! owner_regid=%s",
update_data.ValueToString()), REJECT_INVALID, "owner-had-dexoperator");
}
return true;
}
bool CDEXOperatorUpdateTx::ExecuteTx(CTxExecuteContext &context) {
CCacheWrapper &cw = *context.pCw; CValidationState &state = *context.pState;
DexOperatorDetail oldDetail;
if (!cw.dexCache.GetDexOperator((DexID)update_data.dexId, oldDetail))
return state.DoS(100, ERRORMSG("the dexoperator( id= %u) is not exist!",
update_data.dexId), UPDATE_ACCOUNT_FAIL, "dexoperator-not-exist");
if (!sp_tx_account->IsSelfUid(oldDetail.owner_regid))
return state.DoS(100, ERRORMSG("only owner can update dexoperator! owner_regid=%s, txUid=%s, dexId=%u",
oldDetail.owner_regid.ToString(),txUid.ToString(), update_data.dexId),
UPDATE_ACCOUNT_FAIL, "dexoperator-update-permession-deny");
if (!ProcessDexOperatorFee(*this, context, OPERATOR_ACTION_UPDATE))
return false;
DexOperatorDetail detail = oldDetail;
if (!update_data.UpdateToDexOperator(detail, cw))
return state.DoS(100, ERRORMSG("copy updated dex operator error! dex_id=%u", update_data.dexId),
UPDATE_ACCOUNT_FAIL, "copy-updated-operator-error");
if (!cw.dexCache.UpdateDexOperator(update_data.dexId, oldDetail, detail))
return state.DoS(100, ERRORMSG("save updated dex operator error! dex_id=%u", update_data.dexId),
UPDATE_ACCOUNT_FAIL, "save-updated-operator-error");
return true;
}
| 40.778313
| 146
| 0.629085
|
xiaoyu1998
|
04f50b1dcb0423c4c6aa123021f3eb27c0d528bc
| 650
|
hh
|
C++
|
Sources/AGEngine/Render/Pipelining/Pipelines/CustomRenderPass/GaussianBlur.hh
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 47
|
2015-03-29T09:44:25.000Z
|
2020-11-30T10:05:56.000Z
|
Sources/AGEngine/Render/Pipelining/Pipelines/CustomRenderPass/GaussianBlur.hh
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 313
|
2015-01-01T18:16:30.000Z
|
2015-11-30T07:54:07.000Z
|
Sources/AGEngine/Render/Pipelining/Pipelines/CustomRenderPass/GaussianBlur.hh
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 9
|
2015-06-07T13:21:54.000Z
|
2020-08-25T09:50:07.000Z
|
#pragma once
#include <Render/Pipelining/Render/FrameBufferRender.hh>
#include <glm\glm.hpp>
namespace AGE
{
class Texture2D;
class Program;
class GaussianBlur : public FrameBufferRender
{
public:
GaussianBlur(glm::uvec2 const &screenSize, std::shared_ptr<PaintingManager> painterManager,
std::shared_ptr<Texture2D> src, std::shared_ptr<Texture2D> dst, bool horizontal);
virtual ~GaussianBlur() = default;
protected:
virtual void renderPass(const DRBCameraDrawableList &infos);
glm::vec2 _inverseSourceSize;
std::shared_ptr<Texture2D> _source;
Key<Vertices> _quadVertices;
std::shared_ptr<Painter> _quadPainter;
};
}
| 22.413793
| 93
| 0.763077
|
Another-Game-Engine
|
04f512e764550c0c54c81fc8cc2c4879d458aae7
| 4,332
|
cpp
|
C++
|
benchmarks/Benchmarks/SW_StreamCluster/SW_StreamCluster.cpp
|
cdsc-github/parade-ara-simulator
|
00c977200a8e7aa31b03d560886ec80840a3c416
|
[
"BSD-3-Clause"
] | 31
|
2015-12-15T19:14:10.000Z
|
2021-12-31T17:40:21.000Z
|
benchmarks/Benchmarks/SW_StreamCluster/SW_StreamCluster.cpp
|
cdsc-github/parade-ara-simulator
|
00c977200a8e7aa31b03d560886ec80840a3c416
|
[
"BSD-3-Clause"
] | 5
|
2015-12-04T08:06:47.000Z
|
2020-08-09T21:49:46.000Z
|
benchmarks/Benchmarks/SW_StreamCluster/SW_StreamCluster.cpp
|
cdsc-github/parade-ara-simulator
|
00c977200a8e7aa31b03d560886ec80840a3c416
|
[
"BSD-3-Clause"
] | 21
|
2015-11-05T08:25:45.000Z
|
2021-06-19T02:24:50.000Z
|
#include "../../BenchmarkNode.h"
#include <stdint.h>
#include <iostream>
#include <cmath>
#define ITER_COUNT 2
#define CACHE_LINE 32 // cache line in byte
/* this structure represents a point */
/* these will be passed around to avoid copying coordinates */
typedef struct {
float weight;
float *coord;
long assign; /* number of point where this one is assigned */
float cost; /* cost of that assignment, weight*distance */
} Point;
/* this is the array of points */
typedef struct {
long num; /* number of points; may not be N if this is a sample */
int dim; /* dimensionality */
Point *p; /* the array itself */
} Points;
class SW_StreamCluster : public BenchmarkNode
{
int dataSize;
int dim;
int thread;
bool* is_center; //whether a point is a center
int* center_table; //index table of centers
int* work_mem;
Points points;
int *switch_membership;
float *lower;
float cost_of_opening_x;
float *low;
float *gl_lower;
int number_of_centers_to_close;
int x;
public:
SW_StreamCluster()
{
std::cin >> dataSize;
}
virtual void Initialize(int threadID, int procID);
virtual void Run();
virtual void Shutdown();
float dist(Point p1, Point p2, int dim);
double pgain(long x, Points *points, double z, long int *numcenters, int pid);
};
BENCH_DECL(SW_StreamCluster);
void SW_StreamCluster::Initialize(int threadID, int procID)
{
thread = threadID;
uint8_t* constCluster;
//dataSize=1024;
dim = 32;
is_center = new bool[dataSize];
center_table = new int[dataSize];
work_mem = new int[dataSize];
points.dim = dim;
points.num = dataSize;
points.p = (Point *)malloc(dataSize*sizeof(Point));
for( int i = 0; i < dataSize; i++ ) {
points.p[i].coord = (float*)malloc( dim*sizeof(float) );
}
switch_membership = new int[dataSize];
lower = new float[dataSize];
low = new float[dataSize];
gl_lower = new float[dataSize];
memset(center_table, 0, dataSize*sizeof(int));
memset(work_mem, 0, dataSize*sizeof(int));
memset(switch_membership, 0, dataSize*sizeof(int));
memset(lower, 0, dataSize*sizeof(float));
memset(low, 0, dataSize*sizeof(float));
memset(gl_lower, 0, dataSize*sizeof(float));
for (int i=0;i<dataSize;i++)
{
if (i%2)
is_center[i] = false;
else
is_center[i]= true;
}
}
void SW_StreamCluster::Shutdown()
{
while(true);
}
void SW_StreamCluster::Run()
{
int k1 = 0;
int k2 = dataSize;
for(int it= 0; it< ITER_COUNT; it++)
{
int count = 0;
for( int i = k1; i < k2; i++ ) {
if( is_center[i] ) {
center_table[i] = count++;
}
}
//this section is omitted because it is only required to normalize the partial counting done in the previous step for parallel code. Since this code is sequential, this step is unnecessary. To simplify things, I removed this step in the LCA and CFU versions as well.
/* for( int i = k1; i < k2; i++ ) {
if( is_center[i] ) {
center_table[i] += (int)work_mem[thread];
}
}*/
for (int i = k1; i < k2; i++ ) {
float x_cost = dist(points.p[i], points.p[x], points.dim) * points.p[i].weight;
float current_cost = points.p[i].cost;
if ( x_cost < current_cost ) {
switch_membership[i] = 1;
cost_of_opening_x += x_cost - current_cost;
} else {
int assign = points.p[i].assign;
lower[center_table[assign]] += current_cost - x_cost;
}
}
for ( int i = k1; i < k2; i++ ) {
if( is_center[i] ) {
gl_lower[center_table[i]] = low[i];
if ( low[i] > 0 ) {
++number_of_centers_to_close;
}
}
}
for ( int i = k1; i < k2; i++ ) {
bool close_center = gl_lower[center_table[points.p[i].assign]] > 0 ;
if ( switch_membership[i] || close_center ) {
points.p[i].cost = points.p[i].weight * dist(points.p[i], points.p[x], points.dim);
points.p[i].assign = x;
}
}
for( int i = k1; i < k2; i++ ) {
if( is_center[i] && gl_lower[center_table[i]] > 0 ) {
is_center[i] = false;
}
}
}
}
/* compute Euclidean distance squared between two points */
float SW_StreamCluster::dist(Point p1, Point p2, int dim)
{
int i;
float result=0.0;
for (i=0;i<dim;i++)
result += (p1.coord[i] - p2.coord[i])*(p1.coord[i] - p2.coord[i]);
return(result);
}
| 24.896552
| 268
| 0.627193
|
cdsc-github
|
04f907d4b9efd4565b9880c36d4e309cefed618d
| 1,551
|
hpp
|
C++
|
bulletgba/generator/data/code/kotuanzenx/tsx_proto11.hpp
|
pqrs-org/BulletGBA
|
a294007902970242b496f2528b4762cfef22bc86
|
[
"Unlicense"
] | 5
|
2020-03-24T07:44:49.000Z
|
2021-08-30T14:43:31.000Z
|
bulletgba/generator/data/code/kotuanzenx/tsx_proto11.hpp
|
pqrs-org/BulletGBA
|
a294007902970242b496f2528b4762cfef22bc86
|
[
"Unlicense"
] | null | null | null |
bulletgba/generator/data/code/kotuanzenx/tsx_proto11.hpp
|
pqrs-org/BulletGBA
|
a294007902970242b496f2528b4762cfef22bc86
|
[
"Unlicense"
] | null | null | null |
#ifndef GENERATED_419896c26be84c4028d040a9d3789448_HPP
#define GENERATED_419896c26be84c4028d040a9d3789448_HPP
#include "bullet.hpp"
void stepfunc_10c3a88a8e44bab5c0812abd588467e2_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_6536e4546bdcfcf651852434db03b678_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_afa1c1a48bcda114ef4e13212c0aee71_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_f46bc191f7167f122835b57dc03cf3ba_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_faeb9ac81b7a64ffed123259883c3994_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_ae9f735c6401a821cc04ce1cd68278bf_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_6c1f8924f1816c4b17037ca35cdfb188_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_f802ea525850e7f56f2d815678960bc3_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
extern const BulletStepFunc bullet_2e26dec57daafc633062db6aca6be43b_e9c5251663b26b8b849de773f3f9b7a0[];
const unsigned int bullet_2e26dec57daafc633062db6aca6be43b_e9c5251663b26b8b849de773f3f9b7a0_size = 70;
extern const BulletStepFunc bullet_8edd83cfae72c5dbe91c2e130d65b723_e9c5251663b26b8b849de773f3f9b7a0[];
const unsigned int bullet_8edd83cfae72c5dbe91c2e130d65b723_e9c5251663b26b8b849de773f3f9b7a0_size = 2;
extern const BulletStepFunc bullet_3232f0156ec2c5040d5cdc3a1657932a_e9c5251663b26b8b849de773f3f9b7a0[];
const unsigned int bullet_3232f0156ec2c5040d5cdc3a1657932a_e9c5251663b26b8b849de773f3f9b7a0_size = 2;
#endif
| 59.653846
| 104
| 0.909736
|
pqrs-org
|
04f980874480007455014b3cb0fad4ba69baeea2
| 462
|
cpp
|
C++
|
tests/math_unit/math/mix/scal/fun/value_of_rec_test.cpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 1
|
2019-09-06T15:53:17.000Z
|
2019-09-06T15:53:17.000Z
|
tests/math_unit/math/mix/scal/fun/value_of_rec_test.cpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 8
|
2019-01-17T18:51:16.000Z
|
2019-01-17T18:51:39.000Z
|
tests/math_unit/math/mix/scal/fun/value_of_rec_test.cpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stan/math/mix/scal.hpp>
#include <gtest/gtest.h>
#include <math/rev/scal/util.hpp>
TEST(AgradRev, value_of_rec_0) {
using stan::math::fvar;
using stan::math::value_of_rec;
using stan::math::var;
fvar<var> fv_a(5.0);
fvar<fvar<var> > ffv_a(5.0);
fvar<fvar<fvar<fvar<fvar<var> > > > > fffffv_a(5.0);
EXPECT_FLOAT_EQ(5.0, value_of_rec(fv_a));
EXPECT_FLOAT_EQ(5.0, value_of_rec(ffv_a));
EXPECT_FLOAT_EQ(5.0, value_of_rec(fffffv_a));
}
| 25.666667
| 54
| 0.692641
|
alashworth
|
04f9cf4712dfa5787abb48dfeba3280f57cae510
| 592
|
cxx
|
C++
|
src/Kinematics.cxx
|
luketpickering/HepMCNuEvtTools
|
1ec8590cb81475ae525ed32b70211786c67acaa4
|
[
"MIT"
] | 2
|
2021-02-17T15:09:27.000Z
|
2021-03-15T16:57:05.000Z
|
src/Kinematics.cxx
|
luketpickering/HepMCNuEvtTools
|
1ec8590cb81475ae525ed32b70211786c67acaa4
|
[
"MIT"
] | null | null | null |
src/Kinematics.cxx
|
luketpickering/HepMCNuEvtTools
|
1ec8590cb81475ae525ed32b70211786c67acaa4
|
[
"MIT"
] | null | null | null |
#include "NuHepMC/Kinematics.hxx"
#include "NuHepMC/ParticleStackReaderHelper.hxx"
#include <iostream>
namespace NuHepMC {
HepMC3::FourVector GetFourMomentumTransfer(HepMC3::GenEvent const &evt) {
auto ISProbe = GetProbe(evt);
if (!ISProbe) {
return HepMC3::FourVector::ZERO_VECTOR();
}
auto FSProbe = GetFSProbe(evt, ISProbe->pid());
if (!FSProbe) {
return HepMC3::FourVector::ZERO_VECTOR();
}
return (ISProbe->momentum() - FSProbe->momentum());
}
double GetQ2(HepMC3::GenEvent const &evt) {
return -GetFourMomentumTransfer(evt).m2();
}
} // namespace NuHepMC
| 21.925926
| 73
| 0.709459
|
luketpickering
|
04fc2bddc73e7738bb6eaec9b0a5614d14b68792
| 643
|
cpp
|
C++
|
solutions/0543.diameter-of-binary-tree/0543.diameter-of-binary-tree.1558320628.cpp
|
nettee/leetcode
|
19aa8d54d64cce3679db5878ee0194fad95d8fa1
|
[
"MIT"
] | 1
|
2021-01-14T06:01:02.000Z
|
2021-01-14T06:01:02.000Z
|
solutions/0543.diameter-of-binary-tree/0543.diameter-of-binary-tree.1558320628.cpp
|
nettee/leetcode
|
19aa8d54d64cce3679db5878ee0194fad95d8fa1
|
[
"MIT"
] | 8
|
2018-03-27T11:47:19.000Z
|
2018-11-12T06:02:12.000Z
|
solutions/0543.diameter-of-binary-tree/0543.diameter-of-binary-tree.1558320628.cpp
|
nettee/leetcode
|
19aa8d54d64cce3679db5878ee0194fad95d8fa1
|
[
"MIT"
] | 2
|
2020-04-30T09:47:01.000Z
|
2020-12-03T09:34:08.000Z
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int diam = 0;
maxDepth(root, diam);
return diam;
}
int maxDepth(TreeNode* root, int& diam) {
if (root == nullptr) {
return 0;
}
int left = maxDepth(root->left, diam);
int right = maxDepth(root->right, diam);
diam = max(diam, left + right);
return 1 + max(left, right);
}
};
| 22.964286
| 59
| 0.527216
|
nettee
|
04fc48087dbea9865ea7d0c9765dcc951b4eb33e
| 329
|
cpp
|
C++
|
Chapter4/Practice/1090.cpp
|
flics04/XXXASYBT_CppBase
|
0086df68497197f40286889b18f2d8c28eb833bb
|
[
"MIT"
] | 1
|
2022-02-13T02:22:39.000Z
|
2022-02-13T02:22:39.000Z
|
Chapter4/Practice/1090.cpp
|
flics04/XXXASYBT_CppBase
|
0086df68497197f40286889b18f2d8c28eb833bb
|
[
"MIT"
] | null | null | null |
Chapter4/Practice/1090.cpp
|
flics04/XXXASYBT_CppBase
|
0086df68497197f40286889b18f2d8c28eb833bb
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
int m, k, n, w, t = 0;
cin >> m >> k;
n = m;
while (n) {
w = n % 10;
if (w == 3)
++t;
n /= 10;
}
if (m % 19 == 0 && t == k)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
| 13.708333
| 30
| 0.343465
|
flics04
|
04fc723f94a4f0ba29db7ca4dd467f73898a457a
| 6,364
|
cpp
|
C++
|
src/caffe/layers/mvn_layer.cpp
|
oscmansan/nvcaffe
|
22738c97e9c6991e49a12a924c3c773d95795b5c
|
[
"BSD-2-Clause"
] | null | null | null |
src/caffe/layers/mvn_layer.cpp
|
oscmansan/nvcaffe
|
22738c97e9c6991e49a12a924c3c773d95795b5c
|
[
"BSD-2-Clause"
] | null | null | null |
src/caffe/layers/mvn_layer.cpp
|
oscmansan/nvcaffe
|
22738c97e9c6991e49a12a924c3c773d95795b5c
|
[
"BSD-2-Clause"
] | null | null | null |
#include <algorithm>
#include <vector>
#include "caffe/common_layers.hpp"
#include "caffe/layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype, typename Mtype>
void MVNLayer<Dtype,Mtype>::Reshape(const vector<Blob<Dtype,Mtype>*>& bottom,
const vector<Blob<Dtype,Mtype>*>& top) {
top[0]->Reshape(bottom[0]->num(), bottom[0]->channels(),
bottom[0]->height(), bottom[0]->width());
mean_.Reshape(bottom[0]->num(), bottom[0]->channels(),
1, 1);
variance_.Reshape(bottom[0]->num(), bottom[0]->channels(),
1, 1);
temp_.Reshape(bottom[0]->num(), bottom[0]->channels(),
bottom[0]->height(), bottom[0]->width());
if ( this->layer_param_.mvn_param().across_channels() ) {
sum_multiplier_.Reshape(1, bottom[0]->channels(), bottom[0]->height(),
bottom[0]->width());
} else {
sum_multiplier_.Reshape(1, 1, bottom[0]->height(), bottom[0]->width());
}
Dtype* multiplier_data = sum_multiplier_.mutable_cpu_data();
caffe_set(sum_multiplier_.count(), Get<Dtype>(1), multiplier_data);
eps_ = this->layer_param_.mvn_param().eps();
}
template <typename Dtype, typename Mtype>
void MVNLayer<Dtype,Mtype>::Forward_cpu(const vector<Blob<Dtype,Mtype>*>& bottom,
const vector<Blob<Dtype,Mtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
int num;
if (this->layer_param_.mvn_param().across_channels())
num = bottom[0]->num();
else
num = bottom[0]->num() * bottom[0]->channels();
int dim = bottom[0]->count() / num;
if (this->layer_param_.mvn_param().normalize_variance()) {
// put the squares of bottom into temp_
caffe_powx<Dtype,Mtype>(bottom[0]->count(), bottom_data, Mtype(2),
temp_.mutable_cpu_data());
// computes variance using var(X) = E(X^2) - (EX)^2
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), bottom_data,
sum_multiplier_.cpu_data(), Mtype(0.), mean_.mutable_cpu_data()); // EX
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), temp_.cpu_data(),
sum_multiplier_.cpu_data(), Mtype(0.),
variance_.mutable_cpu_data()); // E(X^2)
caffe_powx<Dtype,Mtype>(mean_.count(), mean_.cpu_data(), Mtype(2),
temp_.mutable_cpu_data()); // (EX)^2
caffe_sub<Dtype,Mtype>(mean_.count(), variance_.cpu_data(), temp_.cpu_data(),
variance_.mutable_cpu_data()); // variance
// do mean and variance normalization
// subtract mean
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(-1.f),
mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f),
temp_.mutable_cpu_data());
caffe_add<Dtype,Mtype>(temp_.count(), bottom_data, temp_.cpu_data(), top_data);
// normalize variance
caffe_powx<Dtype,Mtype>(variance_.count(), variance_.cpu_data(), Mtype(0.5),
variance_.mutable_cpu_data());
caffe_add_scalar<Dtype,Mtype>(variance_.count(), eps_, variance_.mutable_cpu_data());
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.f),
variance_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.),
temp_.mutable_cpu_data());
caffe_div<Dtype,Mtype>(temp_.count(), top_data, temp_.cpu_data(), top_data);
} else {
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), bottom_data,
sum_multiplier_.cpu_data(), Mtype(0.), mean_.mutable_cpu_data()); // EX
// subtract mean
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(-1.),
mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.),
temp_.mutable_cpu_data());
caffe_add<Dtype,Mtype>(temp_.count(), bottom_data, temp_.cpu_data(), top_data);
}
}
template <typename Dtype, typename Mtype>
void MVNLayer<Dtype,Mtype>::Backward_cpu(const vector<Blob<Dtype,Mtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype,Mtype>*>& bottom) {
const Dtype* top_diff = top[0]->cpu_diff();
const Dtype* top_data = top[0]->cpu_data();
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
int num;
if (this->layer_param_.mvn_param().across_channels())
num = bottom[0]->num();
else
num = bottom[0]->num() * bottom[0]->channels();
int dim = bottom[0]->count() / num;
if (this->layer_param_.mvn_param().normalize_variance()) {
caffe_mul<Dtype,Mtype>(temp_.count(), top_data, top_diff, bottom_diff);
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1.), bottom_diff,
sum_multiplier_.cpu_data(), Mtype(0.), mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.),
mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f),
bottom_diff);
caffe_mul<Dtype,Mtype>(temp_.count(), top_data, bottom_diff, bottom_diff);
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1.), top_diff,
sum_multiplier_.cpu_data(), Mtype(0.f), mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.),
mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(1.f),
bottom_diff);
caffe_cpu_axpby<Dtype,Mtype>(temp_.count(), Mtype(1), top_diff, Mtype(-1. / dim),
bottom_diff);
// put the squares of bottom into temp_
caffe_powx<Dtype,Mtype>(temp_.count(), bottom_data, Mtype(2),
temp_.mutable_cpu_data());
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.f),
variance_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f),
temp_.mutable_cpu_data());
caffe_div<Dtype,Mtype>(temp_.count(), bottom_diff, temp_.cpu_data(), bottom_diff);
} else {
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), top_diff,
sum_multiplier_.cpu_data(), Mtype(0.f), mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(-1.f),
mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f),
temp_.mutable_cpu_data());
caffe_add<Dtype,Mtype>(temp_.count(), top_diff, temp_.cpu_data(), bottom_diff);
}
}
#ifdef CPU_ONLY
STUB_GPU(MVNLayer);
#endif
INSTANTIATE_CLASS(MVNLayer);
REGISTER_LAYER_CLASS(MVN);
} // namespace caffe
| 41.058065
| 90
| 0.675519
|
oscmansan
|
04fdfa60440ea7fc5cba70c2ea416036838c44ab
| 10,583
|
cpp
|
C++
|
Server Lib/Projeto IOCP/PANGYA_DB/pangya_db.cpp
|
eantoniobr/SuperSS-Dev
|
f57c094f164cc90c2694df33ba394304cd0e7846
|
[
"MIT"
] | null | null | null |
Server Lib/Projeto IOCP/PANGYA_DB/pangya_db.cpp
|
eantoniobr/SuperSS-Dev
|
f57c094f164cc90c2694df33ba394304cd0e7846
|
[
"MIT"
] | null | null | null |
Server Lib/Projeto IOCP/PANGYA_DB/pangya_db.cpp
|
eantoniobr/SuperSS-Dev
|
f57c094f164cc90c2694df33ba394304cd0e7846
|
[
"MIT"
] | 1
|
2021-11-03T00:21:07.000Z
|
2021-11-03T00:21:07.000Z
|
// Arquivo pangya_db.cpp
// Criado em 25/12/2017 por Acrisio
// Implementação da classe pangya_db
#if defined(_WIN32)
#pragma pack(1)
#endif
#if defined(_WIN32)
#include <WinSock2.h>
#elif defined(__linux__)
#include "../UTIL/WinPort.h"
#include <unistd.h>
#endif
#include "pangya_db.h"
#include "../UTIL/exception.h"
#include "../UTIL/message_pool.h"
#include "../UTIL/string_util.hpp"
using namespace stdA;
// Teste call db cmd log
#ifdef _DEBUG
#define _TESTCMD_LOG 1
#endif
#if defined(_WIN32) && defined(_TESTCMD_LOG)
// !@ Teste
#include <fstream>
#include <map>
struct call_db_cmd_st {
public:
call_db_cmd_st() : m_hMutex(INVALID_HANDLE_VALUE) {
m_hMutex = CreateMutexA(NULL, FALSE, "xg_CALL_DB_CMD_LOG");
if (m_hMutex == NULL)
_smp::message_pool::getInstance().push(new message("[pangya_db::call_db_cmd_st::call_db_cmd_st][Error] fail to create Mutex. Error: " + std::to_string(GetLastError()), CL_FILE_LOG_AND_CONSOLE));
};
~call_db_cmd_st() {
if (isValid())
CloseHandle(m_hMutex);
};
std::map< std::string, std::string > loadCmds() {
std::map< std::string, std::string > v_cmds;
if (!isValid() || !lock())
return v_cmds;
std::ifstream in(url_log);
if (in.is_open()) {
std::string name, value;
while (in.good()) {
in >> name >> value;
v_cmds.insert(std::make_pair(name, value));
}
in.close();
}
if (!unlock())
_smp::message_pool::getInstance().push(new message("[pangya_db::call_db_cmd_st::loadCmds][Error] fail to release Mutex. Error: " + std::to_string(GetLastError()), CL_FILE_LOG_AND_CONSOLE));
return v_cmds;
};
void saveCmds(std::map< std::string, std::string >& _cmds) {
if (_cmds.empty() || !isValid() || !lock())
return;
std::ofstream out(url_log);
if (out.is_open()) {
for (auto& el : _cmds)
out << el.first << " " << el.second << std::endl;
out.close();
}
if (!unlock())
_smp::message_pool::getInstance().push(new message("[pangya_db::call_db_cmd_st::saveCmds][Error] fail to release Mutex. Error: " + std::to_string(GetLastError()), CL_FILE_LOG_AND_CONSOLE));
};
private:
bool isValid() {
return m_hMutex != INVALID_HANDLE_VALUE && m_hMutex != NULL;
};
bool lock() {
if (!isValid())
return false;
DWORD dwResult = WaitForSingleObject(m_hMutex, INFINITE);
return dwResult == WAIT_OBJECT_0 ? true : false;
};
bool unlock() {
if (!isValid())
return false;
return ReleaseMutex(m_hMutex) == TRUE;
};
private:
HANDLE m_hMutex;
const char url_log[30] = "H:/Server Lib/call_db_cmd.log";
};
// !@ Teste
bool logExecuteCmds(std::string _name) {
static call_db_cmd_st cdcs;
// Load
auto v_cmds = cdcs.loadCmds();
auto it = v_cmds.find(_name);
if (it == v_cmds.end()) {
v_cmds.insert(std::make_pair(_name, "yes"));
// Save
cdcs.saveCmds(v_cmds);
return true; // show log
}else if (it->second.compare("no") == 0) {
it->second = "yes";
// Save
cdcs.saveCmds(v_cmds);
return true; // show log
}
return false;
}
// !@ Teste
#endif
list_fifo_asyc< exec_query > pangya_db::m_query_pool;
list_async< exec_query* > pangya_db::m_cache_query;
pangya_db::pangya_db(bool _waitable) : m_exception("", 0), m_waitable(_waitable),
#if defined(_WIN32)
hEvent(INVALID_HANDLE_VALUE)
#elif defined(__linux__)
hEvent(nullptr)
#endif
{
#if defined(_WIN32)
if (_waitable)
if ((hEvent = CreateEvent(NULL, FALSE, FALSE, NULL)) == INVALID_HANDLE_VALUE)
_smp::message_pool::getInstance().push(new message("[pangya_db::pangya_db][Error] Error ao criar evento. ErrorCode: " + std::to_string(STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 52, GetLastError())), CL_FILE_LOG_AND_CONSOLE));
#elif defined(__linux__)
if (_waitable) {
hEvent = new Event(false, 0u);
if (!hEvent->is_good()) {
delete hEvent;
hEvent = nullptr;
_smp::message_pool::getInstance().push(new message("[pangya_db::pangya_db][Error] Error ao criar evento. ErrorCode: " + std::to_string(STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 52, errno)), CL_FILE_LOG_AND_CONSOLE));
}
}
#endif
};
pangya_db::~pangya_db() {
#if defined(_WIN32)
if (hEvent != INVALID_HANDLE_VALUE)
CloseHandle(hEvent);
hEvent = INVALID_HANDLE_VALUE;
#elif defined(__linux__)
if (hEvent != nullptr)
delete hEvent;
hEvent = nullptr;
#endif
};
inline void pangya_db::exec(database& _db) {
response *r = nullptr;
try {
if ((r = prepareConsulta(_db)) != nullptr) {
for (auto num_result = 0u; num_result < r->getNumResultSet(); ++num_result) {
if (r->getResultSetAt(num_result) != nullptr && r->getResultSetAt(num_result)->getNumLines() > 0
&& r->getResultSetAt(num_result)->getState() == result_set::HAVE_DATA) {
for (auto _result = r->getResultSetAt(num_result)->getFirstLine(); _result != nullptr; _result = _result->next) {
lineResult(_result, num_result);
}
}// só faz esse else se for mandar uma exception
clear_result(r->getResultSetAt(num_result));
}
clear_response(r);
}
}catch (exception& e) {
//UNREFERENCED_PARAMETER(e);
if (r != nullptr)
clear_response(r);
//throw;
m_exception = e;
_smp::message_pool::getInstance().push(new message("[pangya_db::" + _getName() + "::exec][Error] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
#if defined(_WIN32) && defined(_TESTCMD_LOG)
// !@ Teste
if (logExecuteCmds(_getName()))
_smp::message_pool::getInstance().push(new message("[pangya_db::" + _getName() + "::exec][Log] Executado. ------------------->>", CL_FILE_LOG_AND_CONSOLE));
#endif
};
exception& pangya_db::getException() {
return m_exception;
};
void pangya_db::waitEvent() {
#if defined(_WIN32)
if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0)
throw exception("[pangya_db::" + _getName() + "::waitEvent][Error] nao conseguiu esperar pelo evento", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 53, GetLastError()));
#elif defined(__linux__)
if (hEvent == nullptr || hEvent->wait(INFINITE) != WAIT_OBJECT_0)
throw exception("[pangya_db::" + _getName() + "::waitEvent][Error] nao conseguiu esperar pelo evento", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 53, errno));
#endif
}
void pangya_db::wakeupWaiter() {
#if defined(_WIN32)
SetEvent(hEvent);
#elif defined(__linux__)
if (hEvent != nullptr)
hEvent->set();
#endif
};
bool pangya_db::isWaitable() {
return m_waitable;
};
inline response* pangya_db::_insert(database& _db, std::string _query) {
return _insert(_db, MbToWc(_query));
}
inline response* pangya_db::_insert(database& _db, std::wstring _query) {
/*exec_query query(_query, exec_query::_INSERT);
postAndWaitResponseQuery(query);
return query.getRes();*/
return _db.ExecQuery(_query);
}
inline response* pangya_db::_update(database& _db, std::string _query) {
return _update(_db, MbToWc(_query));
};
inline response* pangya_db::_update(database& _db, std::wstring _query) {
//exec_query query(_query, exec_query::_UPDATE);
//postAndWaitResponseQuery(query);
////clear_response(query.getRes());
//return query.getRes();
return _db.ExecQuery(_query);
};
inline response* pangya_db::_delete(database& _db, std::string _query) {
return _delete(_db, MbToWc(_query));
};
inline response* pangya_db::_delete(database& _db, std::wstring _query) {
//exec_query query(_query, exec_query::_DELETE);
//postAndWaitResponseQuery(query);
////clear_response(query.getRes());
//return query.getRes();
return _db.ExecQuery(_query);
};
inline response* pangya_db::consulta(database& _db, std::string _query) {
return consulta(_db, MbToWc(_query));
};
inline response* pangya_db::consulta(database& _db, std::wstring _query) {
/*exec_query query(_query, exec_query::_QUERY);
postAndWaitResponseQuery(query);
return query.getRes();*/
return _db.ExecQuery(_query);
};
inline response* pangya_db::procedure(database& _db, std::string _name, std::string _params) {
return procedure(_db, MbToWc(_name), MbToWc(_params));
};
inline response* pangya_db::procedure(database& _db, std::wstring _name, std::wstring _params) {
/*exec_query query(_name, _params, exec_query::_PROCEDURE);
postAndWaitResponseQuery(query);
return query.getRes();*/
return _db.ExecProc(_name, _params);
};
inline void pangya_db::postAndWaitResponseQuery(exec_query& _query) {
DWORD wait = INFINITE;
//pangya_base_db::m_query_pool.push(&_query); // post query
m_query_pool.push(&_query);
while (1) {
try {
_query.waitEvent(wait);
break;
}catch (exception& e) {
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) == STDA_ERROR_TYPE::EXEC_QUERY) {
if (STDA_ERROR_DECODE(e.getCodeError()) == 7 && wait == INFINITE) {
wait = 1000; // Espera um segundo se não for da próxima dá error
continue;
}
//pangya_base_db::m_query_pool.remove(&_query);
m_query_pool.remove(&_query);
throw;
}else throw;
}catch (std::exception& e) {
throw exception("System error: " + std::string(e.what()), STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 100, 0));
}catch (...) {
throw exception("System error: Desconhecido", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 100, 1));
}
}
};
inline void pangya_db::clear_result(result_set*& _rs) {
if (_rs != nullptr)
delete _rs;
_rs = nullptr;
};
inline void pangya_db::clear_response(response* _res) {
if (_res != nullptr)
delete _res;
};
inline void pangya_db::checkColumnNumber(uint32_t _number_cols1, uint32_t _number_cols2) {
if (_number_cols1 != 0 && _number_cols1 != _number_cols2)
throw exception("[pangya_db::" + _getName() + "::checkColumnNumber][Error] numero de colunas retornada pela consulta sao diferente do esperado.", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 2, 0));
};
inline void pangya_db::checkResponse(response* r, std::string _exception_msg) {
if (r == nullptr || r->getNumResultSet() <= 0)
throw exception("[pangya_db::" + _getName() + "::checkResponse][Error] " + _exception_msg, STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 1, 0));
};
inline void pangya_db::checkResponse(response* r, std::wstring _exception_msg) {
if (r == nullptr || r->getNumResultSet() <= 0)
throw exception(L"[pangya_db::" + _wgetName() + L"::checkResponse][Error] " + _exception_msg, STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 1, 0));
};
bool pangya_db::compare(exec_query* _query1, exec_query* _query2) {
return _query1->getQuery().compare(_query2->getQuery()) == 0;
};
| 25.749392
| 230
| 0.681187
|
eantoniobr
|
ca012ee4ec0f3d0223dcb884c068974dd3eb7988
| 7,717
|
cpp
|
C++
|
examples/world_gen/game.cpp
|
jjbandit/game
|
c28affd868201d3151ca75a20883e7fb26e09302
|
[
"WTFPL"
] | 13
|
2017-04-12T16:26:46.000Z
|
2022-03-01T22:04:34.000Z
|
examples/world_gen/game.cpp
|
jjbandit/game
|
c28affd868201d3151ca75a20883e7fb26e09302
|
[
"WTFPL"
] | null | null | null |
examples/world_gen/game.cpp
|
jjbandit/game
|
c28affd868201d3151ca75a20883e7fb26e09302
|
[
"WTFPL"
] | null | null | null |
#include <bonsai_types.h>
#include <game_constants.h>
#include <game_types.h>
#define RANDOM_HOTKEY_MASHING 0
#if RANDOM_HOTKEY_MASHING
static u32 HotkeyFrameTimeout = 0;
static random_series HotkeyEntropy = {};
static hotkeys StashedHotkeys = {};
#endif
model *
AllocateGameModels(game_state *GameState, memory_arena *Memory)
{
model *Result = Allocate(model, GameState->Memory, ModelIndex_Count);
Result[ModelIndex_Enemy] = LoadVoxModel(Memory, &GameState->Heap, ENEMY_MODEL);
Result[ModelIndex_Player] = LoadCollada(Memory, &GameState->Heap, "models/two-axis-animated-cube.dae");
/* Result[ModelIndex_Player] = LoadVoxModel(Memory, PLAYER_MODEL); */
Result[ModelIndex_Loot] = LoadVoxModel(Memory, &GameState->Heap, LOOT_MODEL);
/* chunk_dimension ProjectileDim = Chunk_Dimension(1,30,1); */
/* Result[ModelIndex_Projectile].Chunk = AllocateChunk(Memory, &GameState->Heap, ProjectileDim); */
/* Result[ModelIndex_Projectile].Dim = ProjectileDim; */
/* FillChunk(Result[ModelIndex_Projectile].Chunk, ProjectileDim, GREEN); */
Result[ModelIndex_Proton] = LoadVoxModel(Memory, &GameState->Heap, PROJECTILE_MODEL);
return Result;
}
BONSAI_API_WORKER_THREAD_CALLBACK()
{
switch (Entry->Type)
{
case type_work_queue_entry_init_world_chunk:
{
world_chunk* DestChunk = (world_chunk*)Entry->work_queue_entry_init_world_chunk.Input;
if (!ChunkIsGarbage(DestChunk))
{
s32 Amplititude = 100;
s32 StartingZDepth = -100;
InitializeWorldChunkPerlinPlane(Thread,
DestChunk,
WORLD_CHUNK_DIM,
Amplititude,
StartingZDepth);
/* Assert(DestChunk->CurrentTriangles->SurfacePoints->Count == 0); */
/* GetBoundingVoxels(DestChunk, DestChunk->CurrentTriangles->SurfacePoints); */
/* Triangulate(DestChunk->LodMesh, DestChunk, WORLD_CHUNK_DIM, Thread->TempMemory); */
/* Triangulate(DestChunk->LodMesh, DestChunk->CurrentTriangles, DestChunk, Thread->TempMemory); */
}
} break;
case type_work_queue_entry_copy_buffer:
{
untextured_3d_geometry_buffer* Src = Entry->work_queue_entry_copy_buffer.Src;
untextured_3d_geometry_buffer* Dest = &Entry->work_queue_entry_copy_buffer.Dest;
Assert(Src->At <= Dest->End);
v3 Basis = Entry->work_queue_entry_copy_buffer.Basis;
BufferVertsChecked(Src, Dest, Basis, V3(1.0f));
} break;
InvalidDefaultCase;
}
return;
}
BONSAI_API_MAIN_THREAD_CALLBACK()
{
TIMED_FUNCTION();
GetDebugState()->Plat = GameState->Plat;
GetDebugState()->GameState = GameState;
/* DebugPrint(*GameState->Plat); */
GL.Disable(GL_CULL_FACE);
#if BONSAI_INTERNAL
if (!GetDebugState)
{
GetDebugState = GameState->GetDebugState;
}
#endif
world *World = GameState->World;
graphics *Graphics = GameState->Graphics;
g_buffer_render_group *gBuffer = Graphics->gBuffer;
ao_render_group *AoGroup = Graphics->AoGroup;
camera *Camera = Graphics->Camera;
Graphics->GpuBufferWriteIndex = (Graphics->GpuBufferWriteIndex + 1) % 2;
gpu_mapped_element_buffer* GpuMap = Graphics->GpuBuffers + Graphics->GpuBufferWriteIndex;
MapGpuElementBuffer(GpuMap);
entity *Player = GameState->Player;
ClearFramebuffers(Graphics);
#if RANDOM_HOTKEY_MASHING
if (HotkeyFrameTimeout == 0)
{
Hotkeys->Left = RandomChoice(&HotkeyEntropy);
Hotkeys->Right = RandomChoice(&HotkeyEntropy);
Hotkeys->Forward = RandomChoice(&HotkeyEntropy);
Hotkeys->Backward = RandomChoice(&HotkeyEntropy);
StashedHotkeys = *Hotkeys;
HotkeyFrameTimeout = 100;
}
else
{
HotkeyFrameTimeout--;
*Hotkeys = StashedHotkeys;
}
#endif
#if DEBUG_DRAW_WORLD_AXIES
{
untextured_3d_geometry_buffer CopyDest = ReserveBufferSpace(&GpuMap->Buffer, VERTS_PER_LINE*3);
DEBUG_DrawLine(&CopyDest, V3(0,0,0), V3(10000, 0, 0), RED, 0.5f );
DEBUG_DrawLine(&CopyDest, V3(0,0,0), V3(0, 10000, 0), GREEN, 0.5f );
DEBUG_DrawLine(&CopyDest, V3(0,0,0), V3(0, 0, 10000), BLUE, 0.5f );
}
#endif
if (Hotkeys->Player_Spawn)
{
Unspawn(Player);
world_position PlayerChunkP = World_Position(0, 0, -2);
SpawnPlayer(GameState->Models, Player, Canonical_Position(V3(0,0,2), World_Position(0,0,0)), &GameState->Entropy);
World->Center = PlayerChunkP;
}
SimulatePlayer(World, Player, Camera, Hotkeys, Plat->dt, g_VisibleRegion);
CollectUnusedChunks(World, &GameState->MeshFreelist, GameState->Memory, g_VisibleRegion);
v2 MouseDelta = GetMouseDelta(Plat);
input* GameInput = &Plat->Input;
#if BONSAI_INTERNAL
if (GetDebugState()->UiGroup.PressedInteractionId != StringHash("GameViewport"))
{
GameInput = 0;
}
#endif
UpdateGameCamera(MouseDelta, GameInput, Player->P, Camera, World->ChunkDim);
SimulateEntities(World, GameState->EntityTable, Plat->dt, g_VisibleRegion);
SimulateAndRenderParticleSystems(GameState->EntityTable, World->ChunkDim, &GpuMap->Buffer, Graphics, Plat->dt);
gBuffer->ViewProjection =
ProjectionMatrix(Camera, Plat->WindowWidth, Plat->WindowHeight) *
ViewMatrix(World->ChunkDim, Camera);
DEBUG_COMPUTE_PICK_RAY(Plat, &gBuffer->ViewProjection);
TIMED_BLOCK("BufferMeshes");
BufferWorld(Plat, &GpuMap->Buffer, World, Graphics, g_VisibleRegion);
BufferEntities( GameState->EntityTable, &GpuMap->Buffer, Graphics, World, Plat->dt);
END_BLOCK("BufferMeshes");
#if BONSAI_INTERNAL
for (u32 ChunkIndex = 0;
ChunkIndex < GetDebugState()->PickedChunkCount;
++ChunkIndex)
{
world_chunk *Chunk = GetDebugState()->PickedChunks[ChunkIndex];
untextured_3d_geometry_buffer CopyDest = ReserveBufferSpace(&GpuMap->Buffer, VERTS_PER_AABB);
u8 Color = GREEN;
if (Chunk == GetDebugState()->HotChunk)
{
Color = PINK;
}
DEBUG_DrawChunkAABB(&CopyDest, Graphics, Chunk, World->ChunkDim, Color, 0.35f);
}
#endif
TIMED_BLOCK("Wait for worker threads");
for (;;) { if (QueueIsEmpty(&Plat->HighPriority)) { break; } }
END_BLOCK("Wait for worker threads");
TIMED_BLOCK("RenderToScreen");
RenderGBuffer(GpuMap, Graphics);
RenderAoTexture(AoGroup);
DrawGBufferToFullscreenQuad(Plat, Graphics);
END_BLOCK("RenderToScreen");
Graphics->Lights->Count = 0;
return;
}
BONSAI_API_MAIN_THREAD_INIT_CALLBACK()
{
Info("Initializing Game");
GL = *GL_in;
GetDebugState = GetDebugState_in;
Init_Global_QuadVertexBuffer();
game_state *GameState = Allocate(game_state, GameMemory, 1);
GameState->Memory = GameMemory;
GameState->Noise = perlin_noise(DEBUG_NOISE_SEED);
GameState->Graphics = GraphicsInit(GameMemory);
if (!GameState->Graphics) { Error("Initializing Graphics"); return False; }
StandardCamera(GameState->Graphics->Camera, 10000.0f, 300.0f);
GameState->Plat = Plat;
GameState->Entropy.Seed = DEBUG_NOISE_SEED;
world_position WorldCenter = World_Position(0, 0, 0);
GameState->Heap = InitHeap(Gigabytes(4));
GameState->World = AllocateAndInitWorld(WorldCenter, WORLD_CHUNK_DIM, g_VisibleRegion);
GameState->EntityTable = AllocateEntityTable(GameMemory, TOTAL_ENTITY_COUNT);
GameState->Models = AllocateGameModels(GameState, GameState->Memory);
GameState->Player = GetFreeEntity(GameState->EntityTable);
SpawnPlayer(GameState->Models, GameState->Player, Canonical_Position(Voxel_Position(0), WorldCenter), &GameState->Entropy);
return GameState;
}
BONSAI_API_WORKER_THREAD_INIT_CALLBACK()
{
Thread->MeshFreelist = &GameState->MeshFreelist;
Thread->Noise = &GameState->Noise;
}
| 31.116935
| 125
| 0.705067
|
jjbandit
|
ca01560870d938fafd39fcc70b08ba9abb9f6dca
| 145
|
cpp
|
C++
|
nmnnmm.cpp
|
taareek/c-plus-plus
|
b9d04f710e9b2e65786618f8bbced4a56c149444
|
[
"Unlicense"
] | null | null | null |
nmnnmm.cpp
|
taareek/c-plus-plus
|
b9d04f710e9b2e65786618f8bbced4a56c149444
|
[
"Unlicense"
] | null | null | null |
nmnnmm.cpp
|
taareek/c-plus-plus
|
b9d04f710e9b2e65786618f8bbced4a56c149444
|
[
"Unlicense"
] | null | null | null |
#include<iostream>
using namespace std;
int hey(int a){
int c= a+3;
return c;
}
int main(){
int i= 29;
cout<<hey(i);
}
| 13.181818
| 21
| 0.524138
|
taareek
|
ca0d4c6b467942844ddd87d378229d2df7cddc08
| 1,187
|
cpp
|
C++
|
1175/e_fin.cpp
|
vladshablinsky/algo
|
815392708d00dc8d3159b4866599de64fa9d34fa
|
[
"MIT"
] | 1
|
2021-10-24T00:46:37.000Z
|
2021-10-24T00:46:37.000Z
|
1175/e_fin.cpp
|
vladshablinsky/algo
|
815392708d00dc8d3159b4866599de64fa9d34fa
|
[
"MIT"
] | null | null | null |
1175/e_fin.cpp
|
vladshablinsky/algo
|
815392708d00dc8d3159b4866599de64fa9d34fa
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
using namespace std;
const int INF = 1e9;
const int MAX_N = 5e5 + 5;
const int MAX_P = 21;
int f[MAX_N][MAX_P];
int next_right[MAX_N];
int n, m;
int main() {
cin >> n >> m;
for (int i = 0; i < n; ++i) {
int l, r;
cin >> l >> r;
next_right[l] = max(next_right[l], r);
}
for (int i = 1; i < MAX_N; ++i) {
next_right[i] = max(next_right[i], i);
next_right[i] = max(next_right[i], next_right[i - 1]);
f[i][0] = next_right[i];
}
f[0][0] = next_right[0];
for (int j = 1; j < MAX_P; ++j) {
for (int i = 0; i < MAX_N; ++i) {
f[i][j] = f[f[i][j - 1]][j - 1];
}
}
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
int cur_p = MAX_P - 1;
// cout << "x: " << x << ", y: " << y << endl;
int ans = 0;
for (int j = MAX_P - 1; j >= 0; --j) {
if (f[x][j] < y) {
// cout << "f[" << x << "][" << j << "] = " << f[x][j] << endl;
x = f[x][j];
ans += 1 << j;
}
}
++ans;
if (ans <= n) {
cout << ans << "\n";
} else {
cout << "-1\n";
}
}
return 0;
}
| 19.459016
| 71
| 0.428812
|
vladshablinsky
|
ca105b6ad8eadb8ebbfced706b616d58a3d2c50e
| 87,328
|
hpp
|
C++
|
include/GlobalNamespace/MultiplayerSessionManager.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/MultiplayerSessionManager.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/MultiplayerSessionManager.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: StandaloneMonobehavior
#include "GlobalNamespace/StandaloneMonobehavior.hpp"
// Including type: IMultiplayerSessionManager
#include "GlobalNamespace/IMultiplayerSessionManager.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: IConnectionInitParams`1<T>
template<typename T>
class IConnectionInitParams_1;
// Forward declaring type: NetworkPacketSerializer`2<TType, TData>
template<typename TType, typename TData>
class NetworkPacketSerializer_2;
// Forward declaring type: IConnectedPlayer
class IConnectedPlayer;
// Forward declaring type: SynchronizedActionQueue
class SynchronizedActionQueue;
// Forward declaring type: ConnectedPlayerManager
class ConnectedPlayerManager;
// Forward declaring type: INetworkPacketSubSerializer`1<TData>
template<typename TData>
class INetworkPacketSubSerializer_1;
// Forward declaring type: IConnectionManager
class IConnectionManager;
// Skipping declaration: SessionType because it is already included!
// Forward declaring type: UpdateConnectionStateReason
struct UpdateConnectionStateReason;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: Queue`1<T>
template<typename T>
class Queue_1;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: HashSet`1<T>
template<typename T>
class HashSet_1;
// Forward declaring type: IReadOnlyList`1<T>
template<typename T>
class IReadOnlyList_1;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action
class Action;
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
// Forward declaring type: String
class String;
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
// Forward declaring type: Func`1<TResult>
template<typename TResult>
class Func_1;
}
// Forward declaring namespace: LiteNetLib::Utils
namespace LiteNetLib::Utils {
// Forward declaring type: INetSerializable
class INetSerializable;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0xB8
#pragma pack(push, 1)
// Autogenerated type: MultiplayerSessionManager
// [TokenAttribute] Offset: FFFFFFFF
class MultiplayerSessionManager : public GlobalNamespace::StandaloneMonobehavior/*, public GlobalNamespace::IMultiplayerSessionManager*/ {
public:
// Writing base type padding for base size: 0x2C to desired offset: 0x30
char ___base_padding[0x4] = {};
// Nested type: GlobalNamespace::MultiplayerSessionManager::SessionType
struct SessionType;
// Nested type: GlobalNamespace::MultiplayerSessionManager::ConnectionState
struct ConnectionState;
// Nested type: GlobalNamespace::MultiplayerSessionManager::$$c__DisplayClass97_0
class $$c__DisplayClass97_0;
// Nested type: GlobalNamespace::MultiplayerSessionManager::$$c
class $$c;
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: MultiplayerSessionManager/SessionType
// [TokenAttribute] Offset: FFFFFFFF
struct SessionType/*, public System::Enum*/ {
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: SessionType
constexpr SessionType(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::Enum
operator System::Enum() noexcept {
return *reinterpret_cast<System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public MultiplayerSessionManager/SessionType Player
static constexpr const int Player = 0;
// Get static field: static public MultiplayerSessionManager/SessionType Player
static GlobalNamespace::MultiplayerSessionManager::SessionType _get_Player();
// Set static field: static public MultiplayerSessionManager/SessionType Player
static void _set_Player(GlobalNamespace::MultiplayerSessionManager::SessionType value);
// static field const value: static public MultiplayerSessionManager/SessionType Spectator
static constexpr const int Spectator = 1;
// Get static field: static public MultiplayerSessionManager/SessionType Spectator
static GlobalNamespace::MultiplayerSessionManager::SessionType _get_Spectator();
// Set static field: static public MultiplayerSessionManager/SessionType Spectator
static void _set_Spectator(GlobalNamespace::MultiplayerSessionManager::SessionType value);
// static field const value: static public MultiplayerSessionManager/SessionType DedicatedServer
static constexpr const int DedicatedServer = 2;
// Get static field: static public MultiplayerSessionManager/SessionType DedicatedServer
static GlobalNamespace::MultiplayerSessionManager::SessionType _get_DedicatedServer();
// Set static field: static public MultiplayerSessionManager/SessionType DedicatedServer
static void _set_DedicatedServer(GlobalNamespace::MultiplayerSessionManager::SessionType value);
// Get instance field reference: public System.Int32 value__
int& dyn_value__();
}; // MultiplayerSessionManager/SessionType
#pragma pack(pop)
static check_size<sizeof(MultiplayerSessionManager::SessionType), 0 + sizeof(int)> __GlobalNamespace_MultiplayerSessionManager_SessionTypeSizeCheck;
static_assert(sizeof(MultiplayerSessionManager::SessionType) == 0x4);
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: MultiplayerSessionManager/ConnectionState
// [TokenAttribute] Offset: FFFFFFFF
struct ConnectionState/*, public System::Enum*/ {
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: ConnectionState
constexpr ConnectionState(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::Enum
operator System::Enum() noexcept {
return *reinterpret_cast<System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public MultiplayerSessionManager/ConnectionState Disconnected
static constexpr const int Disconnected = 0;
// Get static field: static public MultiplayerSessionManager/ConnectionState Disconnected
static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Disconnected();
// Set static field: static public MultiplayerSessionManager/ConnectionState Disconnected
static void _set_Disconnected(GlobalNamespace::MultiplayerSessionManager::ConnectionState value);
// static field const value: static public MultiplayerSessionManager/ConnectionState Connecting
static constexpr const int Connecting = 1;
// Get static field: static public MultiplayerSessionManager/ConnectionState Connecting
static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Connecting();
// Set static field: static public MultiplayerSessionManager/ConnectionState Connecting
static void _set_Connecting(GlobalNamespace::MultiplayerSessionManager::ConnectionState value);
// static field const value: static public MultiplayerSessionManager/ConnectionState Connected
static constexpr const int Connected = 2;
// Get static field: static public MultiplayerSessionManager/ConnectionState Connected
static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Connected();
// Set static field: static public MultiplayerSessionManager/ConnectionState Connected
static void _set_Connected(GlobalNamespace::MultiplayerSessionManager::ConnectionState value);
// static field const value: static public MultiplayerSessionManager/ConnectionState Disconnecting
static constexpr const int Disconnecting = 3;
// Get static field: static public MultiplayerSessionManager/ConnectionState Disconnecting
static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Disconnecting();
// Set static field: static public MultiplayerSessionManager/ConnectionState Disconnecting
static void _set_Disconnecting(GlobalNamespace::MultiplayerSessionManager::ConnectionState value);
// Get instance field reference: public System.Int32 value__
int& dyn_value__();
}; // MultiplayerSessionManager/ConnectionState
#pragma pack(pop)
static check_size<sizeof(MultiplayerSessionManager::ConnectionState), 0 + sizeof(int)> __GlobalNamespace_MultiplayerSessionManager_ConnectionStateSizeCheck;
static_assert(sizeof(MultiplayerSessionManager::ConnectionState) == 0x4);
// private readonly NetworkPacketSerializer`2<MultiplayerSessionManager/MessageType,IConnectedPlayer> _packetSerializer
// Size: 0x8
// Offset: 0x30
GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>* packetSerializer;
// Field size check
static_assert(sizeof(GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private readonly System.Collections.Generic.List`1<IConnectedPlayer> _connectedPlayers
// Size: 0x8
// Offset: 0x38
System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>* connectedPlayers;
// Field size check
static_assert(sizeof(System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private readonly System.Collections.Generic.HashSet`1<System.String> _localPlayerState
// Size: 0x8
// Offset: 0x40
System::Collections::Generic::HashSet_1<::Il2CppString*>* localPlayerState;
// Field size check
static_assert(sizeof(System::Collections::Generic::HashSet_1<::Il2CppString*>*) == 0x8);
// private readonly SynchronizedActionQueue _synchronizedActionQueue
// Size: 0x8
// Offset: 0x48
GlobalNamespace::SynchronizedActionQueue* synchronizedActionQueue;
// Field size check
static_assert(sizeof(GlobalNamespace::SynchronizedActionQueue*) == 0x8);
// private System.Int32 _maxPlayerCount
// Size: 0x4
// Offset: 0x50
int maxPlayerCount;
// Field size check
static_assert(sizeof(int) == 0x4);
// private MultiplayerSessionManager/ConnectionState _connectionState
// Size: 0x4
// Offset: 0x54
GlobalNamespace::MultiplayerSessionManager::ConnectionState connectionState;
// Field size check
static_assert(sizeof(GlobalNamespace::MultiplayerSessionManager::ConnectionState) == 0x4);
// private readonly System.Collections.Generic.Queue`1<System.Int32> _freeSortIndices
// Size: 0x8
// Offset: 0x58
System::Collections::Generic::Queue_1<int>* freeSortIndices;
// Field size check
static_assert(sizeof(System::Collections::Generic::Queue_1<int>*) == 0x8);
// private System.Action connectedEvent
// Size: 0x8
// Offset: 0x60
System::Action* connectedEvent;
// Field size check
static_assert(sizeof(System::Action*) == 0x8);
// private System.Action`1<ConnectionFailedReason> connectionFailedEvent
// Size: 0x8
// Offset: 0x68
System::Action_1<GlobalNamespace::ConnectionFailedReason>* connectionFailedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::ConnectionFailedReason>*) == 0x8);
// private System.Action`1<IConnectedPlayer> playerConnectedEvent
// Size: 0x8
// Offset: 0x70
System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerConnectedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private System.Action`1<IConnectedPlayer> playerDisconnectedEvent
// Size: 0x8
// Offset: 0x78
System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerDisconnectedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private System.Action`1<IConnectedPlayer> playerAvatarChangedEvent
// Size: 0x8
// Offset: 0x80
System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerAvatarChangedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private System.Action`1<IConnectedPlayer> playerStateChangedEvent
// Size: 0x8
// Offset: 0x88
System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerStateChangedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private System.Action`1<IConnectedPlayer> connectionOwnerStateChangedEvent
// Size: 0x8
// Offset: 0x90
System::Action_1<GlobalNamespace::IConnectedPlayer*>* connectionOwnerStateChangedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private System.Action`1<DisconnectedReason> disconnectedEvent
// Size: 0x8
// Offset: 0x98
System::Action_1<GlobalNamespace::DisconnectedReason>* disconnectedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::DisconnectedReason>*) == 0x8);
// private IConnectedPlayer <connectionOwner>k__BackingField
// Size: 0x8
// Offset: 0xA0
GlobalNamespace::IConnectedPlayer* connectionOwner;
// Field size check
static_assert(sizeof(GlobalNamespace::IConnectedPlayer*) == 0x8);
// private System.Boolean _exclusiveConnectedPlayerManager
// Size: 0x1
// Offset: 0xA8
bool exclusiveConnectedPlayerManager;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: exclusiveConnectedPlayerManager and: connectedPlayerManager
char __padding16[0x7] = {};
// private ConnectedPlayerManager _connectedPlayerManager
// Size: 0x8
// Offset: 0xB0
GlobalNamespace::ConnectedPlayerManager* connectedPlayerManager;
// Field size check
static_assert(sizeof(GlobalNamespace::ConnectedPlayerManager*) == 0x8);
// Creating value type constructor for type: MultiplayerSessionManager
MultiplayerSessionManager(GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>* packetSerializer_ = {}, System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>* connectedPlayers_ = {}, System::Collections::Generic::HashSet_1<::Il2CppString*>* localPlayerState_ = {}, GlobalNamespace::SynchronizedActionQueue* synchronizedActionQueue_ = {}, int maxPlayerCount_ = {}, GlobalNamespace::MultiplayerSessionManager::ConnectionState connectionState_ = {}, System::Collections::Generic::Queue_1<int>* freeSortIndices_ = {}, System::Action* connectedEvent_ = {}, System::Action_1<GlobalNamespace::ConnectionFailedReason>* connectionFailedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerConnectedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerDisconnectedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerAvatarChangedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerStateChangedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* connectionOwnerStateChangedEvent_ = {}, System::Action_1<GlobalNamespace::DisconnectedReason>* disconnectedEvent_ = {}, GlobalNamespace::IConnectedPlayer* connectionOwner_ = {}, bool exclusiveConnectedPlayerManager_ = {}, GlobalNamespace::ConnectedPlayerManager* connectedPlayerManager_ = {}) noexcept : packetSerializer{packetSerializer_}, connectedPlayers{connectedPlayers_}, localPlayerState{localPlayerState_}, synchronizedActionQueue{synchronizedActionQueue_}, maxPlayerCount{maxPlayerCount_}, connectionState{connectionState_}, freeSortIndices{freeSortIndices_}, connectedEvent{connectedEvent_}, connectionFailedEvent{connectionFailedEvent_}, playerConnectedEvent{playerConnectedEvent_}, playerDisconnectedEvent{playerDisconnectedEvent_}, playerAvatarChangedEvent{playerAvatarChangedEvent_}, playerStateChangedEvent{playerStateChangedEvent_}, connectionOwnerStateChangedEvent{connectionOwnerStateChangedEvent_}, disconnectedEvent{disconnectedEvent_}, connectionOwner{connectionOwner_}, exclusiveConnectedPlayerManager{exclusiveConnectedPlayerManager_}, connectedPlayerManager{connectedPlayerManager_} {}
// Creating interface conversion operator: operator GlobalNamespace::IMultiplayerSessionManager
operator GlobalNamespace::IMultiplayerSessionManager() noexcept {
return *reinterpret_cast<GlobalNamespace::IMultiplayerSessionManager*>(this);
}
// static field const value: static private System.String kMultiplayerSessionState
static constexpr const char* kMultiplayerSessionState = "multiplayer_session";
// Get static field: static private System.String kMultiplayerSessionState
static ::Il2CppString* _get_kMultiplayerSessionState();
// Set static field: static private System.String kMultiplayerSessionState
static void _set_kMultiplayerSessionState(::Il2CppString* value);
// Get instance field reference: private readonly NetworkPacketSerializer`2<MultiplayerSessionManager/MessageType,IConnectedPlayer> _packetSerializer
GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>*& dyn__packetSerializer();
// Get instance field reference: private readonly System.Collections.Generic.List`1<IConnectedPlayer> _connectedPlayers
System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>*& dyn__connectedPlayers();
// Get instance field reference: private readonly System.Collections.Generic.HashSet`1<System.String> _localPlayerState
System::Collections::Generic::HashSet_1<::Il2CppString*>*& dyn__localPlayerState();
// Get instance field reference: private readonly SynchronizedActionQueue _synchronizedActionQueue
GlobalNamespace::SynchronizedActionQueue*& dyn__synchronizedActionQueue();
// Get instance field reference: private System.Int32 _maxPlayerCount
int& dyn__maxPlayerCount();
// Get instance field reference: private MultiplayerSessionManager/ConnectionState _connectionState
GlobalNamespace::MultiplayerSessionManager::ConnectionState& dyn__connectionState();
// Get instance field reference: private readonly System.Collections.Generic.Queue`1<System.Int32> _freeSortIndices
System::Collections::Generic::Queue_1<int>*& dyn__freeSortIndices();
// Get instance field reference: private System.Action connectedEvent
System::Action*& dyn_connectedEvent();
// Get instance field reference: private System.Action`1<ConnectionFailedReason> connectionFailedEvent
System::Action_1<GlobalNamespace::ConnectionFailedReason>*& dyn_connectionFailedEvent();
// Get instance field reference: private System.Action`1<IConnectedPlayer> playerConnectedEvent
System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerConnectedEvent();
// Get instance field reference: private System.Action`1<IConnectedPlayer> playerDisconnectedEvent
System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerDisconnectedEvent();
// Get instance field reference: private System.Action`1<IConnectedPlayer> playerAvatarChangedEvent
System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerAvatarChangedEvent();
// Get instance field reference: private System.Action`1<IConnectedPlayer> playerStateChangedEvent
System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerStateChangedEvent();
// Get instance field reference: private System.Action`1<IConnectedPlayer> connectionOwnerStateChangedEvent
System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_connectionOwnerStateChangedEvent();
// Get instance field reference: private System.Action`1<DisconnectedReason> disconnectedEvent
System::Action_1<GlobalNamespace::DisconnectedReason>*& dyn_disconnectedEvent();
// Get instance field reference: private IConnectedPlayer <connectionOwner>k__BackingField
GlobalNamespace::IConnectedPlayer*& dyn_$connectionOwner$k__BackingField();
// Get instance field reference: private System.Boolean _exclusiveConnectedPlayerManager
bool& dyn__exclusiveConnectedPlayerManager();
// Get instance field reference: private ConnectedPlayerManager _connectedPlayerManager
GlobalNamespace::ConnectedPlayerManager*& dyn__connectedPlayerManager();
// public System.Boolean get_isConnectionOwner()
// Offset: 0x16F1FCC
bool get_isConnectionOwner();
// public IConnectedPlayer get_connectionOwner()
// Offset: 0x16F1FE4
GlobalNamespace::IConnectedPlayer* get_connectionOwner();
// private System.Void set_connectionOwner(IConnectedPlayer value)
// Offset: 0x16F1FEC
void set_connectionOwner(GlobalNamespace::IConnectedPlayer* value);
// public System.Boolean get_isSpectating()
// Offset: 0x16F1FF4
bool get_isSpectating();
// public System.Boolean get_isConnectingOrConnected()
// Offset: 0x16F20D0
bool get_isConnectingOrConnected();
// public System.Boolean get_isConnected()
// Offset: 0x16F20F4
bool get_isConnected();
// public System.Boolean get_isConnecting()
// Offset: 0x16F20E4
bool get_isConnecting();
// public System.Boolean get_isDisconnecting()
// Offset: 0x16F2104
bool get_isDisconnecting();
// public System.Collections.Generic.IReadOnlyList`1<IConnectedPlayer> get_connectedPlayers()
// Offset: 0x16F2114
System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IConnectedPlayer*>* get_connectedPlayers();
// public System.Int32 get_connectedPlayerCount()
// Offset: 0x16F211C
int get_connectedPlayerCount();
// public System.Single get_syncTime()
// Offset: 0x16F216C
float get_syncTime();
// public System.Boolean get_isSyncTimeInitialized()
// Offset: 0x16F2184
bool get_isSyncTimeInitialized();
// public System.Single get_syncTimeDelay()
// Offset: 0x16F2198
float get_syncTimeDelay();
// public IConnectedPlayer get_localPlayer()
// Offset: 0x16F21B0
GlobalNamespace::IConnectedPlayer* get_localPlayer();
// public ConnectedPlayerManager get_connectedPlayerManager()
// Offset: 0x16F21C8
GlobalNamespace::ConnectedPlayerManager* get_connectedPlayerManager();
// public System.Int32 get_maxPlayerCount()
// Offset: 0x16F21D0
int get_maxPlayerCount();
// public System.Void add_connectedEvent(System.Action value)
// Offset: 0x16F158C
void add_connectedEvent(System::Action* value);
// public System.Void remove_connectedEvent(System.Action value)
// Offset: 0x16F1630
void remove_connectedEvent(System::Action* value);
// public System.Void add_connectionFailedEvent(System.Action`1<ConnectionFailedReason> value)
// Offset: 0x16F16D4
void add_connectionFailedEvent(System::Action_1<GlobalNamespace::ConnectionFailedReason>* value);
// public System.Void remove_connectionFailedEvent(System.Action`1<ConnectionFailedReason> value)
// Offset: 0x16F1778
void remove_connectionFailedEvent(System::Action_1<GlobalNamespace::ConnectionFailedReason>* value);
// public System.Void add_playerConnectedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F181C
void add_playerConnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void remove_playerConnectedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F18C0
void remove_playerConnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void add_playerDisconnectedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1964
void add_playerDisconnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void remove_playerDisconnectedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1A08
void remove_playerDisconnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void add_playerAvatarChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1AAC
void add_playerAvatarChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void remove_playerAvatarChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1B50
void remove_playerAvatarChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void add_playerStateChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1BF4
void add_playerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void remove_playerStateChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1C98
void remove_playerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void add_connectionOwnerStateChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1D3C
void add_connectionOwnerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void remove_connectionOwnerStateChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1DE0
void remove_connectionOwnerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void add_disconnectedEvent(System.Action`1<DisconnectedReason> value)
// Offset: 0x16F1E84
void add_disconnectedEvent(System::Action_1<GlobalNamespace::DisconnectedReason>* value);
// public System.Void remove_disconnectedEvent(System.Action`1<DisconnectedReason> value)
// Offset: 0x16F1F28
void remove_disconnectedEvent(System::Action_1<GlobalNamespace::DisconnectedReason>* value);
// public System.Void RegisterSerializer(MultiplayerSessionManager/MessageType serializerType, INetworkPacketSubSerializer`1<IConnectedPlayer> subSerializer)
// Offset: 0x16F2BA4
void RegisterSerializer(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>* subSerializer);
// public System.Void UnregisterSerializer(MultiplayerSessionManager/MessageType serializerType, INetworkPacketSubSerializer`1<IConnectedPlayer> subSerializer)
// Offset: 0x16F2C14
void UnregisterSerializer(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>* subSerializer);
// public System.Void RegisterCallback(MultiplayerSessionManager/MessageType serializerType, System.Action`2<T,IConnectedPlayer> callback, System.Func`1<T> constructor)
// Offset: 0xFFFFFFFF
template<class T>
void RegisterCallback(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType, System::Action_2<T, GlobalNamespace::IConnectedPlayer*>* callback, System::Func_1<T>* constructor) {
static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>);
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::RegisterCallback");
auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RegisterCallback", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(serializerType), ::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(constructor)})));
auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
auto ___instance_arg = this;
::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, serializerType, callback, constructor);
}
// public System.Void UnregisterCallback(MultiplayerSessionManager/MessageType serializerType)
// Offset: 0xFFFFFFFF
template<class T>
void UnregisterCallback(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType) {
static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>);
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::UnregisterCallback");
auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UnregisterCallback", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(serializerType)})));
auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
auto ___instance_arg = this;
::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, serializerType);
}
// public System.Void StartSession(MultiplayerSessionManager/SessionType sessionType, T connectionManager, IConnectionInitParams`1<T> initParams)
// Offset: 0xFFFFFFFF
template<class T>
void StartSession(GlobalNamespace::MultiplayerSessionManager::SessionType sessionType, T connectionManager, GlobalNamespace::IConnectionInitParams_1<T>* initParams) {
static_assert(std::is_base_of_v<GlobalNamespace::IConnectionManager, std::remove_pointer_t<T>>);
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::StartSession");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "StartSession", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sessionType), ::il2cpp_utils::ExtractType(connectionManager), ::il2cpp_utils::ExtractType(initParams)})));
static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
auto ___instance_arg = this;
::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, sessionType, connectionManager, initParams);
}
// public System.Void StartSession(ConnectedPlayerManager connectedPlayerManager)
// Offset: 0x16F2C84
void StartSession(GlobalNamespace::ConnectedPlayerManager* connectedPlayerManager);
// public System.Void SetMaxPlayerCount(System.Int32 maxPlayerCount)
// Offset: 0x16F310C
void SetMaxPlayerCount(int maxPlayerCount);
// private System.Void InitInternal(MultiplayerSessionManager/SessionType sessionType)
// Offset: 0x16F2CD0
void InitInternal(GlobalNamespace::MultiplayerSessionManager::SessionType sessionType);
// public System.Void EndSession()
// Offset: 0x16F2788
void EndSession();
// public System.Void Disconnect()
// Offset: 0x16F3114
void Disconnect();
// public System.Void Send(T message)
// Offset: 0xFFFFFFFF
template<class T>
void Send(T message) {
static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>);
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::Send");
auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Send", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(message)})));
auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
auto ___instance_arg = this;
::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, message);
}
// public System.Void SendUnreliable(T message)
// Offset: 0xFFFFFFFF
template<class T>
void SendUnreliable(T message) {
static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>);
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::SendUnreliable");
auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SendUnreliable", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(message)})));
auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
auto ___instance_arg = this;
::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, message);
}
// public System.Void PerformAtSyncTime(System.Single syncTime, System.Action action)
// Offset: 0x16F317C
void PerformAtSyncTime(float syncTime, System::Action* action);
// private System.Void UpdateSynchronizedActions()
// Offset: 0x16F2314
void UpdateSynchronizedActions();
// private System.Void HandleReinitialized()
// Offset: 0x16F3398
void HandleReinitialized();
// private System.Void HandleConnected()
// Offset: 0x16F33A8
void HandleConnected();
// private System.Void HandleDisconnected(DisconnectedReason disconnectedReason)
// Offset: 0x16F33B8
void HandleDisconnected(GlobalNamespace::DisconnectedReason disconnectedReason);
// private System.Void HandleConnectionFailed(ConnectionFailedReason reason)
// Offset: 0x16F33C8
void HandleConnectionFailed(GlobalNamespace::ConnectionFailedReason reason);
// private System.Void HandleSyncTimeInitialized()
// Offset: 0x16F33D8
void HandleSyncTimeInitialized();
// private System.Void HandlePlayerConnected(IConnectedPlayer player)
// Offset: 0x16F33E8
void HandlePlayerConnected(GlobalNamespace::IConnectedPlayer* player);
// private System.Void HandlePlayerDisconnected(IConnectedPlayer player)
// Offset: 0x16F3A0C
void HandlePlayerDisconnected(GlobalNamespace::IConnectedPlayer* player);
// private System.Void HandlePlayerStateChanged(IConnectedPlayer player)
// Offset: 0x16F3AE0
void HandlePlayerStateChanged(GlobalNamespace::IConnectedPlayer* player);
// private System.Void HandlePlayerAvatarChanged(IConnectedPlayer player)
// Offset: 0x16F3CA0
void HandlePlayerAvatarChanged(GlobalNamespace::IConnectedPlayer* player);
// private System.Void HandlePlayerOrderChanged(IConnectedPlayer player)
// Offset: 0x16F3D38
void HandlePlayerOrderChanged(GlobalNamespace::IConnectedPlayer* player);
// public IConnectedPlayer GetPlayerByUserId(System.String userId)
// Offset: 0x16F3D70
GlobalNamespace::IConnectedPlayer* GetPlayerByUserId(::Il2CppString* userId);
// public IConnectedPlayer GetConnectedPlayer(System.Int32 i)
// Offset: 0x16F3EF8
GlobalNamespace::IConnectedPlayer* GetConnectedPlayer(int i);
// public System.Void SetLocalPlayerState(System.String state, System.Boolean hasState)
// Offset: 0x16F222C
void SetLocalPlayerState(::Il2CppString* state, bool hasState);
// public System.Void KickPlayer(System.String userId)
// Offset: 0x16F3F70
void KickPlayer(::Il2CppString* userId);
// public System.Boolean LocalPlayerHasState(System.String state)
// Offset: 0x16F3F88
bool LocalPlayerHasState(::Il2CppString* state);
// private System.Void UpdateConnectionState(UpdateConnectionStateReason updateReason, DisconnectedReason disconnectedReason, ConnectionFailedReason connectionFailedReason)
// Offset: 0x16F23A8
void UpdateConnectionState(GlobalNamespace::UpdateConnectionStateReason updateReason, GlobalNamespace::DisconnectedReason disconnectedReason, GlobalNamespace::ConnectionFailedReason connectionFailedReason);
// private System.Boolean TryUpdateConnectedPlayer(IConnectedPlayer player, System.Boolean isPlayerConnected)
// Offset: 0x16F34BC
bool TryUpdateConnectedPlayer(GlobalNamespace::IConnectedPlayer* player, bool isPlayerConnected);
// private System.Int32 GetNextAvailableSortIndex()
// Offset: 0x16F40AC
int GetNextAvailableSortIndex();
// public System.Void .ctor()
// Offset: 0x16F4144
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MultiplayerSessionManager* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MultiplayerSessionManager*, creationType>()));
}
// protected override System.Void Start()
// Offset: 0x16F21D8
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::Start()
void Start();
// protected override System.Void Update()
// Offset: 0x16F22DC
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::Update()
void Update();
// protected override System.Void OnDestroy()
// Offset: 0x16F2378
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::OnDestroy()
void OnDestroy();
// protected override System.Void OnApplicationPause(System.Boolean pauseStatus)
// Offset: 0x16F2B44
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::OnApplicationPause(System.Boolean pauseStatus)
void OnApplicationPause(bool pauseStatus);
}; // MultiplayerSessionManager
#pragma pack(pop)
static check_size<sizeof(MultiplayerSessionManager), 176 + sizeof(GlobalNamespace::ConnectedPlayerManager*)> __GlobalNamespace_MultiplayerSessionManagerSizeCheck;
static_assert(sizeof(MultiplayerSessionManager) == 0xB8);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerSessionManager*, "", "MultiplayerSessionManager");
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerSessionManager::SessionType, "", "MultiplayerSessionManager/SessionType");
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerSessionManager::ConnectionState, "", "MultiplayerSessionManager/ConnectionState");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnectionOwner
// Il2CppName: get_isConnectionOwner
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnectionOwner)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnectionOwner", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectionOwner
// Il2CppName: get_connectionOwner
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectionOwner)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectionOwner", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::set_connectionOwner
// Il2CppName: set_connectionOwner
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::set_connectionOwner)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "set_connectionOwner", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isSpectating
// Il2CppName: get_isSpectating
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isSpectating)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isSpectating", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnectingOrConnected
// Il2CppName: get_isConnectingOrConnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnectingOrConnected)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnectingOrConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnected
// Il2CppName: get_isConnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnected)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnecting
// Il2CppName: get_isConnecting
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnecting)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnecting", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isDisconnecting
// Il2CppName: get_isDisconnecting
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isDisconnecting)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isDisconnecting", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectedPlayers
// Il2CppName: get_connectedPlayers
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IConnectedPlayer*>* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectedPlayers)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectedPlayers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerCount
// Il2CppName: get_connectedPlayerCount
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerCount)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectedPlayerCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_syncTime
// Il2CppName: get_syncTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_syncTime)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_syncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isSyncTimeInitialized
// Il2CppName: get_isSyncTimeInitialized
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isSyncTimeInitialized)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isSyncTimeInitialized", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_syncTimeDelay
// Il2CppName: get_syncTimeDelay
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_syncTimeDelay)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_syncTimeDelay", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_localPlayer
// Il2CppName: get_localPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_localPlayer)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_localPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerManager
// Il2CppName: get_connectedPlayerManager
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::ConnectedPlayerManager* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerManager)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectedPlayerManager", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_maxPlayerCount
// Il2CppName: get_maxPlayerCount
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_maxPlayerCount)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_maxPlayerCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_connectedEvent
// Il2CppName: add_connectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action*)>(&GlobalNamespace::MultiplayerSessionManager::add_connectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_connectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_connectedEvent
// Il2CppName: remove_connectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action*)>(&GlobalNamespace::MultiplayerSessionManager::remove_connectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_connectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_connectionFailedEvent
// Il2CppName: add_connectionFailedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::ConnectionFailedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::add_connectionFailedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_connectionFailedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_connectionFailedEvent
// Il2CppName: remove_connectionFailedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::ConnectionFailedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_connectionFailedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_connectionFailedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerConnectedEvent
// Il2CppName: add_playerConnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerConnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerConnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerConnectedEvent
// Il2CppName: remove_playerConnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerConnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerConnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerDisconnectedEvent
// Il2CppName: add_playerDisconnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerDisconnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerDisconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerDisconnectedEvent
// Il2CppName: remove_playerDisconnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerDisconnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerDisconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerAvatarChangedEvent
// Il2CppName: add_playerAvatarChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerAvatarChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerAvatarChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerAvatarChangedEvent
// Il2CppName: remove_playerAvatarChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerAvatarChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerAvatarChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerStateChangedEvent
// Il2CppName: add_playerStateChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerStateChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerStateChangedEvent
// Il2CppName: remove_playerStateChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerStateChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_connectionOwnerStateChangedEvent
// Il2CppName: add_connectionOwnerStateChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_connectionOwnerStateChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_connectionOwnerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_connectionOwnerStateChangedEvent
// Il2CppName: remove_connectionOwnerStateChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_connectionOwnerStateChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_connectionOwnerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_disconnectedEvent
// Il2CppName: add_disconnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::DisconnectedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::add_disconnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "DisconnectedReason")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_disconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_disconnectedEvent
// Il2CppName: remove_disconnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::DisconnectedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_disconnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "DisconnectedReason")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_disconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::RegisterSerializer
// Il2CppName: RegisterSerializer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::RegisterSerializer)> {
static const MethodInfo* get() {
static auto* serializerType = &::il2cpp_utils::GetClassFromName("", "MultiplayerSessionManager/MessageType")->byval_arg;
static auto* subSerializer = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("", "INetworkPacketSubSerializer`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "RegisterSerializer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{serializerType, subSerializer});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UnregisterSerializer
// Il2CppName: UnregisterSerializer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::UnregisterSerializer)> {
static const MethodInfo* get() {
static auto* serializerType = &::il2cpp_utils::GetClassFromName("", "MultiplayerSessionManager/MessageType")->byval_arg;
static auto* subSerializer = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("", "INetworkPacketSubSerializer`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "UnregisterSerializer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{serializerType, subSerializer});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::RegisterCallback
// Il2CppName: RegisterCallback
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UnregisterCallback
// Il2CppName: UnregisterCallback
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::StartSession
// Il2CppName: StartSession
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::StartSession
// Il2CppName: StartSession
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::ConnectedPlayerManager*)>(&GlobalNamespace::MultiplayerSessionManager::StartSession)> {
static const MethodInfo* get() {
static auto* connectedPlayerManager = &::il2cpp_utils::GetClassFromName("", "ConnectedPlayerManager")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "StartSession", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{connectedPlayerManager});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::SetMaxPlayerCount
// Il2CppName: SetMaxPlayerCount
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(int)>(&GlobalNamespace::MultiplayerSessionManager::SetMaxPlayerCount)> {
static const MethodInfo* get() {
static auto* maxPlayerCount = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "SetMaxPlayerCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{maxPlayerCount});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::InitInternal
// Il2CppName: InitInternal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::MultiplayerSessionManager::SessionType)>(&GlobalNamespace::MultiplayerSessionManager::InitInternal)> {
static const MethodInfo* get() {
static auto* sessionType = &::il2cpp_utils::GetClassFromName("", "MultiplayerSessionManager/SessionType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "InitInternal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionType});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::EndSession
// Il2CppName: EndSession
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::EndSession)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "EndSession", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Disconnect
// Il2CppName: Disconnect
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::Disconnect)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "Disconnect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Send
// Il2CppName: Send
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::SendUnreliable
// Il2CppName: SendUnreliable
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::PerformAtSyncTime
// Il2CppName: PerformAtSyncTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(float, System::Action*)>(&GlobalNamespace::MultiplayerSessionManager::PerformAtSyncTime)> {
static const MethodInfo* get() {
static auto* syncTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* action = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "PerformAtSyncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{syncTime, action});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UpdateSynchronizedActions
// Il2CppName: UpdateSynchronizedActions
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::UpdateSynchronizedActions)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "UpdateSynchronizedActions", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleReinitialized
// Il2CppName: HandleReinitialized
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::HandleReinitialized)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleReinitialized", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleConnected
// Il2CppName: HandleConnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::HandleConnected)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleDisconnected
// Il2CppName: HandleDisconnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::DisconnectedReason)>(&GlobalNamespace::MultiplayerSessionManager::HandleDisconnected)> {
static const MethodInfo* get() {
static auto* disconnectedReason = &::il2cpp_utils::GetClassFromName("", "DisconnectedReason")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleDisconnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{disconnectedReason});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleConnectionFailed
// Il2CppName: HandleConnectionFailed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::ConnectionFailedReason)>(&GlobalNamespace::MultiplayerSessionManager::HandleConnectionFailed)> {
static const MethodInfo* get() {
static auto* reason = &::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleConnectionFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reason});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleSyncTimeInitialized
// Il2CppName: HandleSyncTimeInitialized
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::HandleSyncTimeInitialized)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleSyncTimeInitialized", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerConnected
// Il2CppName: HandlePlayerConnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerConnected)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerDisconnected
// Il2CppName: HandlePlayerDisconnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerDisconnected)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerDisconnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerStateChanged
// Il2CppName: HandlePlayerStateChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerStateChanged)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerStateChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerAvatarChanged
// Il2CppName: HandlePlayerAvatarChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerAvatarChanged)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerAvatarChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerOrderChanged
// Il2CppName: HandlePlayerOrderChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerOrderChanged)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerOrderChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::GetPlayerByUserId
// Il2CppName: GetPlayerByUserId
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*)>(&GlobalNamespace::MultiplayerSessionManager::GetPlayerByUserId)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "GetPlayerByUserId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::GetConnectedPlayer
// Il2CppName: GetConnectedPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)(int)>(&GlobalNamespace::MultiplayerSessionManager::GetConnectedPlayer)> {
static const MethodInfo* get() {
static auto* i = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "GetConnectedPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{i});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::SetLocalPlayerState
// Il2CppName: SetLocalPlayerState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*, bool)>(&GlobalNamespace::MultiplayerSessionManager::SetLocalPlayerState)> {
static const MethodInfo* get() {
static auto* state = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* hasState = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "SetLocalPlayerState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{state, hasState});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::KickPlayer
// Il2CppName: KickPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*)>(&GlobalNamespace::MultiplayerSessionManager::KickPlayer)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "KickPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::LocalPlayerHasState
// Il2CppName: LocalPlayerHasState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*)>(&GlobalNamespace::MultiplayerSessionManager::LocalPlayerHasState)> {
static const MethodInfo* get() {
static auto* state = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "LocalPlayerHasState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{state});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UpdateConnectionState
// Il2CppName: UpdateConnectionState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::UpdateConnectionStateReason, GlobalNamespace::DisconnectedReason, GlobalNamespace::ConnectionFailedReason)>(&GlobalNamespace::MultiplayerSessionManager::UpdateConnectionState)> {
static const MethodInfo* get() {
static auto* updateReason = &::il2cpp_utils::GetClassFromName("", "UpdateConnectionStateReason")->byval_arg;
static auto* disconnectedReason = &::il2cpp_utils::GetClassFromName("", "DisconnectedReason")->byval_arg;
static auto* connectionFailedReason = &::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "UpdateConnectionState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{updateReason, disconnectedReason, connectionFailedReason});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::TryUpdateConnectedPlayer
// Il2CppName: TryUpdateConnectedPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*, bool)>(&GlobalNamespace::MultiplayerSessionManager::TryUpdateConnectedPlayer)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
static auto* isPlayerConnected = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "TryUpdateConnectedPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player, isPlayerConnected});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::GetNextAvailableSortIndex
// Il2CppName: GetNextAvailableSortIndex
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::GetNextAvailableSortIndex)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "GetNextAvailableSortIndex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Update
// Il2CppName: Update
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::Update)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::OnDestroy
// Il2CppName: OnDestroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::OnDestroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::OnApplicationPause
// Il2CppName: OnApplicationPause
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(bool)>(&GlobalNamespace::MultiplayerSessionManager::OnApplicationPause)> {
static const MethodInfo* get() {
static auto* pauseStatus = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "OnApplicationPause", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pauseStatus});
}
};
| 73.077824
| 2,247
| 0.774998
|
Fernthedev
|
ca10ce59e8add44aa2c13e8d28484a80163462eb
| 1,122
|
cpp
|
C++
|
imgplane.cpp
|
dghilardi/Sgherender
|
1940dc52034c5e00adc3bd7a2ab6fbcee73007e1
|
[
"MIT"
] | null | null | null |
imgplane.cpp
|
dghilardi/Sgherender
|
1940dc52034c5e00adc3bd7a2ab6fbcee73007e1
|
[
"MIT"
] | null | null | null |
imgplane.cpp
|
dghilardi/Sgherender
|
1940dc52034c5e00adc3bd7a2ab6fbcee73007e1
|
[
"MIT"
] | null | null | null |
#include "imgplane.h"
ImgPlane::ImgPlane(int w, int h) : width(w), height(h)
{
int size = w*h;
for(int i=0; i<size; ++i){
image.push_back(new Color(0,0,0));
raysNumber.push_back(0);
}
}
void ImgPlane::updatePixel(int x, int y, Color &pxl, int rays){
Color *actual = image[x*width+y];
int actualRays = raysNumber[x*width+y];
actual->setColor((actual->getR()*actualRays+pxl.getR()*rays)/(rays+actualRays),
(actual->getG()*actualRays+pxl.getG()*rays)/(rays+actualRays),
(actual->getB()*actualRays+pxl.getB()*rays)/(rays+actualRays)
);
raysNumber[x*width+y] += rays;
}
void ImgPlane::writeImg(const string &fileName){
cv::Mat img(height, width, CV_8UC3);
for(int x=0; x<width; ++x) for(int y=0; y<height; ++y){
Color toAssign = *(image[x*width+y]);
toAssign.clampVars();
img.at<uchar>(y,3*x+2) = (uchar)255*toAssign.getR();
img.at<uchar>(y,3*x+1) = (uchar)255*toAssign.getG();
img.at<uchar>(y,3*x) = (uchar)255*toAssign.getB();
}
cv::imwrite(fileName, img);
}
| 34
| 83
| 0.578431
|
dghilardi
|
ca11d073f33b173a5993690aa4c7400e6d6024cf
| 3,503
|
cpp
|
C++
|
Graph/ManucianGoesToDerby_IMP_msp.cpp
|
Satyabrat35/Programming
|
841ead1bf847b567d8e21963673413cbd65277f4
|
[
"Apache-2.0"
] | null | null | null |
Graph/ManucianGoesToDerby_IMP_msp.cpp
|
Satyabrat35/Programming
|
841ead1bf847b567d8e21963673413cbd65277f4
|
[
"Apache-2.0"
] | null | null | null |
Graph/ManucianGoesToDerby_IMP_msp.cpp
|
Satyabrat35/Programming
|
841ead1bf847b567d8e21963673413cbd65277f4
|
[
"Apache-2.0"
] | null | null | null |
/**************erik****************/
#include<bits/stdc++.h>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
map<int,int> mp1;
set<int> s1;
//set<int>::iterator it;
#define maxm(a,b,c) max(a,max(c,b))
#define minm(a,b,c) min(a,min(c,b))
#define f(i,n) for(int i=1;i<n;i++)
#define rf(i,n) for(int i=n-1;i>=0;i--)
const int MAX = 100005;
vector<pair<int,int> > vec[MAX];
ll dist[MAX];
bool vis[MAX];
void dijkstra(int source){
dist[source] = 0;
multiset < pair < ll , int > > s;
s.insert({0 , source});
while(!s.empty()){
pair <ll , int> p = *s.begin();
s.erase(s.begin());
int x = p.second;
// if( vis[x] ) continue;
// vis[x] = true;
for(int i = 0; i < vec[x].size(); i++){
int e = vec[x][i].second;
int w = vec[x][i].first;
if(w==1){
if(dist[x]%2==0 && dist[e]>dist[x]+1){
dist[e] = dist[x]+2; //if wgt is odd but arrival time is even
s.insert({dist[e],e});
}
else if(dist[x]%2!=0 && dist[e]>dist[x]+1){
dist[e] = dist[x]+1;
s.insert({dist[e],e});
}
}
else if(w==0){
if(dist[x]%2==0 && dist[e]>dist[x]+1){
dist[e] = dist[x]+1;
s.insert({dist[e],e});
}
else if(dist[x]%2!=0 && dist[e]>dist[x]+1){
dist[e] = dist[x]+2; // if wgt is even but arrival time is odd
s.insert({dist[e],e});
}
}
}
}
}
/*void dfs(int x,ll timed,int n){
vis[x]=1;
tot = timed;
if(vis[n]){
//cout<<x<<"*"<<timed+1<<endl;
return;
}
if(timed%2==0){
if(vec[x][0].size()!=0){
bool f = true;
for(int i=0;i<vec[x][0].size();i++){
int y = vec[x][0][i];
if(vis[y]==0){
f = false;
//cout<<y<<'*'<<timed+1<<endl;
dfs(y,timed+1,n);
}
}
if(f){
//cout<<x<<"*"<<timed+1<<endl;
dfs(x,timed+1,n);
}
}
else {
//cout<<x<<"*"<<timed+1<<endl;
dfs(x,timed+1,n);
}
}
else {
if(vec[x][1].size()!=0){
bool f = true;
for(int i=0;i<vec[x][1].size();i++){
int y = vec[x][1][i];
if(vis[y]==0){
f = false;
//cout<<y<<' '<<timed+1<<endl;
dfs(y,timed+1,n);
}
}
//cout<<x<<"*"<<timed+1<<endl;
dfs(x,timed+1,n);
}
else {
//cout<<x<<"*"<<timed+1<<endl;
dfs(x,timed+1,n);
}
}
}*/
int main() {
int n,m,q;
cin>>n>>m>>q;
for(int i=0;i<m;i++){
int x,y;
cin>>x>>y;
vec[x].push_back({0,y});
vec[y].push_back({1,x});
}
for(int i=1;i<=n+1;i++){
dist[i]=1e12;
vec[i].clear();
}
dist[1]=0;
dijkstra(1);
cout<<dist[n]<<endl;
for(int i=0;i<q;i++){
ll tt;
cin>>tt;
if(tt<dist[n]){
cout<<"FML"<<endl;
}
else {
cout<<"GGMU"<<endl;
}
}
//cout<<tot;
return 0;
}
| 26.338346
| 82
| 0.375393
|
Satyabrat35
|
ca147e45cea256785a4437433d70cbc6a13c4bd0
| 143,300
|
cpp
|
C++
|
src/libbrep/PullbackCurve.cpp
|
quadmotor/brlcad
|
05952aafa27ee9df17cd900f5d8f8217ed2194af
|
[
"BSD-4-Clause",
"BSD-3-Clause"
] | 35
|
2015-03-11T11:51:48.000Z
|
2021-07-25T16:04:49.000Z
|
src/libbrep/PullbackCurve.cpp
|
CloudComputer/brlcad
|
05952aafa27ee9df17cd900f5d8f8217ed2194af
|
[
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null |
src/libbrep/PullbackCurve.cpp
|
CloudComputer/brlcad
|
05952aafa27ee9df17cd900f5d8f8217ed2194af
|
[
"BSD-4-Clause",
"BSD-3-Clause"
] | 19
|
2016-05-04T08:39:37.000Z
|
2021-12-07T12:45:54.000Z
|
/* P U L L B A C K C U R V E . C P P
* BRL-CAD
*
* Copyright (c) 2009-2014 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file step/PullbackCurve.cpp
*
* Pull curve back into UV space from 3D space
*
*/
#include "common.h"
#include "vmath.h"
#include "dvec.h"
#include <assert.h>
#include <vector>
#include <list>
#include <limits>
#include <set>
#include <map>
#include <string>
#include "brep.h"
/* interface header */
#include "PullbackCurve.h"
#define RANGE_HI 0.55
#define RANGE_LO 0.45
#define UNIVERSAL_SAMPLE_COUNT 1001
/* FIXME: duplicated with opennurbs_ext.cpp */
class BSpline
{
public:
int p; // degree
int m; // num_knots-1
int n; // num_samples-1 (aka number of control points)
std::vector<double> params;
std::vector<double> knots;
ON_2dPointArray controls;
};
bool
isFlat(const ON_2dPoint& p1, const ON_2dPoint& m, const ON_2dPoint& p2, double flatness)
{
ON_Line line = ON_Line(ON_3dPoint(p1), ON_3dPoint(p2));
return line.DistanceTo(ON_3dPoint(m)) <= flatness;
}
void
utah_ray_planes(const ON_Ray &r, ON_3dVector &p1, double &p1d, ON_3dVector &p2, double &p2d)
{
ON_3dPoint ro(r.m_origin);
ON_3dVector rdir(r.m_dir);
double rdx, rdy, rdz;
double rdxmag, rdymag, rdzmag;
rdx = rdir.x;
rdy = rdir.y;
rdz = rdir.z;
rdxmag = fabs(rdx);
rdymag = fabs(rdy);
rdzmag = fabs(rdz);
if (rdxmag > rdymag && rdxmag > rdzmag)
p1 = ON_3dVector(rdy, -rdx, 0);
else
p1 = ON_3dVector(0, rdz, -rdy);
p1.Unitize();
p2 = ON_CrossProduct(p1, rdir);
p1d = -(p1 * ro);
p2d = -(p2 * ro);
}
enum seam_direction
seam_direction(ON_2dPoint uv1, ON_2dPoint uv2)
{
if (NEAR_EQUAL(uv1.x, 0.0, PBC_TOL) && NEAR_EQUAL(uv2.x, 0.0, PBC_TOL)) {
return WEST_SEAM;
} else if (NEAR_EQUAL(uv1.x, 1.0, PBC_TOL) && NEAR_EQUAL(uv2.x, 1.0, PBC_TOL)) {
return EAST_SEAM;
} else if (NEAR_EQUAL(uv1.y, 0.0, PBC_TOL) && NEAR_EQUAL(uv2.y, 0.0, PBC_TOL)) {
return SOUTH_SEAM;
} else if (NEAR_EQUAL(uv1.y, 1.0, PBC_TOL) && NEAR_EQUAL(uv2.y, 1.0, PBC_TOL)) {
return NORTH_SEAM;
} else {
return UNKNOWN_SEAM_DIRECTION;
}
}
ON_BOOL32
GetDomainSplits(
const ON_Surface *surf,
const ON_Interval &u_interval,
const ON_Interval &v_interval,
ON_Interval domSplits[2][2]
)
{
ON_3dPoint min, max;
ON_Interval dom[2];
double length[2];
// initialize intervals
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
domSplits[i][j] = ON_Interval::EmptyInterval;
}
}
min[0] = u_interval.m_t[0];
min[1] = v_interval.m_t[0];
max[0] = u_interval.m_t[1];
max[1] = v_interval.m_t[1];
for (int i=0; i<2; i++) {
if (surf->IsClosed(i)) {
dom[i] = surf->Domain(i);
length[i] = dom[i].Length();
if ((max[i] - min[i]) >= length[i]) {
domSplits[i][0] = dom[i];
} else {
double minbound = min[i];
double maxbound = max[i];
while (minbound < dom[i].m_t[0]) {
minbound += length[i];
maxbound += length[i];
}
while (minbound > dom[i].m_t[1]) {
minbound -= length[i];
maxbound -= length[i];
}
if (maxbound > dom[i].m_t[1]) {
domSplits[i][0].m_t[0] = minbound;
domSplits[i][0].m_t[1] = dom[i].m_t[1];
domSplits[i][1].m_t[0] = dom[i].m_t[0];
domSplits[i][1].m_t[1] = maxbound - length[i];
} else {
domSplits[i][0].m_t[0] = minbound;
domSplits[i][0].m_t[1] = maxbound;
}
}
} else {
domSplits[i][0].m_t[0] = min[i];
domSplits[i][0].m_t[1] = max[i];
}
}
return true;
}
/*
* Wrapped OpenNURBS 'EvNormal()' because it fails when at surface singularity
* but not on edge of domain. If fails and at singularity this wrapper will
* reevaluate at domain edge.
*/
ON_BOOL32
surface_EvNormal( // returns false if unable to evaluate
const ON_Surface *surf,
double s, double t, // evaluation parameters (s,t)
ON_3dPoint& point, // returns value of surface
ON_3dVector& normal, // unit normal
int side, // optional - determines which side to evaluate from
// 0 = default
// 1 from NE quadrant
// 2 from NW quadrant
// 3 from SW quadrant
// 4 from SE quadrant
int* hint // optional - evaluation hint (int[2]) used to speed
// repeated evaluations
)
{
ON_BOOL32 rc = false;
if (!(rc=surf->EvNormal(s, t, point, normal, side, hint))) {
side = IsAtSingularity(surf, s, t, PBC_SEAM_TOL);// 0 = south, 1 = east, 2 = north, 3 = west
if (side >= 0) {
ON_Interval u = surf->Domain(0);
ON_Interval v = surf->Domain(1);
if (side == 0) {
rc=surf->EvNormal(u.m_t[0], v.m_t[0], point, normal, side, hint);
} else if (side == 1) {
rc=surf->EvNormal(u.m_t[1], v.m_t[1], point, normal, side, hint);
} else if (side == 2) {
rc=surf->EvNormal(u.m_t[1], v.m_t[1], point, normal, side, hint);
} else if (side == 3) {
rc=surf->EvNormal(u.m_t[0], v.m_t[0], point, normal, side, hint);
}
}
}
return rc;
}
ON_BOOL32
surface_GetBoundingBox(
const ON_Surface *surf,
const ON_Interval &u_interval,
const ON_Interval &v_interval,
ON_BoundingBox& bbox,
ON_BOOL32 bGrowBox
)
{
/* TODO: Address for threading
* defined static for first time thru initialization, will
* have to do something else here for multiple threads
*/
static ON_RevSurface *rev_surface = ON_RevSurface::New();
static ON_NurbsSurface *nurbs_surface = ON_NurbsSurface::New();
static ON_Extrusion *extr_surface = new ON_Extrusion();
static ON_PlaneSurface *plane_surface = new ON_PlaneSurface();
static ON_SumSurface *sum_surface = ON_SumSurface::New();
static ON_SurfaceProxy *proxy_surface = new ON_SurfaceProxy();
ON_Interval domSplits[2][2] = { { ON_Interval::EmptyInterval, ON_Interval::EmptyInterval }, { ON_Interval::EmptyInterval, ON_Interval::EmptyInterval }};
if (!GetDomainSplits(surf,u_interval,v_interval,domSplits)) {
return false;
}
bool growcurrent = bGrowBox;
for (int i=0; i<2; i++) {
if (domSplits[0][i] == ON_Interval::EmptyInterval)
continue;
for (int j=0; j<2; j++) {
if (domSplits[1][j] != ON_Interval::EmptyInterval) {
if (dynamic_cast<ON_RevSurface * >(const_cast<ON_Surface *>(surf)) != NULL) {
*rev_surface = *dynamic_cast<ON_RevSurface * >(const_cast<ON_Surface *>(surf));
if (rev_surface->Trim(0, domSplits[0][i]) && rev_surface->Trim(1, domSplits[1][j])) {
if (!rev_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
growcurrent = true;
}
} else if (dynamic_cast<ON_NurbsSurface * >(const_cast<ON_Surface *>(surf)) != NULL) {
*nurbs_surface = *dynamic_cast<ON_NurbsSurface * >(const_cast<ON_Surface *>(surf));
if (nurbs_surface->Trim(0, domSplits[0][i]) && nurbs_surface->Trim(1, domSplits[1][j])) {
if (!nurbs_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
}
growcurrent = true;
} else if (dynamic_cast<ON_Extrusion * >(const_cast<ON_Surface *>(surf)) != NULL) {
*extr_surface = *dynamic_cast<ON_Extrusion * >(const_cast<ON_Surface *>(surf));
if (extr_surface->Trim(0, domSplits[0][i]) && extr_surface->Trim(1, domSplits[1][j])) {
if (!extr_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
}
growcurrent = true;
} else if (dynamic_cast<ON_PlaneSurface * >(const_cast<ON_Surface *>(surf)) != NULL) {
*plane_surface = *dynamic_cast<ON_PlaneSurface * >(const_cast<ON_Surface *>(surf));
if (plane_surface->Trim(0, domSplits[0][i]) && plane_surface->Trim(1, domSplits[1][j])) {
if (!plane_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
}
growcurrent = true;
} else if (dynamic_cast<ON_SumSurface * >(const_cast<ON_Surface *>(surf)) != NULL) {
*sum_surface = *dynamic_cast<ON_SumSurface * >(const_cast<ON_Surface *>(surf));
if (sum_surface->Trim(0, domSplits[0][i]) && sum_surface->Trim(1, domSplits[1][j])) {
if (!sum_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
}
growcurrent = true;
} else if (dynamic_cast<ON_SurfaceProxy * >(const_cast<ON_Surface *>(surf)) != NULL) {
*proxy_surface = *dynamic_cast<ON_SurfaceProxy * >(const_cast<ON_Surface *>(surf));
if (proxy_surface->Trim(0, domSplits[0][i]) && proxy_surface->Trim(1, domSplits[1][j])) {
if (!proxy_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
}
growcurrent = true;
} else {
std::cerr << "Unknown Surface Type" << std::endl;
}
}
}
}
return true;
}
ON_BOOL32
face_GetBoundingBox(
const ON_BrepFace &face,
ON_BoundingBox& bbox,
ON_BOOL32 bGrowBox
)
{
const ON_Surface *surf = face.SurfaceOf();
// may be a smaller trimmed subset of surface so worth getting
// face boundary
bool growcurrent = bGrowBox;
ON_3dPoint min, max;
for (int li = 0; li < face.LoopCount(); li++) {
for (int ti = 0; ti < face.Loop(li)->TrimCount(); ti++) {
ON_BrepTrim *trim = face.Loop(li)->Trim(ti);
trim->GetBoundingBox(min, max, growcurrent);
growcurrent = true;
}
}
ON_Interval u_interval(min.x, max.x);
ON_Interval v_interval(min.y, max.y);
if (!surface_GetBoundingBox(surf, u_interval,v_interval,bbox,growcurrent)) {
return false;
}
return true;
}
ON_BOOL32
surface_GetIntervalMinMaxDistance(
const ON_3dPoint& p,
ON_BoundingBox &bbox,
double &min_distance,
double &max_distance
)
{
min_distance = bbox.MinimumDistanceTo(p);
max_distance = bbox.MaximumDistanceTo(p);
return true;
}
ON_BOOL32
surface_GetIntervalMinMaxDistance(
const ON_Surface *surf,
const ON_3dPoint& p,
const ON_Interval &u_interval,
const ON_Interval &v_interval,
double &min_distance,
double &max_distance
)
{
ON_BoundingBox bbox;
if (surface_GetBoundingBox(surf,u_interval,v_interval,bbox, false)) {
min_distance = bbox.MinimumDistanceTo(p);
max_distance = bbox.MaximumDistanceTo(p);
return true;
}
return false;
}
double
surface_GetOptimalNormalUSplit(const ON_Surface *surf, const ON_Interval &u_interval, const ON_Interval &v_interval,double tol)
{
ON_3dVector normal[4];
double u = u_interval.Mid();
if ((normal[0] = surf->NormalAt(u_interval.m_t[0],v_interval.m_t[0])) &&
(normal[2] = surf->NormalAt(u_interval.m_t[0],v_interval.m_t[1]))) {
double step = u_interval.Length()/2.0;
double stepdir = 1.0;
u = u_interval.m_t[0] + stepdir * step;
while (step > tol) {
if ((normal[1] = surf->NormalAt(u,v_interval.m_t[0])) &&
(normal[3] = surf->NormalAt(u,v_interval.m_t[1]))) {
double udot_1 = normal[0] * normal[1];
double udot_2 = normal[2] * normal[3];
if ((udot_1 < 0.0) || (udot_2 < 0.0)) {
stepdir = -1.0;
} else {
stepdir = 1.0;
}
step = step / 2.0;
u = u + stepdir * step;
}
}
}
return u;
}
double
surface_GetOptimalNormalVSplit(const ON_Surface *surf, const ON_Interval &u_interval, const ON_Interval &v_interval,double tol)
{
ON_3dVector normal[4];
double v = v_interval.Mid();
if ((normal[0] = surf->NormalAt(u_interval.m_t[0],v_interval.m_t[0])) &&
(normal[1] = surf->NormalAt(u_interval.m_t[1],v_interval.m_t[0]))) {
double step = v_interval.Length()/2.0;
double stepdir = 1.0;
v = v_interval.m_t[0] + stepdir * step;
while (step > tol) {
if ((normal[2] = surf->NormalAt(u_interval.m_t[0],v)) &&
(normal[3] = surf->NormalAt(u_interval.m_t[1],v))) {
double vdot_1 = normal[0] * normal[2];
double vdot_2 = normal[1] * normal[3];
if ((vdot_1 < 0.0) || (vdot_2 < 0.0)) {
stepdir = -1.0;
} else {
stepdir = 1.0;
}
step = step / 2.0;
v = v + stepdir * step;
}
}
}
return v;
}
//forward for cyclic
double surface_GetClosestPoint3dFirstOrderByRange(const ON_Surface *surf,const ON_3dPoint& p,const ON_Interval& u_range,
const ON_Interval& v_range,double current_closest_dist,ON_2dPoint& p2d,ON_3dPoint& p3d,double same_point_tol, double within_distance_tol,int level);
double surface_GetClosestPoint3dFirstOrderSubdivision(const ON_Surface *surf,
const ON_3dPoint& p, const ON_Interval &u_interval, double u, const ON_Interval &v_interval, double v,
double current_closest_dist, ON_2dPoint& p2d, ON_3dPoint& p3d,
double same_point_tol, double within_distance_tol, int level)
{
double min_distance, max_distance;
ON_Interval new_u_interval = u_interval;
ON_Interval new_v_interval = v_interval;
for (int iu = 0; iu < 2; iu++) {
new_u_interval.m_t[iu] = u_interval.m_t[iu];
new_u_interval.m_t[1 - iu] = u;
for (int iv = 0; iv < 2; iv++) {
new_v_interval.m_t[iv] = v_interval.m_t[iv];
new_v_interval.m_t[1 - iv] = v;
if (surface_GetIntervalMinMaxDistance(surf, p, new_u_interval,new_v_interval, min_distance, max_distance)) {
double distance = DBL_MAX;
if ((min_distance < current_closest_dist) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
ON_3dVector normal[4];
if ((normal[0] = surf->NormalAt(new_u_interval.m_t[0],new_v_interval.m_t[0])) &&
(normal[1] = surf->NormalAt(new_u_interval.m_t[1],new_v_interval.m_t[0])) &&
(normal[2] = surf->NormalAt(new_u_interval.m_t[0],new_v_interval.m_t[1])) &&
(normal[3] = surf->NormalAt(new_u_interval.m_t[1],new_v_interval.m_t[1]))) {
double udot_1 = normal[0] * normal[1];
double udot_2 = normal[2] * normal[3];
double vdot_1 = normal[0] * normal[2];
double vdot_2 = normal[1] * normal[3];
if ((udot_1 < 0.0) || (udot_2 < 0.0) || (vdot_1 < 0.0) || (vdot_2 < 0.0)) {
double u_split,v_split;
if ((udot_1 < 0.0) || (udot_2 < 0.0)) {
//get optimal U split
u_split = surface_GetOptimalNormalUSplit(surf,new_u_interval,new_v_interval,same_point_tol);
} else {
u_split = new_u_interval.Mid();
}
if ((vdot_1 < 0.0) || (vdot_2 < 0.0)) {
//get optimal V split
v_split = surface_GetOptimalNormalVSplit(surf,new_u_interval,new_v_interval,same_point_tol);
} else {
v_split = new_v_interval.Mid();
}
distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,new_u_interval,u_split,new_v_interval,v_split,current_closest_dist,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_closest_dist) {
current_closest_dist = distance;
if (current_closest_dist < same_point_tol)
return current_closest_dist;
}
} else {
distance = surface_GetClosestPoint3dFirstOrderByRange(surf,p,new_u_interval,new_v_interval,current_closest_dist,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_closest_dist) {
current_closest_dist = distance;
if (current_closest_dist < same_point_tol)
return current_closest_dist;
}
}
}
}
}
}
}
return current_closest_dist;
}
double
surface_GetClosestPoint3dFirstOrderByRange(
const ON_Surface *surf,
const ON_3dPoint& p,
const ON_Interval& u_range,
const ON_Interval& v_range,
double current_closest_dist,
ON_2dPoint& p2d,
ON_3dPoint& p3d,
double same_point_tol,
double within_distance_tol,
int level
)
{
ON_3dPoint p0;
ON_2dPoint p2d0;
ON_3dVector ds, dt, dss, dst, dtt;
ON_2dPoint working_p2d;
ON_3dPoint working_p3d;
ON_3dPoint P;
ON_3dVector Ds, Dt, Dss, Dst, Dtt;
bool notdone = true;
double previous_distance = DBL_MAX;
double distance;
int errcnt = 0;
p2d0.x = u_range.Mid();
p2d0.y = v_range.Mid();
while (notdone && (surf->Ev2Der(p2d0.x, p2d0.y, p0, ds, dt, dss, dst, dtt))) {
if ((distance = p0.DistanceTo(p)) >= previous_distance) {
if (++errcnt <= 10) {
p2d0 = (p2d0 + working_p2d) / 2.0;
continue;
} else {
///////////////////////////
// Don't Subdivide just not getting any closer
///////////////////////////
/*
double distance =
surface_GetClosestPoint3dFirstOrderSubdivision(surf, p,
u_range, u_range.Mid(), v_range, v_range.Mid(),
current_closest_dist, p2d, p3d, tol, level++);
if (distance < current_closest_dist) {
current_closest_dist = distance;
if (current_closest_dist < tol)
return current_closest_dist;
}
*/
break;
}
} else {
if (distance < current_closest_dist) {
current_closest_dist = distance;
p3d = p0;
p2d = p2d0;
if (current_closest_dist < same_point_tol)
return current_closest_dist;
}
previous_distance = distance;
working_p3d = p0;
working_p2d = p2d0;
errcnt = 0;
}
ON_3dVector N = ON_CrossProduct(ds, dt);
N.Unitize();
ON_Plane plane(p0, N);
ON_3dPoint q = plane.ClosestPointTo(p);
ON_2dVector pullback;
ON_3dVector vector = q - p0;
double vlength = vector.Length();
if (vlength > 0.0) {
if (ON_Pullback3dVector(vector, 0.0, ds, dt, dss, dst, dtt,
pullback)) {
p2d0 = p2d0 + pullback;
if (!u_range.Includes(p2d0.x, false)) {
int i = (u_range.m_t[0] <= u_range.m_t[1]) ? 0 : 1;
p2d0.x =
(p2d0.x < u_range.m_t[i]) ?
u_range.m_t[i] : u_range.m_t[1 - i];
}
if (!v_range.Includes(p2d0.y, false)) {
int i = (v_range.m_t[0] <= v_range.m_t[1]) ? 0 : 1;
p2d0.y =
(p2d0.y < v_range.m_t[i]) ?
v_range.m_t[i] : v_range.m_t[1 - i];
}
} else {
///////////////////////////
// Subdivide and go again
///////////////////////////
notdone = false;
distance =
surface_GetClosestPoint3dFirstOrderSubdivision(surf, p,
u_range, u_range.Mid(), v_range, v_range.Mid(),
current_closest_dist, p2d, p3d, same_point_tol, within_distance_tol, level++);
if (distance < current_closest_dist) {
current_closest_dist = distance;
if (current_closest_dist < same_point_tol)
return current_closest_dist;
}
break;
}
} else {
// can't get any closer
notdone = false;
break;
}
}
if (previous_distance < current_closest_dist) {
current_closest_dist = previous_distance;
p3d = working_p3d;
p2d = working_p2d;
}
return current_closest_dist;
}
bool surface_GetClosestPoint3dFirstOrder(
const ON_Surface *surf,
const ON_3dPoint& p,
ON_2dPoint& p2d,
ON_3dPoint& p3d,
double ¤t_distance,
int quadrant, // optional - determines which quadrant to evaluate from
// 0 = default
// 1 from NE quadrant
// 2 from NW quadrant
// 3 from SW quadrant
// 4 from SE quadrant
double same_point_tol,
double within_distance_tol
)
{
ON_3dPoint p0;
ON_2dPoint p2d0;
ON_3dVector ds, dt, dss, dst, dtt;
ON_3dVector T, K;
bool rc = false;
static const ON_Surface *prev_surface = NULL;
static int prev_u_spancnt = 0;
static int u_spancnt = 0;
static int v_spancnt = 0;
static double *uspan = NULL;
static double *vspan = NULL;
static ON_BoundingBox **bbox = NULL;
static double umid = 0.0;
static int umid_index = 0;
static double vmid = 0.0;
static int vmid_index = 0;
current_distance = DBL_MAX;
int prec = std::cerr.precision();
std::cerr.precision(15);
if (prev_surface != surf) {
if (uspan)
delete [] uspan;
if (vspan)
delete [] vspan;
if (bbox) {
for( int i = 0 ; i < (prev_u_spancnt + 2) ; i++ )
delete [] bbox[i] ;
delete [] bbox;
}
u_spancnt = prev_u_spancnt = surf->SpanCount(0);
v_spancnt = surf->SpanCount(1);
// adding 2 here because going to divide at midpoint
uspan = new double[u_spancnt + 2];
vspan = new double[v_spancnt + 2];
bbox = new ON_BoundingBox *[(u_spancnt + 2)];
for( int i = 0 ; i < (u_spancnt + 2) ; i++ )
bbox[i] = new ON_BoundingBox [v_spancnt + 2];
if (surf->GetSpanVector(0, uspan) && surf->GetSpanVector(1, vspan)) {
prev_surface = surf;
umid = surf->Domain(0).Mid();
umid_index = u_spancnt/2;
for (int u_span_index = 0; u_span_index < u_spancnt + 1;u_span_index++) {
if (NEAR_EQUAL(uspan[u_span_index],umid,same_point_tol)) {
umid_index = u_span_index;
break;
} else if (uspan[u_span_index] > umid) {
for (u_span_index = u_spancnt + 1; u_span_index > 0;u_span_index--) {
if (uspan[u_span_index-1] < umid) {
uspan[u_span_index] = umid;
umid_index = u_span_index;
u_spancnt++;
u_span_index = u_spancnt+1;
break;
} else {
uspan[u_span_index] = uspan[u_span_index-1];
}
}
}
}
vmid = surf->Domain(1).Mid();
vmid_index = v_spancnt/2;
for (int v_span_index = 0; v_span_index < v_spancnt + 1;v_span_index++) {
if (NEAR_EQUAL(vspan[v_span_index],vmid,same_point_tol)) {
vmid_index = v_span_index;
break;
} else if (vspan[v_span_index] > vmid) {
for (v_span_index = v_spancnt + 1; v_span_index > 0;v_span_index--) {
if (vspan[v_span_index-1] < vmid) {
vspan[v_span_index] = vmid;
vmid_index = v_span_index;
v_spancnt++;
v_span_index = v_spancnt+1;
break;
} else {
vspan[v_span_index] = vspan[v_span_index-1];
}
}
}
}
for (int u_span_index = 1; u_span_index < u_spancnt + 1;
u_span_index++) {
for (int v_span_index = 1; v_span_index < v_spancnt + 1;
v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
if (!surface_GetBoundingBox(surf,u_interval,v_interval,bbox[u_span_index-1][v_span_index-1], false)) {
std::cerr << "Error computing bounding box for surface interval" << std::endl;
}
}
}
} else {
prev_surface = NULL;
}
}
if (prev_surface == surf) {
if (quadrant == 0) {
for (int u_span_index = 1; u_span_index < u_spancnt + 1;
u_span_index++) {
for (int v_span_index = 1; v_span_index < v_spancnt + 1;
v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
if (current_distance < within_distance_tol) {
rc = true;
goto cleanup;
}
} else if (quadrant == 1) {
if (surf->IsClosed(0)) { //NE,SE,NW.SW
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
} else { //NE,NW,SW,SE
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
}
if (current_distance < within_distance_tol) {
rc = true;
goto cleanup;
}
} else if (quadrant == 2) {
if (surf->IsClosed(0)) { // NW,SW,NE,SE
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
} else { // NW,NE,SW,SE
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
}
if (current_distance < within_distance_tol) {
rc = true;
goto cleanup;
}
} else if (quadrant == 3) {
if (surf->IsClosed(0)) { // SW,NW,SE,NE
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
} else { // SW,SE,NW,NE
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
}
if (current_distance < within_distance_tol) {
rc = true;
goto cleanup;
}
} else if (quadrant == 4) {
if (surf->IsClosed(0)) { // SE,NE,SW,NW
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
} else { // SE,SW,NE,NW
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
}
if (current_distance < within_distance_tol) {
rc = true;
goto cleanup;
}
}
}
cleanup:
std::cerr.precision(prec);
return rc;
}
bool trim_GetClosestPoint3dFirstOrder(
const ON_BrepTrim& trim,
const ON_3dPoint& p,
ON_2dPoint& p2d,
double& t,
double& distance,
const ON_Interval* interval,
double same_point_tol,
double within_distance_tol
)
{
bool rc = false;
const ON_Surface *surf = trim.SurfaceOf();
double t0 = interval->Mid();
ON_3dPoint p3d;
ON_3dPoint p0;
ON_3dVector ds,dt,dss,dst,dtt;
ON_3dVector T,K;
int prec = std::cerr.precision();
ON_BoundingBox tight_bbox;
std::vector<ON_BoundingBox> bbox;
std::cerr.precision(15);
ON_Curve *c = trim.Brep()->m_C2[trim.m_c2i];
ON_NurbsCurve N;
if ( 0 == c->GetNurbForm(N) )
return false;
if ( N.m_order < 2 || N.m_cv_count < N.m_order )
return false;
p2d = trim.PointAt(t);
int quadrant = 0; // optional - determines which quadrant to evaluate from
// 0 = default
// 1 from NE quadrant
// 2 from NW quadrant
// 3 from SW quadrant
// 4 from SE quadrant
ON_Interval u_interval = surf->Domain(0);
ON_Interval v_interval = surf->Domain(1);
if (p2d.y > v_interval.Mid()) {
// North quadrants -> 1 or 2;
if (p2d.x > u_interval.Mid()) {
quadrant = 1; // NE
} else {
quadrant = 2; //NW
}
} else {
// South quadrants -> 3 or 4;
if (p2d.x > u_interval.Mid()) {
quadrant = 4; // SE
} else {
quadrant = 3; //SW
}
}
if (surface_GetClosestPoint3dFirstOrder(surf,p,p2d,p3d,distance,quadrant,same_point_tol,within_distance_tol)) {
ON_BezierCurve B;
bool bGrowBox = false;
ON_3dVector d1,d2;
double max_dist_to_closest_pt = DBL_MAX;
ON_Interval *span_interval = new ON_Interval[N.m_cv_count - N.m_order + 1];
double *min_distance = new double[N.m_cv_count - N.m_order + 1];
double *max_distance = new double[N.m_cv_count - N.m_order + 1];
bool *skip = new bool[N.m_cv_count - N.m_order + 1];
bbox.resize(N.m_cv_count - N.m_order + 1);
for ( int span_index = 0; span_index <= N.m_cv_count - N.m_order; span_index++ )
{
skip[span_index] = true;
if ( !(N.m_knot[span_index + N.m_order-2] < N.m_knot[span_index + N.m_order-1]) )
continue;
// check for span out of interval
int i = (interval->m_t[0] <= interval->m_t[1]) ? 0 : 1;
if ( N.m_knot[span_index + N.m_order-2] > interval->m_t[1-i] )
continue;
if ( N.m_knot[span_index + N.m_order-1] < interval->m_t[i] )
continue;
if ( !N.ConvertSpanToBezier( span_index, B ) )
continue;
ON_Interval bi = B.Domain();
if ( !B.GetTightBoundingBox(tight_bbox,bGrowBox,NULL) )
continue;
bbox[span_index] = tight_bbox;
d1 = tight_bbox.m_min - p2d;
d2 = tight_bbox.m_max - p2d;
min_distance[span_index] = tight_bbox.MinimumDistanceTo(p2d);
if (min_distance[span_index] > max_dist_to_closest_pt) {
max_distance[span_index] = DBL_MAX;
continue;
}
skip[span_index] = false;
span_interval[span_index].m_t[0] = ((N.m_knot[span_index + N.m_order-2]) < interval->m_t[i]) ? interval->m_t[i] : N.m_knot[span_index + N.m_order-2];
span_interval[span_index].m_t[1] = ((N.m_knot[span_index + N.m_order-1]) > interval->m_t[1 -i]) ? interval->m_t[1 -i] : (N.m_knot[span_index + N.m_order-1]);
ON_3dPoint d1sq(d1.x*d1.x,d1.y*d1.y,0.0),d2sq(d2.x*d2.x,d2.y*d2.y,0.0);
double distancesq;
if (d1sq.x < d2sq.x) {
if (d1sq.y < d2sq.y) {
if ((d1sq.x + d2sq.y) < (d2sq.x + d1sq.y)) {
distancesq = d1sq.x + d2sq.y;
} else {
distancesq = d2sq.x + d1sq.y;
}
} else {
if ((d1sq.x + d1sq.y) < (d2sq.x + d2sq.y)) {
distancesq = d1sq.x + d1sq.y;
} else {
distancesq = d2sq.x + d2sq.y;
}
}
} else {
if (d1sq.y < d2sq.y) {
if ((d1sq.x + d1sq.y) < (d2sq.x + d2sq.y)) {
distancesq = d1sq.x + d1sq.y;
} else {
distancesq = d2sq.x + d2sq.y;
}
} else {
if ((d1sq.x + d2sq.y) < (d2sq.x + d1sq.y)) {
distancesq = d1sq.x + d2sq.y;
} else {
distancesq = d2sq.x + d1sq.y;
}
}
}
max_distance[span_index] = sqrt(distancesq);
if (max_distance[span_index] < max_dist_to_closest_pt) {
max_dist_to_closest_pt = max_distance[span_index];
}
if (max_distance[span_index] < min_distance[span_index]) {
// should only be here for near equal fuzz
min_distance[span_index] = max_distance[span_index];
}
}
for ( int span_index = 0; span_index <= N.m_cv_count - N.m_order; span_index++ )
{
if ( skip[span_index] )
continue;
if (min_distance[span_index] > max_dist_to_closest_pt) {
skip[span_index] = true;
continue;
}
}
ON_3dPoint q;
ON_3dPoint point;
double closest_distance = DBL_MAX;
double closestT = DBL_MAX;
for ( int span_index = 0; span_index <= N.m_cv_count - N.m_order; span_index++ )
{
if (skip[span_index]) {
continue;
}
t0 = span_interval[span_index].Mid();
bool closestfound = false;
bool notdone = true;
double distance = DBL_MAX;
double previous_distance = DBL_MAX;
ON_3dVector firstDervative, secondDervative;
while (notdone
&& trim.Ev2Der(t0, point, firstDervative, secondDervative)
&& ON_EvCurvature(firstDervative, secondDervative, T, K)) {
ON_Line line(point, point + 100.0 * T);
q = line.ClosestPointTo(p2d);
double delta_t = (firstDervative * (q - point))
/ (firstDervative * firstDervative);
double new_t0 = t0 + delta_t;
if (!span_interval[span_index].Includes(new_t0, false)) {
// limit to interval
int i = (span_interval[span_index].m_t[0] <= span_interval[span_index].m_t[1]) ? 0 : 1;
new_t0 =
(new_t0 < span_interval[span_index].m_t[i]) ?
span_interval[span_index].m_t[i] : span_interval[span_index].m_t[1 - i];
}
delta_t = new_t0 - t0;
t0 = new_t0;
point = trim.PointAt(t0);
distance = point.DistanceTo(p2d);
if (distance < previous_distance) {
closestfound = true;
closestT = t0;
previous_distance = distance;
if (fabs(delta_t) < same_point_tol) {
notdone = false;
}
} else {
notdone = false;
}
}
if (closestfound && (distance < closest_distance)) {
closest_distance = distance;
rc = true;
t = closestT;
}
}
delete [] span_interval;
delete [] min_distance;
delete [] max_distance;
delete [] skip;
}
std::cerr.precision(prec);
return rc;
}
bool
toUV(PBCData& data, ON_2dPoint& out_pt, double t, double knudge = 0.0)
{
ON_3dPoint pointOnCurve = data.curve->PointAt(t);
ON_3dPoint knudgedPointOnCurve = data.curve->PointAt(t + knudge);
ON_2dPoint uv;
if (data.surftree->getSurfacePoint((const ON_3dPoint&)pointOnCurve, uv, (const ON_3dPoint&)knudgedPointOnCurve, BREP_EDGE_MISS_TOLERANCE) > 0) {
out_pt.Set(uv.x, uv.y);
return true;
} else {
return false;
}
}
bool
toUV(brlcad::SurfaceTree *surftree, const ON_Curve *curve, ON_2dPoint& out_pt, double t, double knudge = 0.0)
{
if (!surftree)
return false;
const ON_Surface *surf = surftree->getSurface();
if (!surf)
return false;
ON_3dPoint pointOnCurve = curve->PointAt(t);
ON_3dPoint knudgedPointOnCurve = curve->PointAt(t + knudge);
ON_3dVector dt;
curve->Ev1Der(t, pointOnCurve, dt);
ON_3dVector tangent = curve->TangentAt(t);
//data.surf->GetClosestPoint(pointOnCurve, &a, &b, 0.0001);
ON_Ray r(pointOnCurve, tangent);
plane_ray pr;
brep_get_plane_ray(r, pr);
ON_3dVector p1;
double p1d;
ON_3dVector p2;
double p2d;
utah_ray_planes(r, p1, p1d, p2, p2d);
VMOVE(pr.n1, p1);
pr.d1 = p1d;
VMOVE(pr.n2, p2);
pr.d2 = p2d;
try {
pt2d_t uv;
ON_2dPoint uv2d = surftree->getClosestPointEstimate(knudgedPointOnCurve);
move(uv, uv2d);
ON_3dVector dir = surf->NormalAt(uv[0], uv[1]);
dir.Reverse();
ON_Ray ray(pointOnCurve, dir);
brep_get_plane_ray(ray, pr);
//know use this as guess to iterate to closer solution
pt2d_t Rcurr;
pt2d_t new_uv;
ON_3dPoint pt;
ON_3dVector su, sv;
#ifdef SHOW_UNUSED
bool found = false;
#endif
fastf_t Dlast = MAX_FASTF;
for (int i = 0; i < 10; i++) {
brep_r(surf, pr, uv, pt, su, sv, Rcurr);
fastf_t d = v2mag(Rcurr);
if (d < BREP_INTERSECTION_ROOT_EPSILON) {
TRACE1("R:" << ON_PRINT2(Rcurr));
#ifdef SHOW_UNUSED
found = true;
break;
#endif
} else if (d > Dlast) {
#ifdef SHOW_UNUSED
found = false; //break;
#endif
break;
//return brep_edge_check(found, sbv, face, surf, ray, hits);
}
brep_newton_iterate(pr, Rcurr, su, sv, uv, new_uv);
move(uv, new_uv);
Dlast = d;
}
///////////////////////////////////////
out_pt.Set(uv[0], uv[1]);
return true;
} catch (...) {
return false;
}
}
double
randomPointFromRange(PBCData& data, ON_2dPoint& out, double lo, double hi)
{
assert(lo < hi);
double random_pos = drand48() * (RANGE_HI - RANGE_LO) + RANGE_LO;
double newt = random_pos * (hi - lo) + lo;
assert(toUV(data, out, newt));
return newt;
}
bool
sample(PBCData& data,
double t1,
double t2,
const ON_2dPoint& p1,
const ON_2dPoint& p2)
{
ON_2dPoint m;
double t = randomPointFromRange(data, m, t1, t2);
if (!data.segments.empty()) {
ON_2dPointArray * samples = data.segments.back();
if (isFlat(p1, m, p2, data.flatness)) {
samples->Append(p2);
} else {
sample(data, t1, t, p1, m);
sample(data, t, t2, m, p2);
}
return true;
}
return false;
}
void
generateKnots(BSpline& bspline)
{
int num_knots = bspline.m + 1;
bspline.knots.resize(num_knots);
for (int i = 0; i <= bspline.p; i++) {
bspline.knots[i] = 0.0;
}
for (int i = bspline.m - bspline.p; i <= bspline.m; i++) {
bspline.knots[i] = 1.0;
}
for (int i = 1; i <= bspline.n - bspline.p; i++) {
bspline.knots[bspline.p + i] = (double)i / (bspline.n - bspline.p + 1.0);
}
}
int
getKnotInterval(BSpline& bspline, double u)
{
int k = 0;
while (u >= bspline.knots[k]) k++;
k = (k == 0) ? k : k - 1;
return k;
}
ON_NurbsCurve*
interpolateLocalCubicCurve(ON_2dPointArray &Q)
{
int num_samples = Q.Count();
int num_segments = Q.Count() - 1;
int qsize = num_samples + 4;
std::vector < ON_2dVector > qarray(qsize);
for (int i = 1; i < Q.Count(); i++) {
qarray[i + 1] = Q[i] - Q[i - 1];
}
qarray[1] = 2.0 * qarray[2] - qarray[3];
qarray[0] = 2.0 * qarray[1] - qarray[2];
qarray[num_samples + 1] = 2 * qarray[num_samples] - qarray[num_samples - 1];
qarray[num_samples + 2] = 2 * qarray[num_samples + 1] - qarray[num_samples];
qarray[num_samples + 3] = 2 * qarray[num_samples + 2] - qarray[num_samples + 1];
std::vector < ON_2dVector > T(num_samples);
std::vector<double> A(num_samples);
for (int k = 0; k < num_samples; k++) {
ON_3dVector a = ON_CrossProduct(qarray[k], qarray[k + 1]);
ON_3dVector b = ON_CrossProduct(qarray[k + 2], qarray[k + 3]);
double alength = a.Length();
if (NEAR_ZERO(alength, PBC_TOL)) {
A[k] = 1.0;
} else {
A[k] = (a.Length()) / (a.Length() + b.Length());
}
T[k] = (1.0 - A[k]) * qarray[k + 1] + A[k] * qarray[k + 2];
T[k].Unitize();
}
std::vector < ON_2dPointArray > P(num_samples - 1);
ON_2dPointArray control_points;
control_points.Append(Q[0]);
for (int i = 1; i < num_samples; i++) {
ON_2dPoint P0 = Q[i - 1];
ON_2dPoint P3 = Q[i];
ON_2dVector T0 = T[i - 1];
ON_2dVector T3 = T[i];
double a, b, c;
ON_2dVector vT0T3 = T0 + T3;
ON_2dVector dP0P3 = P3 - P0;
a = 16.0 - vT0T3.Length() * vT0T3.Length();
b = 12.0 * (dP0P3 * vT0T3);
c = -36.0 * dP0P3.Length() * dP0P3.Length();
double alpha = (-b + sqrt(b * b - 4.0 * a * c)) / (2.0 * a);
ON_2dPoint P1 = P0 + (1.0 / 3.0) * alpha * T0;
control_points.Append(P1);
ON_2dPoint P2 = P3 - (1.0 / 3.0) * alpha * T3;
control_points.Append(P2);
P[i - 1].Append(P0);
P[i - 1].Append(P1);
P[i - 1].Append(P2);
P[i - 1].Append(P3);
}
control_points.Append(Q[num_samples - 1]);
std::vector<double> u(num_segments + 1);
u[0] = 0.0;
for (int k = 0; k < num_segments; k++) {
u[k + 1] = u[k] + 3.0 * (P[k][1] - P[k][0]).Length();
}
int degree = 3;
int n = control_points.Count();
int p = degree;
int m = n + p - 1;
int dimension = 2;
ON_NurbsCurve* c = ON_NurbsCurve::New(dimension, false, degree + 1, n);
c->ReserveKnotCapacity(m);
for (int i = 0; i < degree; i++) {
c->SetKnot(i, 0.0);
}
for (int i = 1; i < num_segments; i++) {
double knot_value = u[i] / u[num_segments];
c->SetKnot(degree + 2 * (i - 1), knot_value);
c->SetKnot(degree + 2 * (i - 1) + 1, knot_value);
}
for (int i = m - p; i < m; i++) {
c->SetKnot(i, 1.0);
}
// insert the control points
for (int i = 0; i < n; i++) {
ON_3dPoint pnt = control_points[i];
c->SetCV(i, pnt);
}
return c;
}
ON_NurbsCurve*
interpolateLocalCubicCurve(const ON_3dPointArray &Q)
{
int num_samples = Q.Count();
int num_segments = Q.Count() - 1;
int qsize = num_samples + 3;
std::vector<ON_3dVector> qarray(qsize + 1);
ON_3dVector *q = &qarray[1];
for (int i = 1; i < Q.Count(); i++) {
q[i] = Q[i] - Q[i - 1];
}
q[0] = 2.0 * q[1] - q[2];
q[-1] = 2.0 * q[0] - q[1];
q[num_samples] = 2 * q[num_samples - 1] - q[num_samples - 2];
q[num_samples + 1] = 2 * q[num_samples] - q[num_samples - 1];
q[num_samples + 2] = 2 * q[num_samples + 1] - q[num_samples];
std::vector<ON_3dVector> T(num_samples);
std::vector<double> A(num_samples);
for (int k = 0; k < num_samples; k++) {
ON_3dVector avec = ON_CrossProduct(q[k - 1], q[k]);
ON_3dVector bvec = ON_CrossProduct(q[k + 1], q[k + 2]);
double alength = avec.Length();
if (NEAR_ZERO(alength, PBC_TOL)) {
A[k] = 1.0;
} else {
A[k] = (avec.Length()) / (avec.Length() + bvec.Length());
}
T[k] = (1.0 - A[k]) * q[k] + A[k] * q[k + 1];
T[k].Unitize();
}
std::vector<ON_3dPointArray> P(num_samples - 1);
ON_3dPointArray control_points;
control_points.Append(Q[0]);
for (int i = 1; i < num_samples; i++) {
ON_3dPoint P0 = Q[i - 1];
ON_3dPoint P3 = Q[i];
ON_3dVector T0 = T[i - 1];
ON_3dVector T3 = T[i];
double a, b, c;
ON_3dVector vT0T3 = T0 + T3;
ON_3dVector dP0P3 = P3 - P0;
a = 16.0 - vT0T3.Length() * vT0T3.Length();
b = 12.0 * (dP0P3 * vT0T3);
c = -36.0 * dP0P3.Length() * dP0P3.Length();
double alpha = (-b + sqrt(b * b - 4.0 * a * c)) / (2.0 * a);
ON_3dPoint P1 = P0 + (1.0 / 3.0) * alpha * T0;
control_points.Append(P1);
ON_3dPoint P2 = P3 - (1.0 / 3.0) * alpha * T3;
control_points.Append(P2);
P[i - 1].Append(P0);
P[i - 1].Append(P1);
P[i - 1].Append(P2);
P[i - 1].Append(P3);
}
control_points.Append(Q[num_samples - 1]);
std::vector<double> u(num_segments + 1);
u[0] = 0.0;
for (int k = 0; k < num_segments; k++) {
u[k + 1] = u[k] + 3.0 * (P[k][1] - P[k][0]).Length();
}
int degree = 3;
int n = control_points.Count();
int p = degree;
int m = n + p - 1;
int dimension = 3;
ON_NurbsCurve* c = ON_NurbsCurve::New(dimension, false, degree + 1, n);
c->ReserveKnotCapacity(m);
for (int i = 0; i < degree; i++) {
c->SetKnot(i, 0.0);
}
for (int i = 1; i < num_segments; i++) {
double knot_value = u[i] / u[num_segments];
c->SetKnot(degree + 2 * (i - 1), knot_value);
c->SetKnot(degree + 2 * (i - 1) + 1, knot_value);
}
for (int i = m - p; i < m; i++) {
c->SetKnot(i, 1.0);
}
// insert the control points
for (int i = 0; i < n; i++) {
ON_3dPoint pnt = control_points[i];
c->SetCV(i, pnt);
}
return c;
}
ON_NurbsCurve*
newNURBSCurve(BSpline& spline, int dimension = 3)
{
// we now have everything to complete our spline
ON_NurbsCurve* c = ON_NurbsCurve::New(dimension,
false,
spline.p + 1,
spline.n + 1);
c->ReserveKnotCapacity(spline.knots.size() - 2);
for (unsigned int i = 1; i < spline.knots.size() - 1; i++) {
c->m_knot[i - 1] = spline.knots[i];
}
for (int i = 0; i < spline.controls.Count(); i++) {
c->SetCV(i, ON_3dPoint(spline.controls[i]));
}
return c;
}
ON_Curve*
interpolateCurve(ON_2dPointArray &samples)
{
ON_NurbsCurve* nurbs;
if (samples.Count() == 2)
// build a line
return new ON_LineCurve(samples[0], samples[1]);
// local vs. global interpolation for large point sampled curves
nurbs = interpolateLocalCubicCurve(samples);
return nurbs;
}
int
IsAtSeam(const ON_Surface *surf, int dir, double u, double v, double tol)
{
int rc = 0;
if (!surf->IsClosed(dir))
return rc;
double p = (dir) ? v : u;
if (NEAR_EQUAL(p, surf->Domain(dir)[0], tol) || NEAR_EQUAL(p, surf->Domain(dir)[1], tol))
rc += (dir + 1);
return rc;
}
/*
* Similar to openNURBS's surf->IsAtSeam() function but uses tolerance to do a near check versus
* the floating point equality used by openNURBS.
* rc = 0 Not on seam, 1 on East/West seam(umin/umax), 2 on North/South seam(vmin/vmax), 3 seam on both U/V boundaries
*/
int
IsAtSeam(const ON_Surface *surf, double u, double v, double tol)
{
int rc = 0;
int i;
for (i = 0; i < 2; i++) {
rc += IsAtSeam(surf, i, u, v, tol);
}
return rc;
}
int
IsAtSeam(const ON_Surface *surf, int dir, const ON_2dPoint &pt, double tol)
{
int rc = 0;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol);
rc = IsAtSeam(surf,dir,unwrapped_pt.x,unwrapped_pt.y,tol);
return rc;
}
/*
* Similar to IsAtSeam(surf,u,v,tol) function but takes a ON_2dPoint
* and unwraps any closed seam extents before passing on IsAtSeam(surf,u,v,tol)
*/
int
IsAtSeam(const ON_Surface *surf, const ON_2dPoint &pt, double tol)
{
int rc = 0;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol);
rc = IsAtSeam(surf,unwrapped_pt.x,unwrapped_pt.y,tol);
return rc;
}
int
IsAtSingularity(const ON_Surface *surf, double u, double v, double tol)
{
// 0 = south, 1 = east, 2 = north, 3 = west
//std::cerr << "IsAtSingularity = u, v - " << u << ", " << v << std::endl;
//std::cerr << "surf->Domain(0) - " << surf->Domain(0)[0] << ", " << surf->Domain(0)[1] << std::endl;
//std::cerr << "surf->Domain(1) - " << surf->Domain(1)[0] << ", " << surf->Domain(1)[1] << std::endl;
if (NEAR_EQUAL(u, surf->Domain(0)[0], tol)) {
if (surf->IsSingular(3))
return 3;
} else if (NEAR_EQUAL(u, surf->Domain(0)[1], tol)) {
if (surf->IsSingular(1))
return 1;
}
if (NEAR_EQUAL(v, surf->Domain(1)[0], tol)) {
if (surf->IsSingular(0))
return 0;
} else if (NEAR_EQUAL(v, surf->Domain(1)[1], tol)) {
if (surf->IsSingular(2))
return 2;
}
return -1;
}
int
IsAtSingularity(const ON_Surface *surf, const ON_2dPoint &pt, double tol)
{
int rc = 0;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol);
rc = IsAtSingularity(surf,unwrapped_pt.x,unwrapped_pt.y,tol);
return rc;
}
ON_2dPointArray *
pullback_samples(PBCData* data,
double t,
double s)
{
if (!data)
return NULL;
const ON_Curve* curve = data->curve;
const ON_Surface* surf = data->surf;
ON_2dPointArray *samples = new ON_2dPointArray();
int numKnots = curve->SpanCount();
double *knots = new double[numKnots + 1];
curve->GetSpanVector(knots);
int istart = 0;
while (t >= knots[istart])
istart++;
if (istart > 0) {
istart--;
knots[istart] = t;
}
int istop = numKnots;
while (s <= knots[istop])
istop--;
if (istop < numKnots) {
istop++;
knots[istop] = s;
}
int samplesperknotinterval;
int degree = curve->Degree();
if (degree > 1) {
samplesperknotinterval = 3 * degree;
} else {
samplesperknotinterval = 18 * degree;
}
ON_2dPoint pt;
ON_3dPoint p = ON_3dPoint::UnsetPoint;
ON_3dPoint p3d = ON_3dPoint::UnsetPoint;
double distance;
for (int i = istart; i <= istop; i++) {
if (i <= numKnots / 2) {
if (i > 0) {
double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval;
for (int j = 1; j < samplesperknotinterval; j++) {
p = curve->PointAt(knots[i - 1] + j * delta);
p3d = ON_3dPoint::UnsetPoint;
if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
samples->Append(pt);
}
}
}
p = curve->PointAt(knots[i]);
p3d = ON_3dPoint::UnsetPoint;
if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
samples->Append(pt);
}
} else {
if (i > 0) {
double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval;
for (int j = 1; j < samplesperknotinterval; j++) {
p = curve->PointAt(knots[i - 1] + j * delta);
p3d = ON_3dPoint::UnsetPoint;
if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
samples->Append(pt);
}
}
p = curve->PointAt(knots[i]);
p3d = ON_3dPoint::UnsetPoint;
if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
samples->Append(pt);
}
}
}
}
delete[] knots;
return samples;
}
/*
* Unwrap 2D UV point values to within actual surface UV. Points often wrap around the closed seam.
*/
ON_2dPoint
UnwrapUVPoint(const ON_Surface *surf,const ON_2dPoint &pt, double tol)
{
ON_2dPoint p = pt;
for (int i=0; i<2; i++) {
if (!surf->IsClosed(i))
continue;
while (p[i] < surf->Domain(i).m_t[0] - tol) {
double length = surf->Domain(i).Length();
if (i<=0) {
p.x = p.x + length;
} else {
p.y = p.y + length;
}
}
while (p[i] >= surf->Domain(i).m_t[1] + tol) {
double length = surf->Domain(i).Length();
if (i<=0) {
p.x = p.x - length;
} else {
p.y = p.y - length;
}
}
}
return p;
}
double
DistToNearestClosedSeam(const ON_Surface *surf,const ON_2dPoint &pt)
{
double dist = -1.0;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt);
for (int i=0; i<2; i++) {
if (!surf->IsClosed(i))
continue;
dist = fabs(unwrapped_pt[i] - surf->Domain(i)[0]);
V_MIN(dist,fabs(surf->Domain(i)[1]-unwrapped_pt[i]));
}
return dist;
}
void
GetClosestExtendedPoint(const ON_Surface *surf,ON_2dPoint &pt,ON_2dPoint &prev_pt, double tol) {
if (surf->IsClosed(0)) {
double length = surf->Domain(0).Length();
double delta=pt.x-prev_pt.x;
while (fabs(delta) > length/2.0) {
if (delta > length/2.0) {
pt.x = pt.x - length;
delta=pt.x-prev_pt.x;
} else {
pt.x = pt.x + length;
delta=pt.x - prev_pt.x;
}
}
}
if (surf->IsClosed(1)) {
double length = surf->Domain(1).Length();
double delta=pt.y-prev_pt.y;
while (fabs(delta) > length/2.0) {
if (delta > length/2.0) {
pt.y = pt.y - length;
delta=pt.y - prev_pt.y;
} else {
pt.y = pt.y + length;
delta=pt.y -prev_pt.y;
}
}
}
}
/*
* Simple check to determine if two consecutive points pulled back from 3d curve sampling
* to 2d UV parameter space crosses the seam of the closed UV. The assumption here is that
* the sampling of the 3d curve is a small fraction of the UV domain.
*
* // dir - 0 = not crossing, 1 = south/east bound, 2 = north/west bound
*/
bool
ConsecutivePointsCrossClosedSeam(const ON_Surface *surf,const ON_2dPoint &pt,const ON_2dPoint &prev_pt, int &udir, int &vdir, double tol)
{
bool rc = false;
/*
* if one of the points is at a seam then not crossing
*/
int dir =0;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt);
ON_2dPoint unwrapped_prev_pt = UnwrapUVPoint(surf,prev_pt);
if (!IsAtSeam(surf,dir,pt,tol) && !IsAtSeam(surf,dir,prev_pt,tol)) {
udir = vdir = 0;
if (surf->IsClosed(0)) {
double delta=unwrapped_pt.x-unwrapped_prev_pt.x;
if (fabs(delta) > surf->Domain(0).Length()/2.0) {
if (delta < 0.0) {
udir = 1; // east bound
} else {
udir= 2; // west bound
}
rc = true;
}
}
}
dir = 1;
if (!IsAtSeam(surf,dir,pt,tol) && !IsAtSeam(surf,dir,prev_pt,tol)) {
if (surf->IsClosed(1)) {
double delta=unwrapped_pt.y-unwrapped_prev_pt.y;
if (fabs(delta) > surf->Domain(1).Length()/2.0) {
if (delta < 0.0) {
vdir = 2; // north bound
} else {
vdir= 1; // south bound
}
rc = true;
}
}
}
return rc;
}
/*
* If within UV tolerance to a seam force force to actually seam value so surface
* seam function can be used.
*/
void
ForceToClosestSeam(const ON_Surface *surf, ON_2dPoint &pt, double tol)
{
int seam;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol);
ON_2dVector wrap = ON_2dVector::ZeroVector;
ON_Interval dom[2] = { ON_Interval::EmptyInterval, ON_Interval::EmptyInterval };
double length[2] = { ON_UNSET_VALUE, ON_UNSET_VALUE};
for (int i=0; i<2; i++) {
dom[i] = surf->Domain(i);
length[i] = dom[i].Length();
if (!surf->IsClosed(i))
continue;
if (pt[i] > (dom[i].m_t[1] + tol)) {
ON_2dPoint p = pt;
while (p[i] > (dom[i].m_t[1] + tol)) {
p[i] -= length[i];
wrap[i] += 1.0;
}
} else if (pt[i] < (dom[i].m_t[0] - tol)) {
ON_2dPoint p = pt;
while (p[i] < (dom[i].m_t[0] - tol)) {
p[i] += length[i];
wrap[i] -= 1.0;
}
}
wrap[i] = wrap[i] * length[i];
}
if ((seam=IsAtSeam(surf, unwrapped_pt, tol)) > 0) {
if (seam == 1) { // east/west seam
if (fabs(unwrapped_pt.x - dom[0].m_t[0]) < length[0]/2.0) {
unwrapped_pt.x = dom[0].m_t[0]; // on east swap to west seam
} else {
unwrapped_pt.x = dom[0].m_t[1]; // on west swap to east seam
}
} else if (seam == 2) { // north/south seam
if (fabs(unwrapped_pt.y - dom[1].m_t[0]) < length[1]/2.0) {
unwrapped_pt.y = dom[1].m_t[0]; // on north swap to south seam
} else {
unwrapped_pt.y = dom[1].m_t[1]; // on south swap to north seam
}
} else { //on both seams
if (fabs(unwrapped_pt.x - dom[0].m_t[0]) < length[0]/2.0) {
unwrapped_pt.x = dom[0].m_t[0]; // on east swap to west seam
} else {
unwrapped_pt.x = dom[0].m_t[1]; // on west swap to east seam
}
if (fabs(pt.y - dom[1].m_t[0]) < length[1]/2.0) {
unwrapped_pt.y = dom[1].m_t[0]; // on north swap to south seam
} else {
unwrapped_pt.y = dom[1].m_t[1]; // on south swap to north seam
}
}
}
pt = unwrapped_pt + wrap;
}
/*
* If point lies on a seam(s) swap to opposite side of UV.
* hint = 1 swap E/W, 2 swap N/S or default 3 swap both
*/
void
SwapUVSeamPoint(const ON_Surface *surf, ON_2dPoint &p, int hint)
{
int seam;
ON_Interval dom[2];
dom[0] = surf->Domain(0);
dom[1] = surf->Domain(1);
if ((seam=surf->IsAtSeam(p.x,p.y)) > 0) {
if (seam == 1) { // east/west seam
if (fabs(p.x - dom[0].m_t[0]) > dom[0].Length()/2.0) {
p.x = dom[0].m_t[0]; // on east swap to west seam
} else {
p.x = dom[0].m_t[1]; // on west swap to east seam
}
} else if (seam == 2) { // north/south seam
if (fabs(p.y - dom[1].m_t[0]) > dom[1].Length()/2.0) {
p.y = dom[1].m_t[0]; // on north swap to south seam
} else {
p.y = dom[1].m_t[1]; // on south swap to north seam
}
} else { //on both seams check hint 1=east/west only, 2=north/south, 3 = both
if (hint == 1) {
if (fabs(p.x - dom[0].m_t[0]) > dom[0].Length()/2.0) {
p.x = dom[0].m_t[0]; // on east swap to west seam
} else {
p.x = dom[0].m_t[1]; // on west swap to east seam
}
} else if (hint == 2) {
if (fabs(p.y - dom[1].m_t[0]) > dom[1].Length()/2.0) {
p.y = dom[1].m_t[0]; // on north swap to south seam
} else {
p.y = dom[1].m_t[1]; // on south swap to north seam
}
} else {
if (fabs(p.x - dom[0].m_t[0]) > dom[0].Length()/2.0) {
p.x = dom[0].m_t[0]; // on east swap to west seam
} else {
p.x = dom[0].m_t[1]; // on west swap to east seam
}
if (fabs(p.y - dom[1].m_t[0]) > dom[1].Length()/2.0) {
p.y = dom[1].m_t[0]; // on north swap to south seam
} else {
p.y = dom[1].m_t[1]; // on south swap to north seam
}
}
}
}
}
/*
* Find where Pullback of 3d curve crosses closed seam of surface UV
*/
bool
Find3DCurveSeamCrossing(PBCData &data,double t0,double t1, double offset,double &seam_t,ON_2dPoint &from,ON_2dPoint &to,double tol)
{
bool rc = true;
const ON_Surface *surf = data.surf;
// quick bail out is surface not closed
if (surf->IsClosed(0) || surf->IsClosed(1)) {
ON_2dPoint p0_2d = ON_2dPoint::UnsetPoint;
ON_2dPoint p1_2d = ON_2dPoint::UnsetPoint;
ON_3dPoint p0_3d = data.curve->PointAt(t0);
ON_3dPoint p1_3d = data.curve->PointAt(t1);
ON_Interval dom[2];
double p0_distance;
double p1_distance;
dom[0] = surf->Domain(0);
dom[1] = surf->Domain(1);
ON_3dPoint check_pt_3d = ON_3dPoint::UnsetPoint;
int udir=0;
int vdir=0;
if (surface_GetClosestPoint3dFirstOrder(surf,p0_3d,p0_2d,check_pt_3d,p0_distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE) &&
surface_GetClosestPoint3dFirstOrder(surf,p1_3d,p1_2d,check_pt_3d,p1_distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE) ) {
if (ConsecutivePointsCrossClosedSeam(surf,p0_2d,p1_2d,udir,vdir,tol)) {
ON_2dPoint p_2d;
//lets check to see if p0 || p1 are already on a seam
int seam0=0;
if ((seam0 = IsAtSeam(surf,p0_2d, tol)) > 0) {
ForceToClosestSeam(surf, p0_2d, tol);
}
int seam1 = 0;
if ((seam1 = IsAtSeam(surf,p1_2d, tol)) > 0) {
ForceToClosestSeam(surf, p1_2d, tol);
}
if (seam0 > 0 ) {
if (seam1 > 0) { // both p0 & p1 on seam shouldn't happen report error and return false
rc = false;
} else { // just p0 on seam
from = to = p0_2d;
seam_t = t0;
SwapUVSeamPoint(surf, to);
}
} else if (seam1 > 0) { // only p1 on seam
from = to = p1_2d;
seam_t = t1;
SwapUVSeamPoint(surf, from);
} else { // crosses the seam somewhere in between the two points
bool seam_not_found = true;
while(seam_not_found) {
double d0 = DistToNearestClosedSeam(surf,p0_2d);
double d1 = DistToNearestClosedSeam(surf,p1_2d);
if ((d0 > 0.0) && (d1 > 0.0)) {
double t = t0 + (t1 - t0)*(d0/(d0+d1));
int seam;
ON_3dPoint p_3d = data.curve->PointAt(t);
double distance;
if (surface_GetClosestPoint3dFirstOrder(surf,p_3d,p_2d,check_pt_3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
if ((seam=IsAtSeam(surf,p_2d, tol)) > 0) {
ForceToClosestSeam(surf, p_2d, tol);
from = to = p_2d;
seam_t = t;
if (p0_2d.DistanceTo(p_2d) < p1_2d.DistanceTo(p_2d)) {
SwapUVSeamPoint(surf, to);
} else {
SwapUVSeamPoint(surf, from);
}
seam_not_found=false;
rc = true;
} else {
if (ConsecutivePointsCrossClosedSeam(surf,p0_2d,p_2d,udir,vdir,tol)) {
p1_2d = p_2d;
t1 = t;
} else if (ConsecutivePointsCrossClosedSeam(surf,p_2d,p1_2d,udir,vdir,tol)) {
p0_2d = p_2d;
t0=t;
} else {
seam_not_found=false;
rc = false;
}
}
} else {
seam_not_found=false;
rc = false;
}
} else {
seam_not_found=false;
rc = false;
}
}
}
}
}
}
return rc;
}
/*
* Find where 2D trim curve crosses closed seam of surface UV
*/
bool
FindTrimSeamCrossing(const ON_BrepTrim &trim,double t0,double t1,double &seam_t,ON_2dPoint &from,ON_2dPoint &to,double tol)
{
bool rc = true;
const ON_Surface *surf = trim.SurfaceOf();
// quick bail out is surface not closed
if (surf->IsClosed(0) || surf->IsClosed(1)) {
ON_2dPoint p0 = trim.PointAt(t0);
ON_2dPoint p1 = trim.PointAt(t1);
ON_Interval dom[2];
dom[0] = surf->Domain(0);
dom[1] = surf->Domain(1);
p0 = UnwrapUVPoint(surf,p0);
p1 = UnwrapUVPoint(surf,p1);
int udir=0;
int vdir=0;
if (ConsecutivePointsCrossClosedSeam(surf,p0,p1,udir,vdir,tol)) {
ON_2dPoint p;
//lets check to see if p0 || p1 are already on a seam
int seam0=0;
if ((seam0 = IsAtSeam(surf,p0, tol)) > 0) {
ForceToClosestSeam(surf, p0, tol);
}
int seam1 = 0;
if ((seam1 = IsAtSeam(surf,p1, tol)) > 0) {
ForceToClosestSeam(surf, p1, tol);
}
if (seam0 > 0 ) {
if (seam1 > 0) { // both p0 & p1 on seam shouldn't happen report error and return false
rc = false;
} else { // just p0 on seam
from = to = p0;
seam_t = t0;
SwapUVSeamPoint(surf, to);
}
} else if (seam1 > 0) { // only p1 on seam
from = to = p1;
seam_t = t1;
SwapUVSeamPoint(surf, from);
} else { // crosses the seam somewhere in between the two points
bool seam_not_found = true;
while (seam_not_found) {
double d0 = DistToNearestClosedSeam(surf,p0);
double d1 = DistToNearestClosedSeam(surf,p1);
if ((d0 > tol) && (d1 > tol)) {
double t = t0 + (t1 - t0)*(d0/(d0+d1));
int seam;
p = trim.PointAt(t);
if ((seam=IsAtSeam(surf,p, tol)) > 0) {
ForceToClosestSeam(surf, p, tol);
from = to = p;
seam_t = t;
if (p0.DistanceTo(p) < p1.DistanceTo(p)) {
SwapUVSeamPoint(surf, to);
} else {
SwapUVSeamPoint(surf, from);
}
seam_not_found=false;
rc = true;
} else {
if (ConsecutivePointsCrossClosedSeam(surf,p0,p,udir,vdir,tol)) {
p1 = p;
t1 = t;
} else if (ConsecutivePointsCrossClosedSeam(surf,p,p1,udir,vdir,tol)) {
p0 = p;
t0=t;
} else {
seam_not_found=false;
rc = false;
}
}
} else {
seam_not_found=false;
rc = false;
}
}
}
}
}
return rc;
}
void
pullback_samples_from_closed_surface(PBCData* data,
double t,
double s)
{
if (!data)
return;
if (!data->surf || !data->curve)
return;
const ON_Curve* curve= data->curve;
const ON_Surface *surf = data->surf;
ON_2dPointArray *samples= new ON_2dPointArray();
size_t numKnots = curve->SpanCount();
double *knots = new double[numKnots+1];
curve->GetSpanVector(knots);
size_t istart = 0;
while ((istart < (numKnots+1)) && (t >= knots[istart]))
istart++;
if (istart > 0) {
knots[--istart] = t;
}
size_t istop = numKnots;
while ((istop > 0) && (s <= knots[istop]))
istop--;
if (istop < numKnots) {
knots[++istop] = s;
}
size_t degree = curve->Degree();
size_t samplesperknotinterval=18*degree;
ON_2dPoint pt;
ON_2dPoint prev_pt;
double prev_t = knots[istart];
double offset = 0.0;
double delta;
for (size_t i=istart; i<istop; i++) {
delta = (knots[i+1] - knots[i])/(double)samplesperknotinterval;
if (i <= numKnots/2) {
offset = PBC_FROM_OFFSET;
} else {
offset = -PBC_FROM_OFFSET;
}
for (size_t j=0; j<=samplesperknotinterval; j++) {
if ((j == samplesperknotinterval) && (i < istop - 1))
continue;
double curr_t = knots[i]+j*delta;
if (curr_t < (s-t)/2.0) {
offset = PBC_FROM_OFFSET;
} else {
offset = -PBC_FROM_OFFSET;
}
ON_3dPoint p = curve->PointAt(curr_t);
ON_3dPoint p3d = ON_3dPoint::UnsetPoint;
double distance;
if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
if (IsAtSeam(surf,pt,PBC_SEAM_TOL) > 0) {
ForceToClosestSeam(surf, pt, PBC_SEAM_TOL);
}
if ((i == istart) && (j == 0)) {
// first point just append and set reference in prev_pt
samples->Append(pt);
prev_pt = pt;
prev_t = curr_t;
continue;
}
int udir= 0;
int vdir= 0;
if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) {
int pt_seam = surf->IsAtSeam(pt.x,pt.y);
int prev_pt_seam = surf->IsAtSeam(prev_pt.x,prev_pt.y);
if ( pt_seam > 0) {
if ((prev_pt_seam > 0) && (samples->Count() == 1)) {
samples->Empty();
SwapUVSeamPoint(surf, prev_pt,pt_seam);
samples->Append(prev_pt);
} else {
if (pt_seam == 3) {
if (prev_pt_seam == 1) {
pt.x = prev_pt.x;
if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) {
SwapUVSeamPoint(surf, pt, 2);
}
} else if (prev_pt_seam == 2) {
pt.y = prev_pt.y;
if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) {
SwapUVSeamPoint(surf, pt, 1);
}
}
} else {
SwapUVSeamPoint(surf, pt, prev_pt_seam);
}
}
} else if (prev_pt_seam > 0) {
if (samples->Count() == 1) {
samples->Empty();
SwapUVSeamPoint(surf, prev_pt);
samples->Append(prev_pt);
}
} else if (data->curve->IsClosed()) {
ON_2dPoint from,to;
double seam_t;
if (Find3DCurveSeamCrossing(*data,prev_t,curr_t,offset,seam_t,from,to,PBC_TOL)) {
samples->Append(from);
data->segments.push_back(samples);
samples= new ON_2dPointArray();
samples->Append(to);
prev_pt = to;
prev_t = seam_t;
} else {
std::cout << "Can not find seam crossing...." << std::endl;
}
}
}
samples->Append(pt);
prev_pt = pt;
prev_t = curr_t;
}
}
}
delete [] knots;
if (samples != NULL) {
data->segments.push_back(samples);
int numsegs = data->segments.size();
if (numsegs > 1) {
if (curve->IsClosed()) {
ON_2dPointArray *reordered_samples= new ON_2dPointArray();
// must have walked over seam but have closed curve so reorder stitching
int seg = 0;
for (std::list<ON_2dPointArray *>::reverse_iterator rit=data->segments.rbegin(); rit!=data->segments.rend(); ++seg) {
samples = *rit;
if (seg < numsegs-1) { // since end points should be repeated
reordered_samples->Append(samples->Count()-1,(const ON_2dPoint *)samples->Array());
} else {
reordered_samples->Append(samples->Count(),(const ON_2dPoint *)samples->Array());
}
data->segments.erase((++rit).base());
rit = data->segments.rbegin();
delete samples;
}
data->segments.clear();
data->segments.push_back(reordered_samples);
} else {
//punt for now
}
}
}
return;
}
PBCData *
pullback_samples(const ON_Surface* surf,
const ON_Curve* curve,
double tolerance,
double flatness)
{
if (!surf)
return NULL;
PBCData *data = new PBCData;
data->tolerance = tolerance;
data->flatness = flatness;
data->curve = curve;
data->surf = surf;
data->surftree = NULL;
double tmin, tmax;
data->curve->GetDomain(&tmin, &tmax);
if (surf->IsClosed(0) || surf->IsClosed(1)) {
if ((tmin < 0.0) && (tmax > 0.0)) {
ON_2dPoint uv = ON_2dPoint::UnsetPoint;
ON_3dPoint p = curve->PointAt(0.0);
ON_3dPoint p3d = ON_3dPoint::UnsetPoint;
double distance;
int quadrant = 0; // optional - 0 = default, 1 from NE quadrant, 2 from NW quadrant, 3 from SW quadrant, 4 from SE quadrant
if (surface_GetClosestPoint3dFirstOrder(surf,p,uv,p3d,distance,quadrant,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
if (IsAtSeam(surf, uv, PBC_SEAM_TOL) > 0) {
ON_2dPointArray *samples1 = pullback_samples(data, tmin, 0.0);
ON_2dPointArray *samples2 = pullback_samples(data, 0.0, tmax);
if (samples1 != NULL) {
data->segments.push_back(samples1);
}
if (samples2 != NULL) {
data->segments.push_back(samples2);
}
} else {
ON_2dPointArray *samples = pullback_samples(data, tmin, tmax);
if (samples != NULL) {
data->segments.push_back(samples);
}
}
} else {
std::cerr << "pullback_samples:Error: cannot evaluate curve at parameter 0.0" << std::endl;
delete data;
return NULL;
}
} else {
pullback_samples_from_closed_surface(data, tmin, tmax);
}
} else {
ON_2dPointArray *samples = pullback_samples(data, tmin, tmax);
if (samples != NULL) {
data->segments.push_back(samples);
}
}
return data;
}
ON_Curve*
refit_edge(const ON_BrepEdge* edge, double UNUSED(tolerance))
{
double edge_tolerance = 0.01;
ON_Brep *brep = edge->Brep();
#ifdef SHOW_UNUSED
ON_3dPoint start = edge->PointAtStart();
ON_3dPoint end = edge->PointAtEnd();
#endif
ON_BrepTrim& trim1 = brep->m_T[edge->m_ti[0]];
ON_BrepTrim& trim2 = brep->m_T[edge->m_ti[1]];
ON_BrepFace *face1 = trim1.Face();
ON_BrepFace *face2 = trim2.Face();
const ON_Surface *surface1 = face1->SurfaceOf();
const ON_Surface *surface2 = face2->SurfaceOf();
bool removeTrimmed = false;
brlcad::SurfaceTree *st1 = new brlcad::SurfaceTree(face1, removeTrimmed);
brlcad::SurfaceTree *st2 = new brlcad::SurfaceTree(face2, removeTrimmed);
ON_Curve *curve = brep->m_C3[edge->m_c3i];
double t0, t1;
curve->GetDomain(&t0, &t1);
ON_Plane plane;
curve->FrameAt(t0, plane);
#ifdef SHOW_UNUSED
ON_3dPoint origin = plane.Origin();
ON_3dVector xaxis = plane.Xaxis();
ON_3dVector yaxis = plane.Yaxis();
ON_3dVector zaxis = plane.zaxis;
ON_3dPoint px = origin + xaxis;
ON_3dPoint py = origin + yaxis;
ON_3dPoint pz = origin + zaxis;
#endif
int numKnots = curve->SpanCount();
double *knots = new double[numKnots + 1];
curve->GetSpanVector(knots);
int samplesperknotinterval;
int degree = curve->Degree();
if (degree > 1) {
samplesperknotinterval = 3 * degree;
} else {
samplesperknotinterval = 18 * degree;
}
ON_2dPoint pt;
double t = 0.0;
ON_3dPoint pointOnCurve;
ON_3dPoint knudgedPointOnCurve;
for (int i = 0; i <= numKnots; i++) {
if (i <= numKnots / 2) {
if (i > 0) {
double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval;
for (int j = 1; j < samplesperknotinterval; j++) {
t = knots[i - 1] + j * delta;
pointOnCurve = curve->PointAt(t);
knudgedPointOnCurve = curve->PointAt(t + PBC_TOL);
ON_3dPoint point = pointOnCurve;
ON_3dPoint knudgepoint = knudgedPointOnCurve;
ON_3dPoint ps1;
ON_3dPoint ps2;
bool found = false;
double dist;
while (!found) {
ON_2dPoint uv;
if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps1 = surface1->PointAt(uv.x, uv.y);
if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps2 = surface2->PointAt(uv.x, uv.y);
}
}
dist = ps1.DistanceTo(ps2);
if (NEAR_ZERO(dist, PBC_TOL)) {
point = ps1;
found = true;
} else {
ON_3dVector v1 = ps1 - point;
ON_3dVector v2 = ps2 - point;
knudgepoint = point;
ON_3dVector deltav = v1 + v2;
if (NEAR_ZERO(deltav.Length(), PBC_TOL)) {
found = true; // as close as we are going to get
} else {
point = point + v1 + v2;
}
}
}
}
}
t = knots[i];
pointOnCurve = curve->PointAt(t);
knudgedPointOnCurve = curve->PointAt(t + PBC_TOL);
ON_3dPoint point = pointOnCurve;
ON_3dPoint knudgepoint = knudgedPointOnCurve;
ON_3dPoint ps1;
ON_3dPoint ps2;
bool found = false;
double dist;
while (!found) {
ON_2dPoint uv;
if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps1 = surface1->PointAt(uv.x, uv.y);
if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps2 = surface2->PointAt(uv.x, uv.y);
}
}
dist = ps1.DistanceTo(ps2);
if (NEAR_ZERO(dist, PBC_TOL)) {
point = ps1;
found = true;
} else {
ON_3dVector v1 = ps1 - point;
ON_3dVector v2 = ps2 - point;
knudgepoint = point;
ON_3dVector deltav = v1 + v2;
if (NEAR_ZERO(deltav.Length(), PBC_TOL)) {
found = true; // as close as we are going to get
} else {
point = point + v1 + v2;
}
}
}
} else {
if (i > 0) {
double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval;
for (int j = 1; j < samplesperknotinterval; j++) {
t = knots[i - 1] + j * delta;
pointOnCurve = curve->PointAt(t);
knudgedPointOnCurve = curve->PointAt(t - PBC_TOL);
ON_3dPoint point = pointOnCurve;
ON_3dPoint knudgepoint = knudgedPointOnCurve;
ON_3dPoint ps1;
ON_3dPoint ps2;
bool found = false;
double dist;
while (!found) {
ON_2dPoint uv;
if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps1 = surface1->PointAt(uv.x, uv.y);
if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps2 = surface2->PointAt(uv.x, uv.y);
}
}
dist = ps1.DistanceTo(ps2);
if (NEAR_ZERO(dist, PBC_TOL)) {
point = ps1;
found = true;
} else {
ON_3dVector v1 = ps1 - point;
ON_3dVector v2 = ps2 - point;
knudgepoint = point;
ON_3dVector deltav = v1 + v2;
if (NEAR_ZERO(deltav.Length(), PBC_TOL)) {
found = true; // as close as we are going to get
} else {
point = point + v1 + v2;
}
}
}
}
t = knots[i];
pointOnCurve = curve->PointAt(t);
knudgedPointOnCurve = curve->PointAt(t - PBC_TOL);
ON_3dPoint point = pointOnCurve;
ON_3dPoint knudgepoint = knudgedPointOnCurve;
ON_3dPoint ps1;
ON_3dPoint ps2;
bool found = false;
double dist;
while (!found) {
ON_2dPoint uv;
if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps1 = surface1->PointAt(uv.x, uv.y);
if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps2 = surface2->PointAt(uv.x, uv.y);
}
}
dist = ps1.DistanceTo(ps2);
if (NEAR_ZERO(dist, PBC_TOL)) {
point = ps1;
found = true;
} else {
ON_3dVector v1 = ps1 - point;
ON_3dVector v2 = ps2 - point;
knudgepoint = point;
ON_3dVector deltav = v1 + v2;
if (NEAR_ZERO(deltav.Length(), PBC_TOL)) {
found = true; // as close as we are going to get
} else {
point = point + v1 + v2;
}
}
}
}
}
}
delete [] knots;
return NULL;
}
bool
has_singularity(const ON_Surface *surf)
{
bool ret = false;
if (UNLIKELY(!surf)) return ret;
// 0 = south, 1 = east, 2 = north, 3 = west
for (int i = 0; i < 4; i++) {
if (surf->IsSingular(i)) {
/*
switch (i) {
case 0:
std::cout << "Singular South" << std::endl;
break;
case 1:
std::cout << "Singular East" << std::endl;
break;
case 2:
std::cout << "Singular North" << std::endl;
break;
case 3:
std::cout << "Singular West" << std::endl;
}
*/
ret = true;
}
}
return ret;
}
bool is_closed(const ON_Surface *surf)
{
bool ret = false;
if (UNLIKELY(!surf)) return ret;
// dir 0 = "s", 1 = "t"
for (int i = 0; i < 2; i++) {
if (surf->IsClosed(i)) {
// switch (i) {
// case 0:
// std::cout << "Closed in U" << std::endl;
// break;
// case 1:
// std::cout << "Closed in V" << std::endl;
// }
ret = true;
}
}
return ret;
}
bool
check_pullback_closed(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator d = pbcs.begin();
if ((*d) == NULL || (*d)->surf == NULL)
return false;
const ON_Surface *surf = (*d)->surf;
//TODO:
// 0 = U, 1 = V
if (surf->IsClosed(0) && surf->IsClosed(1)) {
//TODO: need to check how torus UV looks to determine checks
std::cerr << "Is this some kind of torus????" << std::endl;
} else if (surf->IsClosed(0)) {
//check_pullback_closed_U(pbcs);
std::cout << "check closed in U" << std::endl;
} else if (surf->IsClosed(1)) {
//check_pullback_closed_V(pbcs);
std::cout << "check closed in V" << std::endl;
}
return true;
}
bool
check_pullback_singular_east(std::list<PBCData*> &pbcs)
{
std::list<PBCData *>::iterator cs = pbcs.begin();
if ((*cs) == NULL || (*cs)->surf == NULL)
return false;
const ON_Surface *surf = (*cs)->surf;
double umin, umax;
ON_2dPoint *prev = NULL;
surf->GetDomain(0, &umin, &umax);
std::cout << "Umax: " << umax << std::endl;
while (cs != pbcs.end()) {
PBCData *data = (*cs);
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
int segcnt = 0;
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
std::cerr << std::endl << "Segment:" << ++segcnt << std::endl;
if (true) {
int ilast = samples->Count() - 1;
std::cerr << std::endl << 0 << "- " << (*samples)[0].x << ", " << (*samples)[0].y << std::endl;
std::cerr << ilast << "- " << (*samples)[ilast].x << ", " << (*samples)[ilast].y << std::endl;
} else {
for (int i = 0; i < samples->Count(); i++) {
if (NEAR_EQUAL((*samples)[i].x, umax, PBC_TOL)) {
if (prev != NULL) {
std::cerr << "prev - " << prev->x << ", " << prev->y << std::endl;
}
std::cerr << i << "- " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl << std::endl;
}
prev = &(*samples)[i];
}
}
si ++;
}
cs++;
}
return true;
}
bool
check_pullback_singular(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator d = pbcs.begin();
if ((*d) == NULL || (*d)->surf == NULL)
return false;
const ON_Surface *surf = (*d)->surf;
int cnt = 0;
for (int i = 0; i < 4; i++) {
if (surf->IsSingular(i)) {
cnt++;
}
}
if (cnt > 2) {
//TODO: I don't think this makes sense but check out
std::cerr << "Is this some kind of sickness????" << std::endl;
return false;
} else if (cnt == 2) {
if (surf->IsSingular(0) && surf->IsSingular(2)) {
std::cout << "check singular North-South" << std::endl;
} else if (surf->IsSingular(1) && surf->IsSingular(2)) {
std::cout << "check singular East-West" << std::endl;
} else {
//TODO: I don't think this makes sense but check out
std::cerr << "Is this some kind of sickness????" << std::endl;
return false;
}
} else {
if (surf->IsSingular(0)) {
std::cout << "check singular South" << std::endl;
} else if (surf->IsSingular(1)) {
std::cout << "check singular East" << std::endl;
if (check_pullback_singular_east(pbcs)) {
return true;
}
} else if (surf->IsSingular(2)) {
std::cout << "check singular North" << std::endl;
} else if (surf->IsSingular(3)) {
std::cout << "check singular West" << std::endl;
}
}
return true;
}
#ifdef _DEBUG_TESTING_
void
print_pullback_data(std::string str, std::list<PBCData*> &pbcs, bool justendpoints)
{
std::list<PBCData*>::iterator cs = pbcs.begin();
int trimcnt = 0;
if (justendpoints) {
// print out endpoints before
std::cerr << "EndPoints " << str << ":" << std::endl;
while (cs != pbcs.end()) {
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
int segcnt = 0;
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
std::cerr << std::endl << " Segment:" << ++segcnt << std::endl;
int ilast = samples->Count() - 1;
std::cerr << " T:" << ++trimcnt << std::endl;
int i = 0;
int singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surf, (*samples)[i], PBC_SEAM_TOL);
std::cerr << "--------";
if ((seam > 0) && (singularity >= 0)) {
std::cerr << " S/S " << (*samples)[i].x << ", " << (*samples)[i].y;
} else if (seam > 0) {
std::cerr << " Seam " << (*samples)[i].x << ", " << (*samples)[i].y;
} else if (singularity >= 0) {
std::cerr << " Sing " << (*samples)[i].x << ", " << (*samples)[i].y;
} else {
std::cerr << " " << (*samples)[i].x << ", " << (*samples)[i].y;
}
ON_3dPoint p = surf->PointAt((*samples)[i].x, (*samples)[i].y);
std::cerr << " (" << p.x << ", " << p.y << ", " << p.z << ") " << std::endl;
i = ilast;
singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL);
seam = IsAtSeam(surf, (*samples)[i], PBC_SEAM_TOL);
std::cerr << " ";
if ((seam > 0) && (singularity >= 0)) {
std::cerr << " S/S " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl;
} else if (seam > 0) {
std::cerr << " Seam " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl;
} else if (singularity >= 0) {
std::cerr << " Sing " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl;
} else {
std::cerr << " " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl;
}
p = surf->PointAt((*samples)[i].x, (*samples)[i].y);
std::cerr << " (" << p.x << ", " << p.y << ", " << p.z << ") " << std::endl;
si++;
}
cs++;
}
} else {
// print out all points
trimcnt = 0;
cs = pbcs.begin();
std::cerr << str << ":" << std::endl;
while (cs != pbcs.end()) {
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
int segcnt = 0;
std::cerr << "2d surface domain: " << std::endl;
std::cerr << "in rpp rpp" << surf->Domain(0).m_t[0] << " " << surf->Domain(0).m_t[1] << " " << surf->Domain(1).m_t[0] << " " << surf->Domain(1).m_t[1] << " 0.0 0.01" << std::endl;
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
std::cerr << std::endl << " Segment:" << ++segcnt << std::endl;
std::cerr << " T:" << ++trimcnt << std::endl;
for (int i = 0; i < samples->Count(); i++) {
int singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surf, (*samples)[i], PBC_SEAM_TOL);
if (_debug_print_mged2d_points_) {
std::cerr << "in pt_" << _debug_point_count_++ << " sph " << (*samples)[i].x << " " << (*samples)[i].y << " 0.0 0.1000" << std::endl;
} else if (_debug_print_mged3d_points_) {
ON_3dPoint p = surf->PointAt((*samples)[i].x, (*samples)[i].y);
std::cerr << "in pt_" << _debug_point_count_++ << " sph " << p.x << " " << p.y << " " << p.z << " 0.1000" << std::endl;
} else {
if (i == 0) {
std::cerr << "--------";
} else {
std::cerr << " ";
}
if ((seam > 0) && (singularity >= 0)) {
std::cerr << " S/S " << (*samples)[i].x << ", " << (*samples)[i].y;
} else if (seam > 0) {
std::cerr << " Seam " << (*samples)[i].x << ", " << (*samples)[i].y;
} else if (singularity >= 0) {
std::cerr << " Sing " << (*samples)[i].x << ", " << (*samples)[i].y;
} else {
std::cerr << " " << (*samples)[i].x << ", " << (*samples)[i].y;
}
ON_3dPoint p = surf->PointAt((*samples)[i].x, (*samples)[i].y);
std::cerr << " (" << p.x << ", " << p.y << ", " << p.z << ") " << std::endl;
}
}
si++;
}
cs++;
}
}
/////
}
#endif
bool
resolve_seam_segment_from_prev(const ON_Surface *surface, ON_2dPointArray &segment, ON_2dPoint *prev = NULL)
{
bool complete = false;
double umin, umax, umid;
double vmin, vmax, vmid;
surface->GetDomain(0, &umin, &umax);
surface->GetDomain(1, &vmin, &vmax);
umid = (umin + umax) / 2.0;
vmid = (vmin + vmax) / 2.0;
for (int i = 0; i < segment.Count(); i++) {
int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL);
if ((seam > 0)) {
if (prev != NULL) {
//std::cerr << " at seam " << seam << " but has prev" << std::endl;
//std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
switch (seam) {
case 1: //east/west
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
break;
case 2: //north/south
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
break;
case 3: //both
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
}
prev = &segment[i];
} else {
//std::cerr << " at seam and no prev" << std::endl;
complete = false;
}
} else {
if (singularity < 0) {
prev = &segment[i];
} else {
prev = NULL;
}
}
}
return complete;
}
bool
resolve_seam_segment_from_next(const ON_Surface *surface, ON_2dPointArray &segment, ON_2dPoint *next = NULL)
{
bool complete = false;
double umin, umax, umid;
double vmin, vmax, vmid;
surface->GetDomain(0, &umin, &umax);
surface->GetDomain(1, &vmin, &vmax);
umid = (umin + umax) / 2.0;
vmid = (vmin + vmax) / 2.0;
if (next != NULL) {
complete = true;
for (int i = segment.Count() - 1; i >= 0; i--) {
int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL);
if ((seam > 0)) {
if (next != NULL) {
switch (seam) {
case 1: //east/west
if (next->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
break;
case 2: //north/south
if (next->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
break;
case 3: //both
if (next->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
if (next->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
}
next = &segment[i];
} else {
//std::cerr << " at seam and no prev" << std::endl;
complete = false;
}
} else {
if (singularity < 0) {
next = &segment[i];
} else {
next = NULL;
}
}
}
}
return complete;
}
bool
resolve_seam_segment(const ON_Surface *surface, ON_2dPointArray &segment, bool &u_resolved, bool &v_resolved)
{
ON_2dPoint *prev = NULL;
bool complete = false;
double umin, umax, umid;
double vmin, vmax, vmid;
int prev_seam = 0;
surface->GetDomain(0, &umin, &umax);
surface->GetDomain(1, &vmin, &vmax);
umid = (umin + umax) / 2.0;
vmid = (vmin + vmax) / 2.0;
for (int i = 0; i < segment.Count(); i++) {
int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL);
if ((seam > 0)) {
if (prev != NULL) {
//std::cerr << " at seam " << seam << " but has prev" << std::endl;
//std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
switch (seam) {
case 1: //east/west
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
break;
case 2: //north/south
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
break;
case 3: //both
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
}
prev = &segment[i];
} else {
//std::cerr << " at seam and no prev" << std::endl;
complete = false;
}
prev_seam = seam;
} else {
if (singularity < 0) {
prev = &segment[i];
prev_seam = 0;
} else {
prev = NULL;
}
}
}
prev_seam = 0;
if ((!complete) && (prev != NULL)) {
complete = true;
for (int i = segment.Count() - 2; i >= 0; i--) {
int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL);
if ((seam > 0)) {
if (prev != NULL) {
//std::cerr << " at seam " << seam << " but has prev" << std::endl;
//std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
switch (seam) {
case 1: //east/west
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
break;
case 2: //north/south
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
break;
case 3: //both
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
}
prev = &segment[i];
} else {
//std::cerr << " at seam and no prev" << std::endl;
complete = false;
}
} else {
if (singularity < 0) {
prev = &segment[i];
} else {
prev = NULL;
}
}
}
}
return complete;
}
/*
* number_of_seam_crossings
*/
int
number_of_seam_crossings(std::list<PBCData*> &pbcs)
{
int rc = 0;
std::list<PBCData*>::iterator cs;
cs = pbcs.begin();
while (cs != pbcs.end()) {
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
ON_2dPoint *pt = NULL;
ON_2dPoint *prev_pt = NULL;
ON_2dPoint *next_pt = NULL;
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
for (int i = 0; i < samples->Count(); i++) {
pt = &(*samples)[i];
if (!IsAtSeam(surf,*pt,PBC_SEAM_TOL)) {
if (prev_pt == NULL) {
prev_pt = pt;
} else {
next_pt = pt;
}
int udir=0;
int vdir=0;
if (next_pt != NULL) {
if (ConsecutivePointsCrossClosedSeam(surf,*prev_pt,*next_pt,udir,vdir,PBC_SEAM_TOL)) {
rc++;
}
prev_pt = next_pt;
next_pt = NULL;
}
}
}
if (si != data->segments.end())
si++;
}
if (cs != pbcs.end())
cs++;
}
return rc;
}
/*
* if current and previous point on seam make sure they are on same seam
*/
bool
check_for_points_on_same_seam(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator cs = pbcs.begin();
ON_2dPoint *prev_pt = NULL;
int prev_seam = 0;
while ( cs != pbcs.end()) {
PBCData *data = (*cs);
const ON_Surface *surf = data->surf;
std::list<ON_2dPointArray *>::iterator seg = data->segments.begin();
while (seg != data->segments.end()) {
ON_2dPointArray *points = (*seg);
for (int i=0; i < points->Count(); i++) {
ON_2dPoint *pt = points->At(i);
int seam = IsAtSeam(surf,*pt,PBC_SEAM_TOL);
if (seam > 0) {
if (prev_seam > 0) {
if ((seam == 1) && ((prev_seam % 2) == 1)) {
pt->x = prev_pt->x;
} else if ((seam == 2) && (prev_seam > 1)) {
pt->y = prev_pt->y;
} else if (seam == 3) {
if ((prev_seam % 2) == 1) {
pt->x = prev_pt->x;
}
if (prev_seam > 1) {
pt->y = prev_pt->y;
}
}
}
prev_seam = seam;
prev_pt = pt;
}
}
seg++;
}
cs++;
}
return true;
}
/*
* extend_pullback_at_shared_3D_curve_seam
*/
bool
extend_pullback_at_shared_3D_curve_seam(std::list<PBCData*> &pbcs)
{
const ON_Curve *next_curve = NULL;
std::set<const ON_Curve *> set;
std::map<const ON_Curve *,int> map;
std::list<PBCData*>::iterator cs = pbcs.begin();
while ( cs != pbcs.end()) {
PBCData *data = (*cs++);
const ON_Curve *curve = data->curve;
const ON_Surface *surf = data->surf;
if (cs != pbcs.end()) {
PBCData *nextdata = (*cs);
next_curve = nextdata->curve;
}
if (curve == next_curve) {
std::cerr << "Consecutive seam usage" << std::endl;
//find which direction we need to extend
if (surf->IsClosed(0) && !surf->IsClosed(1)) {
double length = surf->Domain(0).Length();
std::list<ON_2dPointArray *>::iterator seg = data->segments.begin();
while (seg != data->segments.end()) {
ON_2dPointArray *points = (*seg);
for (int i=0; i < points->Count(); i++) {
points->At(i)->x = points->At(i)->x + length;
}
seg++;
}
} else if (!surf->IsClosed(0) && surf->IsClosed(1)) {
double length = surf->Domain(1).Length();
std::list<ON_2dPointArray *>::iterator seg = data->segments.begin();
while (seg != data->segments.end()) {
ON_2dPointArray *points = (*seg);
for (int i=0; i < points->Count(); i++) {
points->At(i)->y = points->At(i)->y + length;
}
seg++;
}
} else {
std::cerr << "both directions" << std::endl;
}
}
next_curve = NULL;
}
return true;
}
/*
* shift_closed_curve_split_over_seam
*/
bool
shift_single_curve_loop_straddled_over_seam(std::list<PBCData*> &pbcs)
{
if (pbcs.size() == 1) { // single curve for this loop
std::list<PBCData*>::iterator cs;
PBCData *data = pbcs.front();
if (!data || !data->surf)
return false;
const ON_Surface *surf = data->surf;
ON_Interval udom = surf->Domain(0);
ON_Interval vdom = surf->Domain(1);
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
ON_2dPoint pt;
ON_2dPoint prev_pt;
if (data->curve->IsClosed()) {
int numseamcrossings = number_of_seam_crossings(pbcs);
if (numseamcrossings == 1) {
ON_2dPointArray part1,part2;
ON_2dPointArray* curr_point_array = &part2;
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
for (int i = 0; i < samples->Count(); i++) {
pt = (*samples)[i];
if (i == 0) {
prev_pt = pt;
curr_point_array->Append(pt);
continue;
}
int udir= 0;
int vdir= 0;
if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) {
if (surf->IsAtSeam(pt.x,pt.y) > 0) {
SwapUVSeamPoint(surf, pt);
curr_point_array->Append(pt);
curr_point_array = &part1;
SwapUVSeamPoint(surf, pt);
} else if (surf->IsAtSeam(prev_pt.x,prev_pt.y) > 0) {
SwapUVSeamPoint(surf, prev_pt);
curr_point_array->Append(prev_pt);
} else {
std::cerr << "shift_single_curve_loop_straddled_over_seam(): Error expecting to see seam in sample points" << std::endl;
}
}
curr_point_array->Append(pt);
prev_pt = pt;
}
samples->Empty();
samples->Append(part1.Count(),part1.Array());
samples->Append(part2.Count(),part2.Array());
if (si != data->segments.end())
si++;
}
}
}
}
return true;
}
/*
* extend_over_seam_crossings - all incoming points assumed to be within UV bounds
*/
bool
extend_over_seam_crossings(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator cs;
ON_2dPoint *pt = NULL;
ON_2dPoint *prev_non_seam_pt = NULL;
ON_2dPoint *prev_pt = NULL;
ON_2dVector curr_uv_offsets = ON_2dVector::ZeroVector;
///// Loop through and fix any seam ambiguities
cs = pbcs.begin();
while (cs != pbcs.end()) {
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
ON_Interval udom = surf->Domain(0);
double ulength = udom.Length();
ON_Interval vdom = surf->Domain(1);
double vlength = vdom.Length();
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
for (int i = 0; i < samples->Count(); i++) {
pt = &(*samples)[i];
if (prev_pt != NULL) {
GetClosestExtendedPoint(surf,*pt,*prev_pt,PBC_SEAM_TOL);
}
prev_pt = pt;
}
if (si != data->segments.end())
si++;
}
if (cs != pbcs.end())
cs++;
}
return true;
}
/*
* run through curve loop to determine correct start/end
* points resolving ambiguities when point lies on a seam or
* singularity
*/
bool
resolve_pullback_seams(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator cs;
///// Loop through and fix any seam ambiguities
ON_2dPoint *prev = NULL;
ON_2dPoint *next = NULL;
bool u_resolved = false;
bool v_resolved = false;
cs = pbcs.begin();
while (cs != pbcs.end()) {
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
double umin, umax;
double vmin, vmax;
surf->GetDomain(0, &umin, &umax);
surf->GetDomain(1, &vmin, &vmax);
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
if (resolve_seam_segment(surf, *samples,u_resolved,v_resolved)) {
// Found a starting point
//1) walk back up with resolved next point
next = (*samples).First();
std::list<PBCData*>::reverse_iterator rcs(cs);
rcs--;
std::list<ON_2dPointArray *>::reverse_iterator rsi(si);
while (rcs != pbcs.rend()) {
PBCData *rdata = (*rcs);
while (rsi != rdata->segments.rend()) {
ON_2dPointArray *rsamples = (*rsi);
// first try and resolve on own merits
if (!resolve_seam_segment(surf, *rsamples,u_resolved,v_resolved)) {
resolve_seam_segment_from_next(surf, *rsamples, next);
}
next = (*rsamples).First();
rsi++;
}
rcs++;
if (rcs != pbcs.rend()) {
rdata = (*rcs);
rsi = rdata->segments.rbegin();
}
}
//2) walk rest of way down with resolved prev point
if (samples->Count() > 1)
prev = &(*samples)[samples->Count() - 1];
else
prev = NULL;
si++;
std::list<PBCData*>::iterator current(cs);
while (cs != pbcs.end()) {
while (si != data->segments.end()) {
samples = (*si);
// first try and resolve on own merits
if (!resolve_seam_segment(surf, *samples,u_resolved,v_resolved)) {
resolve_seam_segment_from_prev(surf, *samples, prev);
}
if (samples->Count() > 1)
prev = &(*samples)[samples->Count() - 1];
else
prev = NULL;
si++;
}
cs++;
if (cs != pbcs.end()) {
data = (*cs);
si = data->segments.begin();
}
}
// make sure to wrap back around with previous
cs = pbcs.begin();
data = (*cs);
si = data->segments.begin();
while ((cs != pbcs.end()) && (cs != current)) {
while (si != data->segments.end()) {
samples = (*si);
// first try and resolve on own merits
if (!resolve_seam_segment(surf, *samples,u_resolved,v_resolved)) {
resolve_seam_segment_from_prev(surf, *samples, prev);
}
if (samples->Count() > 1)
prev = &(*samples)[samples->Count() - 1];
else
prev = NULL;
si++;
}
cs++;
if (cs != pbcs.end()) {
data = (*cs);
si = data->segments.begin();
}
}
}
if (si != data->segments.end())
si++;
}
if (cs != pbcs.end())
cs++;
}
return true;
}
/*
* run through curve loop to determine correct start/end
* points resolving ambiguities when point lies on a seam or
* singularity
*/
bool
resolve_pullback_singularities(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator cs = pbcs.begin();
///// Loop through and fix any seam ambiguities
ON_2dPoint *prev = NULL;
bool complete = false;
int checkcnt = 0;
prev = NULL;
complete = false;
checkcnt = 0;
while (!complete && (checkcnt < 2)) {
cs = pbcs.begin();
complete = true;
checkcnt++;
//std::cerr << "Checkcnt - " << checkcnt << std::endl;
while (cs != pbcs.end()) {
int singularity;
prev = NULL;
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
for (int i = 0; i < samples->Count(); i++) {
// 0 = south, 1 = east, 2 = north, 3 = west
if ((singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL)) >= 0) {
if (prev != NULL) {
//std::cerr << " at singularity " << singularity << " but has prev" << std::endl;
//std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
switch (singularity) {
case 0: //south
(*samples)[i].x = prev->x;
(*samples)[i].y = surf->Domain(1)[0];
break;
case 1: //east
(*samples)[i].y = prev->y;
(*samples)[i].x = surf->Domain(0)[1];
break;
case 2: //north
(*samples)[i].x = prev->x;
(*samples)[i].y = surf->Domain(1)[1];
break;
case 3: //west
(*samples)[i].y = prev->y;
(*samples)[i].x = surf->Domain(0)[0];
}
prev = NULL;
//std::cerr << " curr now: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
} else {
//std::cerr << " at singularity " << singularity << " and no prev" << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
complete = false;
}
} else {
prev = &(*samples)[i];
}
}
if (!complete) {
//std::cerr << "Lets work backward:" << std::endl;
for (int i = samples->Count() - 2; i >= 0; i--) {
// 0 = south, 1 = east, 2 = north, 3 = west
if ((singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL)) >= 0) {
if (prev != NULL) {
//std::cerr << " at singularity " << singularity << " but has prev" << std::endl;
//std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
switch (singularity) {
case 0: //south
(*samples)[i].x = prev->x;
(*samples)[i].y = surf->Domain(1)[0];
break;
case 1: //east
(*samples)[i].y = prev->y;
(*samples)[i].x = surf->Domain(0)[1];
break;
case 2: //north
(*samples)[i].x = prev->x;
(*samples)[i].y = surf->Domain(1)[1];
break;
case 3: //west
(*samples)[i].y = prev->y;
(*samples)[i].x = surf->Domain(0)[0];
}
prev = NULL;
//std::cerr << " curr now: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
} else {
//std::cerr << " at singularity " << singularity << " and no prev" << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
complete = false;
}
} else {
prev = &(*samples)[i];
}
}
}
si++;
}
cs++;
}
}
return true;
}
void
remove_consecutive_intersegment_duplicates(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator cs = pbcs.begin();
while (cs != pbcs.end()) {
PBCData *data = (*cs);
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
if (samples->Count() == 0) {
si = data->segments.erase(si);
} else {
for (int i = 0; i < samples->Count() - 1; i++) {
while ((i < (samples->Count() - 1)) && (*samples)[i].DistanceTo((*samples)[i + 1]) < 1e-9) {
samples->Remove(i + 1);
}
}
si++;
}
}
if (data->segments.empty()) {
cs = pbcs.erase(cs);
} else {
cs++;
}
}
}
bool
check_pullback_data(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator d = pbcs.begin();
if ((*d) == NULL || (*d)->surf == NULL)
return false;
const ON_Surface *surf = (*d)->surf;
bool singular = has_singularity(surf);
bool closed = is_closed(surf);
if (singular) {
if (!resolve_pullback_singularities(pbcs)) {
std::cerr << "Error: Can not resolve singular ambiguities." << std::endl;
}
}
if (closed) {
// check for same 3D curve use
if (!check_for_points_on_same_seam(pbcs)) {
std::cerr << "Error: Can not extend pullback at shared 3D curve seam." << std::endl;
return false;
}
// check for same 3D curve use
if (!extend_pullback_at_shared_3D_curve_seam(pbcs)) {
std::cerr << "Error: Can not extend pullback at shared 3D curve seam." << std::endl;
return false;
}
if (!shift_single_curve_loop_straddled_over_seam(pbcs)) {
std::cerr << "Error: Can not resolve seam ambiguities." << std::endl;
return false;
}
if (!resolve_pullback_seams(pbcs)) {
std::cerr << "Error: Can not resolve seam ambiguities." << std::endl;
return false;
}
if (!extend_over_seam_crossings(pbcs)) {
std::cerr << "Error: Can not resolve seam ambiguities." << std::endl;
return false;
}
}
// consecutive duplicates within segment will cause problems in curve fit
remove_consecutive_intersegment_duplicates(pbcs);
return true;
}
int
check_pullback_singularity_bridge(const ON_Surface *surf, const ON_2dPoint &p1, const ON_2dPoint &p2)
{
if (has_singularity(surf)) {
int is, js;
if (((is = IsAtSingularity(surf, p1, PBC_SEAM_TOL)) >= 0) && ((js = IsAtSingularity(surf, p2, PBC_SEAM_TOL)) >= 0)) {
//create new singular trim
if (is == js) {
return is;
}
}
}
return -1;
}
int
check_pullback_seam_bridge(const ON_Surface *surf, const ON_2dPoint &p1, const ON_2dPoint &p2)
{
if (is_closed(surf)) {
int is, js;
if (((is = IsAtSeam(surf, p1, PBC_SEAM_TOL)) > 0) && ((js = IsAtSeam(surf, p2, PBC_SEAM_TOL)) > 0)) {
//create new seam trim
if (is == js) {
// need to check if seam 3d points are equal
double endpoint_distance = p1.DistanceTo(p2);
double t0, t1;
int dir = is - 1;
surf->GetDomain(dir, &t0, &t1);
if (endpoint_distance > 0.5 * (t1 - t0)) {
return is;
}
}
}
}
return -1;
}
ON_Curve*
pullback_curve(const brlcad::SurfaceTree* surfacetree,
const ON_Surface* surf,
const ON_Curve* curve,
double tolerance,
double flatness)
{
PBCData data;
data.tolerance = tolerance;
data.flatness = flatness;
data.curve = curve;
data.surf = surf;
data.surftree = (brlcad::SurfaceTree*)surfacetree;
ON_2dPointArray samples;
data.segments.push_back(&samples);
// Step 1 - adaptively sample the curve
double tmin, tmax;
data.curve->GetDomain(&tmin, &tmax);
ON_2dPoint& start = samples.AppendNew(); // new point is added to samples and returned
if (!toUV(data, start, tmin, 0.001)) {
return NULL; // fails if first point is out of tolerance!
}
ON_2dPoint uv;
ON_3dPoint p = curve->PointAt(tmin);
ON_3dPoint from = curve->PointAt(tmin + 0.0001);
brlcad::SurfaceTree *st = (brlcad::SurfaceTree *)surfacetree;
if (st->getSurfacePoint((const ON_3dPoint&)p, uv, (const ON_3dPoint&)from) < 0) {
std::cerr << "Error: Can not get surface point." << std::endl;
}
ON_2dPoint p1, p2;
#ifdef SHOW_UNUSED
if (!data.surf)
return NULL;
const ON_Surface *surf = data.surf;
#endif
if (toUV(data, p1, tmin, PBC_TOL) && toUV(data, p2, tmax, -PBC_TOL)) {
#ifdef SHOW_UNUSED
ON_3dPoint a = surf->PointAt(p1.x, p1.y);
ON_3dPoint b = surf->PointAt(p2.x, p2.y);
#endif
p = curve->PointAt(tmax);
from = curve->PointAt(tmax - 0.0001);
if (st->getSurfacePoint((const ON_3dPoint&)p, uv, (const ON_3dPoint&)from) < 0) {
std::cerr << "Error: Can not get surface point." << std::endl;
}
if (!sample(data, tmin, tmax, p1, p2)) {
return NULL;
}
for (int i = 0; i < samples.Count(); i++) {
std::cerr << samples[i].x << ", " << samples[i].y << std::endl;
}
} else {
return NULL;
}
return interpolateCurve(samples);
}
ON_Curve*
pullback_seam_curve(enum seam_direction seam_dir,
const brlcad::SurfaceTree* surfacetree,
const ON_Surface* surf,
const ON_Curve* curve,
double tolerance,
double flatness)
{
PBCData data;
data.tolerance = tolerance;
data.flatness = flatness;
data.curve = curve;
data.surf = surf;
data.surftree = (brlcad::SurfaceTree*)surfacetree;
ON_2dPointArray samples;
data.segments.push_back(&samples);
// Step 1 - adaptively sample the curve
double tmin, tmax;
data.curve->GetDomain(&tmin, &tmax);
ON_2dPoint& start = samples.AppendNew(); // new point is added to samples and returned
if (!toUV(data, start, tmin, 0.001)) {
return NULL; // fails if first point is out of tolerance!
}
ON_2dPoint p1, p2;
if (toUV(data, p1, tmin, PBC_TOL) && toUV(data, p2, tmax, -PBC_TOL)) {
if (!sample(data, tmin, tmax, p1, p2)) {
return NULL;
}
for (int i = 0; i < samples.Count(); i++) {
if (seam_dir == NORTH_SEAM) {
samples[i].y = 1.0;
} else if (seam_dir == EAST_SEAM) {
samples[i].x = 1.0;
} else if (seam_dir == SOUTH_SEAM) {
samples[i].y = 0.0;
} else if (seam_dir == WEST_SEAM) {
samples[i].x = 0.0;
}
std::cerr << samples[i].x << ", " << samples[i].y << std::endl;
}
} else {
return NULL;
}
return interpolateCurve(samples);
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
| 31.11835
| 204
| 0.603803
|
quadmotor
|
ca155a3ed1b5de97d9d89de64f6d806f518bcf37
| 1,895
|
cpp
|
C++
|
Siv3D/src/Siv3D/TCPServer/SivTCPServer.cpp
|
tas9n/OpenSiv3D
|
c561cba1d88eb9cd9606ba983fcc1120192d5615
|
[
"MIT"
] | 2
|
2021-11-22T00:52:48.000Z
|
2021-12-24T09:33:55.000Z
|
Siv3D/src/Siv3D/TCPServer/SivTCPServer.cpp
|
tas9n/OpenSiv3D
|
c561cba1d88eb9cd9606ba983fcc1120192d5615
|
[
"MIT"
] | null | null | null |
Siv3D/src/Siv3D/TCPServer/SivTCPServer.cpp
|
tas9n/OpenSiv3D
|
c561cba1d88eb9cd9606ba983fcc1120192d5615
|
[
"MIT"
] | 1
|
2021-12-31T05:08:00.000Z
|
2021-12-31T05:08:00.000Z
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/TCPServer.hpp>
# include <Siv3D/TCPServer/TCPServerDetail.hpp>
namespace s3d
{
TCPServer::TCPServer()
: pImpl{ std::make_shared<TCPServerDetail>() } {}
TCPServer::~TCPServer() {}
void TCPServer::startAccept(const uint16 port)
{
pImpl->startAccept(port);
}
void TCPServer::startAcceptMulti(const uint16 port)
{
pImpl->startAcceptMulti(port);
}
void TCPServer::cancelAccept()
{
pImpl->cancelAccept();
}
bool TCPServer::isAccepting() const
{
return pImpl->isAccepting();
}
void TCPServer::disconnect()
{
return pImpl->disconnect();
}
bool TCPServer::hasSession() const
{
return pImpl->hasSession();
}
bool TCPServer::hasSession(const TCPSessionID id) const
{
return pImpl->hasSession(id);
}
size_t TCPServer::num_sessions() const
{
return pImpl->num_sessions();
}
Array<TCPSessionID> TCPServer::getSessionIDs() const
{
return pImpl->getSessionIDs();
}
uint16 TCPServer::port() const
{
return pImpl->port();
}
size_t TCPServer::available(const Optional<TCPSessionID>& id)
{
return pImpl->available(id);
}
bool TCPServer::skip(const size_t size, const Optional<TCPSessionID>& id)
{
return pImpl->skip(size, id);
}
bool TCPServer::lookahead(void* dst, const size_t size, const Optional<TCPSessionID>& id) const
{
return pImpl->lookahead(dst, size, id);
}
bool TCPServer::read(void* dst, const size_t size, const Optional<TCPSessionID>& id)
{
return pImpl->read(dst, size, id);
}
bool TCPServer::send(const void* data, const size_t size, const Optional<TCPSessionID>& id)
{
return pImpl->send(data, size, id);
}
}
| 19.536082
| 96
| 0.661214
|
tas9n
|
ca15af76b7aa10d521476e7213ca8ee5d49dec14
| 11,799
|
cpp
|
C++
|
Core-src/PeakFile.cpp
|
HaikuArchives/BeAE
|
b57860a81266dd465655ec98b7524406bfde27aa
|
[
"BSD-3-Clause"
] | 6
|
2015-03-04T19:41:12.000Z
|
2022-03-27T09:44:25.000Z
|
Core-src/PeakFile.cpp
|
HaikuArchives/BeAE
|
b57860a81266dd465655ec98b7524406bfde27aa
|
[
"BSD-3-Clause"
] | 20
|
2015-03-03T21:02:20.000Z
|
2021-08-02T13:26:59.000Z
|
Core-src/PeakFile.cpp
|
HaikuArchives/BeAE
|
b57860a81266dd465655ec98b7524406bfde27aa
|
[
"BSD-3-Clause"
] | 8
|
2015-02-23T19:10:32.000Z
|
2020-10-26T08:03:00.000Z
|
/*
Copyright (c) 2003, Xentronix
Author: Frans van Nispen (frans@xentronix.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer. Redistributions in binary form must
reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Xentronix nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <stdio.h>
#include "Globals.h"
#include "PeakFile.h"
#include "VMSystem.h"
CPeakFile Peak;
#define BUFFER_SIZE 64*256 // 64Kb
// ============================================================
CPeakFile::CPeakFile()
{
buffer_left = NULL;
buffer_right = NULL;
buffer = NULL;
}
// ============================================================
CPeakFile::~CPeakFile()
{
if (buffer) delete[] buffer;
if (buffer_left) free(buffer_left);
if (buffer_right) free(buffer_right);
}
// ============================================================
void CPeakFile::Init(int32 size, bool mono)
{
if (buffer)
delete[] buffer;
buffer = new float[BUFFER_SIZE];
m_size = size;
size = (size >> 7) + 1;
m_mono = mono;
int64 mem = size * 4 +16; // 2 int16's for each channel
if (!mono) mem *= 2;
int16 *p = (int16*)realloc(buffer_left, mem);
if (p){
buffer_left = p; // new block
memset( buffer_left, 0, mem); // wipe buffer
}else{
(new BAlert(NULL,Language.get("MEM_ERROR"),Language.get("OK")))->Go();
be_app->Quit();
}
if (!mono){
int16 *p = (int16*)realloc(buffer_right, mem);
if (p){
buffer_right = p; // new block
memset( buffer_right, 0, mem); // wipe buffer
}else{
(new BAlert(NULL,Language.get("MEM_ERROR"),Language.get("OK")))->Go();
be_app->Quit();
}
}else{
if (buffer_right) free(buffer_right);
buffer_right = NULL;
}
}
// ============================================================
void CPeakFile::CreatePeaks(int32 start, int32 end, int32 progress)
{
float min, max, max_r, min_r;
int32 to, ii;
start &= 0xfffffff8; // mask off 1st 7 bits to round on 128 bytes
int32 p_add = 0, p_count = 0, count = 0;
if (progress){ // init progress process
p_count = (end-start)/(100*128);
p_add = progress/100;
if (!m_mono) p_add <<=1;
}
if (m_mono) // mono
{
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 index = 0;
VM.ReadBlockAt(start, p, BUFFER_SIZE);
#endif
for (int32 i=start; i<=end; i+=128){
min = max = 0.0;
to = i+127;
if (to>Pool.size) to = Pool.size;
for (int32 x=i; x<=to; x++){
#ifndef __VM_SYSTEM // RAM
if (p[x]>max) max = p[x];
if (p[x]<min) min = p[x];
#else
if (p[index]>max) max = p[index];
if (p[index]<min) min = p[index];
index++;
if (index == BUFFER_SIZE){
index = 0;
VM.ReadBlock(p, BUFFER_SIZE);
}
#endif
}
ii = i>>6;
buffer_left[ii] = (int16)(min * 32767);
buffer_left[ii+1] = (int16)(max * 32767);
if (progress && count--<0){ count = p_count; Pool.ProgressUpdate( p_add ); }
}
}
else // Stereo
{
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 index = 0;
VM.ReadBlockAt(start, p, BUFFER_SIZE);
#endif
for (int32 i=start*2; i<=end*2; i+=256){
min = max = 0.0;
min_r = max_r = 0.0;
to = i+255;
if (to>Pool.size) to = Pool.size;
for (int32 x=i; x<=to; x+=2){
#ifndef __VM_SYSTEM // RAM
if (p[x]>max) max = p[x];
if (p[x]<min) min = p[x];
if (p[x+1]>max_r) max_r = p[x+1];
if (p[x+1]<min_r) min_r = p[x+1];
#else
if (p[index]>max) max = p[index];
if (p[index]<min) min = p[index];
if (p[index+1]>max_r) max_r = p[index+1];
if (p[index+1]<min_r) min_r = p[index+1];
index+=2;
if (index >= BUFFER_SIZE){
index = 0;
VM.ReadBlock(p, BUFFER_SIZE);
}
#endif
}
ii = i>>6;
buffer_left[ii] = (int16)(min * 32767);
buffer_left[ii+1] = (int16)(max * 32767);
buffer_right[ii] = (int16)(min_r * 32767);
buffer_right[ii+1] = (int16)(max_r * 32767);
if (progress && count--<0){ count = p_count; Pool.ProgressUpdate( p_add ); }
}
}
Pool.update_peak = true;
}
// ============================================================
void CPeakFile::MonoBuffer(float *out, int32 start, int32 end, float w)
{
if (!buffer_left || !m_mono) return;
float step = (end - start)/w;
int32 iStep = (int32)step;
int32 index, to;
#ifdef __VM_SYSTEM // VM
int32 nBufferSize = MIN( BUFFER_SIZE, end-start);
#endif
if ( step <= 1 )
{
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
#ifndef __VM_SYSTEM // RAM
index = start + (int32)(x * step);
#else
index = (int32)(x * step);
#endif
float fTemp = p[index];
if (fTemp>1.0f) fTemp = 1.0f;
else if (fTemp<-1.0f) fTemp = -1.0f;
*out++ = fTemp;
*out++ = 0.0f;
}
}else
if ( step < 64 )
{ float min, max;
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 idx = 0;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
min = max = 0;
for (int32 i=index; i<=to; i++){
#ifndef __VM_SYSTEM // RAM
if (p[i]>max) max = p[i];
if (p[i]<min) min = p[i];
#else
if (p[idx]>max) max = p[idx];
if (p[idx]<min) min = p[idx];
idx++;
if (idx == nBufferSize){
idx = 0;
VM.ReadBlock(p, nBufferSize);
}
#endif
}
if (max > -min) *out++ = MIN(max, 1);
else *out++ = MAX(min, -1);
*out++ = 0.0f;
}
}else
if ( step < 128 )
{ float min, max;
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 idx = 0;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
min = max = 0;
for (int32 i=index; i<=to; i++){
#ifndef __VM_SYSTEM // RAM
if (p[i]>max) max = p[i];
if (p[i]<min) min = p[i];
#else
if (p[idx]>max) max = p[idx];
if (p[idx]<min) min = p[idx];
idx++;
if (idx == nBufferSize){
idx = 0;
VM.ReadBlock(p, nBufferSize);
}
#endif
}
*out++ = min;
*out++ = max;
}
}
else
{ int16 min, max;
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
index >>= 6; index &= 0xfffffffe;
to >>= 6; to &= 0xfffffffe;
min = max = 0;
for (int32 i=index; i<=to; i+=2){
if (buffer_left[i]<min) min = buffer_left[i];
if (buffer_left[i+1]>max) max = buffer_left[i+1];
}
*out++ = min/32767.0;
*out++ = max/32767.0;
}
}
}
// ============================================================
void CPeakFile::StereoBuffer(float *out, float *out_r, int32 start, int32 end, float w)
{
if (!buffer_left ||!buffer_right || m_mono)
return;
float step = (end - start)/w;
int32 iStep = (int32)step;
int32 index, to;
#ifdef __VM_SYSTEM // VM
int32 nBufferSize = MIN( BUFFER_SIZE, (end-start)*2);
#endif
if ( step <= 1 )
{
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
#ifndef __VM_SYSTEM // RAM
index = start + (int32)(x * step);
#else
index = (int32)(x * step);
#endif
float fTemp = p[index*2];
float fTempR = p[index*2+1];
if (fTemp>1.0f) fTemp = 1.0f;
else if (fTemp<-1.0f) fTemp = -1.0f;
if (fTempR>1.0f) fTempR = 1.0f;
else if (fTempR<-1.0f) fTempR = -1.0f;
*out++ = fTemp;
*out++ = 0.0f;
*out_r++ = fTempR;
*out_r++ = 0.0f;
}
}else
if ( step < 64 )
{ float min, max, min_r, max_r;
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 idx = 0;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
index *= 2;
to *= 2;
min = max = min_r = max_r = 0;
for (int32 i=index; i<=to; i+=2){
#ifndef __VM_SYSTEM // RAM
if (p[i]>max) max = p[i];
if (p[i]<min) min = p[i];
if (p[i+1]>max_r) max_r = p[i+1];
if (p[i+1]<min_r) min_r = p[i+1];
#else
if (p[idx]>max) max = p[idx];
if (p[idx]<min) min = p[idx];
idx++;
if (p[idx]>max_r) max_r = p[idx];
if (p[idx]<min_r) min_r = p[idx];
idx++;
if (idx >= nBufferSize){
idx = 0;
VM.ReadBlock(p, nBufferSize);
}
#endif
}
if (max > -min) *out++ = MIN(max, 1);
else *out++ = MAX(min, -1);
*out++ = 0.0f;
if (max_r > -min_r) *out_r++ = MIN(max_r, 1);
else *out_r++ = MAX(min_r, -1);
*out_r++ = 0.0f;
}
}else
if (step <128)
{ float min, max, min_r, max_r;
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 idx = 0;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
index *= 2;
to *= 2;
min = max = min_r = max_r = 0;
for (int32 i=index; i<=to; i+=2){
#ifndef __VM_SYSTEM // RAM
if (p[i]>max) max = p[i];
if (p[i]<min) min = p[i];
if (p[i+1]>max_r) max_r = p[i+1];
if (p[i+1]<min_r) min_r = p[i+1];
#else
if (p[idx]>max) max = p[idx];
if (p[idx]<min) min = p[idx];
idx++;
if (p[idx]>max_r) max_r = p[idx];
if (p[idx]<min_r) min_r = p[idx];
idx++;
if (idx >= nBufferSize){
idx = 0;
VM.ReadBlock(p, nBufferSize);
}
#endif
}
*out++ = min;
*out++ = max;
*out_r++ = min_r;
*out_r++ = max_r;
}
}
else
{ int16 min, max, min_r, max_r;
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
index >>= 6; index &= 0xfffffffe;
to >>= 6; to &= 0xfffffffe;
min = max = min_r = max_r = 0;
for (int32 i=index; i<=to; i+=2){
if (buffer_left[i]<min) min = buffer_left[i];
if (buffer_left[i+1]>max) max = buffer_left[i+1];
if (buffer_right[i]<min_r) min_r = buffer_right[i];
if (buffer_right[i+1]>max_r) max_r = buffer_right[i+1];
}
*out++ = min/32767.0;
*out++ = max/32767.0;
*out_r++ = min_r/32767.0;
*out_r++ = max_r/32767.0;
}
}
}
| 25.157783
| 89
| 0.56437
|
HaikuArchives
|
ca197403de71028efb91aaef9f94f71c9dba68b3
| 6,493
|
hpp
|
C++
|
src/slave/containerizer/docker.hpp
|
HICAS-ChameLeon/Chameleon
|
cd0666317eb4e92a4f9fe0b2955b46bc224cf862
|
[
"Apache-2.0"
] | 4
|
2019-03-06T03:04:40.000Z
|
2019-07-20T15:35:00.000Z
|
src/slave/containerizer/docker.hpp
|
HICAS-ChameLeon/Chameleon
|
cd0666317eb4e92a4f9fe0b2955b46bc224cf862
|
[
"Apache-2.0"
] | 6
|
2018-11-30T08:04:45.000Z
|
2019-05-15T03:04:28.000Z
|
src/slave/containerizer/docker.hpp
|
HICAS-ChameLeon/Chameleon
|
cd0666317eb4e92a4f9fe0b2955b46bc224cf862
|
[
"Apache-2.0"
] | 4
|
2019-03-11T11:51:22.000Z
|
2020-05-11T07:27:31.000Z
|
/*
* Copyright :SIAT 异构智能计算体系结构与系统研究中心
* Author : Heldon 764165887@qq.com
* Date :19-03-01
* Description:containerizer(docker) codes
*/
#ifndef CHAMELEON_DOCKER_HPP
#define CHAMELEON_DOCKER_HPP
//C++11 dependencies
#include <list>
#include <map>
#include <set>
#include <string>
//stout dependencies
#include <stout/os.hpp>
//google dependencies
#include <gflags/gflags.h>
//libprocess dependencies
#include <process/owned.hpp>
#include <process/shared.hpp>
#include <process/process.hpp>
//chameleon dependencies
#include <resources.hpp>
#include "docker/docker.hpp"
#include "docker/resources.hpp"
namespace chameleon{
namespace slave{
//Foward declaration
class DockerContainerizerProcess;
class DockerContainerizer{
public:
static Try<DockerContainerizer*> create();
DockerContainerizer(process::Shared<Docker> docker);
virtual process::Future<bool> launch(
const mesos::ContainerID& containerId,
const Option<mesos::TaskInfo>& taskInfo,
const mesos::ExecutorInfo& executorInfo,
const std::string directory,
const Option<std::string>& user,
const mesos::SlaveID& slaveId,
const std::map<std::string, std::string>& environment);
virtual ~DockerContainerizer();
private:
process::Owned<DockerContainerizerProcess> m_process;
};
class DockerContainerizerProcess : public process::Process<DockerContainerizerProcess>{
public:
DockerContainerizerProcess(process::Shared<Docker> _docker) : m_docker(_docker){}
//start launch containerizer
virtual process::Future<bool> launch(
const mesos::ContainerID& contaierId,
const Option<mesos::TaskInfo>& taskInfo,
const mesos::ExecutorInfo& executorInfo,
const std::string& directory,
const Option<std::string>& user,
const mesos::SlaveID& slaveId,
const std::map<std::string, std::string>& environment);
// pull the image
virtual process::Future<Nothing> pull(const mesos::ContainerID& containerId);
private:
process::Future<bool> _launch(
const mesos::ContainerID& containerId,
const Option<mesos::TaskInfo>& taskInfo,
const mesos::ExecutorInfo& executorInfo,
const std::string& directory,
const mesos::SlaveID& slaveId);
// Starts the executor in a Docker container.
process::Future<Docker::Container> launchExecutorContainer(
const mesos::ContainerID& containerId,
const std::string& containerName);
//const Flags m_flags;
process::Shared<Docker> m_docker;
struct Container{
const mesos::ContainerID m_id;
const Option<mesos::TaskInfo> m_task;
const mesos::ExecutorInfo m_executor;
mesos::ContainerInfo m_container;
mesos::CommandInfo m_command;
std::map<std::string, std::string> m_environment;
Option<std::map<std::string, std::string>> m_taskEnvironment;
// The sandbox directory for the container.
std::string m_directory;
const Option<std::string> m_user;
mesos::SlaveID m_slaveId;
//const Flags m_flags;
mesos::Resources m_resources;
process::Future<Docker::Image> m_pull;
process::Future<bool> m_launch;
static Try<Container*> create(
const mesos::ContainerID& id,
const Option<mesos::TaskInfo>& taskInfo,
const mesos::ExecutorInfo& executorInfo,
const std::string& directory,
const Option<std::string>& user,
const mesos::SlaveID& slaveId,
const std::map<std::string, std::string>& environment);
static std::string name(const mesos::SlaveID& slaveId, const std::string& id) {
return "chameleon-" + slaveId.value() + "." +
stringify(id);
}
Container(const mesos::ContainerID& id,
const Option<mesos::TaskInfo>& taskInfo,
const mesos::ExecutorInfo& executorInfo,
const std::string& directory,
const Option<std::string>& user,
const mesos::SlaveID& slaveId,
const Option<mesos::CommandInfo>& _command,
const Option<mesos::ContainerInfo>& _container,
const std::map<std::string, std::string>& _environment)
: m_id(id),
m_task(taskInfo),
m_executor(executorInfo),
m_environment(_environment),
m_directory(directory),
m_user(user),
m_slaveId(slaveId){
LOG(INFO)<<"Heldon Enter construct function Container";
m_resources = m_executor.resources();
if (m_task.isSome()) {
CHECK(m_resources.contains(m_task.get().resources()));
}
if (_command.isSome()) {
m_command = _command.get();
} else if (m_task.isSome()) {
m_command = m_task.get().command();
} else {
m_command = m_executor.command();
}
if (_container.isSome()) {
m_container = _container.get();
} else if (m_task.isSome()) {
m_container = m_task.get().container();
} else {
m_container = m_executor.container();
}
}
~Container() {
os::rm(m_directory);
}
std::string name(){
return name(m_slaveId, stringify(m_id));
}
std::string image() const{
if(m_task.isSome()){
return m_task.get().container().docker().image();
}
return m_executor.container().docker().image();
}
};
hashmap<mesos::ContainerID, Container*> m_containers;
};
}
}
#endif //CHAMELEON_DOCKER_HPP
| 33.297436
| 91
| 0.551517
|
HICAS-ChameLeon
|
ca19ce947ee073ce2ea4f581d3a999c5189f0211
| 1,147
|
cpp
|
C++
|
src/behaviour/meleeattackbhv.cpp
|
alexeyden/whack
|
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
|
[
"WTFPL"
] | null | null | null |
src/behaviour/meleeattackbhv.cpp
|
alexeyden/whack
|
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
|
[
"WTFPL"
] | null | null | null |
src/behaviour/meleeattackbhv.cpp
|
alexeyden/whack
|
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
|
[
"WTFPL"
] | null | null | null |
#include "meleeattackbhv.h"
#include "util/math.h"
#include "objects//enemy.h"
#include "level/level.h"
MeleeAttackBhv::MeleeAttackBhv(Enemy* owner):
Behaviour(owner),
_attackTime { 0.0f }
{
}
void MeleeAttackBhv::collision(float x, float y, float z)
{
(void) x;
(void) y;
(void) z;
}
void MeleeAttackBhv::damage(float damage)
{
(void) damage;
}
void MeleeAttackBhv::update(double dt)
{
if(_attackTime > .0f)
_attackTime -= dt;
auto player = owner->level->player();
vec2 delta(player->x() - owner->x(), player->y() - owner->y());
if(delta.length() < minAttackDistance) {
owner->speedXY(.0f, .0f);
if(_attackTime <= .0f) {
player->damage(attackDamage, vec3(owner->x(), owner->y(), owner->z()));
_attackTime = attackCooldown;
}
if(owner->state() != EnemyState::ES_ATTACK)
owner->state(EnemyState::ES_ATTACK);
} else {
delta.normalize();
delta *= owner->maxSpeed();
owner->dir(atan2(delta.y, delta.x));
owner->speedXY(delta.x, delta.y);
}
}
| 21.641509
| 83
| 0.562337
|
alexeyden
|
ca19e5870270f147d6b3ea9fc9cb083435fd16b8
| 76,520
|
cpp
|
C++
|
gui/qtc-gdbmacros/gdbmacros.cpp
|
frooms/stira
|
60b419f3e478397a8ab43ce9315a259567d94a26
|
[
"MIT"
] | 8
|
2016-03-23T08:12:33.000Z
|
2022-01-25T14:07:03.000Z
|
gui/qtc-gdbmacros/gdbmacros.cpp
|
frooms/stira
|
60b419f3e478397a8ab43ce9315a259567d94a26
|
[
"MIT"
] | null | null | null |
gui/qtc-gdbmacros/gdbmacros.cpp
|
frooms/stira
|
60b419f3e478397a8ab43ce9315a259567d94a26
|
[
"MIT"
] | 8
|
2015-06-29T12:00:06.000Z
|
2019-09-03T12:40:47.000Z
|
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include <qglobal.h>
// this relies on contents copied from qobject_p.h
#define PRIVATE_OBJECT_ALLOWED 1
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QHash>
#include <QLocale>
#include <QMap>
#include <QMetaObject>
#include <QMetaProperty>
#include <QModelIndex>
#include <QObject>
#include <QPointer>
#include <QString>
#include <QTextCodec>
#include <QVector>
/*!
\class QDumper
\brief Helper class for producing "nice" output in Qt Creator's debugger.
\internal
The whole "custom dumper" implementation is currently far less modular
than it could be. But as the code is still in a flux, making it nicer
from a pure archtectural point of view seems still be a waste of resources.
Some hints:
New dumpers for non-templated classes should be mentioned in
\c{qDumpObjectData440()} in the \c{protocolVersion == 1} branch.
Templated classes need extra support on the IDE level
(see plugins/debugger/gdbengine.cpp) and should not be mentiond in
\c{qDumpObjectData440()}.
In any case, dumper processesing should end up in
\c{handleProtocolVersion2and3()} and needs an entry in the bis switch there.
Next step is to create a suitable \c{static void qDumpFoo(QDumper &d)}
function. At the bare minimum it should contain something like:
\c{
const Foo &foo = *reinterpret_cast<const Foo *>(d.data);
P(d, "value", ...);
P(d, "type", "Foo");
P(d, "numchild", "0");
}
'P(d, name, value)' roughly expands to:
d << (name) << "=\"" << value << "\"";
Useful (i.e. understood by the IDE) names include:
\list
\o "name" shows up in the first column in the Locals&Watchers view.
\o "value" shows up in the second column.
\o "valueencoded" should be set to "1" if the value is base64 encoded.
Always base64-encode values that might use unprintable or otherwise
"confuse" the protocol (like spaces and quotes). [A-Za-z0-9] is "safe".
A value of "3" is used for base64-encoded UCS4, "2" denotes
base64-encoded UTF16.
\o "numchild" return the number of children in the view. Effectively, only
0 and != 0 will be used, so don't try too hard to get the number right.
\endlist
If the current item has children, it might be queried to produce information
about thes children. In this case the dumper should use something like
\c{
if (d.dumpChildren) {
d << ",children=[";
}
*/
int qtGhVersion = QT_VERSION;
#ifdef QT_GUI_LIB
# include <QPixmap>
# include <QImage>
#endif
#include <list>
#include <map>
#include <string>
#include <vector>
#include <ctype.h>
#include <stdio.h>
#ifdef Q_OS_WIN
# include <windows.h>
#endif
#undef NS
#ifdef QT_NAMESPACE
# define STRINGIFY0(s) #s
# define STRINGIFY1(s) STRINGIFY0(s)
# define NS STRINGIFY1(QT_NAMESPACE) "::"
# define NSX "'" STRINGIFY1(QT_NAMESPACE) "::"
# define NSY "'"
#else
# define NS ""
# define NSX ""
# define NSY ""
#endif
#if PRIVATE_OBJECT_ALLOWED
#if defined(QT_BEGIN_NAMESPACE)
QT_BEGIN_NAMESPACE
#endif
class QVariant;
class QThreadData;
class QObjectConnectionListVector;
class QObjectPrivate : public QObjectData
{
Q_DECLARE_PUBLIC(QObject)
public:
QObjectPrivate() {}
virtual ~QObjectPrivate() {}
// preserve binary compatibility with code compiled without Qt 3 support
QList<QObject *> pendingChildInsertedEvents; // unused
// id of the thread that owns the object
QThreadData *threadData;
struct Sender
{
QObject *sender;
int signal;
int ref;
};
Sender *currentSender; // object currently activating the object
QObject *currentChildBeingDeleted;
QList<QPointer<QObject> > eventFilters;
struct ExtraData;
ExtraData *extraData;
mutable quint32 connectedSignals;
QString objectName;
struct Connection
{
QObject *receiver;
int method;
uint connectionType : 3; // 0 == auto, 1 == direct, 2 == queued, 4 == blocking
QBasicAtomicPointer<int> argumentTypes;
};
typedef QList<Connection> ConnectionList;
QObjectConnectionListVector *connectionLists;
QList<Sender> senders;
int *deleteWatch;
};
#if defined(QT_BEGIN_NAMESPACE)
QT_END_NAMESPACE
#endif
#endif // PRIVATE_OBJECT_ALLOWED
// this can be mangled typenames of nested templates, each char-by-char
// comma-separated integer list
static char qDumpInBuffer[10000];
static char qDumpBuffer[1000];
namespace {
static bool isPointerType(const QByteArray &type)
{
return type.endsWith("*") || type.endsWith("* const");
}
static QByteArray stripPointerType(QByteArray type)
{
if (type.endsWith("*"))
type.chop(1);
if (type.endsWith("* const"))
type.chop(7);
if (type.endsWith(' '))
type.chop(1);
return type;
}
// This is used to abort evaluation of custom data dumpers in a "coordinated"
// way. Abortion will happen anyway when we try to access a non-initialized
// non-trivial object, so there is no way to prevent this from occuring at all
// conceptionally. Gdb will catch SIGSEGV and return to the calling frame.
// This is just fine provided we only _read_ memory in the custom handlers
// below.
volatile int qProvokeSegFaultHelper;
static const void *addOffset(const void *p, int offset)
{
return offset + reinterpret_cast<const char *>(p);
}
static const void *skipvtable(const void *p)
{
return sizeof(void*) + reinterpret_cast<const char *>(p);
}
static const void *deref(const void *p)
{
return *reinterpret_cast<const char* const*>(p);
}
static const void *dfunc(const void *p)
{
return deref(skipvtable(p));
}
static bool isEqual(const char *s, const char *t)
{
return qstrcmp(s, t) == 0;
}
static bool startsWith(const char *s, const char *t)
{
return qstrncmp(s, t, strlen(t)) == 0;
}
// provoke segfault when address is not readable
#define qCheckAccess(d) do { qProvokeSegFaultHelper = *(char*)d; } while (0)
#define qCheckPointer(d) do { if (d) qProvokeSegFaultHelper = *(char*)d; } while (0)
// provoke segfault unconditionally
#define qCheck(b) do { if (!(b)) qProvokeSegFaultHelper = *(char*)0; } while (0)
const char *stripNamespace(const char *type)
{
static const size_t nslen = strlen(NS);
return startsWith(type, NS) ? type + nslen : type;
}
static bool isSimpleType(const char *type)
{
switch (type[0]) {
case 'c':
return isEqual(type, "char");
case 'd':
return isEqual(type, "double");
case 'f':
return isEqual(type, "float");
case 'i':
return isEqual(type, "int");
case 'l':
return isEqual(type, "long") || startsWith(type, "long ");
case 's':
return isEqual(type, "short") || isEqual(type, "signed")
|| startsWith(type, "signed ");
case 'u':
return isEqual(type, "unsigned") || startsWith(type, "unsigned ");
}
return false;
}
static bool isShortKey(const char *type)
{
return isSimpleType(type) || isEqual(type, "QString");
}
static bool isMovableType(const char *type)
{
if (isPointerType(type))
return true;
if (isSimpleType(type))
return true;
type = stripNamespace(type);
switch (type[1]) {
case 'B':
return isEqual(type, "QBrush")
|| isEqual(type, "QBitArray")
|| isEqual(type, "QByteArray") ;
case 'C':
return isEqual(type, "QCustomTypeInfo");
case 'D':
return isEqual(type, "QDate")
|| isEqual(type, "QDateTime");
case 'F':
return isEqual(type, "QFileInfo")
|| isEqual(type, "QFixed")
|| isEqual(type, "QFixedPoint")
|| isEqual(type, "QFixedSize");
case 'H':
return isEqual(type, "QHashDummyValue");
case 'I':
return isEqual(type, "QIcon")
|| isEqual(type, "QImage");
case 'L':
return isEqual(type, "QLine")
|| isEqual(type, "QLineF")
|| isEqual(type, "QLocal");
case 'M':
return isEqual(type, "QMatrix")
|| isEqual(type, "QModelIndex");
case 'P':
return isEqual(type, "QPoint")
|| isEqual(type, "QPointF")
|| isEqual(type, "QPen")
|| isEqual(type, "QPersistentModelIndex");
case 'R':
return isEqual(type, "QResourceRoot")
|| isEqual(type, "QRect")
|| isEqual(type, "QRectF")
|| isEqual(type, "QRegExp");
case 'S':
return isEqual(type, "QSize")
|| isEqual(type, "QSizeF")
|| isEqual(type, "QString");
case 'T':
return isEqual(type, "QTime")
|| isEqual(type, "QTextBlock");
case 'U':
return isEqual(type, "QUrl");
case 'V':
return isEqual(type, "QVariant");
case 'X':
return isEqual(type, "QXmlStreamAttribute")
|| isEqual(type, "QXmlStreamNamespaceDeclaration")
|| isEqual(type, "QXmlStreamNotationDeclaration")
|| isEqual(type, "QXmlStreamEntityDeclaration");
}
return false;
}
struct QDumper
{
explicit QDumper();
~QDumper();
void flush();
void checkFill();
QDumper &operator<<(long c);
QDumper &operator<<(int i);
QDumper &operator<<(double d);
QDumper &operator<<(float d);
QDumper &operator<<(unsigned long c);
QDumper &operator<<(unsigned int i);
QDumper &operator<<(const void *p);
QDumper &operator<<(qulonglong c);
QDumper &operator<<(const char *str);
QDumper &operator<<(const QByteArray &ba);
QDumper &operator<<(const QString &str);
void put(char c);
void addCommaIfNeeded();
void putBase64Encoded(const char *buf, int n);
void putEllipsis();
void disarm();
void beginHash(); // start of data hash output
void endHash(); // start of data hash output
void write(const void *buf, int len); // raw write to stdout
// the dumper arguments
int protocolVersion; // dumper protocol version
int token; // some token to show on success
const char *outertype; // object type
const char *iname; // object name used for display
const char *exp; // object expression
const char *innertype; // 'inner type' for class templates
const void *data; // pointer to raw data
bool dumpChildren; // do we want to see children?
// handling of nested templates
void setupTemplateParameters();
enum { maxTemplateParameters = 10 };
const char *templateParameters[maxTemplateParameters + 1];
int templateParametersCount;
// internal state
bool success; // are we finished?
int pos;
int extraInt[4];
};
QDumper::QDumper()
{
success = false;
pos = 0;
}
QDumper::~QDumper()
{
flush();
char buf[30];
int len = qsnprintf(buf, sizeof(buf) - 1, "%d^done\n", token);
write(buf, len);
}
void QDumper::write(const void *buf, int len)
{
::fwrite(buf, len, 1, stdout);
::fflush(stdout);
}
void QDumper::flush()
{
if (pos != 0) {
char buf[30];
int len = qsnprintf(buf, sizeof(buf) - 1, "%d#%d,", token, pos);
write(buf, len);
write(qDumpBuffer, pos);
write("\n", 1);
pos = 0;
}
}
void QDumper::setupTemplateParameters()
{
char *s = const_cast<char *>(innertype);
templateParametersCount = 1;
templateParameters[0] = s;
for (int i = 1; i != maxTemplateParameters + 1; ++i)
templateParameters[i] = 0;
while (*s) {
while (*s && *s != '@')
++s;
if (*s) {
*s = '\0';
++s;
templateParameters[templateParametersCount++] = s;
}
}
}
QDumper &QDumper::operator<<(unsigned long long c)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%llu", c);
return *this;
}
QDumper &QDumper::operator<<(unsigned long c)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%lu", c);
return *this;
}
QDumper &QDumper::operator<<(float d)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%f", d);
return *this;
}
QDumper &QDumper::operator<<(double d)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%f", d);
return *this;
}
QDumper &QDumper::operator<<(unsigned int i)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%u", i);
return *this;
}
QDumper &QDumper::operator<<(long c)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%ld", c);
return *this;
}
QDumper &QDumper::operator<<(int i)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%d", i);
return *this;
}
QDumper &QDumper::operator<<(const void *p)
{
static char buf[100];
if (p) {
sprintf(buf, "%p", p);
// we get a '0x' prefix only on some implementations.
// if it isn't there, write it out manually.
if (buf[1] != 'x') {
put('0');
put('x');
}
*this << buf;
} else {
*this << "<null>";
}
return *this;
}
void QDumper::checkFill()
{
if (pos >= int(sizeof(qDumpBuffer)) - 100)
flush();
}
void QDumper::put(char c)
{
checkFill();
qDumpBuffer[pos++] = c;
}
void QDumper::addCommaIfNeeded()
{
if (pos == 0)
return;
char c = qDumpBuffer[pos - 1];
if (c == '}' || c == '"' || c == ']')
put(',');
}
void QDumper::putBase64Encoded(const char *buf, int n)
{
const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
"ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
const char padchar = '=';
int padlen = 0;
//int tmpsize = ((n * 4) / 3) + 3;
int i = 0;
while (i < n) {
int chunk = 0;
chunk |= int(uchar(buf[i++])) << 16;
if (i == n) {
padlen = 2;
} else {
chunk |= int(uchar(buf[i++])) << 8;
if (i == n)
padlen = 1;
else
chunk |= int(uchar(buf[i++]));
}
int j = (chunk & 0x00fc0000) >> 18;
int k = (chunk & 0x0003f000) >> 12;
int l = (chunk & 0x00000fc0) >> 6;
int m = (chunk & 0x0000003f);
put(alphabet[j]);
put(alphabet[k]);
put(padlen > 1 ? padchar : alphabet[l]);
put(padlen > 0 ? padchar : alphabet[m]);
}
}
QDumper &QDumper::operator<<(const char *str)
{
if (!str)
return *this << "<null>";
while (*str)
put(*(str++));
return *this;
}
QDumper &QDumper::operator<<(const QByteArray &ba)
{
putBase64Encoded(ba.constData(), ba.size());
return *this;
}
QDumper &QDumper::operator<<(const QString &str)
{
QByteArray ba = str.toUtf8();
putBase64Encoded(ba.constData(), ba.size());
return *this;
}
void QDumper::disarm()
{
flush();
success = true;
}
void QDumper::beginHash()
{
addCommaIfNeeded();
put('{');
}
void QDumper::endHash()
{
put('}');
}
void QDumper::putEllipsis()
{
addCommaIfNeeded();
*this << "{name=\"<incomplete>\",value=\"\",type=\"" << innertype << "\"}";
}
//
// Some helpers to keep the dumper code short
//
// dump property=value pair
#undef P
#define P(dumper,name,value) \
do { \
dumper.addCommaIfNeeded(); \
dumper << (name) << "=\"" << value << "\""; \
} while (0)
// simple string property
#undef S
#define S(dumper, name, value) \
dumper.beginHash(); \
P(dumper, "name", name); \
P(dumper, "value", value); \
P(dumper, "type", NS"QString"); \
P(dumper, "numchild", "0"); \
P(dumper, "valueencoded", "1"); \
dumper.endHash();
// simple integer property
#undef I
#define I(dumper, name, value) \
dumper.beginHash(); \
P(dumper, "name", name); \
P(dumper, "value", value); \
P(dumper, "type", "int"); \
P(dumper, "numchild", "0"); \
dumper.endHash();
// simple boolean property
#undef BL
#define BL(dumper, name, value) \
dumper.beginHash(); \
P(dumper, "name", name); \
P(dumper, "value", (value ? "true" : "false")); \
P(dumper, "type", "bool"); \
P(dumper, "numchild", "0"); \
dumper.endHash();
// a single QChar
#undef QC
#define QC(dumper, name, value) \
dumper.beginHash(); \
P(dumper, "name", name); \
P(dumper, "value", QString(QLatin1String("'%1' (%2, 0x%3)")) \
.arg(value).arg(value.unicode()).arg(value.unicode(), 0, 16)); \
P(dumper, "valueencoded", "1"); \
P(dumper, "type", NS"QChar"); \
P(dumper, "numchild", "0"); \
dumper.endHash();
#undef TT
#define TT(type, value) \
"<tr><td>" << type << "</td><td> : </td><td>" << value << "</td></tr>"
static void qDumpUnknown(QDumper &d)
{
P(d, "iname", d.iname);
P(d, "addr", d.data);
P(d, "value", "<internal error>");
P(d, "type", d.outertype);
P(d, "numchild", "0");
d.disarm();
}
static void qDumpInnerValueHelper(QDumper &d, const char *type, const void *addr,
const char *key = "value")
{
type = stripNamespace(type);
switch (type[1]) {
case 'l':
if (isEqual(type, "float"))
P(d, key, *(float*)addr);
return;
case 'n':
if (isEqual(type, "int"))
P(d, key, *(int*)addr);
else if (isEqual(type, "unsigned"))
P(d, key, *(unsigned int*)addr);
else if (isEqual(type, "unsigned int"))
P(d, key, *(unsigned int*)addr);
else if (isEqual(type, "unsigned long"))
P(d, key, *(unsigned long*)addr);
else if (isEqual(type, "unsigned long long"))
P(d, key, *(qulonglong*)addr);
return;
case 'o':
if (isEqual(type, "bool"))
switch (*(bool*)addr) {
case 0: P(d, key, "false"); break;
case 1: P(d, key, "true"); break;
default: P(d, key, *(bool*)addr); break;
}
else if (isEqual(type, "double"))
P(d, key, *(double*)addr);
else if (isEqual(type, "long"))
P(d, key, *(long*)addr);
else if (isEqual(type, "long long"))
P(d, key, *(qulonglong*)addr);
return;
case 'B':
if (isEqual(type, "QByteArray")) {
d << key << "encoded=\"1\",";
P(d, key, *(QByteArray*)addr);
}
return;
case 'L':
if (startsWith(type, "QList<")) {
const QListData *ldata = reinterpret_cast<const QListData*>(addr);
P(d, "value", "<" << ldata->size() << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", ldata->size());
}
return;
case 'O':
if (isEqual(type, "QObject *")) {
if (addr) {
const QObject *ob = reinterpret_cast<const QObject *>(addr);
P(d, "addr", ob);
P(d, "value", ob->objectName());
P(d, "valueencoded", "1");
P(d, "type", NS"QObject");
P(d, "displayedtype", ob->metaObject()->className());
} else {
P(d, "value", "0x0");
P(d, "type", NS"QObject *");
}
}
return;
case 'S':
if (isEqual(type, "QString")) {
d << key << "encoded=\"1\",";
P(d, key, *(QString*)addr);
}
return;
default:
return;
}
}
static void qDumpInnerValue(QDumper &d, const char *type, const void *addr)
{
P(d, "addr", addr);
P(d, "type", type);
if (!type[0])
return;
qDumpInnerValueHelper(d, type, addr);
}
static void qDumpInnerValueOrPointer(QDumper &d,
const char *type, const char *strippedtype, const void *addr)
{
if (strippedtype) {
if (deref(addr)) {
P(d, "addr", deref(addr));
P(d, "type", strippedtype);
qDumpInnerValueHelper(d, strippedtype, deref(addr));
} else {
P(d, "addr", addr);
P(d, "type", strippedtype);
P(d, "value", "<null>");
P(d, "numchild", "0");
}
} else {
P(d, "addr", addr);
P(d, "type", type);
qDumpInnerValueHelper(d, type, addr);
}
}
//////////////////////////////////////////////////////////////////////////////
static void qDumpQByteArray(QDumper &d)
{
const QByteArray &ba = *reinterpret_cast<const QByteArray *>(d.data);
if (!ba.isEmpty()) {
qCheckAccess(ba.constData());
qCheckAccess(ba.constData() + ba.size());
}
if (ba.size() <= 100)
P(d, "value", ba);
else
P(d, "value", ba.left(100) << " <size: " << ba.size() << ", cut...>");
P(d, "valueencoded", "1");
P(d, "type", NS"QByteArray");
P(d, "numchild", ba.size());
P(d, "childtype", "char");
P(d, "childnumchild", "0");
if (d.dumpChildren) {
d << ",children=[";
char buf[20];
for (int i = 0; i != ba.size(); ++i) {
unsigned char c = ba.at(i);
unsigned char u = isprint(c) && c != '"' ? c : '?';
sprintf(buf, "%02x (%u '%c')", c, c, u);
d.beginHash();
P(d, "name", "[" << i << "]");
P(d, "value", buf);
d.endHash();
}
d << "]";
}
d.disarm();
}
static void qDumpQDateTime(QDumper &d)
{
#ifdef QT_NO_DATESTRING
qDumpUnknown(d);
#else
const QDateTime &date = *reinterpret_cast<const QDateTime *>(d.data);
if (date.isNull()) {
P(d, "value", "(null)");
} else {
P(d, "value", date.toString());
P(d, "valueencoded", "1");
}
P(d, "type", NS"QDateTime");
P(d, "numchild", "3");
if (d.dumpChildren) {
d << ",children=[";
BL(d, "isNull", date.isNull());
I(d, "toTime_t", (long)date.toTime_t());
S(d, "toString", date.toString());
S(d, "toString_(ISO)", date.toString(Qt::ISODate));
S(d, "toString_(SystemLocale)", date.toString(Qt::SystemLocaleDate));
S(d, "toString_(Locale)", date.toString(Qt::LocaleDate));
S(d, "toString", date.toString());
#if 0
d.beginHash();
P(d, "name", "toUTC");
P(d, "exp", "(("NSX"QDateTime"NSY"*)" << d.data << ")"
"->toTimeSpec('"NS"Qt::UTC')");
P(d, "type", NS"QDateTime");
P(d, "numchild", "1");
d.endHash();
#endif
#if 0
d.beginHash();
P(d, "name", "toLocalTime");
P(d, "exp", "(("NSX"QDateTime"NSY"*)" << d.data << ")"
"->toTimeSpec('"NS"Qt::LocalTime')");
P(d, "type", NS"QDateTime");
P(d, "numchild", "1");
d.endHash();
#endif
d << "]";
}
d.disarm();
#endif // ifdef QT_NO_DATESTRING
}
static void qDumpQDir(QDumper &d)
{
const QDir &dir = *reinterpret_cast<const QDir *>(d.data);
P(d, "value", dir.path());
P(d, "valueencoded", "1");
P(d, "type", NS"QDir");
P(d, "numchild", "3");
if (d.dumpChildren) {
d << ",children=[";
S(d, "absolutePath", dir.absolutePath());
S(d, "canonicalPath", dir.canonicalPath());
d << "]";
}
d.disarm();
}
static void qDumpQFile(QDumper &d)
{
const QFile &file = *reinterpret_cast<const QFile *>(d.data);
P(d, "value", file.fileName());
P(d, "valueencoded", "1");
P(d, "type", NS"QFile");
P(d, "numchild", "2");
if (d.dumpChildren) {
d << ",children=[";
S(d, "fileName", file.fileName());
BL(d, "exists", file.exists());
d << "]";
}
d.disarm();
}
static void qDumpQFileInfo(QDumper &d)
{
const QFileInfo &info = *reinterpret_cast<const QFileInfo *>(d.data);
P(d, "value", info.filePath());
P(d, "valueencoded", "1");
P(d, "type", NS"QFileInfo");
P(d, "numchild", "3");
if (d.dumpChildren) {
d << ",children=[";
S(d, "absolutePath", info.absolutePath());
S(d, "absoluteFilePath", info.absoluteFilePath());
S(d, "canonicalPath", info.canonicalPath());
S(d, "canonicalFilePath", info.canonicalFilePath());
S(d, "completeBaseName", info.completeBaseName());
S(d, "completeSuffix", info.completeSuffix());
S(d, "baseName", info.baseName());
#ifdef Q_OS_MACX
BL(d, "isBundle", info.isBundle());
S(d, "bundleName", info.bundleName());
#endif
S(d, "completeSuffix", info.completeSuffix());
S(d, "fileName", info.fileName());
S(d, "filePath", info.filePath());
S(d, "group", info.group());
S(d, "owner", info.owner());
S(d, "path", info.path());
I(d, "groupid", (long)info.groupId());
I(d, "ownerid", (long)info.ownerId());
//QFile::Permissions permissions () const
I(d, "permissions", info.permissions());
//QDir absoluteDir () const
//QDir dir () const
BL(d, "caching", info.caching());
BL(d, "exists", info.exists());
BL(d, "isAbsolute", info.isAbsolute());
BL(d, "isDir", info.isDir());
BL(d, "isExecutable", info.isExecutable());
BL(d, "isFile", info.isFile());
BL(d, "isHidden", info.isHidden());
BL(d, "isReadable", info.isReadable());
BL(d, "isRelative", info.isRelative());
BL(d, "isRoot", info.isRoot());
BL(d, "isSymLink", info.isSymLink());
BL(d, "isWritable", info.isWritable());
d.beginHash();
P(d, "name", "created");
P(d, "value", info.created().toString());
P(d, "valueencoded", "1");
P(d, "exp", "(("NSX"QFileInfo"NSY"*)" << d.data << ")->created()");
P(d, "type", NS"QDateTime");
P(d, "numchild", "1");
d.endHash();
d.beginHash();
P(d, "name", "lastModified");
P(d, "value", info.lastModified().toString());
P(d, "valueencoded", "1");
P(d, "exp", "(("NSX"QFileInfo"NSY"*)" << d.data << ")->lastModified()");
P(d, "type", NS"QDateTime");
P(d, "numchild", "1");
d.endHash();
d.beginHash();
P(d, "name", "lastRead");
P(d, "value", info.lastRead().toString());
P(d, "valueencoded", "1");
P(d, "exp", "(("NSX"QFileInfo"NSY"*)" << d.data << ")->lastRead()");
P(d, "type", NS"QDateTime");
P(d, "numchild", "1");
d.endHash();
d << "]";
}
d.disarm();
}
bool isOptimizedIntKey(const char *keyType)
{
return isEqual(keyType, "int")
#if defined(Q_BYTE_ORDER) && Q_BYTE_ORDER == Q_LITTLE_ENDIAN
|| isEqual(keyType, "short")
|| isEqual(keyType, "ushort")
#endif
|| isEqual(keyType, "uint");
}
int hashOffset(bool optimizedIntKey, bool forKey, unsigned keySize, unsigned valueSize)
{
// int-key optimization, small value
struct NodeOS { void *next; uint k; uint v; } nodeOS;
// int-key optimiatzion, large value
struct NodeOL { void *next; uint k; void *v; } nodeOL;
// no optimization, small value
struct NodeNS { void *next; uint h; uint k; uint v; } nodeNS;
// no optimization, large value
struct NodeNL { void *next; uint h; uint k; void *v; } nodeNL;
// complex key
struct NodeL { void *next; uint h; void *k; void *v; } nodeL;
if (forKey) {
// offsetof(...,...) not yet in Standard C++
const ulong nodeOSk ( (char *)&nodeOS.k - (char *)&nodeOS );
const ulong nodeOLk ( (char *)&nodeOL.k - (char *)&nodeOL );
const ulong nodeNSk ( (char *)&nodeNS.k - (char *)&nodeNS );
const ulong nodeNLk ( (char *)&nodeNL.k - (char *)&nodeNL );
const ulong nodeLk ( (char *)&nodeL.k - (char *)&nodeL );
if (optimizedIntKey)
return valueSize > sizeof(int) ? nodeOLk : nodeOSk;
if (keySize > sizeof(int))
return nodeLk;
return valueSize > sizeof(int) ? nodeNLk : nodeNSk;
} else {
const ulong nodeOSv ( (char *)&nodeOS.v - (char *)&nodeOS );
const ulong nodeOLv ( (char *)&nodeOL.v - (char *)&nodeOL );
const ulong nodeNSv ( (char *)&nodeNS.v - (char *)&nodeNS );
const ulong nodeNLv ( (char *)&nodeNL.v - (char *)&nodeNL );
const ulong nodeLv ( (char *)&nodeL.v - (char *)&nodeL );
if (optimizedIntKey)
return valueSize > sizeof(int) ? nodeOLv : nodeOSv;
if (keySize > sizeof(int))
return nodeLv;
return valueSize > sizeof(int) ? nodeNLv : nodeNSv;
}
}
static void qDumpQHash(QDumper &d)
{
QHashData *h = *reinterpret_cast<QHashData *const*>(d.data);
const char *keyType = d.templateParameters[0];
const char *valueType = d.templateParameters[1];
qCheckPointer(h->fakeNext);
qCheckPointer(h->buckets);
unsigned keySize = d.extraInt[0];
unsigned valueSize = d.extraInt[1];
int n = h->size;
if (n < 0)
qCheck(false);
if (n > 0) {
qCheckPointer(h->fakeNext);
qCheckPointer(*h->buckets);
}
P(d, "value", "<" << n << " items>");
P(d, "numchild", n);
if (d.dumpChildren) {
if (n > 1000)
n = 1000;
bool simpleKey = isShortKey(keyType);
bool simpleValue = isShortKey(valueType);
bool opt = isOptimizedIntKey(keyType);
int keyOffset = hashOffset(opt, true, keySize, valueSize);
int valueOffset = hashOffset(opt, false, keySize, valueSize);
P(d, "extra", "simplekey: " << simpleKey << " simpleValue: " << simpleValue
<< " keySize: " << keyOffset << " valueOffset: " << valueOffset
<< " opt: " << opt);
QHashData::Node *node = h->firstNode();
QHashData::Node *end = reinterpret_cast<QHashData::Node *>(h);
int i = 0;
d << ",children=[";
while (node != end) {
d.beginHash();
if (simpleKey) {
qDumpInnerValueHelper(d, keyType, addOffset(node, keyOffset), "name");
P(d, "nameisindex", "1");
if (simpleValue)
qDumpInnerValueHelper(d, valueType, addOffset(node, valueOffset));
P(d, "type", valueType);
P(d, "addr", addOffset(node, valueOffset));
} else {
P(d, "name", "[" << i << "]");
//P(d, "exp", "*(char*)" << node);
P(d, "exp", "*('"NS"QHashNode<" << keyType << "," << valueType << " >'*)" << node);
P(d, "type", "'"NS"QHashNode<" << keyType << "," << valueType << " >'");
}
d.endHash();
++i;
node = QHashData::nextNode(node);
}
d << "]";
}
d.disarm();
}
static void qDumpQHashNode(QDumper &d)
{
const QHashData *h = reinterpret_cast<const QHashData *>(d.data);
const char *keyType = d.templateParameters[0];
const char *valueType = d.templateParameters[1];
P(d, "value", "");
P(d, "numchild", 2);
if (d.dumpChildren) {
unsigned keySize = d.extraInt[0];
unsigned valueSize = d.extraInt[1];
bool opt = isOptimizedIntKey(keyType);
int keyOffset = hashOffset(opt, true, keySize, valueSize);
int valueOffset = hashOffset(opt, false, keySize, valueSize);
// there is a hash specialization in cast the key are integers or shorts
d << ",children=[";
d.beginHash();
P(d, "name", "key");
P(d, "type", keyType);
P(d, "addr", addOffset(h, keyOffset));
d.endHash();
d.beginHash();
P(d, "name", "value");
P(d, "type", valueType);
P(d, "addr", addOffset(h, valueOffset));
d.endHash();
d << "]";
}
d.disarm();
}
static void qDumpQImage(QDumper &d)
{
#ifdef QT_GUI_LIB
const QImage &im = *reinterpret_cast<const QImage *>(d.data);
P(d, "value", "(" << im.width() << "x" << im.height() << ")");
P(d, "type", NS"QImage");
P(d, "numchild", "0");
d.disarm();
#else
Q_UNUSED(d);
#endif
}
static void qDumpQList(QDumper &d)
{
// This uses the knowledge that QList<T> has only a single member
// of type union { QListData p; QListData::Data *d; };
const QListData &ldata = *reinterpret_cast<const QListData*>(d.data);
const QListData::Data *pdata =
*reinterpret_cast<const QListData::Data* const*>(d.data);
int nn = ldata.size();
if (nn < 0)
qCheck(false);
if (nn > 0) {
qCheckAccess(ldata.d->array);
//qCheckAccess(ldata.d->array[0]);
//qCheckAccess(ldata.d->array[nn - 1]);
#if QT_VERSION >= 0x040400
if (ldata.d->ref._q_value <= 0)
qCheck(false);
#endif
}
int n = nn;
P(d, "value", "<" << n << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", n);
P(d, "childtype", d.innertype);
if (d.dumpChildren) {
unsigned innerSize = d.extraInt[0];
bool innerTypeIsPointer = isPointerType(d.innertype);
QByteArray strippedInnerType = stripPointerType(d.innertype);
// The exact condition here is:
// QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic
// but this data is available neither in the compiled binary nor
// in the frontend.
// So as first approximation only do the 'isLarge' check:
bool isInternal = innerSize <= int(sizeof(void*))
&& isMovableType(d.innertype);
P(d, "internal", (int)isInternal);
P(d, "childtype", d.innertype);
if (n > 1000)
n = 1000;
d << ",children=[";
for (int i = 0; i != n; ++i) {
d.beginHash();
P(d, "name", "[" << i << "]");
if (innerTypeIsPointer) {
void *p = ldata.d->array + i + pdata->begin;
if (p) {
//P(d, "value","@" << p);
qDumpInnerValue(d, strippedInnerType.data(), deref(p));
} else {
P(d, "value", "<null>");
P(d, "numchild", "0");
}
} else {
void *p = ldata.d->array + i + pdata->begin;
if (isInternal) {
//qDumpInnerValue(d, d.innertype, p);
P(d, "addr", p);
qDumpInnerValueHelper(d, d.innertype, p);
} else {
//qDumpInnerValue(d, d.innertype, deref(p));
P(d, "addr", deref(p));
qDumpInnerValueHelper(d, d.innertype, deref(p));
}
}
d.endHash();
}
if (n < nn)
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpQLocale(QDumper &d)
{
const QLocale &locale = *reinterpret_cast<const QLocale *>(d.data);
P(d, "value", locale.name());
P(d, "valueencoded", "1");
P(d, "type", NS"QLocale");
P(d, "numchild", "8");
if (d.dumpChildren) {
d << ",children=[";
d.beginHash();
P(d, "name", "country");
P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->country()");
d.endHash();
d.beginHash();
P(d, "name", "language");
P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->language()");
d.endHash();
d.beginHash();
P(d, "name", "measurementSystem");
P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->measurementSystem()");
d.endHash();
d.beginHash();
P(d, "name", "numberOptions");
P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->numberOptions()");
d.endHash();
S(d, "timeFormat_(short)", locale.timeFormat(QLocale::ShortFormat));
S(d, "timeFormat_(long)", locale.timeFormat(QLocale::LongFormat));
QC(d, "decimalPoint", locale.decimalPoint());
QC(d, "exponential", locale.exponential());
QC(d, "percent", locale.percent());
QC(d, "zeroDigit", locale.zeroDigit());
QC(d, "groupSeparator", locale.groupSeparator());
QC(d, "negativeSign", locale.negativeSign());
d << "]";
}
d.disarm();
}
static void qDumpQMap(QDumper &d)
{
QMapData *h = *reinterpret_cast<QMapData *const*>(d.data);
const char *keyType = d.templateParameters[0];
const char *valueType = d.templateParameters[1];
int n = h->size;
if (n < 0)
qCheck(false);
if (n > 0) {
qCheckAccess(h->backward);
qCheckAccess(h->forward[0]);
qCheckPointer(h->backward->backward);
qCheckPointer(h->forward[0]->backward);
}
P(d, "value", "<" << n << " items>");
P(d, "numchild", n);
if (d.dumpChildren) {
if (n > 1000)
n = 1000;
//unsigned keySize = d.extraInt[0];
//unsigned valueSize = d.extraInt[1];
unsigned mapnodesize = d.extraInt[2];
unsigned valueOff = d.extraInt[3];
bool simpleKey = isShortKey(keyType);
bool simpleValue = isShortKey(valueType);
// both negative:
int keyOffset = 2 * sizeof(void*) - int(mapnodesize);
int valueOffset = 2 * sizeof(void*) - int(mapnodesize) + valueOff;
P(d, "extra", "simplekey: " << simpleKey << " simpleValue: " << simpleValue
<< " keyOffset: " << keyOffset << " valueOffset: " << valueOffset
<< " mapnodesize: " << mapnodesize);
d << ",children=[";
QMapData::Node *node = reinterpret_cast<QMapData::Node *>(h->forward[0]);
QMapData::Node *end = reinterpret_cast<QMapData::Node *>(h);
int i = 0;
while (node != end) {
d.beginHash();
if (simpleKey) {
P(d, "type", valueType);
qDumpInnerValueHelper(d, keyType, addOffset(node, keyOffset), "name");
P(d, "nameisindex", "1");
if (simpleValue)
qDumpInnerValueHelper(d, valueType, addOffset(node, valueOffset));
P(d, "type", valueType);
P(d, "addr", addOffset(node, valueOffset));
} else {
P(d, "name", "[" << i << "]");
P(d, "type", NS"QMapNode<" << keyType << "," << valueType << " >");
// actually, any type (even 'char') will do...
P(d, "exp", "*('"NS"QMapNode<" << keyType << "," << valueType << " >'*)" << node);
//P(d, "exp", "*('"NS"QMapData'*)" << (void*)node);
//P(d, "exp", "*(char*)" << (void*)node);
// P(d, "addr", node); does not work as gdb fails to parse
// e.g. &((*('"NS"QMapNode<QString,Foo>'*)0x616658))
}
d.endHash();
++i;
node = node->forward[0];
}
d << "]";
}
d.disarm();
}
static void qDumpQModelIndex(QDumper &d)
{
const QModelIndex *mi = reinterpret_cast<const QModelIndex *>(d.data);
P(d, "type", NS"QModelIndex");
if (mi->isValid()) {
P(d, "value", "(" << mi->row() << ", " << mi->column() << ")");
P(d, "numchild", 5);
if (d.dumpChildren) {
d << ",children=[";
I(d, "row", mi->row());
I(d, "column", mi->column());
d.beginHash();
P(d, "name", "parent");
const QModelIndex parent = mi->parent();
if (parent.isValid())
P(d, "value", "(" << mi->row() << ", " << mi->column() << ")");
else
P(d, "value", "<invalid>");
P(d, "exp", "(("NSX"QModelIndex"NSY"*)" << d.data << ")->parent()");
P(d, "type", NS"QModelIndex");
P(d, "numchild", "1");
d.endHash();
S(d, "internalId", QString::number(mi->internalId(), 10));
d.beginHash();
P(d, "name", "model");
P(d, "value", static_cast<const void *>(mi->model()));
P(d, "type", NS"QAbstractItemModel*");
P(d, "numchild", "1");
d.endHash();
d << "]";
}
} else {
P(d, "value", "<invalid>");
P(d, "numchild", 0);
}
d.disarm();
}
static void qDumpQMapNode(QDumper &d)
{
const QMapData *h = reinterpret_cast<const QMapData *>(d.data);
const char *keyType = d.templateParameters[0];
const char *valueType = d.templateParameters[1];
qCheckAccess(h->backward);
qCheckAccess(h->forward[0]);
P(d, "value", "");
P(d, "numchild", 2);
if (d.dumpChildren) {
//unsigned keySize = d.extraInt[0];
//unsigned valueSize = d.extraInt[1];
unsigned mapnodesize = d.extraInt[2];
unsigned valueOff = d.extraInt[3];
unsigned keyOffset = 2 * sizeof(void*) - mapnodesize;
unsigned valueOffset = 2 * sizeof(void*) - mapnodesize + valueOff;
d << ",children=[";
d.beginHash();
P(d, "name", "key");
qDumpInnerValue(d, keyType, addOffset(h, keyOffset));
d.endHash();
d.beginHash();
P(d, "name", "value");
qDumpInnerValue(d, valueType, addOffset(h, valueOffset));
d.endHash();
d << "]";
}
d.disarm();
}
static void qDumpQObject(QDumper &d)
{
const QObject *ob = reinterpret_cast<const QObject *>(d.data);
const QMetaObject *mo = ob->metaObject();
unsigned childrenOffset = d.extraInt[0];
P(d, "value", ob->objectName());
P(d, "valueencoded", "1");
P(d, "type", NS"QObject");
P(d, "displayedtype", mo->className());
P(d, "numchild", 4);
if (d.dumpChildren) {
const QObjectList &children = ob->children();
int slotCount = 0;
int signalCount = 0;
for (int i = mo->methodCount(); --i >= 0; ) {
QMetaMethod::MethodType mt = mo->method(i).methodType();
signalCount += (mt == QMetaMethod::Signal);
slotCount += (mt == QMetaMethod::Slot);
}
d << ",children=[";
d.beginHash();
P(d, "name", "properties");
// FIXME: Note that when simply using '(QObject*)'
// in the cast below, Gdb/MI _sometimes_ misparses
// expressions further down in the tree.
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "type", NS"QObjectPropertyList");
P(d, "value", "<" << mo->propertyCount() << " items>");
P(d, "numchild", mo->propertyCount());
d.endHash();
#if 0
d.beginHash();
P(d, "name", "methods");
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "value", "<" << mo->methodCount() << " items>");
P(d, "numchild", mo->methodCount());
d.endHash();
#endif
#if 0
d.beginHash();
P(d, "name", "senders");
P(d, "exp", "(*(class '"NS"QObjectPrivate'*)" << dfunc(ob) << ")->senders");
P(d, "type", NS"QList<"NS"QObjectPrivateSender>");
d.endHash();
#endif
#if PRIVATE_OBJECT_ALLOWED
d.beginHash();
P(d, "name", "signals");
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "type", NS"QObjectSignalList");
P(d, "value", "<" << signalCount << " items>");
P(d, "numchild", signalCount);
d.endHash();
d.beginHash();
P(d, "name", "slots");
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "type", NS"QObjectSlotList");
P(d, "value", "<" << slotCount << " items>");
P(d, "numchild", slotCount);
d.endHash();
#endif
d.beginHash();
P(d, "name", "children");
// works always, but causes additional traffic on the list
//P(d, "exp", "((class '"NS"QObject'*)" << d.data << ")->children()");
//
//P(d, "addr", addOffset(dfunc(ob), childrenOffset));
//P(d, "type", NS"QList<QObject *>");
//P(d, "value", "<" << children.size() << " items>");
qDumpInnerValue(d, NS"QList<"NS"QObject *>",
addOffset(dfunc(ob), childrenOffset));
P(d, "numchild", children.size());
d.endHash();
#if 0
// Unneeded (and not working): Connections are listes as childen
// of the signal or slot they are connected to.
// d.beginHash();
// P(d, "name", "connections");
// P(d, "exp", "*(*(class "NS"QObjectPrivate*)" << dfunc(ob) << ")->connectionLists");
// P(d, "type", NS"QVector<"NS"QList<"NS"QObjectPrivate::Connection> >");
// d.endHash();
#endif
#if 0
d.beginHash();
P(d, "name", "objectprivate");
P(d, "type", NS"QObjectPrivate");
P(d, "addr", dfunc(ob));
P(d, "value", "");
P(d, "numchild", "1");
d.endHash();
#endif
d.beginHash();
P(d, "name", "parent");
qDumpInnerValueHelper(d, NS"QObject *", ob->parent());
d.endHash();
#if 1
d.beginHash();
P(d, "name", "className");
P(d, "value",ob->metaObject()->className());
P(d, "type", "");
P(d, "numchild", "0");
d.endHash();
#endif
d << "]";
}
d.disarm();
}
static void qDumpQObjectPropertyList(QDumper &d)
{
const QObject *ob = (const QObject *)d.data;
const QMetaObject *mo = ob->metaObject();
P(d, "addr", "<synthetic>");
P(d, "type", NS"QObjectPropertyList");
P(d, "numchild", mo->propertyCount());
if (d.dumpChildren) {
d << ",children=[";
for (int i = mo->propertyCount(); --i >= 0; ) {
const QMetaProperty & prop = mo->property(i);
d.beginHash();
P(d, "name", prop.name());
P(d, "exp", "((" << mo->className() << "*)" << ob
<< ")->" << prop.name() << "()");
if (isEqual(prop.typeName(), "QString")) {
P(d, "value", prop.read(ob).toString());
P(d, "valueencoded", "1");
P(d, "type", NS"QString");
P(d, "numchild", "0");
} else if (isEqual(prop.typeName(), "bool")) {
P(d, "value", (prop.read(ob).toBool() ? "true" : "false"));
P(d, "numchild", "0");
} else if (isEqual(prop.typeName(), "int")) {
P(d, "value", prop.read(ob).toInt());
P(d, "numchild", "0");
}
P(d, "type", prop.typeName());
P(d, "numchild", "1");
d.endHash();
}
d << "]";
}
d.disarm();
}
static void qDumpQObjectMethodList(QDumper &d)
{
const QObject *ob = (const QObject *)d.data;
const QMetaObject *mo = ob->metaObject();
P(d, "addr", "<synthetic>");
P(d, "type", NS"QObjectMethodList");
P(d, "numchild", mo->methodCount());
P(d, "childtype", "QMetaMethod::Method");
P(d, "childnumchild", "0");
if (d.dumpChildren) {
d << ",children=[";
for (int i = 0; i != mo->methodCount(); ++i) {
const QMetaMethod & method = mo->method(i);
int mt = method.methodType();
d.beginHash();
P(d, "name", "[" << i << "] " << mo->indexOfMethod(method.signature())
<< " " << method.signature());
P(d, "value", (mt == QMetaMethod::Signal ? "<Signal>" : "<Slot>") << " (" << mt << ")");
d.endHash();
}
d << "]";
}
d.disarm();
}
#if PRIVATE_OBJECT_ALLOWED
const char * qConnectionTypes[] ={
"auto",
"direct",
"queued",
"autocompat",
"blockingqueued"
};
#if QT_VERSION >= 0x040400
static const QObjectPrivate::ConnectionList &qConnectionList(const QObject *ob, int signalNumber)
{
static const QObjectPrivate::ConnectionList emptyList;
const QObjectPrivate *p = reinterpret_cast<const QObjectPrivate *>(dfunc(ob));
if (!p->connectionLists)
return emptyList;
typedef QVector<QObjectPrivate::ConnectionList> ConnLists;
const ConnLists *lists = reinterpret_cast<const ConnLists *>(p->connectionLists);
// there's an optimization making the lists only large enough to hold the
// last non-empty item
if (signalNumber >= lists->size())
return emptyList;
return lists->at(signalNumber);
}
#endif
static void qDumpQObjectSignal(QDumper &d)
{
unsigned signalNumber = d.extraInt[0];
P(d, "addr", "<synthetic>");
P(d, "numchild", "1");
P(d, "type", NS"QObjectSignal");
#if QT_VERSION >= 0x040400
if (d.dumpChildren) {
const QObject *ob = reinterpret_cast<const QObject *>(d.data);
d << ",children=[";
const QObjectPrivate::ConnectionList &connList = qConnectionList(ob, signalNumber);
for (int i = 0; i != connList.size(); ++i) {
const QObjectPrivate::Connection &conn = connList.at(i);
d.beginHash();
P(d, "name", "[" << i << "] receiver");
qDumpInnerValueHelper(d, NS"QObject *", conn.receiver);
d.endHash();
d.beginHash();
P(d, "name", "[" << i << "] slot");
P(d, "type", "");
if (conn.receiver)
P(d, "value", conn.receiver->metaObject()->method(conn.method).signature());
else
P(d, "value", "<invalid receiver>");
P(d, "numchild", "0");
d.endHash();
d.beginHash();
P(d, "name", "[" << i << "] type");
P(d, "type", "");
P(d, "value", "<" << qConnectionTypes[conn.method] << " connection>");
P(d, "numchild", "0");
d.endHash();
}
d << "]";
P(d, "numchild", connList.size());
}
#endif
d.disarm();
}
static void qDumpQObjectSignalList(QDumper &d)
{
const QObject *ob = reinterpret_cast<const QObject *>(d.data);
const QMetaObject *mo = ob->metaObject();
int count = 0;
for (int i = mo->methodCount(); --i >= 0; )
count += (mo->method(i).methodType() == QMetaMethod::Signal);
P(d, "addr", d.data);
P(d, "numchild", count);
#if QT_VERSION >= 0x040400
if (d.dumpChildren) {
d << ",children=[";
for (int i = 0; i != mo->methodCount(); ++i) {
const QMetaMethod & method = mo->method(i);
if (method.methodType() == QMetaMethod::Signal) {
int k = mo->indexOfSignal(method.signature());
const QObjectPrivate::ConnectionList &connList = qConnectionList(ob, k);
d.beginHash();
P(d, "name", "[" << k << "]");
P(d, "value", method.signature());
P(d, "numchild", connList.size());
//P(d, "numchild", "1");
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "type", NS"QObjectSignal");
d.endHash();
}
}
d << "]";
}
#endif
d.disarm();
}
static void qDumpQObjectSlot(QDumper &d)
{
int slotNumber = d.extraInt[0];
P(d, "addr", d.data);
P(d, "numchild", "1");
P(d, "type", NS"QObjectSlot");
#if QT_VERSION >= 0x040400
if (d.dumpChildren) {
d << ",children=[";
int numchild = 0;
const QObject *ob = reinterpret_cast<const QObject *>(d.data);
const QObjectPrivate *p = reinterpret_cast<const QObjectPrivate *>(dfunc(ob));
for (int s = 0; s != p->senders.size(); ++s) {
const QObjectPrivate::Sender &sender = p->senders.at(s);
const QObjectPrivate::ConnectionList &connList
= qConnectionList(sender.sender, sender.signal);
for (int i = 0; i != connList.size(); ++i) {
const QObjectPrivate::Connection &conn = connList.at(i);
if (conn.receiver == ob && conn.method == slotNumber) {
++numchild;
const QMetaMethod & method =
sender.sender->metaObject()->method(sender.signal);
d.beginHash();
P(d, "name", "[" << s << "] sender");
qDumpInnerValueHelper(d, NS"QObject *", sender.sender);
d.endHash();
d.beginHash();
P(d, "name", "[" << s << "] signal");
P(d, "type", "");
P(d, "value", method.signature());
P(d, "numchild", "0");
d.endHash();
d.beginHash();
P(d, "name", "[" << s << "] type");
P(d, "type", "");
P(d, "value", "<" << qConnectionTypes[conn.method] << " connection>");
P(d, "numchild", "0");
d.endHash();
}
}
}
d << "]";
P(d, "numchild", numchild);
}
#endif
d.disarm();
}
static void qDumpQObjectSlotList(QDumper &d)
{
const QObject *ob = reinterpret_cast<const QObject *>(d.data);
#if QT_VERSION >= 0x040400
const QObjectPrivate *p = reinterpret_cast<const QObjectPrivate *>(dfunc(ob));
#endif
const QMetaObject *mo = ob->metaObject();
int count = 0;
for (int i = mo->methodCount(); --i >= 0; )
count += (mo->method(i).methodType() == QMetaMethod::Slot);
P(d, "addr", d.data);
P(d, "numchild", count);
#if QT_VERSION >= 0x040400
if (d.dumpChildren) {
d << ",children=[";
for (int i = 0; i != mo->methodCount(); ++i) {
const QMetaMethod & method = mo->method(i);
if (method.methodType() == QMetaMethod::Slot) {
d.beginHash();
int k = mo->indexOfSlot(method.signature());
P(d, "name", "[" << k << "]");
P(d, "value", method.signature());
// count senders. expensive...
int numchild = 0;
for (int s = 0; s != p->senders.size(); ++s) {
const QObjectPrivate::Sender & sender = p->senders.at(s);
const QObjectPrivate::ConnectionList &connList
= qConnectionList(sender.sender, sender.signal);
for (int c = 0; c != connList.size(); ++c) {
const QObjectPrivate::Connection &conn = connList.at(c);
if (conn.receiver == ob && conn.method == k)
++numchild;
}
}
P(d, "numchild", numchild);
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "type", NS"QObjectSlot");
d.endHash();
}
}
d << "]";
}
#endif
d.disarm();
}
#endif // PRIVATE_OBJECT_ALLOWED
static void qDumpQPixmap(QDumper &d)
{
#ifdef QT_GUI_LIB
const QPixmap &im = *reinterpret_cast<const QPixmap *>(d.data);
P(d, "value", "(" << im.width() << "x" << im.height() << ")");
P(d, "type", NS"QPixmap");
P(d, "numchild", "0");
d.disarm();
#else
Q_UNUSED(d);
#endif
}
static void qDumpQSet(QDumper &d)
{
// This uses the knowledge that QHash<T> has only a single member
// of union { QHashData *d; QHashNode<Key, T> *e; };
QHashData *hd = *(QHashData**)d.data;
QHashData::Node *node = hd->firstNode();
int n = hd->size;
if (n < 0)
qCheck(false);
if (n > 0) {
qCheckAccess(node);
qCheckPointer(node->next);
}
P(d, "value", "<" << n << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", 2 * n);
if (d.dumpChildren) {
if (n > 100)
n = 100;
d << ",children=[";
int i = 0;
for (int bucket = 0; bucket != hd->numBuckets && i <= 10000; ++bucket) {
for (node = hd->buckets[bucket]; node->next; node = node->next) {
d.beginHash();
P(d, "name", "[" << i << "]");
P(d, "type", d.innertype);
P(d, "exp", "(('"NS"QHashNode<" << d.innertype
<< ","NS"QHashDummyValue>'*)"
<< static_cast<const void*>(node) << ")->key"
);
d.endHash();
++i;
if (i > 10000) {
d.putEllipsis();
break;
}
}
}
d << "]";
}
d.disarm();
}
static void qDumpQString(QDumper &d)
{
const QString &str = *reinterpret_cast<const QString *>(d.data);
if (!str.isEmpty()) {
qCheckAccess(str.unicode());
qCheckAccess(str.unicode() + str.size());
}
P(d, "value", str);
P(d, "valueencoded", "1");
P(d, "type", NS"QString");
//P(d, "editvalue", str); // handled generically below
P(d, "numchild", "0");
d.disarm();
}
static void qDumpQStringList(QDumper &d)
{
const QStringList &list = *reinterpret_cast<const QStringList *>(d.data);
int n = list.size();
if (n < 0)
qCheck(false);
if (n > 0) {
qCheckAccess(&list.front());
qCheckAccess(&list.back());
}
P(d, "value", "<" << n << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", n);
P(d, "childtype", NS"QString");
P(d, "childnumchild", "0");
if (d.dumpChildren) {
if (n > 1000)
n = 1000;
d << ",children=[";
for (int i = 0; i != n; ++i) {
d.beginHash();
P(d, "name", "[" << i << "]");
P(d, "value", list[i]);
P(d, "valueencoded", "1");
d.endHash();
}
if (n < list.size())
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpQTextCodec(QDumper &d)
{
const QTextCodec &codec = *reinterpret_cast<const QTextCodec *>(d.data);
P(d, "value", codec.name());
P(d, "valueencoded", "1");
P(d, "type", NS"QTextCodec");
P(d, "numchild", "2");
if (d.dumpChildren) {
d << ",children=[";
S(d, "name", codec.name());
I(d, "mibEnum", codec.mibEnum());
d << "]";
}
d.disarm();
}
static void qDumpQVariantHelper(const void *data, QString *value,
QString *exp, int *numchild)
{
const QVariant &v = *reinterpret_cast<const QVariant *>(data);
switch (v.type()) {
case QVariant::Invalid:
*value = QLatin1String("<invalid>");
*numchild = 0;
break;
case QVariant::String:
*value = QLatin1Char('"') + v.toString() + QLatin1Char('"');
*numchild = 0;
break;
case QVariant::StringList:
*exp = QString(QLatin1String("((QVariant*)%1)->d.data.c"))
.arg((quintptr)data);
*numchild = v.toStringList().size();
break;
case QVariant::Int:
*value = QString::number(v.toInt());
*numchild= 0;
break;
case QVariant::Double:
*value = QString::number(v.toDouble());
*numchild = 0;
break;
default: {
char buf[1000];
const char *format = (v.typeName()[0] == 'Q')
? "'"NS"%s "NS"qVariantValue<"NS"%s >'(*('"NS"QVariant'*)%p)"
: "'%s "NS"qVariantValue<%s >'(*('"NS"QVariant'*)%p)";
qsnprintf(buf, sizeof(buf) - 1, format, v.typeName(), v.typeName(), data);
*exp = QLatin1String(buf);
*numchild = 1;
break;
}
}
}
static void qDumpQVariant(QDumper &d)
{
const QVariant &v = *reinterpret_cast<const QVariant *>(d.data);
QString value;
QString exp;
int numchild = 0;
qDumpQVariantHelper(d.data, &value, &exp, &numchild);
bool isInvalid = (v.typeName() == 0);
if (isInvalid) {
P(d, "value", "(invalid)");
} else if (value.isEmpty()) {
P(d, "value", "(" << v.typeName() << ") " << qPrintable(value));
} else {
QByteArray ba;
ba += '(';
ba += v.typeName();
ba += ") ";
ba += qPrintable(value);
P(d, "value", ba);
P(d, "valueencoded", "1");
}
P(d, "type", NS"QVariant");
P(d, "numchild", (isInvalid ? "0" : "1"));
if (d.dumpChildren) {
d << ",children=[";
d.beginHash();
P(d, "name", "value");
if (!exp.isEmpty())
P(d, "exp", qPrintable(exp));
if (!value.isEmpty()) {
P(d, "value", value);
P(d, "valueencoded", "1");
}
P(d, "type", v.typeName());
P(d, "numchild", numchild);
d.endHash();
d << "]";
}
d.disarm();
}
static void qDumpQVector(QDumper &d)
{
QVectorData *v = *reinterpret_cast<QVectorData *const*>(d.data);
// Try to provoke segfaults early to prevent the frontend
// from asking for unavailable child details
int nn = v->size;
if (nn < 0)
qCheck(false);
if (nn > 0) {
//qCheckAccess(&vec.front());
//qCheckAccess(&vec.back());
}
unsigned innersize = d.extraInt[0];
unsigned typeddatasize = d.extraInt[1];
int n = nn;
P(d, "value", "<" << n << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", n);
if (d.dumpChildren) {
QByteArray strippedInnerType = stripPointerType(d.innertype);
const char *stripped =
isPointerType(d.innertype) ? strippedInnerType.data() : 0;
if (n > 1000)
n = 1000;
d << ",children=[";
for (int i = 0; i != n; ++i) {
d.beginHash();
P(d, "name", "[" << i << "]");
qDumpInnerValueOrPointer(d, d.innertype, stripped,
addOffset(v, i * innersize + typeddatasize));
d.endHash();
}
if (n < nn)
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpStdList(QDumper &d)
{
const std::list<int> &list = *reinterpret_cast<const std::list<int> *>(d.data);
const void *p = d.data;
qCheckAccess(p);
p = deref(p);
qCheckAccess(p);
p = deref(p);
qCheckAccess(p);
p = deref(addOffset(d.data, sizeof(void*)));
qCheckAccess(p);
p = deref(addOffset(p, sizeof(void*)));
qCheckAccess(p);
p = deref(addOffset(p, sizeof(void*)));
qCheckAccess(p);
int nn = 0;
std::list<int>::const_iterator it = list.begin();
for (; nn < 101 && it != list.end(); ++nn, ++it)
qCheckAccess(it.operator->());
if (nn > 100)
P(d, "value", "<more than 100 items>");
else
P(d, "value", "<" << nn << " items>");
P(d, "numchild", nn);
P(d, "valuedisabled", "true");
if (d.dumpChildren) {
QByteArray strippedInnerType = stripPointerType(d.innertype);
const char *stripped =
isPointerType(d.innertype) ? strippedInnerType.data() : 0;
d << ",children=[";
it = list.begin();
for (int i = 0; i < 1000 && it != list.end(); ++i, ++it) {
d.beginHash();
P(d, "name", "[" << i << "]");
qDumpInnerValueOrPointer(d, d.innertype, stripped, it.operator->());
d.endHash();
}
if (it != list.end())
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpStdMap(QDumper &d)
{
typedef std::map<int, int> DummyType;
const DummyType &map = *reinterpret_cast<const DummyType*>(d.data);
const char *keyType = d.templateParameters[0];
const char *valueType = d.templateParameters[1];
const void *p = d.data;
qCheckAccess(p);
p = deref(p);
int nn = map.size();
qCheck(nn >= 0);
DummyType::const_iterator it = map.begin();
for (int i = 0; i < nn && i < 10 && it != map.end(); ++i, ++it)
qCheckAccess(it.operator->());
QByteArray strippedInnerType = stripPointerType(d.innertype);
P(d, "numchild", nn);
P(d, "value", "<" << nn << " items>");
P(d, "valuedisabled", "true");
P(d, "valueoffset", d.extraInt[2]);
if (d.dumpChildren) {
bool simpleKey = isSimpleType(keyType);
bool simpleValue = isShortKey(valueType);
int valueOffset = d.extraInt[2];
d << ",children=[";
it = map.begin();
for (int i = 0; i < 1000 && it != map.end(); ++i, ++it) {
const void *node = it.operator->();
if (simpleKey) {
d.beginHash();
P(d, "type", valueType);
qDumpInnerValueHelper(d, keyType, node, "name");
P(d, "nameisindex", "1");
if (simpleValue)
qDumpInnerValueHelper(d, valueType, addOffset(node, valueOffset));
P(d, "addr", addOffset(node, valueOffset));
d.endHash();
} else {
d.beginHash();
P(d, "name", "[" << i << "]");
P(d, "addr", it.operator->());
P(d, "type", "std::pair<const " << keyType << "," << valueType << " >");
d.endHash();
}
}
if (it != map.end())
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpStdString(QDumper &d)
{
const std::string &str = *reinterpret_cast<const std::string *>(d.data);
if (!str.empty()) {
qCheckAccess(str.c_str());
qCheckAccess(str.c_str() + str.size() - 1);
}
d << ",value=\"";
d.putBase64Encoded(str.c_str(), str.size());
d << "\"";
P(d, "valueencoded", "1");
P(d, "type", "std::string");
P(d, "numchild", "0");
d.disarm();
}
static void qDumpStdWString(QDumper &d)
{
const std::wstring &str = *reinterpret_cast<const std::wstring *>(d.data);
if (!str.empty()) {
qCheckAccess(str.c_str());
qCheckAccess(str.c_str() + str.size() - 1);
}
d << "value=\"";
d.putBase64Encoded((const char *)str.c_str(), str.size() * sizeof(wchar_t));
d << "\"";
P(d, "valueencoded", (sizeof(wchar_t) == 2 ? "2" : "3"));
P(d, "type", "std::wstring");
P(d, "numchild", "0");
d.disarm();
}
static void qDumpStdVector(QDumper &d)
{
// Correct type would be something like:
// std::_Vector_base<int,std::allocator<int, std::allocator<int> >>::_Vector_impl
struct VectorImpl {
char *start;
char *finish;
char *end_of_storage;
};
const VectorImpl *v = static_cast<const VectorImpl *>(d.data);
// Try to provoke segfaults early to prevent the frontend
// from asking for unavailable child details
int nn = (v->finish - v->start) / d.extraInt[0];
if (nn < 0)
qCheck(false);
if (nn > 0) {
qCheckAccess(v->start);
qCheckAccess(v->finish);
qCheckAccess(v->end_of_storage);
}
int n = nn;
P(d, "value", "<" << n << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", n);
if (d.dumpChildren) {
unsigned innersize = d.extraInt[0];
QByteArray strippedInnerType = stripPointerType(d.innertype);
const char *stripped =
isPointerType(d.innertype) ? strippedInnerType.data() : 0;
if (n > 1000)
n = 1000;
d << ",children=[";
for (int i = 0; i != n; ++i) {
d.beginHash();
P(d, "name", "[" << i << "]");
qDumpInnerValueOrPointer(d, d.innertype, stripped,
addOffset(v->start, i * innersize));
d.endHash();
}
if (n < nn)
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpStdVectorBool(QDumper &d)
{
// FIXME
return qDumpStdVector(d);
}
static void handleProtocolVersion2and3(QDumper & d)
{
if (!d.outertype[0]) {
qDumpUnknown(d);
return;
}
d.setupTemplateParameters();
P(d, "iname", d.iname);
P(d, "addr", d.data);
#ifdef QT_NO_QDATASTREAM
if (d.protocolVersion == 3) {
QVariant::Type type = QVariant::nameToType(d.outertype);
if (type != QVariant::Invalid) {
QVariant v(type, d.data);
QByteArray ba;
QDataStream ds(&ba, QIODevice::WriteOnly);
ds << v;
P(d, "editvalue", ba);
}
}
#endif
const char *type = stripNamespace(d.outertype);
// type[0] is usally 'Q', so don't use it
switch (type[1]) {
case 'B':
if (isEqual(type, "QByteArray"))
qDumpQByteArray(d);
break;
case 'D':
if (isEqual(type, "QDateTime"))
qDumpQDateTime(d);
else if (isEqual(type, "QDir"))
qDumpQDir(d);
break;
case 'F':
if (isEqual(type, "QFile"))
qDumpQFile(d);
else if (isEqual(type, "QFileInfo"))
qDumpQFileInfo(d);
break;
case 'H':
if (isEqual(type, "QHash"))
qDumpQHash(d);
else if (isEqual(type, "QHashNode"))
qDumpQHashNode(d);
break;
case 'I':
if (isEqual(type, "QImage"))
qDumpQImage(d);
break;
case 'L':
if (isEqual(type, "QList"))
qDumpQList(d);
else if (isEqual(type, "QLocale"))
qDumpQLocale(d);
break;
case 'M':
if (isEqual(type, "QMap"))
qDumpQMap(d);
else if (isEqual(type, "QMapNode"))
qDumpQMapNode(d);
else if (isEqual(type, "QModelIndex"))
qDumpQModelIndex(d);
break;
case 'O':
if (isEqual(type, "QObject"))
qDumpQObject(d);
else if (isEqual(type, "QObjectPropertyList"))
qDumpQObjectPropertyList(d);
else if (isEqual(type, "QObjectMethodList"))
qDumpQObjectMethodList(d);
#if PRIVATE_OBJECT_ALLOWED
else if (isEqual(type, "QObjectSignal"))
qDumpQObjectSignal(d);
else if (isEqual(type, "QObjectSignalList"))
qDumpQObjectSignalList(d);
else if (isEqual(type, "QObjectSlot"))
qDumpQObjectSlot(d);
else if (isEqual(type, "QObjectSlotList"))
qDumpQObjectSlotList(d);
#endif
break;
case 'P':
if (isEqual(type, "QPixmap"))
qDumpQPixmap(d);
break;
case 'S':
if (isEqual(type, "QSet"))
qDumpQSet(d);
else if (isEqual(type, "QString"))
qDumpQString(d);
else if (isEqual(type, "QStringList"))
qDumpQStringList(d);
break;
case 'T':
if (isEqual(type, "QTextCodec"))
qDumpQTextCodec(d);
break;
case 'V':
if (isEqual(type, "QVariant"))
qDumpQVariant(d);
else if (isEqual(type, "QVector"))
qDumpQVector(d);
break;
case 's':
if (isEqual(type, "wstring"))
qDumpStdWString(d);
break;
case 't':
if (isEqual(type, "std::vector"))
qDumpStdVector(d);
else if (isEqual(type, "std::vector::bool"))
qDumpStdVectorBool(d);
else if (isEqual(type, "std::list"))
qDumpStdList(d);
else if (isEqual(type, "std::map"))
qDumpStdMap(d);
else if (isEqual(type, "std::string") || isEqual(type, "string"))
qDumpStdString(d);
else if (isEqual(type, "std::wstring"))
qDumpStdWString(d);
break;
}
if (!d.success)
qDumpUnknown(d);
}
} // anonymous namespace
extern "C" Q_DECL_EXPORT
void qDumpObjectData440(
int protocolVersion,
int token,
void *data,
bool dumpChildren,
int extraInt0,
int extraInt1,
int extraInt2,
int extraInt3)
{
if (protocolVersion == 1) {
QDumper d;
d.protocolVersion = protocolVersion;
d.token = token;
//qDebug() << "SOCKET: after connect: state: " << qDumperSocket.state();
// simpledumpers is a list of all available dumpers that are
// _not_ templates. templates currently require special
// hardcoded handling in the debugger plugin.
// don't mention them here in this list
d << "simpledumpers=["
"\""NS"QByteArray\","
"\""NS"QDir\","
"\""NS"QImage\","
"\""NS"QFile\","
"\""NS"QFileInfo\","
"\""NS"QLocale\","
"\""NS"QModelIndex\","
//"\""NS"QHash\"," // handled on GH side
//"\""NS"QHashNode\","
//"\""NS"QMap\"," // handled on GH side
//"\""NS"QMapNode\","
"\""NS"QObject\","
"\""NS"QObjectMethodList\"," // hack to get nested properties display
"\""NS"QObjectPropertyList\","
#if PRIVATE_OBJECT_ALLOWED
"\""NS"QObjectSignal\","
"\""NS"QObjectSignalList\","
"\""NS"QObjectSlot\","
"\""NS"QObjectSlotList\","
#endif // PRIVATE_OBJECT_ALLOWED
"\""NS"QString\","
"\""NS"QStringList\","
"\""NS"QTextCodec\","
"\""NS"QVariant\","
"\""NS"QWidget\","
"\""NS"QDateTime\","
"\"string\","
"\"wstring\","
"\"std::string\","
"\"std::wstring\","
// << "\""NS"QRegion\","
"]";
d << ",namespace=\""NS"\"";
d.disarm();
}
else if (protocolVersion == 2 || protocolVersion == 3) {
QDumper d;
d.protocolVersion = protocolVersion;
d.token = token;
d.data = data;
d.dumpChildren = dumpChildren;
d.extraInt[0] = extraInt0;
d.extraInt[1] = extraInt1;
d.extraInt[2] = extraInt2;
d.extraInt[3] = extraInt3;
const char *inbuffer = qDumpInBuffer;
d.outertype = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer;
d.iname = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer;
d.exp = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer;
d.innertype = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer;
d.iname = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer;
handleProtocolVersion2and3(d);
}
else {
qDebug() << "Unsupported protocol version" << protocolVersion;
}
}
| 30.595762
| 103
| 0.511683
|
frooms
|
ca295e08afd4609bcc6a6effd632ed99c3f59b55
| 20,490
|
cpp
|
C++
|
samples/luxcoreui/uimenu.cpp
|
LuxRender/LuxRays
|
edb001ddeb744b534f6fe98c7b789d4635196718
|
[
"Apache-2.0"
] | null | null | null |
samples/luxcoreui/uimenu.cpp
|
LuxRender/LuxRays
|
edb001ddeb744b534f6fe98c7b789d4635196718
|
[
"Apache-2.0"
] | null | null | null |
samples/luxcoreui/uimenu.cpp
|
LuxRender/LuxRays
|
edb001ddeb744b534f6fe98c7b789d4635196718
|
[
"Apache-2.0"
] | null | null | null |
/***************************************************************************
* Copyright 1998-2017 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxRender. *
* *
* 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 <imgui.h>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <nfd.h>
#include "luxcoreapp.h"
using namespace std;
using namespace luxrays;
using namespace luxcore;
//------------------------------------------------------------------------------
// MenuRendering
//------------------------------------------------------------------------------
#if !defined(LUXRAYS_DISABLE_OPENCL)
static void KernelCacheFillProgressHandler(const size_t step, const size_t count) {
LA_LOG("KernelCache FillProgressHandler Step: " << step << "/" << count);
}
#endif
void LuxCoreApp::MenuRendering() {
if (ImGui::MenuItem("Load")) {
nfdchar_t *fileFileName = NULL;
nfdresult_t result = NFD_OpenDialog("cfg;lxs", NULL, &fileFileName);
if (result == NFD_OKAY) {
LoadRenderConfig(fileFileName);
free(fileFileName);
}
}
if (session && ImGui::MenuItem("Export")) {
nfdchar_t *outPath = NULL;
nfdresult_t result = NFD_SaveDialog(NULL, NULL, &outPath);
if (result == NFD_OKAY) {
LA_LOG("Export current scene to directory: " << outPath);
boost::filesystem::path dir(outPath);
boost::filesystem::create_directories(dir);
// Save the current render engine
const string renderEngine = config->GetProperty("renderengine.type").Get<string>();
// Set the render engine to FILESAVER
RenderConfigParse(Properties() <<
Property("renderengine.type")("FILESAVER") <<
Property("filesaver.directory")(outPath) <<
Property("filesaver.renderengine.type")(renderEngine));
// Restore the render engine setting
RenderConfigParse(Properties() <<
Property("renderengine.type")(renderEngine));
}
}
ImGui::Separator();
// Simplified save/resume rendering method: uses predefined names
const string saveResumeName = "current";
if (session && ImGui::MenuItem("Save rendering (simplified)")) {
// Pause the current rendering
session->Pause();
// Save the film
session->GetFilm().SaveFilm(saveResumeName + ".flm");
// Save the render state
RenderState *renderState = session->GetRenderState();
renderState->Save(saveResumeName + ".rst");
delete renderState;
// Resume the current rendering
session->Resume();
}
if (ImGui::MenuItem("Resume rendering (simplified)")) {
// Select the scene
nfdchar_t *sceneFileName = NULL;
nfdresult_t result = NFD_OpenDialog("cfg;lxs", NULL, &sceneFileName);
if (result == NFD_OKAY) {
// Load the start film
Film *startFilm = Film::Create(saveResumeName + ".flm");
// Load the start render state
RenderState *startRenderState = RenderState::Create(saveResumeName + ".rst");
LoadRenderConfig(sceneFileName, startRenderState, startFilm);
free(sceneFileName);
}
}
// Normal saving rendering method: requires to select multiple file names
if (session && ImGui::MenuItem("Save rendering")) {
nfdchar_t *outName = NULL;
nfdresult_t result = NFD_SaveDialog(NULL, NULL, &outName);
if (result == NFD_OKAY) {
// Pause the current rendering
session->Pause();
// Save the film
session->GetFilm().SaveFilm(string(outName) + ".flm");
// Save the render state
RenderState *renderState = session->GetRenderState();
renderState->Save(string(outName) + ".rst");
delete renderState;
// Resume the current rendering
session->Resume();
}
}
if (ImGui::MenuItem("Resume rendering")) {
// Select the scene
nfdchar_t *sceneFileName = NULL;
nfdresult_t result = NFD_OpenDialog("cfg;lxs", NULL, &sceneFileName);
if (result == NFD_OKAY) {
// Select the film
nfdchar_t *filmFileName = NULL;
result = NFD_OpenDialog("flm", NULL, &filmFileName);
if (result == NFD_OKAY) {
// Select the render state
nfdchar_t *renderStateFileName = NULL;
result = NFD_OpenDialog("rst", NULL, &renderStateFileName);
if (result == NFD_OKAY) {
// Load the start film
Film *startFilm = Film::Create(filmFileName);
// Load the start render state
RenderState *startRenderState = RenderState::Create(renderStateFileName);
LoadRenderConfig(sceneFileName, startRenderState, startFilm);
free(renderStateFileName);
}
free(filmFileName);
}
free(sceneFileName);
}
// Film *startFilm = new Film("aa.flm");
// RenderState *startRenderState = new RenderState("aa.rst");
// LoadRenderConfig("scenes/luxball/luxball-hdr.cfg", startRenderState, startFilm);
}
ImGui::Separator();
if (session) {
if (session->IsInPause()) {
if (ImGui::MenuItem("Resume"))
session->Resume();
} else {
if (ImGui::MenuItem("Pause"))
session->Pause();
}
if (ImGui::MenuItem("Cancel"))
DeleteRendering();
if (session && ImGui::MenuItem("Restart", "Space bar")) {
// Restart rendering
session->Stop();
session->Start();
}
ImGui::Separator();
}
#if !defined(LUXRAYS_DISABLE_OPENCL)
if (ImGui::MenuItem("Fill kernel cache")) {
if (session) {
// Stop any current rendering
DeleteRendering();
}
Properties props;
/*props <<
Property("opencl.devices.select")("010") <<
Property("opencl.code.alwaysenabled")(
"MATTE MIRROR GLASS ARCHGLASS MATTETRANSLUCENT GLOSSY2 "
"METAL2 ROUGHGLASS ROUGHMATTE ROUGHMATTETRANSLUCENT "
"GLOSSYTRANSLUCENT "
"GLOSSY2_ABSORPTION GLOSSY2_MULTIBOUNCE "
"HOMOGENEOUS_VOL CLEAR_VOL "
"IMAGEMAPS_BYTE_FORMAT IMAGEMAPS_HALF_FORMAT "
"IMAGEMAPS_1xCHANNELS IMAGEMAPS_3xCHANNELS "
"HAS_BUMPMAPS "
"INFINITE TRIANGLELIGHT") <<
Property("kernelcachefill.renderengine.types")("PATHOCL") <<
Property("kernelcachefill.sampler.types")("SOBOL") <<
Property("kernelcachefill.camera.types")("perspective") <<
Property("kernelcachefill.light.types")("infinite", "trianglelight") <<
Property("kernelcachefill.texture.types")("checkerboard2d", "checkerboard3d");*/
KernelCacheFill(props, KernelCacheFillProgressHandler);
}
ImGui::Separator();
#endif
if (ImGui::MenuItem("Quit", "ESC"))
glfwSetWindowShouldClose(window, GL_TRUE);
}
//------------------------------------------------------------------------------
// MenuEngine
//------------------------------------------------------------------------------
void LuxCoreApp::MenuEngine() {
const string currentEngineType = config->ToProperties().Get("renderengine.type").Get<string>();
if (ImGui::MenuItem("PATHOCL", "1", (currentEngineType == "PATHOCL"))) {
SetRenderingEngineType("PATHOCL");
CloseAllRenderConfigEditors();
}
if (ImGui::MenuItem("LIGHTCPU", "2", (currentEngineType == "LIGHTCPU"))) {
SetRenderingEngineType("LIGHTCPU");
CloseAllRenderConfigEditors();
}
if (ImGui::MenuItem("PATHCPU", "3", (currentEngineType == "PATHCPU"))) {
SetRenderingEngineType("PATHCPU");
CloseAllRenderConfigEditors();
}
if (ImGui::MenuItem("BIDIRCPU", "4", (currentEngineType == "BIDIRCPU"))) {
SetRenderingEngineType("BIDIRCPU");
CloseAllRenderConfigEditors();
}
if (ImGui::MenuItem("BIDIRVMCPU", "5", (currentEngineType == "BIDIRVMCPU"))) {
SetRenderingEngineType("BIDIRVMCPU");
CloseAllRenderConfigEditors();
}
#if !defined(LUXRAYS_DISABLE_OPENCL)
if (ImGui::MenuItem("RTPATHOCL", "6", (currentEngineType == "RTPATHOCL"))) {
SetRenderingEngineType("RTPATHOCL");
CloseAllRenderConfigEditors();
}
#endif
if (ImGui::MenuItem("TILEPATHCPU", "7", (currentEngineType == "TILEPATHCPU"))) {
SetRenderingEngineType("TILEPATHCPU");
CloseAllRenderConfigEditors();
}
#if !defined(LUXRAYS_DISABLE_OPENCL)
if (ImGui::MenuItem("TILEPATHOCL", "8", (currentEngineType == "TILEPATHOCL"))) {
SetRenderingEngineType("TILEPATHOCL");
CloseAllRenderConfigEditors();
}
#endif
if (ImGui::MenuItem("RTPATHCPU", "9", (currentEngineType == "RTPATHCPU"))) {
SetRenderingEngineType("RTPATHCPU");
CloseAllRenderConfigEditors();
}
}
//------------------------------------------------------------------------------
// MenuSampler
//------------------------------------------------------------------------------
void LuxCoreApp::MenuSampler() {
const string currentSamplerType = config->ToProperties().Get("sampler.type").Get<string>();
if (ImGui::MenuItem("RANDOM", NULL, (currentSamplerType == "RANDOM"))) {
samplerWindow.Close();
RenderConfigParse(Properties() << Property("sampler.type")("RANDOM"));
}
if (ImGui::MenuItem("SOBOL", NULL, (currentSamplerType == "SOBOL"))) {
samplerWindow.Close();
RenderConfigParse(Properties() << Property("sampler.type")("SOBOL"));
}
if (ImGui::MenuItem("METROPOLIS", NULL, (currentSamplerType == "METROPOLIS"))) {
samplerWindow.Close();
RenderConfigParse(Properties() << Property("sampler.type")("METROPOLIS"));
}
}
//------------------------------------------------------------------------------
// MenuTiles
//------------------------------------------------------------------------------
void LuxCoreApp::MenuTiles() {
bool showPending = config->GetProperties().Get(Property("screen.tiles.pending.show")(true)).Get<bool>();
if (ImGui::MenuItem("Show pending", NULL, showPending))
RenderConfigParse(Properties() << Property("screen.tiles.pending.show")(!showPending));
bool showConverged = config->GetProperties().Get(Property("screen.tiles.converged.show")(false)).Get<bool>();
if (ImGui::MenuItem("Show converged", NULL, showConverged))
RenderConfigParse(Properties() << Property("screen.tiles.converged.show")(!showConverged));
bool showNotConverged = config->GetProperties().Get(Property("screen.tiles.notconverged.show")(false)).Get<bool>();
if (ImGui::MenuItem("Show not converged", NULL, showNotConverged))
RenderConfigParse(Properties() << Property("screen.tiles.notconverged.show")(!showNotConverged));
ImGui::Separator();
bool showPassCount = config->GetProperties().Get(Property("screen.tiles.passcount.show")(false)).Get<bool>();
if (ImGui::MenuItem("Show pass count", NULL, showPassCount))
RenderConfigParse(Properties() << Property("screen.tiles.passcount.show")(!showPassCount));
bool showError = config->GetProperties().Get(Property("screen.tiles.error.show")(false)).Get<bool>();
if (ImGui::MenuItem("Show error", NULL, showError))
RenderConfigParse(Properties() << Property("screen.tiles.error.show")(!showError));
}
//------------------------------------------------------------------------------
// MenuFilm
//------------------------------------------------------------------------------
void LuxCoreApp::MenuFilm() {
if (ImGui::BeginMenu("Set resolution")) {
if (ImGui::MenuItem("320x240"))
SetFilmResolution(320, 240);
if (ImGui::MenuItem("640x480"))
SetFilmResolution(640, 480);
if (ImGui::MenuItem("800x600"))
SetFilmResolution(800, 600);
if (ImGui::MenuItem("1024x768"))
SetFilmResolution(1024, 768);
if (ImGui::MenuItem("1280x720"))
SetFilmResolution(1280, 720);
if (ImGui::MenuItem("1920x1080"))
SetFilmResolution(1920, 1080);
ImGui::Separator();
if (ImGui::MenuItem("Use window resolution")) {
int currentFrameBufferWidth, currentFrameBufferHeight;
glfwGetFramebufferSize(window, ¤tFrameBufferWidth, ¤tFrameBufferHeight);
SetFilmResolution(currentFrameBufferWidth, currentFrameBufferHeight);
}
ImGui::Separator();
ImGui::TextUnformatted("Width x Height");
ImGui::PushItemWidth(100);
ImGui::InputInt("##width", &menuFilmWidth);
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::TextUnformatted("x");
ImGui::SameLine();
ImGui::PushItemWidth(100);
ImGui::InputInt("##height", &menuFilmHeight);
ImGui::PopItemWidth();
ImGui::SameLine();
if (ImGui::Button("Apply"))
SetFilmResolution(menuFilmWidth, menuFilmHeight);
ImGui::EndMenu();
}
ImGui::Separator();
if (session && ImGui::MenuItem("Save outputs"))
session->GetFilm().SaveOutputs();
if (session && ImGui::MenuItem("Save film"))
session->GetFilm().SaveFilm("film.flm");
}
//------------------------------------------------------------------------------
// MenuImagePipeline
//------------------------------------------------------------------------------
void LuxCoreApp::MenuImagePipeline() {
const unsigned int imagePipelineCount = session->GetFilm().GetChannelCount(Film::CHANNEL_IMAGEPIPELINE);
for (unsigned int i = 0; i < imagePipelineCount; ++i) {
if (ImGui::MenuItem(string("Pipeline #" + ToString(i)).c_str(), NULL, (i == imagePipelineIndex)))
imagePipelineIndex = i;
}
if (imagePipelineIndex > imagePipelineCount)
imagePipelineIndex = 0;
}
//------------------------------------------------------------------------------
// MenuScreen
//------------------------------------------------------------------------------
void LuxCoreApp::MenuScreen() {
if (ImGui::BeginMenu("Interpolation mode")) {
if (ImGui::MenuItem("Nearest", NULL, (renderFrameBufferTexMinFilter == GL_NEAREST))) {
renderFrameBufferTexMinFilter = GL_NEAREST;
renderFrameBufferTexMagFilter = GL_NEAREST;
}
if (ImGui::MenuItem("Linear", NULL, (renderFrameBufferTexMinFilter == GL_LINEAR))) {
renderFrameBufferTexMinFilter = GL_LINEAR;
renderFrameBufferTexMagFilter = GL_LINEAR;
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Refresh interval")) {
if (ImGui::MenuItem("5ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(5)));
if (ImGui::MenuItem("10ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(10)));
if (ImGui::MenuItem("20ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(20)));
if (ImGui::MenuItem("50ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(50)));
if (ImGui::MenuItem("100ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(100)));
if (ImGui::MenuItem("500ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(500)));
if (ImGui::MenuItem("1000ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(1000)));
if (ImGui::MenuItem("2000ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(2000)));
ImGui::EndMenu();
}
if (ImGui::MenuItem("Decrease refresh interval","n"))
DecScreenRefreshInterval();
if (ImGui::MenuItem("Increase refresh interval","m"))
IncScreenRefreshInterval();
if (ImGui::BeginMenu("UI font scale")) {
ImGuiIO &io = ImGui::GetIO();
if (ImGui::MenuItem("1.0", NULL, (io.FontGlobalScale == 1.f)))
io.FontGlobalScale = 1.f;
if (ImGui::MenuItem("1.25", NULL, (io.FontGlobalScale == 1.25f)))
io.FontGlobalScale = 1.25f;
if (ImGui::MenuItem("1.5", NULL, (io.FontGlobalScale == 1.5f)))
io.FontGlobalScale = 1.5f;
if (ImGui::MenuItem("1.75", NULL, (io.FontGlobalScale == 1.75f)))
io.FontGlobalScale = 1.75f;
if (ImGui::MenuItem("2.0", NULL, (io.FontGlobalScale == 2.f)))
io.FontGlobalScale = 2.f;
ImGui::EndMenu();
}
}
//------------------------------------------------------------------------------
// MenuTool
//------------------------------------------------------------------------------
void LuxCoreApp::MenuTool() {
if (ImGui::MenuItem("Camera edit", NULL, (currentTool == TOOL_CAMERA_EDIT))) {
currentTool = TOOL_CAMERA_EDIT;
RenderConfigParse(Properties() << Property("screen.tool.type")("CAMERA_EDIT"));
}
if (ImGui::MenuItem("Object selection", NULL, (currentTool == TOOL_OBJECT_SELECTION))) {
currentTool = TOOL_OBJECT_SELECTION;
Properties props;
props << Property("screen.tool.type")("OBJECT_SELECTION");
// Check if the session a OBJECT_ID AOV enabled
if(!session->GetFilm().HasOutput(Film::OUTPUT_OBJECT_ID)) {
// Enable OBJECT_ID AOV
props <<
Property("film.outputs.LUXCOREUI_OBJECTSELECTION_AOV.type")("OBJECT_ID") <<
Property("film.outputs.LUXCOREUI_OBJECTSELECTION_AOV.filename")("dummy.png");
}
RenderConfigParse(props);
}
if (ImGui::MenuItem("Image view", NULL, (currentTool == TOOL_IMAGE_VIEW))) {
currentTool = TOOL_IMAGE_VIEW;
RenderConfigParse(Properties() << Property("screen.tool.type")("IMAGE_VIEW"));
}
}
//------------------------------------------------------------------------------
// MenuWindow
//------------------------------------------------------------------------------
void LuxCoreApp::MenuWindow() {
if (session) {
const string currentRenderEngineType = config->ToProperties().Get("renderengine.type").Get<string>();
if (ImGui::MenuItem("Render Engine editor", NULL, renderEngineWindow.IsOpen()))
renderEngineWindow.Toggle();
if (ImGui::MenuItem("Sampler editor", NULL, samplerWindow.IsOpen(),
!boost::starts_with(currentRenderEngineType, "TILE") && !boost::starts_with(currentRenderEngineType, "RT")))
samplerWindow.Toggle();
if (ImGui::MenuItem("Pixel Filter editor", NULL, pixelFilterWindow.IsOpen()))
pixelFilterWindow.Toggle();
if (ImGui::MenuItem("OpenCL Device editor", NULL, oclDeviceWindow.IsOpen(),
boost::ends_with(currentRenderEngineType, "OCL")))
oclDeviceWindow.Toggle();
if (ImGui::MenuItem("Light Strategy editor", NULL, lightStrategyWindow.IsOpen()))
lightStrategyWindow.Toggle();
if (ImGui::MenuItem("Accelerator editor", NULL, acceleratorWindow.IsOpen()))
acceleratorWindow.Toggle();
if (ImGui::MenuItem("Epsilon editor", NULL, epsilonWindow.IsOpen()))
epsilonWindow.Toggle();
ImGui::Separator();
if (ImGui::MenuItem("Film Radiance Groups editor", NULL, filmRadianceGroupsWindow.IsOpen()))
filmRadianceGroupsWindow.Toggle();
if (ImGui::MenuItem("Film Outputs editor", NULL, filmOutputsWindow.IsOpen()))
filmOutputsWindow.Toggle();
if (ImGui::MenuItem("Film Channels window", NULL, filmChannelsWindow.IsOpen()))
filmChannelsWindow.Toggle();
ImGui::Separator();
if (session && ImGui::MenuItem("Statistics", "j", statsWindow.IsOpen()))
statsWindow.Toggle();
}
if (ImGui::MenuItem("Log console", NULL, logWindow.IsOpen()))
logWindow.Toggle();
if (ImGui::MenuItem("Help", NULL, helpWindow.IsOpen()))
helpWindow.Toggle();
}
//------------------------------------------------------------------------------
// MainMenuBar
//------------------------------------------------------------------------------
void LuxCoreApp::MainMenuBar() {
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("Rendering")) {
MenuRendering();
ImGui::EndMenu();
}
if (session) {
const string currentEngineType = config->ToProperties().Get("renderengine.type").Get<string>();
if (ImGui::BeginMenu("Engine")) {
MenuEngine();
ImGui::EndMenu();
}
if ((!boost::starts_with(currentEngineType, "TILE")) &&
(!boost::starts_with(currentEngineType, "RT")) &&
ImGui::BeginMenu("Sampler")) {
MenuSampler();
ImGui::EndMenu();
}
if (boost::starts_with(currentEngineType, "TILE") && ImGui::BeginMenu("Tiles")) {
MenuTiles();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Film")) {
MenuFilm();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Image")) {
MenuImagePipeline();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Screen")) {
MenuScreen();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Tool")) {
MenuTool();
ImGui::EndMenu();
}
}
if (ImGui::BeginMenu("Window")) {
MenuWindow();
ImGui::EndMenu();
}
menuBarHeight = ImGui::GetWindowHeight();
ImGui::EndMainMenuBar();
}
}
| 34.436975
| 116
| 0.621523
|
LuxRender
|
ca2a341497fe45225d9ffdab7a85dc569d2c9fb1
| 26,189
|
cpp
|
C++
|
src/Layers/xrRender/ParticleEffect.cpp
|
Samsuper12/ixray-1.6
|
95b8ad458d4550118c7fbf34c5de872f3d1ca75e
|
[
"Linux-OpenIB"
] | 2
|
2020-05-17T10:02:18.000Z
|
2020-08-08T21:10:36.000Z
|
src/Layers/xrRender/ParticleEffect.cpp
|
Samsuper12/ixray-1.6
|
95b8ad458d4550118c7fbf34c5de872f3d1ca75e
|
[
"Linux-OpenIB"
] | null | null | null |
src/Layers/xrRender/ParticleEffect.cpp
|
Samsuper12/ixray-1.6
|
95b8ad458d4550118c7fbf34c5de872f3d1ca75e
|
[
"Linux-OpenIB"
] | null | null | null |
#include "stdafx.h"
#pragma hdrstop
#include "ParticleEffect.h"
#ifndef _EDITOR
#include <xmmintrin.h>
#include "../../xrCPU_Pipe/ttapi.h"
#pragma comment(lib,"xrCPU_Pipe.lib")
#endif
using namespace PAPI;
using namespace PS;
const u32 PS::uDT_STEP = 33;
const float PS::fDT_STEP = float(uDT_STEP)/1000.f;
static void ApplyTexgen( const Fmatrix &mVP )
{
Fmatrix mTexgen;
#if defined(USE_DX10) || defined(USE_DX11)
Fmatrix mTexelAdjust =
{
0.5f, 0.0f, 0.0f, 0.0f,
0.0f, -0.5f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.0f, 1.0f
};
#else // USE_DX10
float _w = float(RDEVICE.dwWidth);
float _h = float(RDEVICE.dwHeight);
float o_w = (.5f / _w);
float o_h = (.5f / _h);
Fmatrix mTexelAdjust =
{
0.5f, 0.0f, 0.0f, 0.0f,
0.0f, -0.5f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.5f + o_w, 0.5f + o_h, 0.0f, 1.0f
};
#endif // USE_DX10
mTexgen.mul(mTexelAdjust,mVP);
RCache.set_c( "mVPTexgen", mTexgen );
}
void PS::OnEffectParticleBirth(void* owner, u32 , PAPI::Particle& m, u32 )
{
CParticleEffect* PE = static_cast<CParticleEffect*>(owner); VERIFY(PE);
CPEDef* PED = PE->GetDefinition();
if (PED){
if (PED->m_Flags.is(CPEDef::dfRandomFrame))
m.frame = (u16)iFloor(Random.randI(PED->m_Frame.m_iFrameCount)*255.f);
if (PED->m_Flags.is(CPEDef::dfAnimated)&&PED->m_Flags.is(CPEDef::dfRandomPlayback)&&Random.randI(2))
m.flags.set(Particle::ANIMATE_CCW,TRUE);
}
}
void PS::OnEffectParticleDead(void* , u32 , PAPI::Particle& , u32 )
{
// CPEDef* PE = static_cast<CPEDef*>(owner);
}
//------------------------------------------------------------------------------
// class CParticleEffect
//------------------------------------------------------------------------------
CParticleEffect::CParticleEffect()
{
m_HandleEffect = ParticleManager()->CreateEffect(1); VERIFY(m_HandleEffect>=0);
m_HandleActionList = ParticleManager()->CreateActionList(); VERIFY(m_HandleActionList>=0);
m_RT_Flags.zero ();
m_Def = 0;
m_fElapsedLimit = 0.f;
m_MemDT = 0;
m_InitialPosition.set (0,0,0);
m_DestroyCallback = 0;
m_CollisionCallback = 0;
m_XFORM.identity ();
}
CParticleEffect::~CParticleEffect()
{
// Log ("--- destroy PE");
OnDeviceDestroy ();
ParticleManager()->DestroyEffect (m_HandleEffect);
ParticleManager()->DestroyActionList (m_HandleActionList);
}
void CParticleEffect::Play()
{
m_RT_Flags.set (flRT_DefferedStop,FALSE);
m_RT_Flags.set (flRT_Playing,TRUE);
ParticleManager()->PlayEffect(m_HandleEffect,m_HandleActionList);
}
void CParticleEffect::Stop(BOOL bDefferedStop)
{
ParticleManager()->StopEffect(m_HandleEffect,m_HandleActionList,bDefferedStop);
if (bDefferedStop){
m_RT_Flags.set (flRT_DefferedStop,TRUE);
}else{
m_RT_Flags.set (flRT_Playing,FALSE);
}
}
void CParticleEffect::RefreshShader()
{
OnDeviceDestroy();
OnDeviceCreate();
}
void CParticleEffect::UpdateParent(const Fmatrix& m, const Fvector& velocity, BOOL bXFORM)
{
m_RT_Flags.set (flRT_XFORM, bXFORM);
if (bXFORM) m_XFORM.set (m);
else{
m_InitialPosition = m.c;
ParticleManager()->Transform(m_HandleActionList,m,velocity);
}
}
void CParticleEffect::OnFrame(u32 frame_dt)
{
if (m_Def && m_RT_Flags.is(flRT_Playing)){
m_MemDT += frame_dt;
int StepCount = 0;
if (m_MemDT>=uDT_STEP) {
// allow maximum of three steps (99ms) to avoid slowdown after loading
// it will really skip updates at less than 10fps, which is unplayable
StepCount = m_MemDT/uDT_STEP;
m_MemDT = m_MemDT%uDT_STEP;
clamp (StepCount,0,3);
}
for (;StepCount; StepCount--) {
if (m_Def->m_Flags.is(CPEDef::dfTimeLimit)){
if (!m_RT_Flags.is(flRT_DefferedStop)){
m_fElapsedLimit -= fDT_STEP;
if (m_fElapsedLimit<0.f){
m_fElapsedLimit = m_Def->m_fTimeLimit;
Stop (true);
break;
}
}
}
ParticleManager()->Update(m_HandleEffect,m_HandleActionList,fDT_STEP);
PAPI::Particle* particles;
u32 p_cnt;
ParticleManager()->GetParticles(m_HandleEffect,particles,p_cnt);
// our actions
if (m_Def->m_Flags.is(CPEDef::dfFramed|CPEDef::dfAnimated)) m_Def->ExecuteAnimate (particles,p_cnt,fDT_STEP);
if (m_Def->m_Flags.is(CPEDef::dfCollision)) m_Def->ExecuteCollision (particles,p_cnt,fDT_STEP,this,m_CollisionCallback);
//-move action
if (p_cnt)
{
vis.box.invalidate ();
float p_size = 0.f;
for(u32 i = 0; i < p_cnt; i++){
Particle &m = particles[i];
vis.box.modify((Fvector&)m.pos);
if (m.size.x>p_size) p_size = m.size.x;
if (m.size.y>p_size) p_size = m.size.y;
if (m.size.z>p_size) p_size = m.size.z;
}
vis.box.grow (p_size);
vis.box.getsphere (vis.sphere.P,vis.sphere.R);
}
if (m_RT_Flags.is(flRT_DefferedStop)&&(0==p_cnt)){
m_RT_Flags.set (flRT_Playing|flRT_DefferedStop,FALSE);
break;
}
}
} else {
vis.box.set (m_InitialPosition,m_InitialPosition);
vis.box.grow (EPS_L);
vis.box.getsphere (vis.sphere.P,vis.sphere.R);
}
}
BOOL CParticleEffect::Compile(CPEDef* def)
{
m_Def = def;
if (m_Def){
// refresh shader
RefreshShader ();
// append actions
IReader F (m_Def->m_Actions.pointer(),m_Def->m_Actions.size());
ParticleManager()->LoadActions (m_HandleActionList,F);
ParticleManager()->SetMaxParticles (m_HandleEffect,m_Def->m_MaxParticles);
ParticleManager()->SetCallback (m_HandleEffect,OnEffectParticleBirth,OnEffectParticleDead,this,0);
// time limit
if (m_Def->m_Flags.is(CPEDef::dfTimeLimit))
m_fElapsedLimit = m_Def->m_fTimeLimit;
}
if (def) shader = def->m_CachedShader;
return TRUE;
}
void CParticleEffect::SetBirthDeadCB(PAPI::OnBirthParticleCB bc, PAPI::OnDeadParticleCB dc, void* owner, u32 p)
{
ParticleManager()->SetCallback (m_HandleEffect,bc,dc,owner,p);
}
u32 CParticleEffect::ParticlesCount()
{
return ParticleManager()->GetParticlesCount(m_HandleEffect);
}
//------------------------------------------------------------------------------
// Render
//------------------------------------------------------------------------------
void CParticleEffect::Copy(dxRender_Visual* )
{
FATAL ("Can't duplicate particle system - NOT IMPLEMENTED");
}
void CParticleEffect::OnDeviceCreate()
{
if (m_Def){
if (m_Def->m_Flags.is(CPEDef::dfSprite)){
geom.create (FVF::F_LIT, RCache.Vertex.Buffer(), RCache.QuadIB);
if (m_Def) shader = m_Def->m_CachedShader;
}
}
}
void CParticleEffect::OnDeviceDestroy()
{
if (m_Def){
if (m_Def->m_Flags.is(CPEDef::dfSprite)){
geom.destroy ();
shader.destroy ();
}
}
}
#ifndef _EDITOR
//----------------------------------------------------
IC void FillSprite_fpu (FVF::LIT*& pv, const Fvector& T, const Fvector& R, const Fvector& pos, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float angle)
{
float sa = _sin(angle);
float ca = _cos(angle);
Fvector Vr, Vt;
Vr.x = T.x*r1*sa+R.x*r1*ca;
Vr.y = T.y*r1*sa+R.y*r1*ca;
Vr.z = T.z*r1*sa+R.z*r1*ca;
Vt.x = T.x*r2*ca-R.x*r2*sa;
Vt.y = T.y*r2*ca-R.y*r2*sa;
Vt.z = T.z*r2*ca-R.z*r2*sa;
Fvector a,b,c,d;
a.sub (Vt,Vr);
b.add (Vt,Vr);
c.invert (a);
d.invert (b);
pv->set (d.x+pos.x,d.y+pos.y,d.z+pos.z, clr, lt.x,rb.y); pv++;
pv->set (a.x+pos.x,a.y+pos.y,a.z+pos.z, clr, lt.x,lt.y); pv++;
pv->set (c.x+pos.x,c.y+pos.y,c.z+pos.z, clr, rb.x,rb.y); pv++;
pv->set (b.x+pos.x,b.y+pos.y,b.z+pos.z, clr, rb.x,lt.y); pv++;
}
__forceinline void fsincos( const float angle , float &sine , float &cosine )
{ __asm {
fld DWORD PTR [angle]
fsincos
mov eax , DWORD PTR [cosine]
fstp DWORD PTR [eax]
mov eax , DWORD PTR [sine]
fstp DWORD PTR [eax]
} }
IC void FillSprite (FVF::LIT*& pv, const Fvector& T, const Fvector& R, const Fvector& pos, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float sina , float cosa )
{
#ifdef _GPA_ENABLED
TAL_SCOPED_TASK_NAMED( "FillSprite()" );
#endif // _GPA_ENABLED
__m128 Vr, Vt, _T , _R , _pos , _zz , _sa , _ca , a , b , c , d;
_sa = _mm_set1_ps( sina );
_ca = _mm_set1_ps( cosa );
_T = _mm_load_ss( (float*) &T.x );
_T = _mm_loadh_pi( _T , (__m64*) &T.y );
_R = _mm_load_ss( (float*) &R.x );
_R = _mm_loadh_pi( _R , (__m64*) &R.y );
_pos = _mm_load_ss( (float*) &pos.x );
_pos = _mm_loadh_pi( _pos , (__m64*) &pos.y );
_zz = _mm_setzero_ps();
Vr = _mm_mul_ps( _mm_set1_ps( r1 ) , _mm_add_ps( _mm_mul_ps( _T , _sa ) , _mm_mul_ps( _R , _ca ) ) );
Vt = _mm_mul_ps( _mm_set1_ps( r2 ) , _mm_sub_ps( _mm_mul_ps( _T , _ca ) , _mm_mul_ps( _R , _sa ) ) );
a = _mm_sub_ps( Vt , Vr );
b = _mm_add_ps( Vt , Vr );
c = _mm_sub_ps( _zz , a );
d = _mm_sub_ps( _zz , b );
a = _mm_add_ps( a , _pos );
d = _mm_add_ps( d , _pos );
b = _mm_add_ps( b , _pos );
c = _mm_add_ps( c , _pos );
_mm_store_ss( (float*) &pv->p.x , d );
_mm_storeh_pi( (__m64*) &pv->p.y , d );
pv->color = clr;
pv->t.set( lt.x , rb.y );
pv++;
_mm_store_ss( (float*) &pv->p.x , a );
_mm_storeh_pi( (__m64*) &pv->p.y , a );
pv->color = clr;
pv->t.set( lt.x , lt.y );
pv++;
_mm_store_ss( (float*) &pv->p.x , c );
_mm_storeh_pi( (__m64*) &pv->p.y , c );
pv->color = clr;
pv->t.set( rb.x , rb.y );
pv++;
_mm_store_ss( (float*) &pv->p.x , b );
_mm_storeh_pi( (__m64*) &pv->p.y , b );
pv->color = clr;
pv->t.set( rb.x , lt.y );
pv++;
}
IC void FillSprite (FVF::LIT*& pv, const Fvector& pos, const Fvector& dir, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float sina , float cosa )
{
#ifdef _GPA_ENABLED
TAL_SCOPED_TASK_NAMED( "FillSpriteTransform()" );
#endif // _GPA_ENABLED
const Fvector& T = dir;
Fvector R;
// R.crossproduct(T,RDEVICE.vCameraDirection).normalize_safe();
__m128 _t , _t1 , _t2 , _r , _r1 , _r2 ;
// crossproduct
_t = _mm_load_ss( (float*) &T.x );
_t = _mm_loadh_pi( _t , (__m64*) &T.y );
_r = _mm_load_ss( (float*) &RDEVICE.vCameraDirection.x );
_r = _mm_loadh_pi( _r , (__m64*) &RDEVICE.vCameraDirection.y );
_t1 = _mm_shuffle_ps( _t , _t , _MM_SHUFFLE( 0 , 3 , 1 , 2 ) );
_t2 = _mm_shuffle_ps( _t , _t , _MM_SHUFFLE( 2 , 0 , 1 , 3 ) );
_r1 = _mm_shuffle_ps( _r , _r , _MM_SHUFFLE( 2 , 0 , 1 , 3 ) );
_r2 = _mm_shuffle_ps( _r , _r , _MM_SHUFFLE( 0 , 3 , 1 , 2 ) );
_t1 = _mm_mul_ps( _t1 , _r1 );
_t2 = _mm_mul_ps( _t2 , _r2 );
_t1 = _mm_sub_ps( _t1 , _t2 ); // z | y | 0 | x
// normalize_safe
_t2 = _mm_mul_ps( _t1 , _t1 ); // zz | yy | 00 | xx
_r1 = _mm_movehl_ps( _t2 , _t2 ); // zz | yy | zz | yy
_t2 = _mm_add_ss( _t2 , _r1 ); // zz | yy | 00 | xx + yy
_r1 = _mm_shuffle_ps( _r1 , _r1 , _MM_SHUFFLE( 1 , 1 , 1 , 1 ) ); // zz | zz | zz | zz
_t2 = _mm_add_ss( _t2 , _r1 ); // zz | yy | 00 | xx + yy + zz
_r1 = _mm_set_ss( std::numeric_limits<float>::min() );
if ( _mm_comigt_ss( _t2 , _r1 ) ) {
_t2 = _mm_rsqrt_ss( _t2 );
_t2 = _mm_shuffle_ps( _t2 , _t2 , _MM_SHUFFLE( 0 , 0 , 0 , 0 ) );
_t1 = _mm_mul_ps( _t1 , _t2 );
}
_mm_store_ss( (float*) &R.x , _t1 );
_mm_storeh_pi( (__m64*) &R.y , _t1 );
FillSprite( pv , T , R , pos , lt , rb , r1 , r2 , clr , sina , cosa );
}
extern ENGINE_API float psHUD_FOV;
struct PRS_PARAMS {
FVF::LIT* pv;
u32 p_from;
u32 p_to;
PAPI::Particle* particles;
CParticleEffect* pPE;
};
__forceinline void magnitude_sse( Fvector &vec , float &res )
{
__m128 tv,tu;
tv = _mm_load_ss( (float*) &vec.x ); // tv = 0 | 0 | 0 | x
tv = _mm_loadh_pi( tv , (__m64*) &vec.y ); // tv = z | y | 0 | x
tv = _mm_mul_ps( tv , tv ); // tv = zz | yy | 0 | xx
tu = _mm_movehl_ps( tv , tv ); // tu = zz | yy | zz | yy
tv = _mm_add_ss( tv , tu ); // tv = zz | yy | 0 | xx + yy
tu = _mm_shuffle_ps( tu , tu , _MM_SHUFFLE( 1 , 1 , 1 , 1 ) ); // tu = zz | zz | zz | zz
tv = _mm_add_ss( tv , tu ); // tv = zz | yy | 0 | xx + yy + zz
tv = _mm_sqrt_ss( tv ); // tv = zz | yy | 0 | sqrt( xx + yy + zz )
_mm_store_ss( (float*) &res , tv );
}
void ParticleRenderStream( LPVOID lpvParams )
{
#ifdef _GPA_ENABLED
TAL_SCOPED_TASK_NAMED( "ParticleRenderStream()" );
TAL_ID rtID = TAL_MakeID( 1 , Core.dwFrame , 0);
TAL_AddRelationThis(TAL_RELATION_IS_CHILD_OF, rtID);
#endif // _GPA_ENABLED
float sina = 0.0f , cosa = 0.0f;
DWORD angle = 0xFFFFFFFF;
PRS_PARAMS* pParams = (PRS_PARAMS *) lpvParams;
FVF::LIT* pv = pParams->pv;
u32 p_from = pParams->p_from;
u32 p_to = pParams->p_to;
PAPI::Particle* particles = pParams->particles;
CParticleEffect &pPE = *pParams->pPE;
for(u32 i = p_from; i < p_to; i++){
PAPI::Particle &m = particles[i];
Fvector2 lt,rb;
lt.set (0.f,0.f);
rb.set (1.f,1.f);
_mm_prefetch( (char*) &particles[i + 1] , _MM_HINT_NTA );
if ( angle != *((DWORD*)&m.rot.x) ) {
angle = *((DWORD*)&m.rot.x);
__asm {
fld DWORD PTR [angle]
fsincos
fstp DWORD PTR [cosa]
fstp DWORD PTR [sina]
}
}
_mm_prefetch( 64 + (char*) &particles[i + 1] , _MM_HINT_NTA );
if (pPE.m_Def->m_Flags.is(CPEDef::dfFramed))
pPE.m_Def->m_Frame.CalculateTC(iFloor(float(m.frame)/255.f),lt,rb);
float r_x = m.size.x*0.5f;
float r_y = m.size.y*0.5f;
float speed;
BOOL speed_calculated = FALSE;
if (pPE.m_Def->m_Flags.is(CPEDef::dfVelocityScale)){
magnitude_sse( m.vel , speed );
speed_calculated = TRUE;
r_x += speed*pPE.m_Def->m_VelocityScale.x;
r_y += speed*pPE.m_Def->m_VelocityScale.y;
}
if (pPE.m_Def->m_Flags.is(CPEDef::dfAlignToPath)){
if ( ! speed_calculated )
magnitude_sse( m.vel , speed );
if ((speed<EPS_S)&&pPE.m_Def->m_Flags.is(CPEDef::dfWorldAlign)){
Fmatrix M;
M.setXYZ (pPE.m_Def->m_APDefaultRotation);
if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){
Fvector p;
pPE.m_XFORM.transform_tiny(p,m.pos);
M.mulA_43 (pPE.m_XFORM);
FillSprite (pv,M.k,M.i,p,lt,rb,r_x,r_y,m.color,sina,cosa);
}else{
FillSprite (pv,M.k,M.i,m.pos,lt,rb,r_x,r_y,m.color,sina,cosa);
}
}else if ((speed>=EPS_S)&&pPE.m_Def->m_Flags.is(CPEDef::dfFaceAlign)){
Fmatrix M; M.identity();
M.k.div (m.vel,speed);
M.j.set (0,1,0); if (_abs(M.j.dotproduct(M.k))>.99f) M.j.set(0,0,1);
M.i.crossproduct (M.j,M.k); M.i.normalize ();
M.j.crossproduct (M.k,M.i); M.j.normalize ();
if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){
Fvector p;
pPE.m_XFORM.transform_tiny(p,m.pos);
M.mulA_43 (pPE.m_XFORM);
FillSprite (pv,M.j,M.i,p,lt,rb,r_x,r_y,m.color,sina,cosa);
}else{
FillSprite (pv,M.j,M.i,m.pos,lt,rb,r_x,r_y,m.color,sina,cosa);
}
}else{
Fvector dir;
if (speed>=EPS_S) dir.div (m.vel,speed);
else dir.setHP(-pPE.m_Def->m_APDefaultRotation.y,-pPE.m_Def->m_APDefaultRotation.x);
if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){
Fvector p,d;
pPE.m_XFORM.transform_tiny (p,m.pos);
pPE.m_XFORM.transform_dir (d,dir);
FillSprite (pv,p,d,lt,rb,r_x,r_y,m.color,sina,cosa);
}else{
FillSprite (pv,m.pos,dir,lt,rb,r_x,r_y,m.color,sina,cosa);
}
}
}else{
if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){
Fvector p;
pPE.m_XFORM.transform_tiny (p,m.pos);
FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,p,lt,rb,r_x,r_y,m.color,sina,cosa);
}else{
FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,m.pos,lt,rb,r_x,r_y,m.color,sina,cosa);
}
}
}
}
void CParticleEffect::Render(float )
{
#ifdef _GPA_ENABLED
TAL_SCOPED_TASK_NAMED( "CParticleEffect::Render()" );
#endif // _GPA_ENABLED
u32 dwOffset,dwCount;
// Get a pointer to the particles in gp memory
PAPI::Particle* particles;
u32 p_cnt;
ParticleManager()->GetParticles(m_HandleEffect,particles,p_cnt);
if(p_cnt>0){
if (m_Def&&m_Def->m_Flags.is(CPEDef::dfSprite)){
FVF::LIT* pv_start = (FVF::LIT*)RCache.Vertex.Lock(p_cnt*4*4,geom->vb_stride,dwOffset);
FVF::LIT* pv = pv_start;
u32 nWorkers = ttapi_GetWorkersCount();
if ( p_cnt < nWorkers * 20 )
nWorkers = 1;
PRS_PARAMS* prsParams = (PRS_PARAMS*) _alloca( sizeof(PRS_PARAMS) * nWorkers );
// Give ~1% more for the last worker
// to minimize wait in final spin
u32 nSlice = p_cnt / 128;
u32 nStep = ( ( p_cnt - nSlice ) / nWorkers );
//u32 nStep = ( p_cnt / nWorkers );
//Msg( "Rnd: %u" , nStep );
for ( u32 i = 0 ; i < nWorkers ; ++i ) {
prsParams[i].pv = pv + i*nStep*4;
prsParams[i].p_from = i * nStep;
prsParams[i].p_to = ( i == ( nWorkers - 1 ) ) ? p_cnt : ( prsParams[i].p_from + nStep );
prsParams[i].particles = particles;
prsParams[i].pPE = this;
ttapi_AddWorker( ParticleRenderStream , (LPVOID) &prsParams[i] );
}
ttapi_RunAllWorkers();
dwCount = p_cnt<<2;
RCache.Vertex.Unlock(dwCount,geom->vb_stride);
if (dwCount)
{
#ifndef _EDITOR
Fmatrix Pold = Device.mProject;
Fmatrix FTold = Device.mFullTransform;
if(GetHudMode())
{
RDEVICE.mProject.build_projection( deg2rad(psHUD_FOV*Device.fFOV),
Device.fASPECT,
VIEWPORT_NEAR,
g_pGamePersistent->Environment().CurrentEnv->far_plane);
Device.mFullTransform.mul (Device.mProject, Device.mView);
RCache.set_xform_project (Device.mProject);
RImplementation.rmNear ();
ApplyTexgen(Device.mFullTransform);
}
#endif
RCache.set_xform_world (Fidentity);
RCache.set_Geometry (geom);
RCache.set_CullMode (m_Def->m_Flags.is(CPEDef::dfCulling)?(m_Def->m_Flags.is(CPEDef::dfCullCCW)?CULL_CCW:CULL_CW):CULL_NONE);
RCache.Render (D3DPT_TRIANGLELIST,dwOffset,0,dwCount,0,dwCount/2);
RCache.set_CullMode (CULL_CCW );
#ifndef _EDITOR
if(GetHudMode())
{
RImplementation.rmNormal ();
Device.mProject = Pold;
Device.mFullTransform = FTold;
RCache.set_xform_project (Device.mProject);
ApplyTexgen(Device.mFullTransform);
}
#endif
}
}
}
}
#else
//----------------------------------------------------
IC void FillSprite (FVF::LIT*& pv, const Fvector& T, const Fvector& R, const Fvector& pos, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float angle)
{
float sa = _sin(angle);
float ca = _cos(angle);
Fvector Vr, Vt;
Vr.x = T.x*r1*sa+R.x*r1*ca;
Vr.y = T.y*r1*sa+R.y*r1*ca;
Vr.z = T.z*r1*sa+R.z*r1*ca;
Vt.x = T.x*r2*ca-R.x*r2*sa;
Vt.y = T.y*r2*ca-R.y*r2*sa;
Vt.z = T.z*r2*ca-R.z*r2*sa;
Fvector a,b,c,d;
a.sub (Vt,Vr);
b.add (Vt,Vr);
c.invert (a);
d.invert (b);
pv->set (d.x+pos.x,d.y+pos.y,d.z+pos.z, clr, lt.x,rb.y); pv++;
pv->set (a.x+pos.x,a.y+pos.y,a.z+pos.z, clr, lt.x,lt.y); pv++;
pv->set (c.x+pos.x,c.y+pos.y,c.z+pos.z, clr, rb.x,rb.y); pv++;
pv->set (b.x+pos.x,b.y+pos.y,b.z+pos.z, clr, rb.x,lt.y); pv++;
}
IC void FillSprite (FVF::LIT*& pv, const Fvector& pos, const Fvector& dir, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float angle)
{
float sa = _sin(angle);
float ca = _cos(angle);
const Fvector& T = dir;
Fvector R; R.crossproduct(T,RDEVICE.vCameraDirection).normalize_safe();
Fvector Vr, Vt;
Vr.x = T.x*r1*sa+R.x*r1*ca;
Vr.y = T.y*r1*sa+R.y*r1*ca;
Vr.z = T.z*r1*sa+R.z*r1*ca;
Vt.x = T.x*r2*ca-R.x*r2*sa;
Vt.y = T.y*r2*ca-R.y*r2*sa;
Vt.z = T.z*r2*ca-R.z*r2*sa;
Fvector a,b,c,d;
a.sub (Vt,Vr);
b.add (Vt,Vr);
c.invert (a);
d.invert (b);
pv->set (d.x+pos.x,d.y+pos.y,d.z+pos.z, clr, lt.x,rb.y); pv++;
pv->set (a.x+pos.x,a.y+pos.y,a.z+pos.z, clr, lt.x,lt.y); pv++;
pv->set (c.x+pos.x,c.y+pos.y,c.z+pos.z, clr, rb.x,rb.y); pv++;
pv->set (b.x+pos.x,b.y+pos.y,b.z+pos.z, clr, rb.x,lt.y); pv++;
}
extern ENGINE_API float psHUD_FOV;
void CParticleEffect::Render(float )
{
u32 dwOffset,dwCount;
// Get a pointer to the particles in gp memory
PAPI::Particle* particles;
u32 p_cnt;
ParticleManager()->GetParticles(m_HandleEffect,particles,p_cnt);
if(p_cnt>0){
if (m_Def&&m_Def->m_Flags.is(CPEDef::dfSprite)){
FVF::LIT* pv_start = (FVF::LIT*)RCache.Vertex.Lock(p_cnt*4*4,geom->vb_stride,dwOffset);
FVF::LIT* pv = pv_start;
for(u32 i = 0; i < p_cnt; i++){
PAPI::Particle &m = particles[i];
Fvector2 lt,rb;
lt.set (0.f,0.f);
rb.set (1.f,1.f);
if (m_Def->m_Flags.is(CPEDef::dfFramed)) m_Def->m_Frame.CalculateTC(iFloor(float(m.frame)/255.f),lt,rb);
float r_x = m.size.x*0.5f;
float r_y = m.size.y*0.5f;
if (m_Def->m_Flags.is(CPEDef::dfVelocityScale)){
float speed = m.vel.magnitude();
r_x += speed*m_Def->m_VelocityScale.x;
r_y += speed*m_Def->m_VelocityScale.y;
}
if (m_Def->m_Flags.is(CPEDef::dfAlignToPath)){
float speed = m.vel.magnitude();
if ((speed<EPS_S)&&m_Def->m_Flags.is(CPEDef::dfWorldAlign)){
Fmatrix M;
M.setXYZ (m_Def->m_APDefaultRotation);
if (m_RT_Flags.is(flRT_XFORM)){
Fvector p;
m_XFORM.transform_tiny(p,m.pos);
M.mulA_43 (m_XFORM);
FillSprite (pv,M.k,M.i,p,lt,rb,r_x,r_y,m.color,m.rot.x);
}else{
FillSprite (pv,M.k,M.i,m.pos,lt,rb,r_x,r_y,m.color,m.rot.x);
}
}else if ((speed>=EPS_S)&&m_Def->m_Flags.is(CPEDef::dfFaceAlign)){
Fmatrix M; M.identity();
M.k.div (m.vel,speed);
M.j.set (0,1,0); if (_abs(M.j.dotproduct(M.k))>.99f) M.j.set(0,0,1);
M.i.crossproduct (M.j,M.k); M.i.normalize ();
M.j.crossproduct (M.k,M.i); M.j.normalize ();
if (m_RT_Flags.is(flRT_XFORM)){
Fvector p;
m_XFORM.transform_tiny(p,m.pos);
M.mulA_43 (m_XFORM);
FillSprite (pv,M.j,M.i,p,lt,rb,r_x,r_y,m.color,m.rot.x);
}else{
FillSprite (pv,M.j,M.i,m.pos,lt,rb,r_x,r_y,m.color,m.rot.x);
}
}else{
Fvector dir;
if (speed>=EPS_S) dir.div (m.vel,speed);
else dir.setHP(-m_Def->m_APDefaultRotation.y,-m_Def->m_APDefaultRotation.x);
if (m_RT_Flags.is(flRT_XFORM)){
Fvector p,d;
m_XFORM.transform_tiny (p,m.pos);
m_XFORM.transform_dir (d,dir);
FillSprite (pv,p,d,lt,rb,r_x,r_y,m.color,m.rot.x);
}else{
FillSprite (pv,m.pos,dir,lt,rb,r_x,r_y,m.color,m.rot.x);
}
}
}else{
if (m_RT_Flags.is(flRT_XFORM)){
Fvector p;
m_XFORM.transform_tiny (p,m.pos);
FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,p,lt,rb,r_x,r_y,m.color,m.rot.x);
}else{
FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,m.pos,lt,rb,r_x,r_y,m.color,m.rot.x);
}
}
}
dwCount = u32(pv-pv_start);
RCache.Vertex.Unlock(dwCount,geom->vb_stride);
if (dwCount)
{
#ifndef _EDITOR
Fmatrix Pold = Device.mProject;
Fmatrix FTold = Device.mFullTransform;
if(GetHudMode())
{
RDEVICE.mProject.build_projection( deg2rad(psHUD_FOV*Device.fFOV),
Device.fASPECT,
VIEWPORT_NEAR,
g_pGamePersistent->Environment().CurrentEnv->far_plane);
Device.mFullTransform.mul (Device.mProject, Device.mView);
RCache.set_xform_project (Device.mProject);
RImplementation.rmNear ();
ApplyTexgen(Device.mFullTransform);
}
#endif
RCache.set_xform_world (Fidentity);
RCache.set_Geometry (geom);
RCache.set_CullMode (m_Def->m_Flags.is(CPEDef::dfCulling)?(m_Def->m_Flags.is(CPEDef::dfCullCCW)?CULL_CCW:CULL_CW):CULL_NONE);
RCache.Render (D3DPT_TRIANGLELIST,dwOffset,0,dwCount,0,dwCount/2);
RCache.set_CullMode (CULL_CCW );
#ifndef _EDITOR
if(GetHudMode())
{
RImplementation.rmNormal ();
Device.mProject = Pold;
Device.mFullTransform = FTold;
RCache.set_xform_project (Device.mProject);
ApplyTexgen(Device.mFullTransform);
}
#endif
}
}
}
}
#endif // _EDITOR
| 33.277001
| 186
| 0.559013
|
Samsuper12
|
ca2edbd855f22ff164a345a4f5558a5ebf336c32
| 375
|
cpp
|
C++
|
cpp-eindopdracht/creditsview.cpp
|
TvanBronswijk/cpp-eindopdracht
|
657febe944cd856da44c3cc6cb6d1822c1fbf740
|
[
"MIT"
] | null | null | null |
cpp-eindopdracht/creditsview.cpp
|
TvanBronswijk/cpp-eindopdracht
|
657febe944cd856da44c3cc6cb6d1822c1fbf740
|
[
"MIT"
] | null | null | null |
cpp-eindopdracht/creditsview.cpp
|
TvanBronswijk/cpp-eindopdracht
|
657febe944cd856da44c3cc6cb6d1822c1fbf740
|
[
"MIT"
] | null | null | null |
#include "creditsview.h"
#include "gamecontext.h"
CreditsView::CreditsView(GameContext* context) : View(context)
{
}
std::ostream & CreditsView::display()
{
return std::cout
<< "This game was created by Tobi van Bronswijk and Rick van Berlo."
<< std::endl
<< "Thanks for playing!"
<< std::endl;
}
bool CreditsView::handle_input(char c)
{
back();
return true;
}
| 17.045455
| 70
| 0.685333
|
TvanBronswijk
|
ca33067d758bb649588693b6048e4b820f51f274
| 201
|
hpp
|
C++
|
src/ProjectForecast/Systems/EventFeedbackSystem.hpp
|
yxbh/Project-Forecast
|
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
|
[
"BSD-3-Clause"
] | 4
|
2019-04-09T13:03:11.000Z
|
2021-01-27T04:58:29.000Z
|
src/ProjectForecast/Systems/EventFeedbackSystem.hpp
|
yxbh/Project-Forecast
|
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
|
[
"BSD-3-Clause"
] | 2
|
2017-02-06T03:48:45.000Z
|
2020-08-31T01:30:10.000Z
|
src/ProjectForecast/Systems/EventFeedbackSystem.hpp
|
yxbh/Project-Forecast
|
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
|
[
"BSD-3-Clause"
] | 4
|
2020-06-28T08:19:53.000Z
|
2020-06-28T16:30:19.000Z
|
#pragma once
#include "KEngine/Interfaces/ISystem.hpp"
namespace pf
{
/// <summary>
///
/// </summary>
class EventFeedbackSystem : public ke::ISystem
{
public:
};
}
| 12.5625
| 50
| 0.567164
|
yxbh
|
ca360ecf778f3a531c706dd39105f1e5f08c6be8
| 20
|
cpp
|
C++
|
lib/threads/event.cpp
|
ashcharles/openset
|
51dc29b9dffdb745a24e01a9e4d86c79d2ff20d6
|
[
"MIT"
] | 18
|
2017-09-28T16:46:27.000Z
|
2022-03-13T19:32:04.000Z
|
lib/threads/event.cpp
|
perple-io/openset
|
201ee4a6247b6cce369885e05794e7dd3e8b8508
|
[
"MIT"
] | 14
|
2017-10-05T13:40:48.000Z
|
2019-10-18T15:44:44.000Z
|
lib/threads/event.cpp
|
perple-io/openset
|
201ee4a6247b6cce369885e05794e7dd3e8b8508
|
[
"MIT"
] | 4
|
2017-12-07T22:34:10.000Z
|
2021-07-17T00:19:43.000Z
|
#include "event.h"
| 10
| 19
| 0.65
|
ashcharles
|
ca3655bb3d549aaa22baf73498a48a3fa13b99a9
| 2,233
|
cpp
|
C++
|
examples/tsp/src/tsp/tsp_instance.cpp
|
luishpmendes/ns-brkga
|
61b3ec35ea4276359b1baa7c0f6c92087c4f8d3b
|
[
"MIT"
] | 11
|
2019-11-25T17:34:40.000Z
|
2021-12-25T16:31:48.000Z
|
examples/tsp/src/tsp/tsp_instance.cpp
|
luishpmendes/ns-brkga
|
61b3ec35ea4276359b1baa7c0f6c92087c4f8d3b
|
[
"MIT"
] | 3
|
2020-04-22T15:53:50.000Z
|
2021-12-17T21:28:55.000Z
|
examples/tsp/src/tsp/tsp_instance.cpp
|
luishpmendes/ns-brkga
|
61b3ec35ea4276359b1baa7c0f6c92087c4f8d3b
|
[
"MIT"
] | 7
|
2020-05-20T17:05:04.000Z
|
2021-12-13T17:41:56.000Z
|
/******************************************************************************
* tsp_instance.cpp: Implementation for TSP_Instance class.
*
* (c) Copyright 2015-2019, Carlos Eduardo de Andrade.
* All Rights Reserved.
*
* Created on : Mar 05, 2019 by andrade
* Last update: Mar 05, 2019 by andrade
*
* This code is released under LICENSE.md.
*
* 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 "tsp/tsp_instance.hpp"
#include <fstream>
#include <stdexcept>
using namespace std;
//-----------------------------[ Constructor ]--------------------------------//
TSP_Instance::TSP_Instance(const std::string& filename):
num_nodes(0),
distances()
{
ifstream file(filename, ios::in);
if(!file)
throw runtime_error("Cannot open instance file");
file.exceptions(ifstream::failbit | ifstream::badbit);
try {
file >> num_nodes;
distances.resize((num_nodes * (num_nodes - 1)) / 2);
for(unsigned i = 0; i < distances.size(); ++i)
file >> distances[i];
}
catch(std::ifstream::failure& e) {
throw fstream::failure("Error reading the instance file");
}
}
//-------------------------------[ Distance ]---------------------------------//
double TSP_Instance::distance(unsigned i, unsigned j) const {
if(i > j)
swap(i, j);
return distances[(i * (num_nodes - 1)) - ((i - 1) * i / 2) + (j - i - 1)];
}
| 36.606557
| 80
| 0.596059
|
luishpmendes
|
ca37ed05ba42645e28e8b89162b3eca996b386f1
| 10,338
|
hxx
|
C++
|
Modules/Learning/Supervised/include/otbSharkRandomForestsMachineLearningModel.hxx
|
heralex/OTB
|
c52b504b64dc89c8fe9cac8af39b8067ca2c3a57
|
[
"Apache-2.0"
] | 317
|
2015-01-19T08:40:58.000Z
|
2022-03-17T11:55:48.000Z
|
Modules/Learning/Supervised/include/otbSharkRandomForestsMachineLearningModel.hxx
|
guandd/OTB
|
707ce4c6bb4c7186e3b102b2b00493a5050872cb
|
[
"Apache-2.0"
] | 18
|
2015-07-29T14:13:45.000Z
|
2021-03-29T12:36:24.000Z
|
Modules/Learning/Supervised/include/otbSharkRandomForestsMachineLearningModel.hxx
|
guandd/OTB
|
707ce4c6bb4c7186e3b102b2b00493a5050872cb
|
[
"Apache-2.0"
] | 132
|
2015-02-21T23:57:25.000Z
|
2022-03-25T16:03:16.000Z
|
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbSharkRandomForestsMachineLearningModel_hxx
#define otbSharkRandomForestsMachineLearningModel_hxx
#include <fstream>
#include "itkMacro.h"
#include "otbSharkRandomForestsMachineLearningModel.h"
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#pragma GCC diagnostic ignored "-Wignored-qualifiers"
#endif
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#include "otbSharkUtils.h"
#include <algorithm>
namespace otb
{
template <class TInputValue, class TOutputValue>
SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::SharkRandomForestsMachineLearningModel()
{
this->m_ConfidenceIndex = true;
this->m_ProbaIndex = true;
this->m_IsRegressionSupported = false;
this->m_IsDoPredictBatchMultiThreaded = true;
this->m_NormalizeClassLabels = true;
this->m_ComputeMargin = false;
}
/** Train the machine learning model */
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::Train()
{
#ifdef _OPENMP
omp_set_num_threads(itk::MultiThreader::GetGlobalDefaultNumberOfThreads());
#endif
std::vector<shark::RealVector> features;
std::vector<unsigned int> class_labels;
Shark::ListSampleToSharkVector(this->GetInputListSample(), features);
Shark::ListSampleToSharkVector(this->GetTargetListSample(), class_labels);
if (m_NormalizeClassLabels)
{
Shark::NormalizeLabelsAndGetDictionary(class_labels, m_ClassDictionary);
}
shark::ClassificationDataset TrainSamples = shark::createLabeledDataFromRange(features, class_labels);
// Set parameters
m_RFTrainer.setMTry(m_MTry);
m_RFTrainer.setNTrees(m_NumberOfTrees);
m_RFTrainer.setNodeSize(m_NodeSize);
// m_RFTrainer.setOOBratio(m_OobRatio);
m_RFTrainer.train(m_RFModel, TrainSamples);
}
template <class TInputValue, class TOutputValue>
typename SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::ConfidenceValueType
SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::ComputeConfidence(shark::RealVector& probas, bool computeMargin) const
{
assert(!probas.empty() && "probas vector is empty");
assert((!computeMargin || probas.size() > 1) && "probas size should be at least 2 if computeMargin is true");
ConfidenceValueType conf{0};
if (computeMargin)
{
std::nth_element(probas.begin(), probas.begin() + 1, probas.end(), std::greater<double>());
conf = static_cast<ConfidenceValueType>(probas[0] - probas[1]);
}
else
{
auto max_proba = *(std::max_element(probas.begin(), probas.end()));
conf = static_cast<ConfidenceValueType>(max_proba);
}
return conf;
}
template <class TInputValue, class TOutputValue>
typename SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::TargetSampleType
SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::DoPredict(const InputSampleType& value, ConfidenceValueType* quality,
ProbaSampleType* proba) const
{
shark::RealVector samples(value.Size());
for (size_t i = 0; i < value.Size(); i++)
{
samples.push_back(value[i]);
}
if (quality != nullptr || proba != nullptr)
{
shark::RealVector probas = m_RFModel.decisionFunction()(samples);
if (quality != nullptr)
{
(*quality) = ComputeConfidence(probas, m_ComputeMargin);
}
if (proba != nullptr)
{
for (size_t i = 0; i < probas.size(); i++)
{
// probas contain the N class probability indexed between 0 and N-1
(*proba)[i] = static_cast<unsigned int>(probas[i] * 1000);
}
}
}
unsigned int res{0};
m_RFModel.eval(samples, res);
TargetSampleType target;
if (m_NormalizeClassLabels)
{
target[0] = m_ClassDictionary[static_cast<TOutputValue>(res)];
}
else
{
target[0] = static_cast<TOutputValue>(res);
}
return target;
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::DoPredictBatch(const InputListSampleType* input, const unsigned int& startIndex,
const unsigned int& size, TargetListSampleType* targets,
ConfidenceListSampleType* quality, ProbaListSampleType* proba) const
{
assert(input != nullptr);
assert(targets != nullptr);
assert(input->Size() == targets->Size() && "Input sample list and target label list do not have the same size.");
assert(((quality == nullptr) || (quality->Size() == input->Size())) &&
"Quality samples list is not null and does not have the same size as input samples list");
assert(((proba == nullptr) || (input->Size() == proba->Size())) && "Proba sample list and target label list do not have the same size.");
if (startIndex + size > input->Size())
{
itkExceptionMacro(<< "requested range [" << startIndex << ", " << startIndex + size << "[ partially outside input sample list range.[0," << input->Size()
<< "[");
}
std::vector<shark::RealVector> features;
Shark::ListSampleRangeToSharkVector(input, features, startIndex, size);
shark::Data<shark::RealVector> inputSamples = shark::createDataFromRange(features);
#ifdef _OPENMP
omp_set_num_threads(itk::MultiThreader::GetGlobalDefaultNumberOfThreads());
#endif
if (proba != nullptr || quality != nullptr)
{
shark::Data<shark::RealVector> probas = m_RFModel.decisionFunction()(inputSamples);
if (proba != nullptr)
{
unsigned int id = startIndex;
for (shark::RealVector&& p : probas.elements())
{
ProbaSampleType prob{(unsigned int)p.size()};
for (size_t i = 0; i < p.size(); i++)
{
prob[i] = p[i] * 1000;
}
proba->SetMeasurementVector(id, prob);
++id;
}
}
if (quality != nullptr)
{
unsigned int id = startIndex;
for (shark::RealVector&& p : probas.elements())
{
ConfidenceSampleType confidence;
auto conf = ComputeConfidence(p, m_ComputeMargin);
confidence[0] = static_cast<ConfidenceValueType>(conf);
quality->SetMeasurementVector(id, confidence);
++id;
}
}
}
auto prediction = m_RFModel(inputSamples);
unsigned int id = startIndex;
for (const auto& p : prediction.elements())
{
TargetSampleType target;
if (m_NormalizeClassLabels)
{
target[0] = m_ClassDictionary[static_cast<TOutputValue>(p)];
}
else
{
target[0] = static_cast<TOutputValue>(p);
}
targets->SetMeasurementVector(id, target);
++id;
}
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::Save(const std::string& filename, const std::string& itkNotUsed(name))
{
std::ofstream ofs(filename);
if (!ofs)
{
itkExceptionMacro(<< "Error opening " << filename.c_str());
}
// Add comment with model file name
ofs << "#" << m_RFModel.name();
if (m_NormalizeClassLabels)
ofs << " with_dictionary";
ofs << std::endl;
if (m_NormalizeClassLabels)
{
ofs << m_ClassDictionary.size() << " ";
for (const auto& l : m_ClassDictionary)
{
ofs << l << " ";
}
ofs << std::endl;
}
shark::TextOutArchive oa(ofs);
m_RFModel.save(oa, 0);
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::Load(const std::string& filename, const std::string& itkNotUsed(name))
{
std::ifstream ifs(filename);
if (ifs.good())
{
// Check if the first line is a comment and verify the name of the model in this case.
std::string line;
getline(ifs, line);
if (line.at(0) == '#')
{
if (line.find(m_RFModel.name()) == std::string::npos)
itkExceptionMacro("The model file : " + filename + " cannot be read.");
if (line.find("with_dictionary") == std::string::npos)
{
m_NormalizeClassLabels = false;
}
}
else
{
// rewind if first line is not a comment
ifs.clear();
ifs.seekg(0, std::ios::beg);
}
if (m_NormalizeClassLabels)
{
size_t nbLabels{0};
ifs >> nbLabels;
m_ClassDictionary.resize(nbLabels);
for (size_t i = 0; i < nbLabels; ++i)
{
unsigned int label;
ifs >> label;
m_ClassDictionary[i] = label;
}
}
shark::TextInArchive ia(ifs);
m_RFModel.load(ia, 0);
}
}
template <class TInputValue, class TOutputValue>
bool SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::CanReadFile(const std::string& file)
{
try
{
this->Load(file);
m_RFModel.name();
}
catch (...)
{
return false;
}
return true;
}
template <class TInputValue, class TOutputValue>
bool SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::CanWriteFile(const std::string& itkNotUsed(file))
{
return true;
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::PrintSelf(std::ostream& os, itk::Indent indent) const
{
// Call superclass implementation
Superclass::PrintSelf(os, indent);
}
} // end namespace otb
#endif
| 32.30625
| 157
| 0.671697
|
heralex
|
ca3906359b23d981bcf6b446dc1fe368b6b4eada
| 3,562
|
cpp
|
C++
|
Tools/Base64.cpp
|
xuyuanwang1993/p2p_work_on_kcp
|
9f4081cdeee6550c3295215a123ecffd13128dac
|
[
"MIT"
] | 13
|
2019-09-19T01:04:00.000Z
|
2022-02-24T08:26:25.000Z
|
Tools/Base64.cpp
|
xuyuanwang1993/p2p_work_on_kcp
|
9f4081cdeee6550c3295215a123ecffd13128dac
|
[
"MIT"
] | 2
|
2019-10-16T12:57:29.000Z
|
2019-11-08T12:07:43.000Z
|
Tools/Base64.cpp
|
xuyuanwang1993/p2p_work_on_kcp
|
9f4081cdeee6550c3295215a123ecffd13128dac
|
[
"MIT"
] | 5
|
2019-10-16T12:45:20.000Z
|
2022-01-19T15:03:36.000Z
|
#include "Base64.h"
#include <mutex>
#include <iostream>
using namespace std;
using namespace sensor_tool;
std::string sensor_tool::base64Encode(const std::string & origin_string)
{
static const char base64Char[] ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string ret("");
if(origin_string.empty()) return ret;
unsigned const numOrig24BitValues = origin_string.size()/3;
bool havePadding = origin_string.size() > numOrig24BitValues*3;//判断是否有余数
bool havePadding2 = origin_string.size() == numOrig24BitValues*3 + 2;//判断余数是否等于2
unsigned const numResultBytes = 4*(numOrig24BitValues + havePadding);//计算最终结果的size
ret.resize(numResultBytes);//确定返回字符串大小
unsigned i;
for (i = 0; i < numOrig24BitValues; ++i) {
ret[4*i+0] = base64Char[(origin_string[3*i]>>2)&0x3F];
ret[4*i+1] = base64Char[(((origin_string[3*i]&0x3)<<4) | (origin_string[3*i+1]>>4))&0x3F];
ret[4*i+2] = base64Char[((origin_string[3*i+1]<<2) | (origin_string[3*i+2]>>6))&0x3F];
ret[4*i+3] = base64Char[origin_string[3*i+2]&0x3F];
}
//处理不足3位的情况
//余1位需在后面补齐2个'='
//余2位需补齐一个'='
if (havePadding) {
ret[4*i+0] = base64Char[(origin_string[3*i]>>2)&0x3F];
if (havePadding2) {
ret[4*i+1] = base64Char[(((origin_string[3*i]&0x3)<<4) | (origin_string[3*i+1]>>4))&0x3F];
ret[4*i+2] = base64Char[(origin_string[3*i+1]<<2)&0x3F];
} else {
ret[4*i+1] = base64Char[((origin_string[3*i]&0x3)<<4)&0x3F];
ret[4*i+2] = '=';
}
ret[4*i+3] = '=';
}
return ret;
}
std::string sensor_tool::base64Decode(const std::string & origin_string)
{
static char base64DecodeTable[256];
static std::once_flag oc_init;
std::call_once(oc_init,[&](){
int i;//初始化映射表
for (i = 0; i < 256; ++i) base64DecodeTable[i] = (char)0x80;
for (i = 'A'; i <= 'Z'; ++i) base64DecodeTable[i] = 0 + (i - 'A');
for (i = 'a'; i <= 'z'; ++i) base64DecodeTable[i] = 26 + (i - 'a');
for (i = '0'; i <= '9'; ++i) base64DecodeTable[i] = 52 + (i - '0');
base64DecodeTable[(unsigned char)'+'] = 62;
base64DecodeTable[(unsigned char)'/'] = 63;
base64DecodeTable[(unsigned char)'='] = 0;
});
std::string ret("");
if(origin_string.empty()) return ret;
int k=0;
int paddingCount = 0;
int const jMax = origin_string.size() - 3;
ret.resize(3*origin_string.size()/4);
for(int j=0;j<jMax;j+=4)
{
char inTmp[4], outTmp[4];
for (int i = 0; i < 4; ++i) {
inTmp[i] = origin_string[i+j];
if (inTmp[i] == '=') ++paddingCount;
outTmp[i] = base64DecodeTable[(unsigned char)inTmp[i]];
if ((outTmp[i]&0x80) != 0) outTmp[i] = 0; // this happens only if there was an invalid character; pretend that it was 'A'
}
ret[k++]=(outTmp[0]<<2) | (outTmp[1]>>4);
ret[k++] = (outTmp[1]<<4) | (outTmp[2]>>2);
ret[k++] = (outTmp[2]<<6) | outTmp[3];
}
ret.assign(ret.c_str());//清除空白字符
return ret;
}
void Base64_test()
{
std::string qwer("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.");
std::string qaz=sensor_tool::base64Encode(qwer);
std::cout<<qaz<<std::endl;
std::cout<<qwer<<std::endl;
std::cout<<(int)(sensor_tool::base64Decode(qaz)==qwer)<<std::endl;
}
| 42.404762
| 294
| 0.603593
|
xuyuanwang1993
|
ca3ea5838e7403cb98c2bf2326214e7d9c5990b2
| 666
|
hpp
|
C++
|
modules/scene_manager/include/rcl_interfaces/srv/get_parameters__struct.hpp
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1
|
2020-05-19T14:33:49.000Z
|
2020-05-19T14:33:49.000Z
|
ros2_mod_ws/install/include/rcl_interfaces/srv/get_parameters__struct.hpp
|
mintforpeople/robobo-ros2-ios-port
|
1a5650304bd41060925ebba41d6c861d5062bfae
|
[
"Apache-2.0"
] | 3
|
2019-11-14T12:20:06.000Z
|
2020-08-07T13:51:10.000Z
|
modules/scene_manager/include/rcl_interfaces/srv/get_parameters__struct.hpp
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
// generated from rosidl_generator_cpp/resource/srv__struct.hpp.em
// generated code does not contain a copyright notice
#ifndef RCL_INTERFACES__SRV__GET_PARAMETERS__STRUCT_HPP_
#define RCL_INTERFACES__SRV__GET_PARAMETERS__STRUCT_HPP_
#include "rcl_interfaces/srv/get_parameters__request.hpp"
#include "rcl_interfaces/srv/get_parameters__response.hpp"
namespace rcl_interfaces
{
namespace srv
{
struct GetParameters
{
using Request = rcl_interfaces::srv::GetParameters_Request;
using Response = rcl_interfaces::srv::GetParameters_Response;
};
} // namespace srv
} // namespace rcl_interfaces
#endif // RCL_INTERFACES__SRV__GET_PARAMETERS__STRUCT_HPP_
| 24.666667
| 66
| 0.83033
|
Omnirobotic
|
ca4561089a60eae8772f3015894f365b5a63d25f
| 3,044
|
cpp
|
C++
|
PhotoSynthViewer/src/DynamicLines.cpp
|
dddExperiments/PhotoSynthToolkit
|
4f81577ca347c30c9c142bad2e6edc278e38a4ca
|
[
"Unlicense",
"MIT"
] | 17
|
2015-02-10T17:44:42.000Z
|
2021-07-13T01:07:37.000Z
|
PhotoSynthViewer/src/DynamicLines.cpp
|
Acidburn0zzz/PhotoSynthToolkit
|
4f81577ca347c30c9c142bad2e6edc278e38a4ca
|
[
"Unlicense",
"MIT"
] | null | null | null |
PhotoSynthViewer/src/DynamicLines.cpp
|
Acidburn0zzz/PhotoSynthToolkit
|
4f81577ca347c30c9c142bad2e6edc278e38a4ca
|
[
"Unlicense",
"MIT"
] | 11
|
2015-01-15T04:21:40.000Z
|
2017-06-12T09:24:47.000Z
|
////http://www.ogre3d.org/tikiwiki/DynamicLineDrawing
#include "DynamicLines.h"
#include <Ogre.h>
#include <cassert>
#include <cmath>
using namespace Ogre;
enum {
POSITION_BINDING,
TEXCOORD_BINDING
};
DynamicLines::DynamicLines(OperationType opType)
{
initialize(opType,false);
setMaterial("BaseWhiteNoLighting");
mDirty = true;
}
DynamicLines::~DynamicLines()
{
}
void DynamicLines::setOperationType(OperationType opType)
{
mRenderOp.operationType = opType;
}
RenderOperation::OperationType DynamicLines::getOperationType() const
{
return mRenderOp.operationType;
}
void DynamicLines::addPoint(const Vector3 &p)
{
mPoints.push_back(p);
mDirty = true;
}
void DynamicLines::addPoint(Real x, Real y, Real z)
{
mPoints.push_back(Vector3(x,y,z));
mDirty = true;
}
const Vector3& DynamicLines::getPoint(unsigned short index) const
{
assert(index < mPoints.size() && "Point index is out of bounds!!");
return mPoints[index];
}
unsigned short DynamicLines::getNumPoints(void) const
{
return (unsigned short)mPoints.size();
}
void DynamicLines::setPoint(unsigned short index, const Vector3 &value)
{
assert(index < mPoints.size() && "Point index is out of bounds!!");
mPoints[index] = value;
mDirty = true;
}
void DynamicLines::clear()
{
mPoints.clear();
mDirty = true;
}
void DynamicLines::update()
{
if (mDirty) fillHardwareBuffers();
}
void DynamicLines::createVertexDeclaration()
{
VertexDeclaration *decl = mRenderOp.vertexData->vertexDeclaration;
decl->addElement(POSITION_BINDING, 0, VET_FLOAT3, VES_POSITION);
}
void DynamicLines::fillHardwareBuffers()
{
int size = mPoints.size();
prepareHardwareBuffers(size,0);
if (!size) {
mBox.setExtents(Vector3::ZERO,Vector3::ZERO);
mDirty=false;
return;
}
Vector3 vaabMin = mPoints[0];
Vector3 vaabMax = mPoints[0];
HardwareVertexBufferSharedPtr vbuf =
mRenderOp.vertexData->vertexBufferBinding->getBuffer(0);
Real *prPos = static_cast<Real*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
{
for(int i = 0; i < size; i++)
{
*prPos++ = mPoints[i].x;
*prPos++ = mPoints[i].y;
*prPos++ = mPoints[i].z;
if(mPoints[i].x < vaabMin.x)
vaabMin.x = mPoints[i].x;
if(mPoints[i].y < vaabMin.y)
vaabMin.y = mPoints[i].y;
if(mPoints[i].z < vaabMin.z)
vaabMin.z = mPoints[i].z;
if(mPoints[i].x > vaabMax.x)
vaabMax.x = mPoints[i].x;
if(mPoints[i].y > vaabMax.y)
vaabMax.y = mPoints[i].y;
if(mPoints[i].z > vaabMax.z)
vaabMax.z = mPoints[i].z;
}
}
vbuf->unlock();
mBox.setExtents(vaabMin, vaabMax);
mDirty = false;
}
/*
void DynamicLines::getWorldTransforms(Matrix4 *xform) const
{
// return identity matrix to prevent parent transforms
*xform = Matrix4::IDENTITY;
}
*/
/*
const Quaternion &DynamicLines::getWorldOrientation(void) const
{
return Quaternion::IDENTITY;
}
const Vector3 &DynamicLines::getWorldPosition(void) const
{
return Vector3::ZERO;
}
*/
| 21.138889
| 76
| 0.676084
|
dddExperiments
|
ca47311ad3f0177055e82ffce67aab26f62f4ec4
| 11,578
|
hpp
|
C++
|
simcore/simulation/library/default_params.hpp
|
lamsoa729/simcore
|
daf7056cb0c17563ed0f6bdee343fa1f6cd59729
|
[
"MIT"
] | null | null | null |
simcore/simulation/library/default_params.hpp
|
lamsoa729/simcore
|
daf7056cb0c17563ed0f6bdee343fa1f6cd59729
|
[
"MIT"
] | null | null | null |
simcore/simulation/library/default_params.hpp
|
lamsoa729/simcore
|
daf7056cb0c17563ed0f6bdee343fa1f6cd59729
|
[
"MIT"
] | null | null | null |
YAML::Node default_config;
default_config["species"]["num"] = "0";
default_config["species"]["insertion_type"] = "random";
default_config["species"]["insert_file"] = "none";
default_config["species"]["overlap"] = "0";
default_config["species"]["draw_type"] = "orientation";
default_config["species"]["color"] = "0";
default_config["species"]["posit_flag"] = "0";
default_config["species"]["spec_flag"] = "0";
default_config["species"]["checkpoint_flag"] = "0";
default_config["species"]["n_posit"] = "100";
default_config["species"]["n_spec"] = "100";
default_config["species"]["n_checkpoint"] = "10000";
default_config["filament"]["diameter"] = "1";
default_config["filament"]["length"] = "-1";
default_config["filament"]["persistence_length"] = "400";
default_config["filament"]["max_length"] = "500";
default_config["filament"]["min_bond_length"] = "1.5";
default_config["filament"]["spiral_flag"] = "0";
default_config["filament"]["spiral_number_fail_condition"] = "0";
default_config["filament"]["driving_factor"] = "0";
default_config["filament"]["friction_ratio"] = "2";
default_config["filament"]["dynamic_instability_flag"] = "0";
default_config["filament"]["force_induced_catastrophe_flag"] = "0";
default_config["filament"]["optical_trap_flag"] = "0";
default_config["filament"]["optical_trap_spring"] = "20";
default_config["filament"]["optical_trap_fixed"] = "0";
default_config["filament"]["cilia_trap_flag"] = "0";
default_config["filament"]["fic_factor"] = "0.828";
default_config["filament"]["f_shrink_to_grow"] = "0.017";
default_config["filament"]["f_shrink_to_pause"] = "0.0";
default_config["filament"]["f_pause_to_grow"] = "0.0";
default_config["filament"]["f_pause_to_shrink"] = "0.0";
default_config["filament"]["f_grow_to_pause"] = "0.0";
default_config["filament"]["f_grow_to_shrink"] = "0.00554";
default_config["filament"]["metric_forces"] = "1";
default_config["filament"]["v_poly"] = "0.44";
default_config["filament"]["v_depoly"] = "0.793";
default_config["filament"]["theta_analysis"] = "0";
default_config["filament"]["lp_analysis"] = "0";
default_config["filament"]["global_order_analysis"] = "0";
default_config["filament"]["packing_fraction"] = "-1";
default_config["filament"]["perlen_ratio"] = "-1";
default_config["filament"]["n_bonds"] = "-1";
default_config["filament"]["driving_method"] = "0";
default_config["filament"]["n_equil"] = "0";
default_config["filament"]["orientation_corr_analysis"] = "0";
default_config["filament"]["orientation_corr_n_steps"] = "1000";
default_config["filament"]["crossing_analysis"] = "0";
default_config["filament"]["intrinsic_curvature"] = "0";
default_config["filament"]["flagella_flag"] = "0";
default_config["filament"]["flagella_freq"] = "1";
default_config["filament"]["flagella_period"] = "2";
default_config["filament"]["flagella_amplitude"] = "1";
default_config["filament"]["flocking_analysis"] = "0";
default_config["filament"]["polydispersity_flag"] = "0";
default_config["filament"]["polydispersity_factor"] = "0.03";
default_config["filament"]["polydispersity_warn_on_truncate"] = "0";
default_config["passive_filament"]["diameter"] = "1";
default_config["passive_filament"]["length"] = "-1";
default_config["passive_filament"]["persistence_length"] = "400";
default_config["passive_filament"]["max_length"] = "500";
default_config["passive_filament"]["min_length"] = "1";
default_config["passive_filament"]["max_bond_length"] = "5";
default_config["passive_filament"]["min_bond_length"] = "1.5";
default_config["passive_filament"]["driving_factor"] = "0";
default_config["passive_filament"]["friction_ratio"] = "2";
default_config["passive_filament"]["metric_forces"] = "1";
default_config["passive_filament"]["theta_analysis"] = "0";
default_config["passive_filament"]["lp_analysis"] = "0";
default_config["passive_filament"]["packing_fraction"] = "-1";
default_config["passive_filament"]["perlen_ratio"] = "-1";
default_config["passive_filament"]["n_bonds"] = "-1";
default_config["hard_rod"]["diameter"] = "1";
default_config["hard_rod"]["length"] = "40";
default_config["hard_rod"]["min_length"] = "3";
default_config["hard_rod"]["max_length"] = "300";
default_config["hard_rod"]["max_bond_length"] = "5";
default_config["hard_rod"]["driving_factor"] = "0";
default_config["br_bead"]["diameter"] = "1";
default_config["br_bead"]["driving_factor"] = "0";
default_config["br_bead"]["packing_fraction"] = "-1";
default_config["md_bead"]["diameter"] = "1";
default_config["md_bead"]["mass"] = "1";
default_config["md_bead"]["driving_factor"] = "0";
default_config["centrosome"]["diameter"] = "10";
default_config["centrosome"]["n_filaments_min"] = "0";
default_config["centrosome"]["n_filaments_max"] = "10";
default_config["centrosome"]["fixed_spacing"] = "0";
default_config["centrosome"]["alignment_potential"] = "0";
default_config["centrosome"]["k_spring"] = "1000";
default_config["centrosome"]["k_align"] = "0";
default_config["centrosome"]["spring_length"] = "0";
default_config["motor"]["diameter"] = "3";
default_config["motor"]["walker"] = "0";
default_config["motor"]["step_direction"] = "0";
default_config["motor"]["k_off"] = "2";
default_config["motor"]["k_on"] = "10";
default_config["motor"]["concentration"] = "0";
default_config["motor"]["velocity"] = "1";
default_config["motor"]["diffusion_flag"] = "1";
default_config["motor"]["k_spring"] = "1000";
default_config["motor"]["f_spring_max"] = "100";
default_config["bead_spring"]["diameter"] = "1";
default_config["bead_spring"]["length"] = "40";
default_config["bead_spring"]["persistence_length"] = "4000";
default_config["bead_spring"]["max_bond_length"] = "1";
default_config["bead_spring"]["bond_rest_length"] = "0.8";
default_config["bead_spring"]["bond_spring"] = "100";
default_config["bead_spring"]["driving_factor"] = "0";
default_config["bead_spring"]["lp_analysis"] = "0";
default_config["bead_spring"]["theta_analysis"] = "0";
default_config["bead_spring"]["packing_fraction"] = "-1";
default_config["spherocylinder"]["diameter"] = "1";
default_config["spherocylinder"]["length"] = "5";
default_config["spherocylinder"]["diffusion_analysis"] = "0";
default_config["spherocylinder"]["n_diffusion_samples"] = "1";
default_config["spherocylinder"]["midstep"] = "0";
default_config["spindle"]["diameter"] = "10";
default_config["spindle"]["length"] = "20";
default_config["spindle"]["n_filaments_bud"] = "1";
default_config["spindle"]["n_filaments_mother"] = "0";
default_config["spindle"]["alignment_potential"] = "0";
default_config["spindle"]["k_spring"] = "1000";
default_config["spindle"]["k_align"] = "0";
default_config["spindle"]["spring_length"] = "0";
default_config["spindle"]["spb_diameter"] = "5";
default_config["crosslink"]["concentration"] = "0";
default_config["crosslink"]["diameter"] = "1";
default_config["crosslink"]["walker"] = "0";
default_config["crosslink"]["velocity"] = "1";
default_config["crosslink"]["diffusion_flag"] = "0";
default_config["crosslink"]["k_on"] = "10";
default_config["crosslink"]["k_off"] = "2";
default_config["crosslink"]["k_on_d"] = "10";
default_config["crosslink"]["k_off_d"] = "2";
default_config["crosslink"]["force_dep_factor"] = "1";
default_config["crosslink"]["polar_affinity"] = "0";
default_config["crosslink"]["k_spring"] = "10";
default_config["crosslink"]["f_spring_max"] = "1000";
default_config["crosslink"]["f_stall"] = "100";
default_config["crosslink"]["force_dep_vel_flag"] = "1";
default_config["crosslink"]["k_align"] = "0";
default_config["crosslink"]["rest_length"] = "0";
default_config["crosslink"]["step_direction"] = "0";
default_config["crosslink"]["tether_draw_type"] = "orientation";
default_config["crosslink"]["tether_diameter"] = "0.5";
default_config["crosslink"]["tether_color"] = "3.1416";
default_config["crosslink"]["end_pausing"] = "0";
default_config["crosslink"]["r_capture"] = "5";
default_config["seed"] = "7859459105545";
default_config["n_runs"] = "1";
default_config["n_random"] = "1";
default_config["run_name"] = "sc";
default_config["n_dim"] = "3";
default_config["n_periodic"] = "0";
default_config["boundary"] = "0";
default_config["system_radius"] = "100";
default_config["n_steps"] = "1000000";
default_config["i_step"] = "0";
default_config["delta"] = "0.001";
default_config["cell_length"] = "10";
default_config["n_update_cells"] = "0";
default_config["graph_flag"] = "0";
default_config["n_graph"] = "1000";
default_config["graph_diameter"] = "0";
default_config["graph_background"] = "1";
default_config["draw_boundary"] = "1";
default_config["load_checkpoint"] = "0";
default_config["checkpoint_run_name"] = "sc";
default_config["n_load"] = "0";
default_config["print_complete"] = "0";
default_config["insertion_type"] = "species";
default_config["movie_flag"] = "0";
default_config["movie_directory"] = "frames";
default_config["time_analysis"] = "0";
default_config["bud_height"] = "680";
default_config["bud_radius"] = "300";
default_config["lj_epsilon"] = "1";
default_config["wca_eps"] = "1";
default_config["wca_sig"] = "1";
default_config["ss_a"] = "1";
default_config["ss_rs"] = "1.5";
default_config["ss_eps"] = "1";
default_config["f_cutoff"] = "2000";
default_config["max_overlap"] = "100000";
default_config["constant_pressure"] = "0";
default_config["constant_volume"] = "0";
default_config["target_pressure"] = "0";
default_config["target_radius"] = "100";
default_config["pressure_time"] = "100";
default_config["compressibility"] = "1";
default_config["stoch_flag"] = "1";
default_config["thermo_flag"] = "0";
default_config["n_thermo"] = "1000";
default_config["interaction_flag"] = "1";
default_config["species_insertion_failure_threshold"] = "10000";
default_config["species_insertion_reattempt_threshold"] = "10";
default_config["uniform_crystal"] = "0";
default_config["n_steps_equil"] = "0";
default_config["n_steps_target"] = "100000";
default_config["static_particle_number"] = "0";
default_config["checkpoint_from_spec"] = "0";
default_config["potential"] = "wca";
default_config["soft_potential_mag"] = "10";
default_config["soft_potential_mag_target"] = "-1";
default_config["like_like_interactions"] = "1";
default_config["auto_graph"] = "0";
default_config["local_order_analysis"] = "0";
default_config["local_order_width"] = "50";
default_config["local_order_bin_width"] = "0.5";
default_config["local_order_average"] = "1";
default_config["local_order_n_analysis"] = "100";
default_config["density_analysis"] = "0";
default_config["density_bin_width"] = "0.1";
default_config["density_com_only"] = "0";
default_config["polar_order_analysis"] = "0";
default_config["polar_order_n_bins"] = "100";
default_config["polar_order_contact_cutoff"] = "3";
default_config["polar_order_color"] = "0";
default_config["overlap_analysis"] = "0";
default_config["highlight_overlaps"] = "0";
default_config["reduced"] = "0";
default_config["reload_reduce_switch"] = "0";
default_config["flock_polar_min"] = "0.5";
default_config["flock_contact_min"] = "1.5";
default_config["highlight_flock"] = "0";
default_config["flock_color_ext"] = "1.57";
default_config["flock_color_int"] = "4.71";
default_config["in_out_flag"] = "0";
| 50.121212
| 70
| 0.687856
|
lamsoa729
|
ca476e6a035c65f65acd00770f2efc24acfec253
| 10,417
|
cpp
|
C++
|
fileIO.cpp
|
CherryPill/tex_edit
|
6a0287f892068a44e60bd67d60a4b4272bbc3c60
|
[
"MIT"
] | null | null | null |
fileIO.cpp
|
CherryPill/tex_edit
|
6a0287f892068a44e60bd67d60a4b4272bbc3c60
|
[
"MIT"
] | null | null | null |
fileIO.cpp
|
CherryPill/tex_edit
|
6a0287f892068a44e60bd67d60a4b4272bbc3c60
|
[
"MIT"
] | null | null | null |
#include <windows.h>
#include <tchar.h>
#include <commctrl.h>
#include <richedit.h>
#include <iostream>
#include <string>
#include <atlstr.h>
#include <cassert>
#include "appconst.h"
#include "toolbarControl.h"
#include "statusControl.h"
#include "mainWindowProc.h"
#include "menuids.h"
#include "mainPrefs.h"
#include "fileIO.h"
#include "globalVars.h"
#include "recentFiles.h"
#include "translations.h"
#include "service.h"
//converts menuindex to vector index and gets the filename from the string vector
WPARAM convertMenu2VecIndex(WPARAM menuIndex) {
//use throw catch here if menuIndex<22
WPARAM vecIndex = recentDocsList.size()-(menuIndex-IDM_REC_CLEAR);
//WPARAM vecIndex = (menuIndex - IDM_REC_CLEAR - 1);
return vecIndex;
}
std::string getRecentlyOpenedFileName(WPARAM index) {
return recentDocsList.at(index);
}
int detectFileType(std::string strPath) {
int startingPos = strPath.length()-4-1;
return strPath.find("rtf",startingPos)==-1?1:2;
}
int getActivatedFileMode(void) {
return OPENMODE; //1 - txt, 2 - rtf.
}
LPCTSTR getCurrentlyOpenedFileName(void) {
return (LPCTSTR)currentlyOpenedFile;
}
DWORD CALLBACK EditStreamCallbackIn(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, PLONG pcb) {
HANDLE hFile = (HANDLE)dwCookie;
if (ReadFile(hFile, lpBuff, cb, (DWORD *)pcb, NULL)) {
return 0;
}
return -1;
}
DWORD CALLBACK EditStreamCallbackOut(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, PLONG pcb) {
HANDLE hFile = (HANDLE)dwCookie;
if (WriteFile(hFile, lpBuff, cb, (DWORD *)pcb, NULL)) {
return 0;
}
return -1;
}
void openFileDiag(HWND mainWindow, int mode) { //0 - open, 1 - save as {
int fileTypeSaveOpen = 0;
OPENFILENAME fileName;
TCHAR szFile[MAX_PATH];
ZeroMemory(&fileName, sizeof(fileName));
fileName.lStructSize = sizeof(fileName);
fileName.lpstrFile = szFile;
fileName.lpstrFile[0] = '\0';
fileName.hwndOwner = mainWindow;
fileName.nMaxFile = sizeof(szFile);
fileName.lpstrFilter = _T("Text Files (*.txt)\0*.txt\0RTF files (*.rtf)\0*.rtf*\0");
//_T("Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0");
fileName.nFilterIndex = OPENMODE; //1 - .txt, 2 - .rtf
if (mode) {
fileName.Flags =
OFN_PATHMUSTEXIST
| OFN_OVERWRITEPROMPT
| OFN_EXPLORER
| OFN_HIDEREADONLY;
}
else {
fileName.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
}
if (mode) {
if (GetSaveFileName(&fileName)) {
fileTypeSaveOpen = fileName.nFilterIndex;
loadSaveFile(fileName.lpstrFile,mode,fileTypeSaveOpen);
_tcscpy(currentlyOpenedFile, szFile);
SetWindowText(hwnd, getCurrentlyOpenedFileName());
changeStatusControlMessage(2);
fileChanged = false;
fileLoaded = true;
disableFastSaveIcon();
}
//usr canceled out
else {
fileChanged = true;
}
}
else {
if (GetOpenFileName(&fileName)) {
fileTypeSaveOpen = fileName.nFilterIndex;
loadSaveFile(fileName.lpstrFile,mode,fileTypeSaveOpen);
_tcscpy(currentlyOpenedFile,szFile);
SetWindowText(hwnd, getCurrentlyOpenedFileName());
changeStatusControlMessage(1);
fileLoaded = true;
fileChanged = false;
//append
if (!recentDocsList.size()) {
recentDocsList_push(getCurrentlyOpenedFileName(), 0);
}
//insert before currAddRecent-1
else {
recentDocsList_push(getCurrentlyOpenedFileName(), 1);
}
}
}
}
//stream mode: 1 - write to file, 0 - write to editor
void loadSaveFile(LPTSTR filePath, int streamMode, int fileType) {
streamMode?FillFileFromRichEdit((LPCTSTR(filePath)),fileType):FillRichEditFromFile((LPCTSTR)filePath,fileType);
}
//1 - txt, 2 - rtf
void FillRichEditFromFile(LPCTSTR pszFile, int fileType) {
//settings.recentDocsList.push_back(pszFile);
WPARAM OPENFILETYPE;
assert(fileType>0);
if (fileType == 1) {
OPENMODE = 1;
OPENFILETYPE = SF_TEXT;
}
else if (fileType == 2) {
OPENMODE = 2;
OPENFILETYPE = SF_RTF;
}
BOOL fSuccess = FALSE;
HANDLE hFile = CreateFile(pszFile, GENERIC_READ,
FILE_SHARE_READ, 0, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, NULL);
//file exists
if (hFile != INVALID_HANDLE_VALUE) {
EDITSTREAM es = {0}; //main stream structure
es.pfnCallback = EditStreamCallbackIn;
es.dwCookie = (DWORD_PTR)hFile;
if (SendMessage(richEditControl, EM_STREAMIN, OPENFILETYPE, (LPARAM)&es) && es.dwError == 0) {
fSuccess = TRUE;
}
CloseHandle(hFile);
//TODO change to string CA2T/CT2A
std::wstring str = CW2W(pszFile);
//incrementRecentDocs(str); non-functional
//setting titlebar text to file path
//TODO resolve for settings file
if (settings.bShowCompleteFilePathInTitle) {
setWindowTitleToFile(pszFile, 1);
}
else {
setWindowTitleToFile(pszFile, 0);
}
//cutoff
//txt clause block toolbar formatting
if (!OPENMODE) {
disableFormattingOptions();
}
else {
enableFormattingOptions();
}
//save pszFile to global tracker
}
else {
//if file isn't found
MessageBox(hwnd, commDlgMsgError_EN[1], commDlgMsgErrorCaptions_EN[0], MB_ICONERROR | MB_OK);
if (askForDeletion())
{
recentDocsList_delete(pszFile);
}
//TODO: Prompt to delete from the recent list of files
}
}
void saveFile(void)
{
//stub
}
void FillFileFromRichEdit(LPCTSTR pszFile, int fileType) {
WPARAM SAVEFILETYPE;
assert(fileType);
if (fileType == 1) {
_tcscat((wchar_t*)pszFile,txtExt); //appending extension
SAVEFILETYPE = SF_TEXT;
}
else if (fileType == 2) {
_tcscat((wchar_t*)pszFile, rtfExt);
SAVEFILETYPE = SF_RTF;
}
BOOL fSuccess = FALSE;
HANDLE hFile = CreateFile(pszFile, GENERIC_WRITE,
0, 0, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
EDITSTREAM es = { 0 }; //main stream structure
es.pfnCallback = EditStreamCallbackOut;
es.dwCookie = (DWORD_PTR)hFile;
if (SendMessage(richEditControl, EM_STREAMOUT, (CP_UTF8 << 16) | SF_USECODEPAGE | SF_TEXT, (LPARAM)&es) && es.dwError == 0)
{
fSuccess = TRUE;
}
//cursor goes back to normal here
CloseHandle(hFile);
_tcscpy(currentlyOpenedFile, pszFile);
}
else {
MessageBox(hwnd, commDlgMsgError_EN[0], commDlgMsgErrorCaptions_EN[0], MB_OK | MB_ICONERROR);
}
}
void silentSaving(void) {
//silentSaving();
//initWaitCursor();
FillFileFromRichEdit(getCurrentlyOpenedFileName(), getActivatedFileMode()); //EXPLICIT CALL BE CAREFUL HERE
//resetCursor();
//MessageBox(hwnd, _T("Silently saved"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
changeStatusControlMessage(3);
SetWindowText(hwnd, getCurrentlyOpenedFileName());
fileChanged = false;
fileSaved = true;
disableFastSaveIcon();
}
void setWindowTitleToFile(LPCTSTR filePath, int mode)
{
TCHAR titleAppend[126];
LPCTSTR *file;
//complete
if (mode) {
_tcscpy(titleAppend, filePath);
_tcscat(titleAppend, _T(" - TexEdit"));
}
else {
file = cutoffFileName(filePath);
_tcscpy(titleAppend,(const wchar_t*)file);
}
SetWindowText(hwnd, titleAppend);
}
LPCTSTR *cutoffFileName(LPCTSTR fullPath) {
wchar_t fileNameExt[CHAR_MAX];
wchar_t drive[CHAR_MAX];
wchar_t dir[CHAR_MAX];
wchar_t fileName[CHAR_MAX];
wchar_t ext[CHAR_MAX];
_wsplitpath(fullPath,drive,dir,fileName,ext);
//LPCTSTR *res = (LPCTSTR*)_tcsrchr((const wchar_t*)fullPath,(wchar_t)'\\');
//assert(res);
//res = (LPCTSTR*)_tcstok((wchar_t*)res,(const wchar_t*)'\\');
_tcscpy(fileNameExt,fileName);
_tcscat(fileNameExt,ext);
return (LPCTSTR*)fileNameExt;
}
//save as
void initSavingAsSequence(void) {
openFileDiag(hwnd,1);
}
void initSilentSavingSequence(void) {
if (fileLoaded) {
if (fileChanged) {
silentSaving();
}
}
else {
if (fileChanged) {
openFileDiag(hwnd, 1);
}
else {
MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
}
}
}
//1 - txt, 2 - rtf
void fromRecent::initOpeningSequence(LPCTSTR filePath,int mode) {
if (fileLoaded) {
if (fileChanged) {
if (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL) == IDYES) {
silentSaving();
}
else{
FillRichEditFromFile(filePath, mode);
}
}
else {
FillRichEditFromFile(filePath, mode);
}
}
else {
if (fileChanged) {
switch (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL)) {
case IDYES: {
openFileDiag(hwnd, 1);
break;
}
case IDNO: {
FillRichEditFromFile(filePath, mode);
break;
}
case IDCANCEL: {
break;
}
}
}
else {
FillRichEditFromFile(filePath, mode);
//MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
}
}
}
void normal::initOpeningSequence(void) {
if (fileLoaded) {
if (fileChanged) {
if (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL) == IDYES) {
silentSaving();
}
else {
openFileDiag(hwnd,0);
}
}
else {
openFileDiag(hwnd,0);
}
}
else {
if (fileChanged) {
switch (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL)) {
case IDYES: {
openFileDiag(hwnd, 1);
break;
}
case IDNO: {
openFileDiag(hwnd, 0);
break;
}
case IDCANCEL: {
break;
}
}
}
else {
openFileDiag(hwnd,0);
//MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
}
}
}
//1 - txt, 2 - rtf
void initNewSequence(int mode) {
if (fileLoaded) {
if (fileChanged) {
if (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL) == IDYES) {
silentSaving();
}
else {
activateRespMode(mode);
}
}
else {
activateRespMode(mode);
}
}
else {
//bug with multiple new instances
if (fileChanged) {
switch (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL)) {
case IDYES: {
openFileDiag(hwnd, 1);
break;
}
case IDNO: {
activateRespMode(mode);
break;
}
case IDCANCEL: {
break;
}
}
}
else {
//MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
activateRespMode(mode);
}
}
}
void activateRespMode(int mode) {
if (mode == 2) {
activateNewRTFMode();
}
else if (mode == 1) {
activateNewTXTMode();
}
fileLoaded = false;
fileChanged = false;
}
| 25.657635
| 131
| 0.690698
|
CherryPill
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.