hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
87c4d8fa66c9f5f2e3ed02ff173f3d1779959733 | 9,058 | cpp | C++ | examples/common-qt/tcpclient.cpp | JohanVanslembrouck/corolib | 0ebbabfe368c29901bf96ae1d3b6e989e3ff82c9 | [
"MIT"
] | 1 | 2021-08-19T13:49:01.000Z | 2021-08-19T13:49:01.000Z | examples/common-qt/tcpclient.cpp | JohanVanslembrouck/corolib | 0ebbabfe368c29901bf96ae1d3b6e989e3ff82c9 | [
"MIT"
] | null | null | null | examples/common-qt/tcpclient.cpp | JohanVanslembrouck/corolib | 0ebbabfe368c29901bf96ae1d3b6e989e3ff82c9 | [
"MIT"
] | null | null | null | /**
* @file
* @brief
*
* @author Johan Vanslembrouck (johan.vanslembrouck@altran.com, johan.vanslembrouck@gmail.com)
*/
#include "tcpclient.h"
/**
* @brief TcpClient::TcpClient
* @param name
* @param autoConnect
* @param waitForConnectionTimeout
* @param reconnectTimeout
* @param reconnectTimeoutAfterDisconnect
*/
TcpClient::TcpClient(const QString& name,
bool autoConnect,
qint32 waitForConnectionTimeout,
qint32 reconnectTimeout,
qint32 reconnectTimeoutAfterDisconnect)
: m_timer(this)
, m_autoConnect(autoConnect)
, m_name(name)
, m_waitForConnectionTimeout(waitForConnectionTimeout)
, m_reconnectTimeout(reconnectTimeout)
, m_reconnectTimeoutAfterDisconnect(reconnectTimeoutAfterDisconnect)
{
qInfo() << Q_FUNC_INFO << m_name << ", autoConnect = " << autoConnect;
}
/**
* @brief TCPClient::configure
*/
void TcpClient::configure()
{
qInfo() << Q_FUNC_INFO << m_name;
// Client starts timer to reconnect to server if connection was lost.
m_timer.setSingleShot(true);
connect(&m_timer, &QTimer::timeout, this, &TcpClient::connectToServerTimed);
}
/**
* @brief TcpClient::connectToServerTimed
*/
void TcpClient::connectToServerTimed()
{
qInfo() << Q_FUNC_INFO << m_name;
connectToServer(m_serverIPaddress, m_serverPort);
}
/**
* @brief TcpClient::enableKeepAlive
* @param socket
*/
void TcpClient::enableKeepAlive(QTcpSocket *socket)
{
// https://doc.qt.io/qt-5/qabstractsocket.html#setSocketOption
// Note: On Windows Runtime, QAbstractSocket::KeepAliveOption must be set before the socket is connected.
if (socket)
{
// https://doc.qt.io/qt-5/qabstractsocket.html#SocketOption-enum
socket->setSocketOption(QAbstractSocket::KeepAliveOption, true);
}
}
/**
* @brief TcpClient::connectToServer
* @param serverIPaddress
* @param serverPort
* @return
*/
bool TcpClient::connectToServer(QString& serverIPaddress, quint16 serverPort)
{
qInfo() << Q_FUNC_INFO << m_name;
qInfo() << "serverIPaddress = " << serverIPaddress << ", serverPort = " << serverPort;
bool retVal = false;
m_serverIPaddress = serverIPaddress;
m_serverPort = serverPort;
QTcpSocket* socket = new QTcpSocket(this);
if (socket)
{
socket->connectToHost(serverIPaddress, serverPort);
qInfo() << "Start waiting";
if (socket->waitForConnected(m_waitForConnectionTimeout)) // default value = 30000 msec
{
qDebug() << Q_FUNC_INFO << "Connected to server:" << serverIPaddress << ":" << serverPort;
enableKeepAlive(socket);
ConnectionInfo* connectionInfo = new ConnectionInfo;
if (connectionInfo)
{
connectionInfo->m_socket = socket;
connectionInfo->m_connection_ReadyRead = connect(socket, &QTcpSocket::readyRead, this, &TcpClient::readyReadTcp);
connectionInfo->m_connection_disconnected = connect(socket, &QTcpSocket::disconnected, this, &TcpClient::disconnectedServer);
connectionInfo->m_connection_stateChanged = connect(socket, &QTcpSocket::stateChanged, this, &TcpClient::stateChanged);
m_connectionInfoList.append(connectionInfo);
emit connectedSig();
retVal = true;
}
else
{
qCritical() << Q_FUNC_INFO << "could not allocate connection info object";
}
}
else
{
if (true)
{
QAbstractSocket::SocketError error = socket->error();
QAbstractSocket::SocketState state = socket->state();
qDebug() << Q_FUNC_INFO;
qDebug() << " Error = " << error;
qDebug() << " State = " << state;
qDebug() << " Could not connect to server...";
}
closeConnection(socket);
// Start timer to reconnect to server
qDebug() << Q_FUNC_INFO << "Starting timer";
m_timer.start(m_reconnectTimeout);
}
}
else
{
qCritical() << Q_FUNC_INFO << "could not allocate QTcpSocket object";
}
return retVal;
}
/**
* @brief TcpClient::disconnectFromServer
* Function called from business logic class to disconnect from server
*/
void TcpClient::disconnectFromServer()
{
qDebug() << Q_FUNC_INFO << m_name;
foreach (ConnectionInfo *connectionInfo, m_connectionInfoList)
{
disconnect(connectionInfo->m_connection_ReadyRead);
disconnect(connectionInfo->m_connection_disconnected);
disconnect(connectionInfo->m_connection_stateChanged);
closeConnection(connectionInfo->m_socket);
}
m_connectionInfoList.clear();
// Stop the timer for in case it was running to try to reconnect
m_timer.stop();
}
/**
* @brief TCPClient::sendMessage
* @param message
*/
void TcpClient::sendMessage(QByteArray& message)
{
qInfo() << Q_FUNC_INFO << m_name;
qInfo() << message.length() << message;
foreach (ConnectionInfo *connectionInfo, m_connectionInfoList)
{
qInfo() << connectionInfo->m_socket;
if (connectionInfo->m_socket)
{
qint64 nrBytesWritten = connectionInfo->m_socket->write(message);
if (nrBytesWritten == -1)
qWarning() << Q_FUNC_INFO << "write returned -1";
else if (nrBytesWritten < message.length())
qWarning() << Q_FUNC_INFO << "only" << nrBytesWritten << "of" << message.length() << "bytes written";
bool res = connectionInfo->m_socket->flush();
// We get a lot of these messages when the network connection is unavailable for a long time
if (!res)
qInfo() << Q_FUNC_INFO << "flush returned false";
}
}
}
/**
* @brief TcpClient::readyReadTcp
*
*/
void TcpClient::readyReadTcp()
{
qInfo() << Q_FUNC_INFO << m_name;
QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
if (socket)
{
QByteArray data = socket->readAll();
if (data.length() < 650)
qInfo() << data.length() << data;
else
qInfo() << data.length();
emit readyReadTcpSig(data);
}
else
{
qCritical() << Q_FUNC_INFO << "sender() returned null pointer";
}
}
/**
* @brief TcpClient::disconnectedServer
* is used exclusively on the client side to deal with a disconnected server.
*/
void TcpClient::disconnectedServer()
{
qInfo() << Q_FUNC_INFO << m_name;
qDebug() << Q_FUNC_INFO << "Disconnected from server";
QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
if (socket)
{
qDebug() << "Socket disconnected " << socket;
qDebug() << "Socket parent " << socket->parent();
QList<ConnectionInfo*> toRemoveList;
int count = 0;
foreach (ConnectionInfo* connectionInfo, m_connectionInfoList)
{
if (connectionInfo->m_socket == socket)
{
disconnect(connectionInfo->m_connection_ReadyRead);
disconnect(connectionInfo->m_connection_disconnected);
disconnect(connectionInfo->m_connection_stateChanged);
toRemoveList.append(connectionInfo);
count++;
}
}
if (count == 0)
qCritical() << Q_FUNC_INFO << "socket not found in connection info list";
if (count > 1)
qCritical() << Q_FUNC_INFO << "socket found" << count << "times in connection info list";
foreach (ConnectionInfo* connectionInfo, m_connectionInfoList)
{
m_connectionInfoList.removeOne(connectionInfo);
delete connectionInfo;
}
toRemoveList.clear();
closeConnection(socket);
if (m_autoConnect)
{
// Start timer to reconnect to server
qDebug() << Q_FUNC_INFO << "Starting timer" << endl;
m_timer.start(m_reconnectTimeoutAfterDisconnect);
}
emit disconnectedServerSig();
}
else
{
qCritical() << Q_FUNC_INFO << "sender() returned null pointer";
}
}
/**
* @brief TCPClient::stateChanged
* @param socketState
*/
void TcpClient::stateChanged(QAbstractSocket::SocketState socketState)
{
qInfo() << Q_FUNC_INFO << m_name;
qInfo() << "Socket state changed to: " << socketState;
}
/**
* @brief TcpClient::closeConnection
* @param socket
*/
void TcpClient::closeConnection(QTcpSocket *socket)
{
qDebug() << Q_FUNC_INFO << m_name << "socket = " << socket;
if (socket)
{
socket->disconnectFromHost(); // necessary?
socket->close();
// deleteLater() will schedule the object delete through the event loop so that any pending events for the object
// will be removed from the event queue and it can be safely deleted.
socket->deleteLater();
}
}
| 30.093023 | 141 | 0.616582 | [
"object"
] |
87c55ac6b46a1870dfc17f0457d35f8fd906175e | 444 | cpp | C++ | AtCoder/abc126/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/abc126/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/abc126/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
string S; cin >> S;
int a = (S[0] - '0') * 10 + (S[1] - '0'), b = (S[2] - '0') * 10 + (S[3] - '0');
if ((1 <= a && a <= 12) && (1 <= b && b <= 12)) printf("%s\n", "AMBIGUOUS");
else if (1 <= b && b <= 12) printf("%s\n", "YYMM");
else if (1 <= a && a <= 12) printf("%s\n", "MMYY");
else printf("%s\n", "NA");
}
| 31.714286 | 83 | 0.452703 | [
"vector"
] |
d7acfb2c39d4f836c378c6aba0b152e2bce1fb78 | 16,873 | cpp | C++ | code/EEC/csource/ECcrits_c.cpp | ftelschow/HPE | 9a6885d210bbc3235a859561fa180264d951755b | [
"MIT"
] | null | null | null | code/EEC/csource/ECcrits_c.cpp | ftelschow/HPE | 9a6885d210bbc3235a859561fa180264d951755b | [
"MIT"
] | null | null | null | code/EEC/csource/ECcrits_c.cpp | ftelschow/HPE | 9a6885d210bbc3235a859561fa180264d951755b | [
"MIT"
] | null | null | null | /***********************************************
* This file contains c implementations of the
* Euler characteristic for different dimensions
* using the lower star/critical value trick
*
***********************************************/
#include <math.h>
#include <matrix.h>
/* This is the C++ subroutine computing the change in Euler characterisitic in 2D
* Input:
* - *z: pointer to the input array
* - cc: integer giving the connectivity (currently, only 8 is supported)
* - ADD all inputs with short discribtion
*/
void ECcrit1D(double *z, double *out, mwSize i)
{
/*****************************************************************
* Initialize variables and constants
*****************************************************************/
int ii, s_ind, ss, ind_ss; // variables for loops
int dec = 0; // initialize the change in Euler characteristic as being 1, since 1 voxel is added
int nn = 0; // counter for accessing the values in dec while looping
double x[9]; // initialize array for values of neighbourhood of a voxel
int ind_t[9]; // initialize array for indices of neighbourhood of a voxel
/*****************************************************************
* loop over each voxel of the input z. Note that the original image
* was zero paded by with one -Inf. Hence we start each dimension at
* 1 and end at end-1.
*****************************************************************/
for(ii=1;ii<(i-1);ii++)
{
/*
* getting the indices of the 3x3x3 neighbourhood of
* the voxel (ii,jj,kk) and saving them in the ind_t array
*/
ind_t[0] = ii-1;
ind_t[1] = ii;
ind_t[2] = ii+1;
/* filling the x array using the indices of the
* neighbourhood ind_t and the input array z
*/
for(ss = 0; ss < 2; ss++)
{
s_ind = ind_t[ss];
x[ss] = *(z+s_ind);
}
/*****************************************************************
* let the even entries of out pointer point to the center voxel (ii,jj)
*****************************************************************/
*(out + nn*2) = x[1];
/******************************************************************
* compute the change in dec by checking which nD-faces are created
******************************************************************/
// minima increase EC by one
if(x[0] > x[1] && x[2] > x[1])
dec = 1;
// maxima decrease EC by one
if(x[0] > x[1] && x[2] > x[1])
dec = -1;
// save the dec in the odd out locations
*(out + nn*2 + 1) = dec;
// increase counter moving through dec saving locations
nn += 1;
// reset dec to be 1
dec = 1;
}
}
/* This is the C++ subroutine computing the change in Euler characterisitic in 2D
* Input:
* - *z: pointer to the input array
* - cc: integer giving the connectivity (currently, only 4 is supported)
* - ADD all inputs with short discribtion
*/
void ECcrit2D(double *z, double cc, double *out, mwSize i, mwSize j)
{
/*****************************************************************
* Initialize variables and constants
*****************************************************************/
int ii, jj, s_ind, ss, ind_ss; // variables for loops
int dec = 1; // initialize the change in Euler characteristic as being 1, since 1 voxel is added
int nn = 0; // counter for accessing the values in dec while looping
double x[9]; // initialize array for values of neighbourhood of a voxel
int ind_t[9]; // initialize array for indices of neighbourhood of a voxel
/*****************************************************************
* loop over each voxel of the input z. Note that the original image
* was zero paded by with one -Inf. Hence we start each dimension at
* 1 and end at end-1.
*****************************************************************/
for(ii=1;ii<(i-1);ii++)
{
for(jj=1;jj<(j-1);jj++)
{
/*
* getting the indices of the 3x3 neighbourhood of
* the voxel (ii,jj) and saving them in the ind_t array
*/
ind_t[0] = (ii-1) + (jj-1)*i;
ind_t[1] = (ii-1) + jj*i;
ind_t[2] = (ii-1) + (jj+1)*i;
ind_t[3] = ii + (jj-1)*i;
ind_t[4] = ii + jj*i;
ind_t[5] = ii + (jj+1)*i;
ind_t[6] = (ii+1) + (jj-1)*i;
ind_t[7] = (ii+1) + jj*i;
ind_t[8] = (ii+1) + (jj+1)*i;
/* filling the x array using the indices of the
* neighbourhood ind_t and the input array z
*/
for(ss = 0; ss < 9; ss++)
{
s_ind = ind_t[ss];
x[ss] = *(z+s_ind);
}
/*****************************************************************
* let the even entries of out pointer point to the center voxel (ii,jj)
*****************************************************************/
*(out + nn*2) = x[4];
/******************************************************************
* compute the change in dec by checking which nD-faces are created
******************************************************************/
if(cc==4){
// subtract number of edges
double ind1[4] = {1, 3, 5, 7};
double count_t = 0;
for( ss=0; ss < cc; ss++ ){
ind_ss = ind1[ss];
// if new edge appears increase dec by 1
if(x[ind_ss] > x[4])
{
count_t += 1;
}
}
dec = dec - count_t;
// add number of faces
if(x[0] > x[4] && x[1] > x[4] && x[3] > x[4])
dec += 1;
if(x[1] > x[4] && x[2] > x[4] && x[5] > x[4])
dec += 1;
if(x[3] > x[4] && x[6] > x[4] && x[7] > x[4])
dec += 1;
if(x[5] > x[4] && x[7] > x[4] && x[8] > x[4])
dec += 1;
} else if( cc == 8 ){
// subtract number of edges
double ind1[8] = { 0, 1, 2, 3, 5, 6, 7, 8 };
double count_t = 0;
for( ss=0; ss < cc; ss++ ){
ind_ss = ind1[ss];
// if new edge appears increase dec by 1
if( x[ind_ss] > x[4] )
{
count_t += 1;
}
}
dec = dec - count_t;
/* add number of faces, be careful since triangulation
requires to consider more cases */
// upper left quadrant
if( x[0] > x[4] && x[1] > x[4] && x[3] > x[4] ){
// +2 lines, +3 faces, +1 vertex = ECchange = 1-2+3
dec += 2;
} else if( ( x[0] > x[4] && x[1] > x[4] ) ||
( x[3] > x[4] && x[1] > x[4] ) ||
( x[0] > x[4] && x[3] > x[4] ) ) {
dec += 1;
}
// lower left quadrant
if( x[1] > x[4] && x[2] > x[4] && x[5] > x[4] ){
// +2 lines, +3 faces, +1 vertex = ECchange = 1-2+3
dec += 2;
} else if( ( x[2] > x[4] && x[1] > x[4] ) ||
( x[5] > x[4] && x[1] > x[4] ) ||
( x[2] > x[4] && x[5] > x[4] ) ) {
dec += 1;
}
// upper right quadrant
if( x[3] > x[4] && x[6] > x[4] && x[7] > x[4] ){
// +2 lines, +3 faces, +1 vertex = ECchange = 1-2+3
dec += 2;
} else if( ( x[6] > x[4] && x[3] > x[4] ) ||
( x[3] > x[4] && x[7] > x[4] ) ||
( x[6] > x[4] && x[7] > x[4] ) ) {
dec += 1;
}
// lower right quadrant
if( x[5] > x[4] && x[7] > x[4] && x[8] > x[4] ){
// +2 lines, +3 faces, +1 vertex = ECchange = 1-2+3
dec += 2;
} else if( ( x[5] > x[4] && x[8] > x[4] ) ||
( x[7] > x[4] && x[8] > x[4] ) ||
( x[5] > x[4] && x[7] > x[4] ) ) {
dec += 1;
}
}
// save the negative dec in the odd out locations (minus
// sign convention used to recreate the ec curve)
*(out + nn*2 + 1) = -dec;
// increase counter moving through dec saving locations
nn += 1;
// reset dec to be 1
dec = 1;
}
}
}
/* This is the C++ subroutine computing the change in Euler characterisitic in 3D
* Input:
* - *z: pointer to the input array
* - cc: integer giving the connectivity (currently, only 8 is supported)
* - ADD all inputs with short discribtion
*/
void ECcrit3D(double *z, double cc, double *out, mwSize i, mwSize j, mwSize k)
{
/*****************************************************************
* Initialize variables and constants
*****************************************************************/
int ii, jj, kk, s_ind, ss, ind_ss; // variables for loops
int dec = 1; // initialize the change in Euler characteristic as being 1, since 1 voxel is added
int nn = 0; // counter for accessing the values in dec while looping
double x[27]; // initialize array for values of neighbourhood of a voxel
int ind_t[27]; // initialize array for indices of neighbourhood of a voxel
/*****************************************************************
* loop over each voxel of the input z. Note that the original image
* was zero paded by with one -Inf. Hence we start each dimension at
* 1 and end at end-1.
*****************************************************************/
for(ii=1;ii<(i-1);ii++)
{
for(jj=1;jj<(j-1);jj++)
{
for(kk=1;kk<(k-1);kk++)
{
/*
* getting the indices of the 3x3x3 neighbourhood of
* the voxel (ii,jj,kk) and saving them in the ind_t array
*/
ind_t[0] = (ii-1)+(jj-1)*i+(kk-1)*i*j;
ind_t[1] = (ii-1)+(jj-1)*i+kk*i*j;
ind_t[2] = (ii-1)+(jj-1)*i+(kk+1)*i*j;
ind_t[3] = (ii-1)+jj*i+(kk-1)*i*j;
ind_t[4] = (ii-1)+jj*i+kk*i*j;
ind_t[5] = (ii-1)+jj*i+(kk+1)*i*j;
ind_t[6] = (ii-1)+(jj+1)*i+(kk-1)*i*j;
ind_t[7] = (ii-1)+(jj+1)*i+kk*i*j;
ind_t[8] = (ii-1)+(jj+1)*i+(kk+1)*i*j;
ind_t[9] = ii+(jj-1)*i+(kk-1)*i*j;
ind_t[10] = ii+(jj-1)*i+kk*i*j;
ind_t[11] = ii+(jj-1)*i+(kk+1)*i*j;
ind_t[12] = ii+jj*i+(kk-1)*i*j;
ind_t[13] = ii+jj*i+kk*i*j;
ind_t[14] = ii+jj*i+(kk+1)*i*j;
ind_t[15] = ii+(jj+1)*i+(kk-1)*i*j;
ind_t[16] = ii+(jj+1)*i+kk*i*j;
ind_t[17] = ii+(jj+1)*i+(kk+1)*i*j;
ind_t[18] = (ii+1)+(jj-1)*i+(kk-1)*i*j;
ind_t[19] = (ii+1)+(jj-1)*i+kk*i*j;
ind_t[20] = (ii+1)+(jj-1)*i+(kk+1)*i*j;
ind_t[21] = (ii+1)+jj*i+(kk-1)*i*j;
ind_t[22] = (ii+1)+jj*i+kk*i*j;
ind_t[23] = (ii+1)+jj*i+(kk+1)*i*j;
ind_t[24] = (ii+1)+(jj+1)*i+(kk-1)*i*j;
ind_t[25] = (ii+1)+(jj+1)*i+kk*i*j;
ind_t[26] = (ii+1)+(jj+1)*i+(kk+1)*i*j;
/* filling the x array using the indices of the
* neighbourhood ind_t and the input array z
*/
for(ss = 0; ss<27; ss++)
{
s_ind = ind_t[ss];
x[ss] = *(z+s_ind);
}
/*****************************************************************
* let the even entries of out pointer point to the center voxel (ii,jj,kk)
*****************************************************************/
*(out + nn*2) = x[13];
/******************************************************************
* compute the change in dec by checking which nD-faces are created
******************************************************************/
// subtract number of edges (1D faces)
double ind1[6] = {4, 10, 12, 14, 16, 22};
double count_t = 0;
// find number of newly created 1D faces
for(ss=0;ss<6;ss++){
ind_ss = ind1[ss];
// if new edge appears increase dec by 1
if(x[ind_ss]>x[13])
{
count_t += 1;
}
}
// subtract number of 1D faces from dec
dec = dec - count_t;
// add number of newly created faces
if(x[9] > x[13] && x[10] > x[13] && x[12] > x[13])
dec += 1;
if(x[10] > x[13] && x[11] > x[13] && x[14] > x[13])
dec += 1;
if(x[14] > x[13] && x[16] > x[13] && x[17] > x[13])
dec += 1;
if(x[12] > x[13] && x[15] > x[13] && x[16] > x[13])
dec += 1;
if(x[3] > x[13] && x[4] > x[13] && x[12] > x[13])
dec += 1;
if(x[4] > x[13] && x[5] > x[13] && x[14] > x[13])
dec += 1;
if(x[12] > x[13] && x[21] > x[13] && x[22] > x[13])
dec += 1;
if(x[14] > x[13] && x[22] > x[13] && x[23] > x[13])
dec += 1;
if(x[1] > x[13] && x[4] > x[13] && x[10] > x[13])
dec += 1;
if(x[4] > x[13] && x[7] > x[13] && x[16] > x[13])
dec += 1;
if(x[10] > x[13] && x[22] > x[13] && x[19] > x[13])
dec += 1;
if(x[16] > x[13] && x[22] > x[13] && x[25] > x[13])
dec += 1;
// subtract number of newly created 3D faces
if(x[0] >= x[13] && x[1] >= x[13] && x[3] >= x[13] && x[4] >= x[13] && x[9] >= x[13] && x[10] >= x[13] && x[12] >= x[13] && x[13] >= x[13])
dec -= 1;
if(x[1] >= x[13] && x[2] >= x[13] && x[4] >= x[13] && x[5] >= x[13] && x[10] >= x[13] && x[11] >= x[13] && x[13] >= x[13] && x[14] >= x[13])
dec -= 1;
if(x[4] >= x[13] && x[5] >= x[13] && x[7] >= x[13] && x[8] >= x[13] && x[13] >= x[13] && x[14] >= x[13] && x[16] >= x[13] && x[17] >= x[13])
dec -= 1;
if(x[3] >= x[13] && x[4] >= x[13] && x[6] >= x[13] && x[7] >= x[13] && x[12] >= x[13] && x[13] >= x[13] && x[15] >= x[13] && x[16] >= x[13])
dec -= 1;
if(x[9] >= x[13] && x[10] >= x[13] && x[12] >= x[13] && x[13] >= x[13] && x[18] >= x[13] && x[19] >= x[13] && x[21] >= x[13] && x[22] >= x[13])
dec -= 1;
if(x[10] >= x[13] && x[11] >= x[13] && x[13] >= x[13] && x[14] >= x[13] && x[19] >= x[13] && x[20] >= x[13] && x[22] >= x[13] && x[23] >= x[13])
dec -= 1;
if(x[13] >= x[13] && x[14] >= x[13] && x[16] >= x[13] && x[17] >= x[13] && x[22] >= x[13] && x[23] >= x[13] && x[25] >= x[13] && x[26] >= x[13])
dec -= 1;
if(x[12] >= x[13] && x[13] >= x[13] && x[15] >= x[13] && x[16] >= x[13] && x[21] >= x[13] && x[22] >= x[13] && x[24] >= x[13] && x[25] >= x[13])
dec -= 1;
// save the negative dec in the odd out locations (minus
// sign convention used to recreate the ec curve)
*(out + nn*2 + 1) = -dec;
// increase counter moving through dec saving locations
nn += 1;
// reset dec to be 1
dec = 1;
}
}
}
}
| 45.357527 | 160 | 0.354057 | [
"3d"
] |
d7b4f4a6c601c3403336430c7429d2c48783836f | 3,468 | cpp | C++ | library/dynamicProgramming/optimizationDivideConquer_OptimalSquareDistance1D.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 40 | 2017-11-26T05:29:18.000Z | 2020-11-13T00:29:26.000Z | library/dynamicProgramming/optimizationDivideConquer_OptimalSquareDistance1D.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 101 | 2019-02-09T06:06:09.000Z | 2021-12-25T16:55:37.000Z | library/dynamicProgramming/optimizationDivideConquer_OptimalSquareDistance1D.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 6 | 2017-01-03T14:17:58.000Z | 2021-01-22T10:37:04.000Z | #include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
#include "optimizationDivideConquer_OptimalSquareDistance1D.h"
#include "optimizationDivideConquer_OptimalKMeans1D.h"
/////////// For Testing ///////////////////////////////////////////////////////
#include <time.h>
#include <cassert>
#include <string>
#include <iostream>
#include "../common/iostreamhelper.h"
#include "../common/profile.h"
#include "../common/rand.h"
static vector<int> makeRandomData(int N, int maxValue) {
vector<int> res(N);
for (int i = 0; i < N; i++) {
res[i] = RandInt32::get() % maxValue;
}
sort(res.begin(), res.end());
return res;
}
static vector<double> makeRandomData(int N, double maxValue) {
vector<double> res(N);
for (int i = 0; i < N; i++) {
res[i] = RandInt32::get() * maxValue / numeric_limits<int>::max();
}
sort(res.begin(), res.end());
return res;
}
static double calcDistanceL2(const vector<int>& vec, const vector<pair<int, int>>& groups) {
vector<double> centroids(groups.size());
for (int i = 0; i < int(groups.size()); i++) {
for (int j = groups[i].first; j <= groups[i].second; j++)
centroids[i] += vec[j];
centroids[i] /= (groups[i].second - groups[i].first + 1);
}
double res = 0.0;
for (int i = 0; i < int(groups.size()); i++) {
for (int j = groups[i].first; j <= groups[i].second; j++)
res += (vec[j] - centroids[i]) * (vec[j] - centroids[i]);
}
return res;
}
static double calcDistanceL2(const vector<double>& vec, const vector<pair<int, int>>& groups) {
vector<double> centroids(groups.size());
for (int i = 0; i < int(groups.size()); i++) {
for (int j = groups[i].first; j <= groups[i].second; j++)
centroids[i] += vec[j];
centroids[i] /= (groups[i].second - groups[i].first + 1);
}
double res = 0.0;
for (int i = 0; i < int(groups.size()); i++) {
for (int j = groups[i].first; j <= groups[i].second; j++)
res += (vec[j] - centroids[i]) * (vec[j] - centroids[i]);
}
return res;
}
void testOptimalSquareDistance1D() {
return; //TODO: if you want to test, make this line a comment.
cout << "--- OptimalSquareDistance1D ------------------------------" << endl;
{
OptimalSquareDistance1D osd(vector<int>{ 1, 2, 4 });
assert(osd.solve(2) == 0.5);
}
{
int N = 100;
int K = 10;
auto data = makeRandomData(N, 10000.0);
OptimalKMeans1D okm(data);
double dist = okm.solve(K);
auto groups = okm.getGroup();
double dist2 = calcDistanceL2(data, groups);
assert(groups.size() == K);
cout << "groups = " << groups << endl;
cout << "L2 distance = " << dist << ", " << dist2 << endl;
cout << "diff = " << abs(dist - dist2) << endl;
assert(abs(dist - dist2) / dist < 1e-6);
}
{
int N = 1000000;
#ifdef _DEBUG
N = 1000;
#endif
int K = 128;
auto data = makeRandomData(N, 5.0);
PROFILE_START(0);
OptimalKMeans1D okm(data);
double dist = okm.solve(K);
PROFILE_STOP(0);
PROFILE_START(1);
auto groups = okm.getGroup();
double dist2 = calcDistanceL2(data, groups);
PROFILE_STOP(1);
if (dist == 0.0 || dist2 == 0.0)
cout << "ERROR" << endl;
}
cout << "OK!" << endl;
}
| 27.967742 | 95 | 0.537486 | [
"vector"
] |
d7b8f2d9191b170100e86b7d4eb00d65c013035d | 28,427 | cpp | C++ | SOMTRANSIT/MAXTRANSIT/samples/objects/particles/pbomb.cpp | SOM-Firmwide/SOMTRANSIT | a83879c3b60bd24c45bcf4c01fcd11632e799973 | [
"MIT"
] | null | null | null | SOMTRANSIT/MAXTRANSIT/samples/objects/particles/pbomb.cpp | SOM-Firmwide/SOMTRANSIT | a83879c3b60bd24c45bcf4c01fcd11632e799973 | [
"MIT"
] | null | null | null | SOMTRANSIT/MAXTRANSIT/samples/objects/particles/pbomb.cpp | SOM-Firmwide/SOMTRANSIT | a83879c3b60bd24c45bcf4c01fcd11632e799973 | [
"MIT"
] | null | null | null | /**********************************************************************
*<
FILE: pbomb.cpp
DESCRIPTION: Particle Bomb
CREATED BY: Audrey Peterson
HISTORY: 12/11/96
Modified: 9/18/01 Bayboro: removed dependency to EDP
*> Copyright (c) 1996, All Rights Reserved. For Yost Group Inc.
**********************************************************************/
#include "SuprPrts.h"
#include "iparamm.h"
#include "simpmod.h"
#include "simpobj.h"
#include "texutil.h"
class BombMtl: public Material {
public:
BombMtl();
};
static BombMtl swMtl;
#define BOMB_R float(1)
#define BOMB_G float(1)
#define BOMB_B float(0)
const Point3 HOOPCOLOR(1.0f,1.0f,0.0f);
BombMtl::BombMtl():Material()
{ Kd[0] = BOMB_R;
Kd[1] = BOMB_G;
Kd[2] = BOMB_B;
Ks[0] = BOMB_R;
Ks[1] = BOMB_G;
Ks[2] = BOMB_B;
shininess = (float)0.0;
shadeLimit = GW_WIREFRAME;
selfIllum = (float)1.0;
}
static Class_ID PBOMB_CLASS_ID(0x4c200df3, 0x1a347a77);
static Class_ID PBOMBMOD_CLASS_ID(0xc0609ea, 0x1300b3d);
class PBombMod;
class PBombObject : public SimpleWSMObject // ,IOperatorInterface // Bayboro 9/18/01
{
public:
PBombObject();
~PBombObject();
static IParamMap *pmapParam;
static IObjParam *ip;
static HWND hSot;
ForceField *GetForceField(INode *node);
BOOL SupportsDynamics() {return TRUE;}
IOResult Load(ILoad *iload);
// From Animatable
void BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev );
void EndEditParams( IObjParam *ip, ULONG flags,Animatable *next);
void MapKeys(TimeMap *map,DWORD flags);
// from object
CreateMouseCallBack* GetCreateMouseCallBack();
// From SimpleWSMObject
void InvalidateUI();
// From Animatable
void DeleteThis() {delete this;}
Class_ID ClassID() {return PBOMB_CLASS_ID;}
RefTargetHandle Clone(RemapDir& remap);
const TCHAR *GetObjectName() {return GetString(IDS_RB_PBOMB);}
// From WSMObject
Modifier *CreateWSMMod(INode *node);
// From SimpleWSMObject
ParamDimension *GetParameterDim(int pbIndex);
TSTR GetParameterName(int pbIndex);
void BuildMesh(TimeValue t);
int Display(TimeValue t, INode* inode, ViewExp *vpt, int flags);
int DialogID() {return IDD_SW_PARTICLEBOMB;}
ParamUIDesc *UIDesc();
int UIDescLength();
TSTR UIStrName();
void GetWorldBoundBox(TimeValue t, INode* inode, ViewExp* vpt, Box3& box );
// int NPOpInterface(TimeValue t,ParticleData *part,float dt,INode *node,int index); // Bayboro 9/18/01
// void* GetInterface(ULONG id); // Bayboro 9/18/01
ForceField *ff;
void SetUpModifier(TimeValue t,INode *node);
PBombMod *mf;
};
IObjParam *PBombObject::ip = NULL;
IParamMap *PBombObject::pmapParam = NULL;
HWND PBombObject::hSot = NULL;
class PBombClassDesc:public ClassDesc {
public:
int IsPublic() {return 1;}
void * Create(BOOL loading = FALSE) { return new PBombObject;}
const TCHAR * ClassName() {return GetString(IDS_AP_PBOMB_CLASS);}
SClass_ID SuperClassID() {return WSM_OBJECT_CLASS_ID; }
Class_ID ClassID() {return PBOMB_CLASS_ID;}
const TCHAR* Category() {return GetString(IDS_EP_SW_FORCES);}
};
static PBombClassDesc PBombDesc;
ClassDesc* GetPBombObjDesc() {return &PBombDesc;}
class PBombMod;
class PBombField : public ForceField {
public:
PBombObject *obj;
TimeValue dtsq,dt;
INode *node;
int count;
Matrix3 tm,invtm;
Interval tmValid;
Point3 force;
Interval fValid;
Point3 Force(TimeValue t,const Point3 &pos, const Point3 &vel, int index);
};
class PBombMod : public SimpleWSMMod {
public:
PBombField force;
int seed;
PBombMod() {}
PBombMod(INode *node,PBombObject *obj);
// From Animatable
void GetClassName(TSTR& s) {s= GetString(IDS_RB_PBOMBMOD);}
SClass_ID SuperClassID() {return WSM_CLASS_ID;}
void DeleteThis() {delete this;}
Class_ID ClassID() { return PBOMBMOD_CLASS_ID;}
RefTargetHandle Clone(RemapDir& remap);
const TCHAR *GetObjectName() {return GetString(IDS_RB_PBOMBBINDING);}
void ModifyObject(TimeValue t, ModContext &mc, ObjectState *os, INode *node);
// From SimpleWSMMod
Interval GetValidity(TimeValue t);
Deformer& GetDeformer(TimeValue t,ModContext &mc,Matrix3& mat,Matrix3& invmat);
};
class PBombModClassDesc:public ClassDesc {
public:
int IsPublic() { return 0; }
void * Create(BOOL loading = FALSE) {return new PBombMod;}
const TCHAR * ClassName() { return GetString(IDS_RB_PBOMBMOD);}
SClass_ID SuperClassID() {return WSM_CLASS_ID;}
Class_ID ClassID() {return PBOMBMOD_CLASS_ID;}
const TCHAR* Category() {return _T("");}
};
static PBombModClassDesc PBombModDesc;
ClassDesc* GetPBombModDesc() {return &PBombModDesc;}
class BombModData : public LocalModData {
public:
int seed;
LocalModData *Clone ();
};
LocalModData *BombModData::Clone () {
BombModData *clone;
clone = new BombModData ();
clone->seed=seed;
return(clone);
}
//--- BombObject Parameter map/block descriptors ------------------
#define PB_SYMMETRY 0
#define PB_CHAOS 1
#define PB_STARTTIME 2
#define PB_LASTSFOR 3
#define PB_DELTA_V 4
#define PB_DECAY 5
#define PB_DECAYTYPE 6
#define PB_ICONSIZE 7
#define PB_RANGEON 8
static int symIDs[] = {IDC_SP_BLASTSPHR,IDC_SP_BLASTCYL,IDC_SP_BLASTPLAN};
static int decayIDs[] = {IDC_SP_DECAYOFF,IDC_SP_DECAYLIN,IDC_SP_DECAYEXP};
#define SPHERE 0
#define PLANAR 2
#define CYLIND 1
static ParamUIDesc descParamBomb[] = {
// Blast Symmetry
ParamUIDesc(PB_SYMMETRY,TYPE_RADIO,symIDs,3),
// Direction Chaos
ParamUIDesc(
PB_CHAOS,
EDITTYPE_FLOAT,
IDC_SP_BLASTCHAOS,IDC_SP_BLASTCHAOSSPIN,
0.0f, 100.0f,
0.01f,
stdPercentDim),
// Start Time for Impulse
ParamUIDesc(
PB_STARTTIME,
EDITTYPE_TIME,
IDC_SP_BLASTSTRT,IDC_SP_BLASTSTRTSPIN,
-999999999.0f,999999999.0f,
10.0f),
// Lasts For Time
ParamUIDesc(
PB_LASTSFOR,
EDITTYPE_TIME,
IDC_SP_BLASTSTOP,IDC_SP_BLASTSTOPSPIN,
0.0f,999999999.0f,
10.0f),
// DeltaV
ParamUIDesc(
PB_DELTA_V,
EDITTYPE_FLOAT,
IDC_SP_BLASTDV,IDC_SP_BLASTDVSPIN,
-999999999.0f,999999999.0f,
SPIN_AUTOSCALE),
// Decay Range
ParamUIDesc(
PB_DECAY,
EDITTYPE_UNIVERSE,
IDC_SP_BLASTDECAY,IDC_SP_BLASTDECAYSPIN,
0.0f,999999999.0f,
SPIN_AUTOSCALE),
// Decay Type
ParamUIDesc(PB_DECAYTYPE,TYPE_RADIO,decayIDs,3),
// Icon Size
ParamUIDesc(
PB_ICONSIZE,
EDITTYPE_UNIVERSE,
IDC_SP_BLAST_ICONSIZE,IDC_SP_BLAST_ICONSIZESPIN,
0.0f, 9999999.0f,
SPIN_AUTOSCALE),
// Enable Range Indicator
ParamUIDesc(PB_RANGEON,TYPE_SINGLECHECKBOX,IDC_PBOMB_RANGEON),
};
#define BOMBPARAMDESC_LENGTH 9
ParamBlockDescID descVer0[] = {
{ TYPE_INT, NULL, FALSE, 0 }, //PB_SYMMETRY
{ TYPE_FLOAT, NULL, FALSE, 1 }, //PB_CHAOS
{ TYPE_INT, NULL, FALSE, 2 }, //PB_STARTTIME
{ TYPE_INT, NULL, FALSE, 3 }, //PB_LASTSFOR
{ TYPE_FLOAT, NULL, TRUE, 4 }, //PB_DELTA_V
{ TYPE_FLOAT, NULL, TRUE, 5 }, // PB_DECAY
{ TYPE_INT, NULL, FALSE, 6 }, // PB_DECAYTYPE
{ TYPE_FLOAT, NULL, FALSE, 7 }}; // PB_ICONSIZE
ParamBlockDescID descVer1[] = {
{ TYPE_INT, NULL, FALSE, 0 }, //PB_SYMMETRY
{ TYPE_FLOAT, NULL, FALSE, 1 }, //PB_CHAOS
{ TYPE_INT, NULL, FALSE, 2 }, //PB_STARTTIME
{ TYPE_INT, NULL, FALSE, 3 }, //PB_LASTSFOR
{ TYPE_FLOAT, NULL, TRUE, 4 }, //PB_DELTA_V
{ TYPE_FLOAT, NULL, TRUE, 5 }, // PB_DECAY
{ TYPE_INT, NULL, FALSE, 6 }, // PB_DECAYTYPE
{ TYPE_FLOAT, NULL, FALSE, 7 }, // PB_ICONSIZE
{ TYPE_INT, NULL, FALSE, 8 } // Range Indicator
};
#define PBLOCK_LENGTH 9
static ParamVersionDesc pbombversions[] = {
ParamVersionDesc(descVer0,8,0),
ParamVersionDesc(descVer1,9,1),
};
#define NUM_OLDVERSIONS 1
#define CURRENT_VERSION 1
static ParamVersionDesc curVersionPBomb(descVer1,PBLOCK_LENGTH,CURRENT_VERSION);
//--- Deflect object methods -----------------------------------------
class PBombPostLoadCallback : public PostLoadCallback
{
public:
ParamBlockPLCB *cb;
PBombPostLoadCallback(ParamBlockPLCB *c) {cb=c;}
virtual void proc(ILoad *iload)
{
if (cb == NULL || !cb->IsValid())
{
delete this;
return;
}
// The call to IsValid above verified that the pblock is safe
DWORD oldVer = ((PBombObject*)(cb->GetTarget()))->pblock->GetVersion();
ReferenceTarget *targ = cb->GetTarget();
cb->proc(iload);
cb = NULL;
if (oldVer<1)
((PBombObject*)targ)->pblock->SetValue(PB_RANGEON,0,0);
delete this;
}
virtual int Priority() { return 0; }
};
IOResult PBombObject::Load(ILoad *iload)
{ IOResult res = IO_OK;
iload->RegisterPostLoadCallback(
new PBombPostLoadCallback(
new ParamBlockPLCB(pbombversions,NUM_OLDVERSIONS,&curVersionPBomb,this,0)));
return IO_OK;
}
PBombObject::PBombObject()
{
int FToTick=(int)((float)TIME_TICKSPERSEC/(float)GetFrameRate());
ReplaceReference(0, CreateParameterBlock(descVer1, PBLOCK_LENGTH, CURRENT_VERSION));
assert(pblock);
ff = NULL;
mf = NULL;
pblock->SetValue(PB_SYMMETRY,0,0);
pblock->SetValue(PB_CHAOS,0,0.10f);
pblock->SetValue(PB_STARTTIME,0,FToTick*30);
pblock->SetValue(PB_LASTSFOR,0,FToTick);
pblock->SetValue(PB_DELTA_V,0,1.0f);
pblock->SetValue(PB_DECAY,0,1000.0f);
pblock->SetValue(PB_DECAYTYPE,0,1);
srand(12345);
}
class PBombDlgProc : public ParamMapUserDlgProc {
public:
PBombObject *po;
PBombDlgProc(PBombObject *p) {po=p;}
INT_PTR DlgProc(TimeValue t,IParamMap *map,HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam);
void Update(TimeValue t);
void DeleteThis() {delete this;}
};
void PBombDlgProc::Update(TimeValue t)
{ int decay;
po->pblock->GetValue(PB_DECAYTYPE,0,decay,FOREVER);
HWND hWnd=po->pmapParam->GetHWnd();
if (decay==0)
SpinnerOff(hWnd,IDC_SP_BLASTDECAYSPIN,IDC_SP_BLASTDECAY);
else
SpinnerOn(hWnd,IDC_SP_BLASTDECAYSPIN,IDC_SP_BLASTDECAY);
EnableWindow(GetDlgItem(hWnd,IDC_SP_BLASTDECAY_TXT), decay);
EnableWindow(GetDlgItem(hWnd,IDC_PBOMB_RANGEON), decay);
}
INT_PTR PBombDlgProc::DlgProc(
TimeValue t,IParamMap *map,HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
{ switch (msg)
{case WM_INITDIALOG:
{ Update(t);
break;
}
case WM_COMMAND:
switch (LOWORD(wParam))
{ case IDC_SP_DECAYOFF:
{ SpinnerOff(hWnd,IDC_SP_BLASTDECAYSPIN,IDC_SP_BLASTDECAY);
return TRUE;
}
case IDC_SP_DECAYLIN:
case IDC_SP_DECAYEXP:
{ SpinnerOn(hWnd,IDC_SP_BLASTDECAYSPIN,IDC_SP_BLASTDECAY);
return TRUE;
}
}
}
return FALSE;
}
void PBombObject::BeginEditParams(IObjParam *ip,ULONG flags,Animatable *prev)
{
SimpleWSMObject::BeginEditParams(ip,flags,prev);
this->ip = ip;
if (pmapParam) {
// Left over
pmapParam->SetParamBlock(pblock);
} else {
hSot = ip->AddRollupPage(
hInstance,
MAKEINTRESOURCE(IDD_SW_DESC_BOTH),
DefaultSOTProc,
GetString(IDS_RB_TOP),
(LPARAM)ip,APPENDROLL_CLOSED);
// Gotta make a new one.
pmapParam = CreateCPParamMap(
descParamBomb,BOMBPARAMDESC_LENGTH,
pblock,
ip,
hInstance,
MAKEINTRESOURCE(IDD_SW_PARTICLEBOMB),
GetString(IDS_RB_PARAMETERS),
0);
}
if (pmapParam) pmapParam->SetUserDlgProc(new PBombDlgProc(this));
}
void PBombObject::EndEditParams(
IObjParam *ip, ULONG flags,Animatable *next)
{
SimpleWSMObject::EndEditParams(ip,flags,next);
this->ip = NULL;
if (flags & END_EDIT_REMOVEUI ) {
DestroyCPParamMap(pmapParam);
ip->DeleteRollupPage(hSot);
pmapParam = NULL;
}
else
{
pmapParam->SetUserDlgProc(nullptr);
pmapParam->SetParamBlock(nullptr);
}
}
ForceField *PBombObject::GetForceField(INode *node)
{
PBombField *pb = new PBombField;
pb->obj = this;
pb->node = node;
pb->tmValid.SetEmpty();
pb->fValid.SetEmpty();
pb->dt=GetTicksPerFrame();
pb->dtsq=pb->dt*pb->dt;
return pb;
}
void PBombObject::MapKeys(TimeMap *map,DWORD flags)
{ TimeValue TempTime;
pblock->GetValue(PB_STARTTIME,0,TempTime,FOREVER);
TempTime=map->map(TempTime);
pblock->SetValue(PB_STARTTIME,0,TempTime);
pblock->GetValue(PB_LASTSFOR,0,TempTime,FOREVER);
TempTime=map->map(TempTime);
pblock->SetValue(PB_LASTSFOR,0,TempTime);
}
void PBombObject::BuildMesh(TimeValue t)
{ ivalid = FOREVER;
float length;
pblock->GetValue(PB_ICONSIZE,t,length,ivalid);
float u,zval;
#define NUM_SEGS 12
#define NUM_SEGS2 24
int btype, norvs, norfs, rangeverts=0, rangefaces=0;
pblock->GetValue(PB_SYMMETRY,0,btype,FOREVER);
// int dorange,hoops;
// pblock->GetValue(PB_RANGEON,0,hoops,FOREVER);
// pblock->GetValue(PB_DECAYTYPE,0,dorange,FOREVER);
// if (dorange && hoops){ rangeverts=73;rangefaces=72;}
if (btype<2)
{ length/=2.0f;
if (btype==0)
{ mesh.setNumVerts((norvs=58)+rangeverts);
mesh.setNumFaces((norfs=58)+rangefaces);
int fbase=22,vbase=21,newv;
for (int i=0; i<NUM_SEGS; i++)
{ u = float(i)/float(NUM_SEGS) * TWOPI;
mesh.setVert(i+vbase, Point3((float)cos(u) * length, (float)sin(u) * length, 0.0f));
}
newv=NUM_SEGS+vbase;
for (int i=0; i<NUM_SEGS; i++)
{ u = float(i)/float(NUM_SEGS) * TWOPI;
mesh.setVert(i+newv, Point3(0.0f, (float)cos(u) * length, (float)sin(u) * length));
} newv+=NUM_SEGS;
for (int i=0; i<NUM_SEGS; i++)
{ u = float(i)/float(NUM_SEGS) * TWOPI;
mesh.setVert(i+newv, Point3((float)cos(u) * length, 0.0f, (float)sin(u) * length));
}
newv+=NUM_SEGS;
mesh.setVert(newv, Point3(0.0f, 0.0f, 0.0f));
int vi=vbase;
for (int i=fbase; i<newv+1; i++)
{ int i1 = vi+1;
if ((i1-vbase)%NUM_SEGS==0) i1 -= NUM_SEGS;
mesh.faces[i].setEdgeVisFlags(1,0,0);
mesh.faces[i].setSmGroup(0);
mesh.faces[i].setVerts(vi,i1,newv);
vi++;
}
zval=0.85f*length;
}
else
{ mesh.setNumVerts((norvs=21)+rangeverts);
mesh.setNumFaces((norfs=22)+rangefaces);
zval=-0.85f*length;
}
float hlen=0.4f*length;
mesh.setVert(0,Point3(0.0f,0.0f,zval));
for (int i=1;i<9;i++)
{ u= TWOPI*float(i-1)/8.0f;
mesh.setVert(i, Point3((float)cos(u) * hlen,(float)sin(u) * hlen, zval));
}
zval=1.25f*length;
mesh.setVert(9,Point3(0.0f,0.0f,zval));
for (int i=10;i<18;i++)
{ u= TWOPI*float(i-10)/8.0f;
mesh.setVert(i, Point3((float)cos(u) * hlen,(float)sin(u) * hlen, zval));
}
int fcount=1;
for (int i=0;i<8;i++)
{ mesh.faces[i].setEdgeVisFlags(0,1,0);
mesh.faces[i].setSmGroup(0);
mesh.faces[i].setVerts(0,fcount,fcount+1);
fcount++;
}
mesh.faces[7].setVerts(0,8,1);
fcount=10;
for (int i=8;i<16;i++)
{ mesh.faces[i].setEdgeVisFlags(0,1,0);
mesh.faces[i].setSmGroup(0);
mesh.faces[i].setVerts(9,fcount,fcount+1);
fcount++;
}
mesh.faces[15].setVerts(9,17,10);
for (int i=16;i<22;i++)
{ mesh.faces[i].setSmGroup(0);
mesh.faces[i].setEdgeVisFlags(0,1,0);
}
mesh.faces[16].setVerts(1,10,14);
mesh.faces[16].setEdgeVisFlags(1,0,0);
mesh.faces[17].setVerts(1,14,5);
mesh.faces[18].setVerts(3,12,16);
mesh.faces[18].setEdgeVisFlags(1,0,0);
mesh.faces[19].setVerts(3,16,7);
mesh.setVert(18,Point3(0.0f,0.0f,1.5f*length));
mesh.setVert(19,Point3(0.25f*length,0.0f,1.75f*length));
mesh.setVert(20,Point3(0.75f*length,0.0f,2.0f*length));
mesh.faces[20].setVerts(9,19,18);
mesh.faces[20].setEdgeVisFlags(0,1,1);
mesh.faces[21].setVerts(9,20,19);
}
else
{ mesh.setNumVerts((norvs=45)+rangeverts);
mesh.setNumFaces((norfs=22)+rangefaces);
mesh.setVert(0,Point3(length,length,0.0f));
mesh.setVert(1,Point3(-length,length,0.0f));
mesh.setVert(2,Point3(-length,-length,0.0f));
mesh.setVert(3,Point3(length,-length,0.0f));
mesh.faces[0].setVerts(0,1,2);
mesh.faces[0].setEdgeVisFlags(1,1,0);
mesh.faces[0].setSmGroup(0);
mesh.faces[1].setVerts(0,2,3);
mesh.faces[1].setEdgeVisFlags(0,1,1);
mesh.faces[1].setSmGroup(0);
int vnum;
float r=0.1f*length;
Point3 basept=Point3(0.3f*length,0.3f*length,0.5f*length);
mesh.setVert(4,basept);
mesh.setVert(5,basept+Point3(0.0f,-r,-r));
mesh.setVert(6,basept+Point3(0.0f,r,-r));
mesh.setVert(7,basept+Point3(r,0.0f,-r));
mesh.setVert(8,basept+Point3(-r,0.0f,-r));
vnum=9;
for (int i=4;i<9;i++)
{ mesh.setVert(vnum,Point3(mesh.verts[i].x,mesh.verts[i].y,-mesh.verts[i].z));
mesh.setVert(vnum+5,Point3(-mesh.verts[i].x,mesh.verts[i].y,mesh.verts[i].z));
mesh.setVert(vnum+10,Point3(-mesh.verts[i].x,mesh.verts[i].y,-mesh.verts[i].z));
mesh.setVert(vnum+15,Point3(mesh.verts[i].x,-mesh.verts[i].y,mesh.verts[i].z));
mesh.setVert(vnum+20,Point3(mesh.verts[i].x,-mesh.verts[i].y,-mesh.verts[i].z));
mesh.setVert(vnum+25,Point3(-mesh.verts[i].x,-mesh.verts[i].y,mesh.verts[i].z));
mesh.setVert(vnum+30,Point3(-mesh.verts[i].x,-mesh.verts[i].y,-mesh.verts[i].z));
vnum++;
}
mesh.setVert(44,Point3(0.0f,0.0f,0.0f));
int fnum=2;
vnum=4;
for (int i=1;i<9;i++)
{ mesh.faces[fnum++].setVerts(vnum,vnum+1,vnum+2);
mesh.faces[fnum++].setVerts(vnum,vnum+3,vnum+4);
vnum+=5;
}
for (int i=2;i<18;i++)
{ mesh.faces[i].setSmGroup(0);
mesh.faces[i].setEdgeVisFlags(1,1,1);
}
for (int i=18;i<22;i++)
{ mesh.faces[i].setSmGroup(0);
mesh.faces[i].setEdgeVisFlags(0,0,1);
}
mesh.faces[18].setVerts(4,44,9);
mesh.faces[19].setVerts(14,44,19);
mesh.faces[20].setVerts(24,44,29);
mesh.faces[21].setVerts(34,44,39);
}
/* if (dorange && hoops)
{ int newv;
pblock->GetValue(PB_DECAY,t,length,ivalid);
for (int i=0; i<NUM_SEGS2; i++)
{ u = float(i)/float(NUM_SEGS2) * TWOPI;
mesh.setVert(i+norvs, Point3((float)cos(u) * length, (float)sin(u) * length, 0.0f));
}
newv=NUM_SEGS2+norvs;
for (int i=0; i<NUM_SEGS2; i++)
{ u = float(i)/float(NUM_SEGS2) * TWOPI;
mesh.setVert(i+newv, Point3(0.0f, (float)cos(u) * length, (float)sin(u) * length));
} newv+=NUM_SEGS2;
for (int i=0; i<NUM_SEGS2; i++)
{ u = float(i)/float(NUM_SEGS2) * TWOPI;
mesh.setVert(i+newv, Point3((float)cos(u) * length, 0.0f, (float)sin(u) * length));
}
newv+=NUM_SEGS2;
mesh.setVert(newv, Point3(0.0f, 0.0f, 0.0f));
int vi=norvs;
for (int i=norfs; i<norfs+rangefaces; i++)
{ int i1 = vi+1;
if ((i1-norvs)%NUM_SEGS2==0) i1 -= NUM_SEGS2;
mesh.faces[i].setEdgeVisFlags(1,0,0);
mesh.faces[i].setSmGroup(0);
mesh.faces[i].setVerts(vi,i1,newv);
vi++;
}
}*/
mesh.InvalidateGeomCache();
}
class PBombObjCreateCallback : public CreateMouseCallBack {
public:
PBombObject *ob;
Point3 p0, p1;
IPoint2 sp0;
int proc( ViewExp *vpt,int msg, int point, int flags, IPoint2 m, Matrix3& mat);
};
int PBombObjCreateCallback::proc(
ViewExp *vpt,int msg, int point, int flags, IPoint2 m, Matrix3& mat)
{
if ( ! vpt || ! vpt->IsAlive() )
{
// why are we here
DbgAssert(!_T("Invalid viewport!"));
return FALSE;
}
DWORD snapdim = SNAP_IN_3D;
if (msg == MOUSE_FREEMOVE)
{ vpt->SnapPreview(m,m,NULL, snapdim);
}
if (msg==MOUSE_POINT||msg==MOUSE_MOVE) {
switch(point) {
case 0:
// if hidden by category, re-display particles and objects
GetCOREInterface()->SetHideByCategoryFlags(
GetCOREInterface()->GetHideByCategoryFlags() & ~(HIDE_OBJECTS|HIDE_PARTICLES));
sp0 = m;
p0 = vpt->SnapPoint(m,m,NULL,snapdim);
mat.SetTrans(p0);
break;
case 1:
p1 = vpt->SnapPoint(m,m,NULL,snapdim);
float x=Length(p1-p0);
ob->pblock->SetValue(PB_ICONSIZE,0,x);
ob->pmapParam->Invalidate();
if (msg==MOUSE_POINT) {
if (Length(m-sp0)<3) return CREATE_ABORT;
else return CREATE_STOP;
}
break;
}
} else {
if (msg == MOUSE_ABORT)
return CREATE_ABORT;
}
return TRUE;
}
static PBombObjCreateCallback pbombCreateCB;
CreateMouseCallBack* PBombObject::GetCreateMouseCallBack()
{
pbombCreateCB.ob = this;
return &pbombCreateCB;
}
void PBombObject::InvalidateUI()
{
if (pmapParam) pmapParam->Invalidate();
}
Modifier *PBombObject::CreateWSMMod(INode *node)
{
return new PBombMod(node,this);
}
RefTargetHandle PBombObject::Clone(RemapDir& remap)
{
PBombObject* newob = new PBombObject();
newob->ReplaceReference(0,remap.CloneRef(pblock));
BaseClone(this, newob, remap);
return newob;
}
ParamDimension *PBombObject::GetParameterDim(int pbIndex)
{
switch (pbIndex) {
case PB_CHAOS: return stdPercentDim;
case PB_ICONSIZE:
case PB_DECAY:
return stdWorldDim;
case PB_STARTTIME:
case PB_LASTSFOR:
return stdTimeDim;
default: return defaultDim;
}
}
TSTR PBombObject::GetParameterName(int pbIndex)
{
switch (pbIndex) {
case PB_SYMMETRY: return GetString(IDS_RB_SYMMETRY);
case PB_CHAOS: return GetString(IDS_RB_CHAOS);
case PB_STARTTIME: return GetString(IDS_RB_STARTTIME);
case PB_LASTSFOR: return GetString(IDS_RB_LASTSFOR);
case PB_DELTA_V: return GetString(IDS_AP_STRENGTH);
case PB_DECAY: return GetString(IDS_RB_DECAY);
case PB_DECAYTYPE: return GetString(IDS_RB_DECAYTYPE);
case PB_ICONSIZE: return GetString(IDS_RB_ICONSIZE);
default: return _T("");
}
}
ParamUIDesc *PBombObject::UIDesc()
{
return descParamBomb;
}
int PBombObject::UIDescLength()
{
return BOMBPARAMDESC_LENGTH;
}
TSTR PBombObject::UIStrName()
{
return GetString(IDS_RB_BOMBPARAM);
}
PBombMod::PBombMod(INode *node,PBombObject *obj)
{
ReplaceReference(SIMPWSMMOD_NODEREF,node);
seed=12345;
}
Interval PBombMod::GetValidity(TimeValue t)
{
if (nodeRef) {
Interval valid = FOREVER;
Matrix3 tm;
float f;
((PBombObject*)GetWSMObject(t))->pblock->GetValue(PB_DELTA_V,t,f,valid);
((PBombObject*)GetWSMObject(t))->pblock->GetValue(PB_DECAY,t,f,valid);
((PBombObject*)GetWSMObject(t))->pblock->GetValue(PB_ICONSIZE,t,f,valid);
tm = nodeRef->GetObjectTM(t,&valid);
return valid;
} else {
return FOREVER;
}
}
class PBombDeformer : public Deformer {
public:
Point3 Map(int i, Point3 p) {return p;}
};
static PBombDeformer gdeformer;
Deformer& PBombMod::GetDeformer(
TimeValue t,ModContext &mc,Matrix3& mat,Matrix3& invmat)
{
return gdeformer;
}
RefTargetHandle PBombMod::Clone(RemapDir& remap)
{
PBombMod *newob = new PBombMod(nodeRef,(PBombObject*)obRef);
newob->SimpleWSMModClone(this, remap);
BaseClone(this, newob, remap);
return newob;
}
void PBombMod::ModifyObject(
TimeValue t, ModContext &mc, ObjectState *os, INode *node)
{
ParticleObject *obj = GetParticleInterface(os->obj);
if (obj) {
/* if (!mc.localdata)
{ mc.localdata=seed; seed+=5;} */
force.obj = (PBombObject*)GetWSMObject(t);
force.node = nodeRef;
force.tmValid.SetEmpty();
force.fValid.SetEmpty();
force.dt=GetTicksPerFrame();
force.dtsq=force.dt*force.dt;
obj->ApplyForceField(&force);
}
}
class BombDrawLineProc:public PolyLineProc {
GraphicsWindow *gw;
public:
BombDrawLineProc() { gw = NULL; }
BombDrawLineProc(GraphicsWindow *g) { gw = g; }
int proc(Point3 *p, int n) { gw->polyline(n, p, NULL, NULL, 0, NULL); return 0; }
int Closed(Point3 *p, int n) { gw->polyline(n, p, NULL, NULL, TRUE, NULL); return 0; }
void SetLineColor(float r, float g, float b) {gw->setColor(LINE_COLOR,r,g,b);}
void SetLineColor(Point3 c) {gw->setColor(LINE_COLOR,c);}
void Marker(Point3 *p,MarkerType type) {gw->marker(p,type);}
};
static void DrawFalloffSphere(float range, BombDrawLineProc& lp)
{ float u;
Point3 pt[3],pty[3],ptz[3],first,firsty;
int nsegs=16;
lp.SetLineColor(GetUIColor(COLOR_END_RANGE));
pt[0]=(first= Point3(range,0.0f,0.0f));
pty[0] =(firsty=Point3(0.0f,range,0.0f));
ptz[0] = pt[0];
for (int i=0; i<nsegs; i++)
{ u = float(i)/float(nsegs) * TWOPI;
float crange=(float)cos(u)*range,srange=(float)sin(u)*range;
pt[1]=Point3(crange, srange, 0.0f);
lp.proc(pt,2); pt[0]=pt[1];
pty[1]=Point3(0.0f, crange, srange);
lp.proc(pty,2); pty[0]=pty[1];
ptz[1]=Point3(crange, 0.0f, srange);
lp.proc(ptz,2); ptz[0]=ptz[1];
}
pt[1]=first;lp.proc(pt,2);
pty[1]=firsty;lp.proc(pty,2);
ptz[1]=first;lp.proc(ptz,2);
}
void PBombObject::GetWorldBoundBox(TimeValue t, INode* inode, ViewExp* vpt, Box3& box )
{
if ( ! vpt || ! vpt->IsAlive() )
{
box.Init();
return;
}
Box3 meshBox;
Matrix3 mat = inode->GetObjectTM(t);
box.Init();
int hoopson,dorange;
pblock->GetValue(PB_RANGEON,t,hoopson,FOREVER);
pblock->GetValue(PB_DECAYTYPE,0,dorange,FOREVER);
if ((hoopson)&&(dorange))
{ float decay; pblock->GetValue(PB_DECAY,t,decay,FOREVER);
if (decay>0.0f)
{ float range; range=2.0f*decay;
Box3 rangeBox(Point3(-range,-range,-range),Point3(range,range,range));
for(int i = 0; i < 8; i++) box += mat * rangeBox[i];
}
}
GetLocalBoundBox(t,inode,vpt,meshBox);
for(int i = 0; i < 8; i++)
box += mat * meshBox[i];
}
int PBombObject::Display(TimeValue t, INode* inode, ViewExp *vpt, int flags)
{
if ( ! vpt || ! vpt->IsAlive() )
{
// why are we here
DbgAssert(!_T("Invalid viewport!"));
return FALSE;
}
GraphicsWindow *gw = vpt->getGW();
Material *mtl = &swMtl;
Matrix3 mat = inode->GetObjectTM(t);
// UpdateMesh(t);
DWORD rlim = gw->getRndLimits();
gw->setRndLimits(GW_WIREFRAME|GW_EDGES_ONLY|/*GW_BACKCULL|*/ (rlim&GW_Z_BUFFER?GW_Z_BUFFER:0) );//removed BC 2/16/99 DB
gw->setTransform(mat);
if (inode->Selected())
gw->setColor( LINE_COLOR, GetSelColor());
else if(!inode->IsFrozen())
gw->setColor(LINE_COLOR,GetUIColor(COLOR_SPACE_WARPS));
mesh.render(gw, mtl, NULL, COMP_ALL);
int dorange,hoopson;
pblock->GetValue(PB_RANGEON,0,hoopson,FOREVER);
pblock->GetValue(PB_DECAYTYPE,0,dorange,FOREVER);
float length;
if (hoopson && dorange)
{ pblock->GetValue(PB_DECAY,t,length,FOREVER);
float range;
range=length;
BombDrawLineProc lp(gw);
DrawFalloffSphere(range,lp);
}
gw->setRndLimits(rlim);
return(0);
}
Point3 PBombField::Force(TimeValue t,const Point3 &pos, const Point3 &vel,int index)
{ float d,chaos,dv;
Point3 dlta,xb,yb,zb,center,expv;
int decaytype,symm;
Point3 zero=Zero;
fValid = FOREVER;
if (!tmValid.InInterval(t))
{ tmValid = FOREVER;
tm = node->GetObjectTM(t,&tmValid);
invtm = Inverse(tm);
}
xb=tm.GetRow(0);
yb=tm.GetRow(1);
zb=tm.GetRow(2);
center=tm.GetTrans();
fValid &= tmValid;
TimeValue t0,t2,lastsfor;
if (obj == NULL) return Point3(0.0f,0.0f,0.0f); //667105 watje xrefs can change the base object type through proxies which will cause this to be null or the user can copy a new object type over ours
obj->pblock->GetValue(PB_STARTTIME,t,t0,fValid);
obj->pblock->GetValue(PB_LASTSFOR,t,lastsfor,fValid);
t2=t0+lastsfor;
dlta=Zero;
if ((t>=t0)&&(t<=t2))
{ float L=Length(dlta=pos-center);
obj->pblock->GetValue(PB_DECAY,t,d,fValid);
obj->pblock->GetValue(PB_DECAYTYPE,t,decaytype,fValid);
if ((decaytype==0)||(L<=d))
{ obj->pblock->GetValue(PB_DELTA_V,t,dv,fValid);
obj->pblock->GetValue(PB_CHAOS,t,chaos,fValid);
obj->pblock->GetValue(PB_SYMMETRY,t,symm,fValid);
Point3 r;
if (symm==SPHERE)
expv=(r=dlta/L);
else if (symm==PLANAR)
{ L=DotProd(dlta,zb);
expv=(L<0.0f?L=-L,-zb:zb);
}
else
{ Point3 E;
E=DotProd(dlta,xb)*xb+DotProd(dlta,yb)*yb;
L=Length(E);
expv=E/L;
}
dlta=(dv*expv)/(float)dtsq;
if (decaytype==1)
dlta*=(d-L)/d;
else if (decaytype==2)
dlta*=(1/(float)exp(L/d));
if ((!FloatEQ0(chaos))&&(lastsfor==0.0f))
{ float theta;
theta=HalfPI*chaos*RND01();
// Martell 4/14/01: Fix for order of ops bug.
float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11();
Point3 d=Point3(xtmp,ytmp,ztmp);
Point3 c=Normalize(dlta^d);
RotateOnePoint(&dlta.x,&zero.x,&c.x,theta);
}
} else dlta=Zero;
}
return dlta;
}
/* // Bayboro 9/18/01
void* PBombObject::GetInterface(ULONG id)
{
switch (id)
{
case I_NEWPARTOPERATOR: return (IOperatorInterface*)this;
}
return Object::GetInterface(id);
}
#define DONTCARE 2
#define NORMALOP -1
int PBombObject::NPOpInterface(TimeValue t,ParticleData *part,float dt,INode *node,int index)
{
if (!mf)
mf = (PBombMod *)CreateWSMMod(node);
SetUpModifier(t,node);
Point3 findforce = mf->force.Force(t,part->position,part->velocity,index);
part->velocity += 10.0f*findforce * dt;
return (NORMALOP);
}
*/ // Bayboro 9/18/01
PBombObject::~PBombObject()
{
DeleteAllRefsFromMe();
if (ff)
delete ff;
if (mf)
delete mf;
}
void PBombObject::SetUpModifier(TimeValue t,INode *node)
{
mf->force.obj = (PBombObject*)(mf->GetWSMObject(t));
mf->force.node = mf->nodeRef;
mf->force.tmValid.SetEmpty();
mf->force.fValid.SetEmpty();
mf->force.dt = GetTicksPerFrame();
mf->force.dtsq = mf->force.dt * mf->force.dt;
}
| 27.787879 | 201 | 0.677279 | [
"mesh",
"render",
"object"
] |
d7bc055978d823d2d6c67708eebe87a2a64ab204 | 13,477 | cpp | C++ | ChaosEngine/src/Chaos/Nodes/Node.cpp | JJRWalker/ChaosEngine | 47efb82cf8fac75af50ae639b85423304c90a52f | [
"Apache-2.0"
] | 3 | 2020-06-15T01:47:07.000Z | 2021-06-11T22:20:59.000Z | ChaosEngine/src/Chaos/Nodes/Node.cpp | JJRWalker/ChaosEngine | 47efb82cf8fac75af50ae639b85423304c90a52f | [
"Apache-2.0"
] | null | null | null | ChaosEngine/src/Chaos/Nodes/Node.cpp | JJRWalker/ChaosEngine | 47efb82cf8fac75af50ae639b85423304c90a52f | [
"Apache-2.0"
] | null | null | null | #include "chaospch.h"
#include "Node.h"
#include "Math.h"
#include "Colliders.h"
#include "Chaos/Serialisation/Binary.h"
#include "Chaos/Core/Application.h"
// have to include all node types here in order to serialize them, not ideal but will have to do for the moment
#include <Chaos/Nodes/Camera.h>
#include <Chaos/Nodes/Sprite.h>
#include <Chaos/Nodes/Colliders.h>
#include <Chaos/Nodes/Animator.h>
#include <Chaos/Nodes/Lights.h>
#include <Chaos/Nodes/MeshRenderer.h>
namespace Chaos
{
// Mainly used for serialization, will return a node of the type given via enum, node type must exist in ENodeType enum in Types.h
Node* Node::Create(uint32_t type)
{
switch (type)
{
case NodeType::NODE: return new Node();
case NodeType::CAMERA: return new Camera();
case NodeType::SPRITE: return new Sprite();
case NodeType::SUB_SPRITE: return new SubSprite();
case NodeType::ANIMATOR: return new Animator();
case NodeType::UI_SPRITE: return new UISprite();
case NodeType::BOX_COLLIDER_2D: return new BoxCollider2D();
case NodeType::CIRCLE_COLLIDER: return new CircleCollider();
case NodeType::POINT_LIGHT: return new PointLight();
case NodeType::MESH_RENDERER: return new MeshRenderer();
}
// defined in user side GameApp, looks for types defined there
return CreateUserDefinedNode(type);
}
Node::Node()
{
ID = Level::Get()->NodeCount;
Level::Get()->Nodes[ID] = this;
Level::Get()->NodeCount++;
}
Node::~Node()
{
Level* level = Level::Get();
if (Parent)
{
Parent->Children.Remove(this);
}
while (Children[0])
{
delete Children[0];
}
for (int i = ID; i < level->NodeCount; ++i)
{
level->Nodes[i] = level->Nodes[i + 1];
if (level->Nodes[i])
--level->Nodes[i]->ID;
}
level->Nodes[level->NodeCount - 1] = nullptr;
--level->NodeCount;
}
void Node::OnStart()
{
}
void Node::OnUpdate(float delta)
{
}
void Node::OnFixedUpdate(float delta)
{
}
void Node::OnShowEditorDetails(Texture* editorTexture, void* editorImageHandle)
{
}
void Node::OnDebug()
{
}
void Node::SetEnabled(bool state)
{
Enabled = state;
}
bool Node::IsEnabled()
{
return Enabled;
}
// sets destroy flag for it will destroy children on delete
void Node::Destroy()
{
PendingDestruction = true;
}
// recursively translates the local local matrix by the parent matrix to get global transform matrix
float* Node::GetWorldTransform()
{
memcpy((void*)&m_globalTransform[0], (void*)&Transform[0], sizeof(float) * 16);
if (Parent)
{
float* parentTransform = Parent->GetWorldTransform();
m_globalTransform[0] *= parentTransform[0];
m_globalTransform[1] *= parentTransform[1];
m_globalTransform[2] *= parentTransform[2];
m_globalTransform[4] *= parentTransform[4];
m_globalTransform[5] *= parentTransform[5];
m_globalTransform[6] *= parentTransform[6];
m_globalTransform[8] *= parentTransform[8];
m_globalTransform[9] *= parentTransform[9];
m_globalTransform[10] *= parentTransform[10];
m_globalTransform[12] += parentTransform[12];
m_globalTransform[13] += parentTransform[13];
m_globalTransform[14] += parentTransform[14];
}
return &m_globalTransform[0];
}
Vec2 Node::GetPosition()
{
Vec2 pos = Vec2(Transform[12], Transform[13]);
return pos;
}
Vec2 Node::GetWorldPosition()
{
Vec2 pos = Vec2(Transform[12], Transform[13]);
if (Parent)
pos = pos + Parent->GetWorldPosition();
return pos;
}
void Node::SetPosition(Vec2 position)
{
Transform[12] = position.X;
Transform[13] = position.Y;
}
void Node::SetWorldPosition(Vec2 position)
{
Vec2 worldPosition = GetWorldPosition();
if (Parent)
position = position + Parent->GetWorldPosition();
Transform[12] = position.X;
Transform[13] = position.Y;
}
Vec3 Node::GetPosition3D()
{
Vec3 pos = Vec3(Transform[12], Transform[13], Transform[14]);
return pos;
}
Vec3 Node::GetWorldPosition3D()
{
Vec3 pos = Vec3(Transform[12], Transform[13], Transform[14]);
if (Parent)
pos = pos + Parent->GetWorldPosition3D();
return pos;
}
void Node::SetPosition(Vec3 position)
{
Transform[12] = position.X;
Transform[13] = position.Y;
Transform[14] = position.Z;
}
void Node::SetWorldPosition(Vec3 position)
{
if (Parent)
position = position + Parent->GetWorldPosition3D();
Transform[12] = position.X;
Transform[13] = position.Y;
Transform[14] = position.Z;
}
float Node::GetDepth()
{
return Transform[14];
}
float Node::GetWorldDepth()
{
float depth = Transform[14];
if (Parent)
depth += GetWorldDepth();
return Transform[14];
}
void Node::SetDepth(float depth)
{
Transform[14] = depth;
}
void Node::SetWorldDepth(float depth)
{
if (Parent)
depth += Parent->GetWorldDepth();
Transform[14] = depth;
}
void Node::Translate(Vec2 translation)
{
Transform[12] += translation.X;
Transform[13] += translation.Y;
}
float Node::GetRotation()
{
float theta = atan2(Transform[4], Transform[0]);
if (Parent)
theta += Parent->GetRotation();
return theta;
}
float Node::GetWorldRotation()
{
float theta = atan2(Transform[4], Transform[0]);
if (Parent)
theta += Parent->GetRotation();
return theta;
}
void Node::SetRotation(float rotation)
{
Vec2 scale = GetScale();
float offset = 0;
rotation += offset;
//rotation = rotation - (int)(rotation / PI) * PI;
Transform[0] = cosf(rotation) * scale.X;
Transform[1] = -sinf(rotation) * scale.X;
Transform[4] = sinf(rotation) * scale.Y;
Transform[5] = cosf(rotation) * scale.Y;
}
void Node::SetWorldRotation(float rotation)
{
Vec2 scale = GetScale();
float offset = 0;
if (Parent)
offset = Parent->GetRotation();
rotation += offset;
//rotation = rotation - (int)(rotation / PI) * PI;
Transform[0] = cosf(rotation) * scale.X;
Transform[1] = -sinf(rotation) * scale.X;
Transform[4] = sinf(rotation) * scale.Y;
Transform[5] = cosf(rotation) * scale.Y;
}
void Node::Rotate(float rotation)
{
float currentRotation = GetRotation();
SetRotation(currentRotation + rotation);
}
Vec2 Node::GetScale()
{
Vec2 right = Vec2(Transform[0], Transform[1]);
Vec2 up = Vec2(Transform[4], Transform[5]);
int rightMod = right.X + right.Y < 0 ? -1 : 1;
int upMod = up.X + up.Y < 0 ? -1 : 1;
Vec2 scale = Vec2(right.Magnitude(), up.Magnitude());
return scale;
}
Vec2 Node::GetWorldScale()
{
Vec2 right = Vec2(Transform[0], Transform[1]);
Vec2 up = Vec2(Transform[4], Transform[5]);
int rightMod = right.X + right.Y < 0 ? -1 : 1;
int upMod = up.X + up.Y < 0 ? -1 : 1;
Vec2 scale = Vec2(right.Magnitude(), up.Magnitude());
if (Parent)
scale = scale * Parent->GetScale();
return scale;
}
void Node::SetScale(Vec2 scale)
{
Vec2 offset = Vec2();
float rotation = GetRotation();
Transform[0] = cosf(rotation) * scale.X;
Transform[1] = -sinf(rotation) * scale.X;
Transform[4] = sinf(rotation) * scale.Y;
Transform[5] = cosf(rotation) * scale.Y;
}
void Node::SetWorldScale(Vec2 scale)
{
Vec2 offset = Vec2();
float rotation = GetRotation();
if (Parent)
offset = Parent->GetScale();
Transform[0] = cosf(rotation) * scale.X;
Transform[1] = -sinf(rotation) * scale.X;
Transform[4] = sinf(rotation) * scale.Y;
Transform[5] = cosf(rotation) * scale.Y;
}
Binary Node::SaveToBinary()
{
size_t finalDataSize = 0;
Binary version((void*)&m_nodeVersion, sizeof(m_nodeVersion));
finalDataSize += sizeof(m_nodeVersion);
Binary type((void*)&Type, sizeof(Type));
finalDataSize += sizeof(Type);
size_t nameLen = strlen(Name.c_str()) + 1;
Binary nameSize((void*)&nameLen, sizeof(size_t));
finalDataSize += sizeof(size_t);
Binary name((void*)&Name[0], nameLen);
finalDataSize += nameLen; // char is 1 byte so we can just add the length
Binary id((void*)&ID, sizeof(ID));
finalDataSize += sizeof(ID);
Binary transform((void*)&Transform, sizeof(Transform));
Binary globalTransform((void*)&m_globalTransform, sizeof(m_globalTransform));
finalDataSize += sizeof(Transform);
finalDataSize += sizeof(m_globalTransform);
Binary enabled((void*)&Enabled, sizeof(Enabled));
finalDataSize += sizeof(Enabled);
size_t numberOfChildren = Children.Size();
Binary childCount((void*)&numberOfChildren, sizeof(size_t));
finalDataSize += sizeof(size_t);
// need to copy this data as once the Binary object leaves scope it'll take it with it.
Binary data(finalDataSize);
data.Write(version.Data, version.Capacity());
data.Write(type.Data, type.Capacity());
data.Write(nameSize.Data, nameSize.Capacity());
data.Write(name.Data, name.Capacity());
data.Write(id.Data, id.Capacity());
data.Write(transform.Data, transform.Capacity());
data.Write(globalTransform.Data, globalTransform.Capacity());
data.Write(enabled.Data, enabled.Capacity());
data.Write(childCount.Data, childCount.Capacity());
size_t totalChildrenSize = 0;
std::vector<Binary> childBinaries;
for (size_t child = 0; child < Children.Size(); ++child)
{
Binary childBinary = Children[child]->SaveToBinary();
Binary finalChildBinary(childBinary.Capacity() + sizeof(size_t));
size_t childSize = childBinary.Capacity();
finalChildBinary.Write((void*)&childSize, sizeof(size_t));
finalChildBinary.Write(childBinary.Data, childBinary.Capacity());
totalChildrenSize += finalChildBinary.Capacity();
childBinaries.push_back(finalChildBinary);
}
Binary finalBinary(finalDataSize + totalChildrenSize);
// write the total number of children so we know how much data to skip when we load
finalBinary.Write(data.Data, data.Capacity());
for (int i = 0; i < childBinaries.size(); ++i)
{
finalBinary.Write(childBinaries[i].Data, childBinaries[i].Capacity());
}
return finalBinary;
}
size_t Node::LoadFromBinary(char* data)
{
size_t location = 0;
memcpy((void*)&m_nodeVersion, (void*)&data[location], sizeof(uint32_t));
location += sizeof(uint32_t);
switch (m_nodeVersion)
{
case NODE_VERSION_0:
{
memcpy((void*)&Type, (void*)&data[location], sizeof(size_t));
location += sizeof(Type);
size_t namelen;
memcpy((void*)&namelen, (void*)&data[location], sizeof(size_t));
location += sizeof(size_t);
Name.resize(namelen - 1);
memcpy((void*)&Name[0], (void*)&data[location], namelen);
location += namelen;
memcpy((void*)&ID, (void*)&data[location], sizeof(ID));
location += sizeof(ID);
memcpy((void*)&Transform, (void*)&data[location], sizeof(Transform));
location += sizeof(Transform);
memcpy((void*)&m_globalTransform, (void*)&data[location], sizeof(m_globalTransform));
location += sizeof(m_globalTransform);
bool enabled;
memcpy((void*)&enabled, (void*)&data[location], sizeof(enabled));
location += sizeof(enabled);
size_t childCount;
memcpy((void*)&childCount, (void*)&data[location], sizeof(size_t));
location += sizeof(size_t);
for (int i = 0; i < childCount; ++i)
{
size_t childSize;
memcpy((void*)&childSize, (void*)&data[location], sizeof(size_t));
location += sizeof(size_t);
// memcpy the type without changing location so we know which kind of node to create.
uint32_t type;
memcpy((void*)&type, (void*)&data[location + sizeof(uint32_t)], sizeof(type));
Node* child = Node::Create(type);
child->LoadFromBinary(&data[location]);
AddChild(child);
location += childSize;
}
// need to set enabled here rather than just loading the value into Enabled
// certain nodes override this, not calling set enabled causes issues on load
SetEnabled(enabled);
DebugEnabled = false;
PendingDestruction = false;
return location;
} break;
default:
{
LOGCORE_ERROR("NODE: LoadFromBinary: Loading from version number {0} not supported in this engine version!", m_nodeVersion);
} break;
}
return 0;
}
size_t Node::GetSize()
{
return sizeof(*this);
}
const char* Node::GetType()
{
return typeid(*this).name();
}
void Node::ColliderStay(Collider* self, Collider* other)
{
}
void Node::ColliderEnter(Collider* self, Collider* other)
{
}
void Node::ColliderExit(Collider* self, Collider* other)
{
}
void Node::TriggerStay(Collider* self, Collider* other)
{
}
void Node::TriggerEnter(Collider* self, Collider* other)
{
}
void Node::TriggerExit(Collider* self, Collider* other)
{
}
// NOTE: remember to free() when done with the data
Node** Node::GetAllChildren(size_t& size, bool recursive)
{
size = 0;
Node** returnedNodes = (Node**)malloc(sizeof(Node*) * MAX_NODES);
if (recursive)
{
GetAllChildrenRecursively(size, returnedNodes);
return returnedNodes;
}
for (int child = 0; child < Children.Size(); ++child)
{
returnedNodes[size] = Children[child];
++size;
}
return returnedNodes;
}
void Node::GetAllChildrenRecursively(size_t& size, Node** nodesOut)
{
for (int child = 0; child < Children.Size(); ++child)
{
nodesOut[size] = Children[child];
++size;
Children[child]->GetAllChildrenRecursively(size, nodesOut);
}
}
} | 22.312914 | 131 | 0.656823 | [
"object",
"vector",
"transform"
] |
d7bd09508935d6502e562da2dd3a49141061e382 | 9,751 | cpp | C++ | benchmarks/accuracy_and_overhead/phoenix/phoenix++-1.0/tests/pca/pca.cpp | quanshousio/CompilerInterrupts | 67e72514a90c76c7106e4202001003b9ef359a5e | [
"MIT"
] | null | null | null | benchmarks/accuracy_and_overhead/phoenix/phoenix++-1.0/tests/pca/pca.cpp | quanshousio/CompilerInterrupts | 67e72514a90c76c7106e4202001003b9ef359a5e | [
"MIT"
] | null | null | null | benchmarks/accuracy_and_overhead/phoenix/phoenix++-1.0/tests/pca/pca.cpp | quanshousio/CompilerInterrupts | 67e72514a90c76c7106e4202001003b9ef359a5e | [
"MIT"
] | null | null | null | /* Copyright (c) 2007-2011, Stanford University
* 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 Stanford University 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 STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY 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 <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef TBB
#include "tbb/scalable_allocator.h"
#endif
#include "map_reduce.h"
typedef struct {
int row_num;
int const* matrix;
} pca_map_data_t;
typedef struct {
int const* matrix;
long long const* means;
int row_num;
int col_num;
} pca_cov_data_t;
#define DEF_GRID_SIZE 100 // all values in the matrix are from 0 to this value
#define DEF_NUM_ROWS 10
#define DEF_NUM_COLS 10
int num_rows;
int num_cols;
int grid_size;
/** parse_args()
* Parse the user arguments to determine the number of rows and colums
*/
void parse_args(int argc, char **argv)
{
int c;
extern char *optarg;
num_rows = DEF_NUM_ROWS;
num_cols = DEF_NUM_COLS;
grid_size = DEF_GRID_SIZE;
while ((c = getopt(argc, argv, "r:c:s:")) != EOF)
{
switch (c) {
case 'r':
num_rows = atoi(optarg);
break;
case 'c':
num_cols = atoi(optarg);
break;
case 's':
grid_size = atoi(optarg);
break;
case '?':
printf("Usage: %s -r <num_rows> -c <num_cols> -s <max value>\n", argv[0]);
exit(1);
}
}
if (num_rows <= 0 || num_cols <= 0 || grid_size <= 0) {
printf("Illegal argument value. All values must be numeric and greater than 0\n");
exit(1);
}
printf("Number of rows = %d\n", (int)num_rows);
printf("Number of cols = %d\n", (int)num_cols);
printf("Max value for each element = %d\n", (int)grid_size);
}
/** dump_points()
* Print the values in the matrix to the screen
*/
void dump_points(int *vals, int rows, int cols)
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
printf("%5d ",vals[i*cols+j]);
}
printf("\n");
}
}
/** generate_points()
* Create the values in the matrix
*/
void generate_points(int *pts, int rows, int cols)
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
pts[i * cols + j] = rand() % grid_size;
}
}
}
#ifdef MUST_USE_HASH
class MeanMR : public MapReduce<MeanMR, pca_map_data_t, int, long long, hash_container<int, long long, one_combiner, std::tr1::hash<int>
#elif defined(MUST_USE_FIXED_HASH)
class MeanMR : public MapReduce<MeanMR, pca_map_data_t, int, long long, fixed_hash_container<int, long long, one_combiner, 32768, std::tr1::hash<int>
#else
class MeanMR : public MapReduce<MeanMR, pca_map_data_t, int, long long, common_array_container<int, long long, one_combiner, 1000
#endif
#ifdef TBB
, tbb::scalable_allocator
#endif
> >
{
int *matrix;
int row;
public:
explicit MeanMR(int* _matrix) : matrix(_matrix), row(0) {}
void* locate(data_type* d, uint64_t len) const
{
return (void*)const_cast<int*>(d->matrix + d->row_num * num_cols);
}
/** pca_mean_map()
* Map task to compute the mean
*/
void map(data_type const& data, map_container& out) const
{
long long sum = 0;
int const* m = data.matrix + data.row_num * num_cols;
for(int j = 0; j < num_cols; j++)
{
sum += m[j];
}
emit_intermediate(out, data.row_num, sum/num_cols);
}
int split(pca_map_data_t& out)
{
/* End of data reached, return FALSE. */
if (row >= num_rows)
{
return 0;
}
out.matrix = matrix;
out.row_num = row++;
/* Return true since the out data is valid. */
return 1;
}
};
#ifdef MUST_USE_HASH
class CovMR : public MapReduceSort<CovMR, pca_cov_data_t, intptr_t, long long, hash_container<intptr_t, long long, one_combiner, std::tr1::hash<intptr_t>
#elif defined(MUST_USE_FIXED_HASH)
class CovMR : public MapReduceSort<CovMR, pca_cov_data_t, intptr_t, long long, fixed_hash_container<intptr_t, long long, one_combiner, 256, std::tr1::hash<intptr_t>
#else
class CovMR : public MapReduceSort<CovMR, pca_cov_data_t, intptr_t, long long, common_array_container<intptr_t, long long, one_combiner, 1000*1000
#endif
#ifdef TBB
, tbb::scalable_allocator
#endif
> >
{
int *matrix;
long long const* means;
int row;
int col;
public:
explicit CovMR(int* _matrix, long long const* _means) :
matrix(_matrix), means(_means), row(0), col(0) {}
void* locate(data_type* d, uint64_t len) const
{
return (void*)const_cast<int*>(d->matrix + d->row_num * num_cols);
}
/** pca_cov_map()
* Map task for computing the covariance matrix
*
*/
void map(data_type const& data, map_container& out) const
{
int const* v1 = data.matrix + data.row_num*num_cols;
int const* v2 = data.matrix + data.col_num*num_cols;
long long m1 = data.means[data.row_num];
long long m2 = data.means[data.col_num];
long long sum = 0;
for(int i = 0; i < num_cols; i++)
{
sum += (v1[i] - m1) * (v2[i] - m2);
}
sum /= (num_cols-1);
emit_intermediate(out, data.row_num*num_cols + data.col_num, sum);
}
/** pca_cov_split()
* Splitter function for computing the covariance
* Need to produce a task for each variable (row) pair
*/
int split(pca_cov_data_t& out)
{
/* End of data reached, return FALSE. */
if (row >= num_rows)
{
return 0;
}
out.matrix = matrix;
out.means = means;
out.row_num = row;
out.col_num = col;
col++;
if(col >= num_rows) // yes, num_rows
{
row++;
// will only compute upper right triangle since
// covariance matrix is symmetric
col = row;
}
/* Return true since the out data is valid. */
return 1;
}
};
int main(int argc, char **argv)
{
struct timespec begin, end;
double library_time = 0;
get_time (begin);
parse_args(argc, argv);
// Allocate space for the matrix
int* matrix = (int *)malloc(sizeof(int) * num_rows * num_cols);
//Generate random values for all the points in the matrix
generate_points(matrix, num_rows, num_cols);
// Print the points
//dump_points(matrix, num_rows, num_cols);
// Setup scheduler args for computing the mean
printf("PCA Mean: Calling MapReduce Scheduler\n");
get_time (end);
print_time("initialize", begin, end);
get_time (begin);
std::vector<MeanMR::keyval> result;
MeanMR meanMR(matrix);
meanMR.run(result);
get_time (end);
library_time += time_diff (end, begin);
printf("PCA Mean: MapReduce Completed\n");
get_time (begin);
assert (result.size() == (size_t)num_rows);
long long* means = new long long[num_rows];
for(size_t i = 0; i < result.size(); i++)
{
means[result[i].key] = result[i].val;
}
get_time (end);
print_time("inter library", begin, end);
printf("PCA Cov: Calling MapReduce Scheduler\n");
get_time (begin);
std::vector<CovMR::keyval> result2;
CovMR covMR(matrix, means);
covMR.run(result2);
get_time (end);
library_time += time_diff (end, begin);
print_time("library", library_time);
get_time (begin);
printf("PCA Cov: MapReduce Completed\n");
assert(result2.size() == (size_t)((((num_rows * num_rows) - num_rows)/2) + num_rows));
// Free the allocated structures
int cnt = 0;
long long sum = 0;
for (size_t i = 0; i < result2.size(); i++)
{
sum += result2[i].val;
//printf("%5d ", result2[i].val);
cnt++;
if (cnt == num_rows)
{
//printf("\n");
num_rows--;
cnt = 0;
}
}
printf("\n\nCovariance sum: %lld\n", sum);
delete [] means;
free (matrix);
get_time (end);
print_time("finalize", begin, end);
return 0;
}
// vim: ts=8 sw=4 sts=4 smarttab smartindent
| 27.780627 | 164 | 0.605887 | [
"vector"
] |
d7bfa315c285628980404ec9c4b21e0e8f0efb95 | 4,269 | cpp | C++ | src/tests/kalman/test-kalman-eigen-benchmark.cpp | skyward-er/skyward-boardcore | 05b9fc2ef45d27487af57cc11ed8b85524451510 | [
"MIT"
] | 6 | 2022-01-06T14:20:45.000Z | 2022-02-28T07:32:39.000Z | src/tests/kalman/test-kalman-eigen-benchmark.cpp | skyward-er/skyward-boardcore | 05b9fc2ef45d27487af57cc11ed8b85524451510 | [
"MIT"
] | null | null | null | src/tests/kalman/test-kalman-eigen-benchmark.cpp | skyward-er/skyward-boardcore | 05b9fc2ef45d27487af57cc11ed8b85524451510 | [
"MIT"
] | null | null | null | /* Copyright (c) 2020 Skyward Experimental Rocketry
* Author: Luca Conterio
*
* 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.
*/
// This prgram runs through a simulated flight and reports the apogee detection,
// while measuring the time elapsed
#define EIGEN_RUNTIME_NO_MALLOC
#include <Common.h>
#include <drivers/HardwareTimer.h>
#include <kalman/KalmanEigen.h>
#include <src/tests/kalman/test-kalman-data.h>
#include <iostream>
#include "math/SkyQuaternion.h"
#include "util/util.h"
using namespace Eigen;
using namespace miosix;
int main()
{
// Setting pin mode for signaling ADA status
{
FastInterruptDisableLock dLock;
RCC->APB1ENR |= RCC_APB1ENR_TIM5EN;
}
printf("RUNNING...\n");
// Timer for benchmarking purposes
HardwareTimer<uint32_t> timer{TIM5, TimerUtils::getPrescalerInputFrequency(
TimerUtils::InputClock::APB1)};
const int n = 3;
const int p = 1;
Matrix<float, n, n> F =
(Matrix<float, n, n>(n, n) << 1, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
.finished();
// Output matrix
Matrix<float, p, n> H{1, 0, 0};
// Initial error covariance matrix
Matrix<float, n, n> P = (Matrix<float, n, n>(n, n) << 0.1, 0.0, 0.0, 0.0,
0.1, 0.0, 0.0, 0.0, 0.1)
.finished();
// Model variance matrix
Matrix<float, n, n> Q = (Matrix<float, n, n>(n, n) << 0.01, 0.0, 0.0, 0.0,
0.01, 0.0, 0.0, 0.0, 0.01)
.finished();
// Measurement variance
Matrix<float, p, p> R{10};
Matrix<float, n, 1> x0(INPUT[0], 0.0, 0.0);
Matrix<float, p, 1> y(p); // vector with p elements (only one in this case)
KalmanEigen<float, n, p>::KalmanConfig config;
config.F = F;
config.H = H;
config.Q = Q;
config.R = R;
config.P = P;
config.x = x0;
KalmanEigen<float, n, p> filter(config);
float last_time = 0.0; // Variable to save the time of the last sample
float time; // Current time as read from csv file
float T; // Time elapsed between last sample and current one
timer.start();
uint32_t tick1;
uint32_t tick2;
printf("%d %d \n", TIME.size(), INPUT.size());
for (unsigned i = 1; i < TIME.size(); i++)
{
time = TIME[i];
T = time - last_time;
F(0, 1) = T;
F(0, 2) = 0.5 * T * T;
F(1, 2) = T;
y(0) = INPUT[i];
tick1 = timer.tick();
filter.predict(F);
if (!filter.correct(y))
{
printf("Correction failed at iteration : %d \n", i);
}
tick2 = timer.tick();
printf("%d : %f \n", i, timer.toMilliSeconds(tick2 - tick1));
// printf("%f, %f, %f;\n", filter.getState()(0), filter.getState()(1),
// filter.getState()(2));
// printf("%u \n", MemoryProfiling::getCurrentFreeStack());
last_time = time;
if (filter.getState()(1) < 0)
{
printf("APOGEE DETECTED at iteration %d ! \n", i);
}
}
timer.stop();
// printf("Total time %d \n", timer.interval());
return 0;
}
| 29.853147 | 80 | 0.593347 | [
"vector",
"model"
] |
d7c981fe5912d25f282cd97bb4c960943055bf1d | 8,404 | cc | C++ | src/main.cc | pstanisz/algorithms | 701d907704e8a33de242d4eabc4ee5164afd1be5 | [
"MIT"
] | null | null | null | src/main.cc | pstanisz/algorithms | 701d907704e8a33de242d4eabc4ee5164afd1be5 | [
"MIT"
] | null | null | null | src/main.cc | pstanisz/algorithms | 701d907704e8a33de242d4eabc4ee5164afd1be5 | [
"MIT"
] | null | null | null | /*
* @brief Entry point for algorithms application
*/
#include <iostream>
#include <vector>
#include <cstdlib>
#include <functional>
#include "utils.hh"
#include "sorting.hh"
#include "binarysearching.hh"
#include "merging.hh"
#include "set.hh"
int main()
{
using namespace Algorithms;
std::cout << "Sandbox for checking various STL algorithms" << std::endl;
const std::vector<int> testVecInput1 { 1, 3, 2, 8, 3, 6, 8, 1, 4, 9 };
const std::vector<int> testVecInput2 { 3, 6, 9, 1, 2, 8, 3 };
const std::vector<std::pair<int, char>> testVecInput3 { {3, 'a'}, {1, 'b'}, {2, 'c'}, {9, 'd'},
{7, 'e'}, {4, 'f'}, {3, 'g'}, {4, 'h'},
{8, 'i'}, {7, 'j'}};
const std::vector<std::pair<int, char>> testVecInput4 { {3, 'k'}, {7, 'l'}};
// Ordinary sort
{
std::cout << std::endl << "sort/is_sorted check" << std::endl;
auto testVec1(testVecInput1);
Sorting::doSort(testVec1);
auto testVec3(testVecInput3);
Sorting::doSort(testVec3);
}
// Stable sort
{
std::cout << std::endl << "stable_sort/is_sorted check" << std::endl;
auto testVec1(testVecInput1);
Sorting::doStableSort(testVec1);
auto testVec3(testVecInput3);
Sorting::doStableSort(testVec3);
}
// Partial sort
{
std::cout << std::endl << "partial_sort/is_sorted_until check" << std::endl;
auto testVec1(testVecInput1);
auto middleIter1 = Utils::getMiddleIterator(testVec1);
Sorting::doPartialSort(testVec1, middleIter1);
auto testVec3(testVecInput3);
auto middleIter2 = Utils::getMiddleIterator(testVec3);
Sorting::doPartialSort(testVec3, middleIter2);
}
// Partial sort copy
{
std::cout << std::endl << "partial_sort_copy/is_sorted check" << std::endl;
auto testVec1(testVecInput1);
auto middleIter1 = Utils::getMiddleIterator(testVec1);
Sorting::doPartialSortCopy(testVec1, middleIter1);
auto testVec3(testVecInput3);
auto middleIter2 = Utils::getMiddleIterator(testVec3);
Sorting::doPartialSortCopy(testVec3, middleIter2);
}
// Nth element
{
std::cout << std::endl << "nth_element" << std::endl;
auto testVec1(testVecInput1);
auto middleIter1 = Utils::getMiddleIterator(testVec1);
Sorting::doNthElement(testVec1, middleIter1);
auto testVec3(testVecInput3);
auto middleIter2 = Utils::getMiddleIterator(testVec3);
Sorting::doNthElement(testVec3, middleIter2);
}
// Lower bound
{
std::cout << std::endl << "lower_bound check" << std::endl;
auto testVec1(testVecInput1);
std::sort(testVec1.begin(), testVec1.end());
BinarySearching::doLowerBound(testVec1, 4);
auto testVec3(testVecInput3);
std::sort(testVec3.begin(), testVec3.end());
BinarySearching::doLowerBound(testVec3, std::make_pair(3, 'b'));
}
// Upper bound
{
std::cout << std::endl << "upper_bound check" << std::endl;
auto testVec1(testVecInput1);
std::sort(testVec1.begin(), testVec1.end());
BinarySearching::doUpperBound(testVec1, 4);
auto testVec3(testVecInput3);
std::sort(testVec3.begin(), testVec3.end());
BinarySearching::doUpperBound(testVec3, std::make_pair(3, 'b'));
}
// Equal range
{
std::cout << std::endl << "equal_range check" << std::endl;
auto testVec1(testVecInput1);
std::sort(testVec1.begin(), testVec1.end());
BinarySearching::doEqualRange(testVec1, 3);
auto testVec3(testVecInput3);
std::sort(testVec3.begin(), testVec3.end());
BinarySearching::doEqualRange(testVec3, std::make_pair(3, 'g'));
}
// Binary search
{
std::cout << std::endl << "binary_search check" << std::endl;
auto testVec1(testVecInput1);
std::sort(testVec1.begin(), testVec1.end());
BinarySearching::doBinarySearch(testVec1, 3);
auto testVec3(testVecInput3);
std::sort(testVec3.begin(), testVec3.end());
BinarySearching::doBinarySearch(testVec3, std::make_pair(3, 'b'));
}
// Merge
{
std::cout << std::endl << "merge check" << std::endl;
auto testVec1(testVecInput1);
std::sort(testVec1.begin(), testVec1.end());
auto testVec2(testVecInput2);
std::sort(testVec2.begin(), testVec2.end());
Merging::doMerge(testVec1, testVec2);
auto testVec3(testVecInput3);
std::sort(testVec3.begin(), testVec3.end());
auto testVec4(testVecInput4);
std::sort(testVec4.begin(), testVec4.end());
Merging::doMerge(testVec3, testVec4);
}
// Inplace merge
{
std::cout << std::endl << "inplace merge check" << std::endl;
auto testVec1(testVecInput1);
auto middleIter1 = Utils::getMiddleIterator(testVec1);
std::sort(testVec1.begin(), middleIter1);
std::sort(middleIter1, testVec1.end());
Merging::doInplaceMerge(testVec1, middleIter1);
auto testVec3(testVecInput3);
auto middleIter3 = Utils::getMiddleIterator(testVec3);
std::sort(testVec3.begin(), middleIter3);
std::sort(middleIter3, testVec3.end());
Merging::doInplaceMerge(testVec3, middleIter3);
}
// Includes
{
std::cout << std::endl << "includes check" << std::endl;
auto testVec1(testVecInput1);
auto testVec2(testVecInput2);
std::sort(testVec1.begin(), testVec1.end());
std::sort(testVec2.begin(), testVec2.end());
Set::doIncludes(testVec1, testVec2);
auto testVec3(testVecInput3);
auto testVec4(testVecInput4);
std::sort(testVec3.begin(), testVec3.end());
std::sort(testVec4.begin(), testVec4.end());
Set::doIncludes(testVec3, testVec4);
}
// Set union
{
std::cout << std::endl << "set_union check" << std::endl;
auto testVec1(testVecInput1);
auto testVec2(testVecInput2);
std::sort(testVec1.begin(), testVec1.end());
std::sort(testVec2.begin(), testVec2.end());
Set::doSetUnion(testVec1, testVec2);
auto testVec3(testVecInput3);
auto testVec4(testVecInput4);
std::sort(testVec3.begin(), testVec3.end());
std::sort(testVec4.begin(), testVec4.end());
Set::doSetUnion(testVec3, testVec4);
}
// Set intersection
{
std::cout << std::endl << "set_intersection check" << std::endl;
auto testVec1(testVecInput1);
auto testVec2(testVecInput2);
std::sort(testVec1.begin(), testVec1.end());
std::sort(testVec2.begin(), testVec2.end());
Set::doSetIntersection(testVec1, testVec2);
auto testVec3(testVecInput3);
auto testVec4(testVecInput4);
std::sort(testVec3.begin(), testVec3.end());
std::sort(testVec4.begin(), testVec4.end());
Set::doSetIntersection(testVec3, testVec4);
}
// Set difference
{
std::cout << std::endl << "set_difference check" << std::endl;
auto testVec1(testVecInput1);
auto testVec2(testVecInput2);
std::sort(testVec1.begin(), testVec1.end());
std::sort(testVec2.begin(), testVec2.end());
Set::doSetDifference(testVec1, testVec2);
auto testVec3(testVecInput3);
auto testVec4(testVecInput4);
std::sort(testVec3.begin(), testVec3.end());
std::sort(testVec4.begin(), testVec4.end());
Set::doSetDifference(testVec3, testVec4);
}
// Set symmetric difference
{
std::cout << std::endl << "set_symmetric_difference check" << std::endl;
auto testVec1(testVecInput1);
auto testVec2(testVecInput2);
std::sort(testVec1.begin(), testVec1.end());
std::sort(testVec2.begin(), testVec2.end());
Set::doSetSymmetricDifference(testVec1, testVec2);
auto testVec3(testVecInput3);
auto testVec4(testVecInput4);
std::sort(testVec3.begin(), testVec3.end());
std::sort(testVec4.begin(), testVec4.end());
Set::doSetSymmetricDifference(testVec3, testVec4);
}
return EXIT_SUCCESS;
}
| 29.28223 | 99 | 0.597692 | [
"vector"
] |
d7cf81fcbf08a6da406bb7c09b882ceb06a85bfd | 3,632 | cc | C++ | code/dictionary_benchmark/benchmark.cc | dendisuhubdy/LowLatencyProgrammingPresentation | 73aade6543174c4c5427bd409039a08c6be86732 | [
"MIT"
] | 10 | 2018-07-10T12:04:17.000Z | 2022-03-30T21:22:37.000Z | code/dictionary_benchmark/benchmark.cc | dendisuhubdy/LowLatencyProgrammingPresentation | 73aade6543174c4c5427bd409039a08c6be86732 | [
"MIT"
] | 1 | 2018-01-24T16:17:37.000Z | 2018-01-24T20:27:10.000Z | code/dictionary_benchmark/benchmark.cc | dendisuhubdy/LowLatencyProgrammingPresentation | 73aade6543174c4c5427bd409039a08c6be86732 | [
"MIT"
] | 4 | 2018-03-13T19:05:38.000Z | 2020-04-07T09:24:33.000Z | #include "../v0/dictionary.hh"
#include "../v1/dictionary.hh"
#include "../v2/dictionary.hh"
#include "../v3/dictionary.hh"
#include "../v4/dictionary.hh"
#include <benchmark/benchmark.h>
// instrumentation
#include <papipp.h>
#include <valgrind/callgrind.h>
#include <iostream>
#include <vector>
#include <random>
#include <unordered_set>
static std::random_device rd;
static std::uniform_int_distribution<int> charDist(48, 127);
static std::lognormal_distribution<float> lengthDist(2.19, 0.25);
std::vector<std::string> wordsIn;
std::vector<std::string> wordsNotIn;
static std::string CreateRandomString()
{
std::size_t len = (int)(std::floor(lengthDist(rd))) + 1;
std::string out;
out.reserve(len);
for(std::size_t i = 0; i < len; i++)
out.push_back(charDist(rd));
return out;
}
static std::vector<std::string> CreateVectorOfUniqueRandomStrings(std::size_t len)
{
std::unordered_set<std::string> strings;
strings.reserve(len);
while (strings.size() < len)
strings.insert(CreateRandomString());
return std::vector<std::string>(strings.begin(), strings.end());
}
template<typename DictType>
void InDictionary(benchmark::State& state)
{
int idx = 0;
DictType dict(wordsIn );
bool allFound = true;
// papi - perf counters
//papi::event_set<PAPI_TOT_INS, PAPI_TOT_CYC, PAPI_BR_MSP, PAPI_L1_DCM> events;
//events.start_counters();
// enable Callgrind instrumentation
//CALLGRIND_START_INSTRUMENTATION;
for(auto _ : state)
{
const std::string& word = wordsIn[idx];
idx = (idx+1) % wordsIn.size();
benchmark::DoNotOptimize(allFound &= dict.in_dictionary(word));
}
//CALLGRIND_STOP_INSTRUMENTATION; // vcallgrind
// events.stop_counters();
// std::cout << events.get<PAPI_TOT_INS>().counter()/double(events.get<PAPI_TOT_CYC>().counter()) << " instr per cycle\n";
// std::cout << events.get<PAPI_TOT_INS>().counter()/double(state.iterations()) << " instructions\n";
// std::cout << events.get<PAPI_L1_DCM>().counter()/double(state.iterations()) << " l1 cache misses\n"
// << events.get<PAPI_BR_MSP>().counter()/double(state.iterations()) << " branch misses" << std::endl;
// std::cout << "iterations: " << state.iterations() << std::endl;
if (!allFound)
std::cout << "InDictionary consistency check failed" << std::endl;
}
template<typename DictType>
void NotInDictionary(benchmark::State& state)
{
int idx = 0;
DictType dict(wordsIn);
bool someFound = false;
for(auto _ : state)
{
const std::string& word = wordsNotIn[idx];
idx = (idx+1) % wordsNotIn.size();
benchmark::DoNotOptimize(someFound |= dict.in_dictionary(word));
}
if (someFound)
std::cout << "NotInDictionary consistency check failed" << std::endl;
}
BENCHMARK_TEMPLATE(InDictionary, v0::Dictionary);
BENCHMARK_TEMPLATE(NotInDictionary, v0::Dictionary);
BENCHMARK_TEMPLATE(InDictionary, v1::Dictionary);
BENCHMARK_TEMPLATE(NotInDictionary, v1::Dictionary);
BENCHMARK_TEMPLATE(InDictionary, v2::Dictionary);
BENCHMARK_TEMPLATE(NotInDictionary, v2::Dictionary);
BENCHMARK_TEMPLATE(InDictionary, v3::Dictionary);
BENCHMARK_TEMPLATE(NotInDictionary, v3::Dictionary);
BENCHMARK_TEMPLATE(InDictionary, v4::Dictionary);
BENCHMARK_TEMPLATE(NotInDictionary, v4::Dictionary);
int main(int argc, char** argv)
{
static const int DICT_SIZE = 99171;
std::vector<std::string> words = CreateVectorOfUniqueRandomStrings(DICT_SIZE*2);
wordsIn.assign(words.begin(), words.begin() + DICT_SIZE);
wordsNotIn.assign(words.begin() + DICT_SIZE, words.end());
benchmark::Initialize(&argc, argv);
if (::benchmark::ReportUnrecognizedArguments(argc, argv))
return 1;
benchmark::RunSpecifiedBenchmarks();
}
| 27.938462 | 123 | 0.724394 | [
"vector"
] |
d7cf939e984231c6dbd1958578087ddea3cf5542 | 5,578 | cpp | C++ | src/turtle_input_helper.cpp | paulhilbert/duraark_rdf | 2f82913dcf1e62ca702c92d093c69b3d3dc2a71a | [
"CC0-1.0"
] | null | null | null | src/turtle_input_helper.cpp | paulhilbert/duraark_rdf | 2f82913dcf1e62ca702c92d093c69b3d3dc2a71a | [
"CC0-1.0"
] | null | null | null | src/turtle_input_helper.cpp | paulhilbert/duraark_rdf | 2f82913dcf1e62ca702c92d093c69b3d3dc2a71a | [
"CC0-1.0"
] | null | null | null | #include <turtle_input_helper.hpp>
#include <iostream>
#include <boost/spirit/include/qi.hpp>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
namespace duraark_rdf {
std::set<uint32_t> parse_index_list_(const std::string& str) {
using boost::spirit::qi::uint_;
using boost::spirit::qi::char_;
using boost::spirit::qi::phrase_parse;
using boost::spirit::ascii::space;
auto first = str.begin();
auto last = str.end();
uint32_t index_begin = 0, index_end = 0;
std::set<uint32_t> indices;
auto match_first = [&] (uint32_t idx) { index_begin = index_end = idx; };
auto match_second = [&] (uint32_t idx) { index_end = idx; };
auto match_after = [&] () { for (uint32_t i=index_begin; i<=index_end; ++i) { indices.insert(i); }; };
bool r = phrase_parse(first, last, *((uint_[match_first] >> -(char_('-') >> uint_[match_second]))[match_after]), space);
if (!r || first != last) {
return std::set<uint32_t>();
}
return indices;
}
std::pair<std::string, bool>
parse_transformation_string(turtle_input& input, const std::string& guid_0,
const std::string& guid_1) {
auto entity_triples = input.filter_triples(
turtle_input::filter(),
turtle_input::filter::equals("rel:globalUniqueId"));
std::string name_0 = "", name_1 = "";
for (auto& entity : entity_triples) {
std::string crt_guid = entity.second["rel:globalUniqueId"];
if (crt_guid == guid_0) {
name_0 = fs::path(entity.first).filename().stem().string();
}
if (crt_guid == guid_1) {
name_1 = fs::path(entity.first).filename().stem().string();
}
}
if (name_0 == "") {
throw std::runtime_error("Unable to find object for GUID \"" + guid_0 +
"\"");
}
if (name_1 == "") {
throw std::runtime_error("Unable to find object for GUID \"" + guid_1 +
"\"");
}
bool inverse = false;
std::string tr_name = "obj:" + name_0 + "_to_" + name_1;
auto tr_obj = input.filter_triples(
turtle_input::filter::contains(tr_name),
turtle_input::filter::equals("rel:transformParam"));
if (!tr_obj.size()) {
tr_name = "obj:" + name_1 + "_to_" + name_0;
tr_obj = input.filter_triples(turtle_input::filter::contains(tr_name),
turtle_input::filter("rel:transformParam"));
if (!tr_obj.size()) {
throw std::runtime_error(
"No transformation found for given objects");
}
inverse = true;
}
auto& pred = tr_obj[tr_name];
auto pred_found = pred.find("rel:transformParam");
if (pred_found == pred.end()) {
throw std::runtime_error(
"Transform object has no \"rel:transformParam\" attribute");
}
return {pred_found->second, inverse};
}
Eigen::Matrix4f
parse_registration(turtle_input& input, const std::string& guid_0,
const std::string& guid_1) {
std::pair<std::string, bool> t = parse_transformation_string(input, guid_0, guid_1);
std::istringstream iss(t.first);
std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
assert(tokens.size() == 16);
Eigen::Matrix4f m;
for (uint32_t i = 0; i < 4; ++i) {
for (uint32_t j = 0; j < 4; ++j) {
double value;
std::stringstream convert_str(tokens[i*4+j]);
convert_str >> value;
convert_str.str("");
m(i, j) = value;
}
}
if (t.second) {
Eigen::Matrix4f inv = m.inverse();
m = inv;
}
return m;
}
std::vector<subset_association_t> parse_subset_associations(turtle_input& input, std::map<std::string, uint32_t>& possible_hits, std::set<std::string>* const pointcloud_entities) {
// parse point-cloud entities
std::map<std::string, std::string> pc_guids;
if (pointcloud_entities) pointcloud_entities->clear();
auto entity_triples = input.filter_triples(
turtle_input::filter::contains("PC_"),
turtle_input::filter::equals("rel:globalUniqueId"));
for (const auto& entity : entity_triples) {
std::string pc_guid = entity.second.at("rel:globalUniqueId");
pc_guids[entity.first] = pc_guid;
if (pointcloud_entities) pointcloud_entities->insert(pc_guid);
}
std::vector<subset_association_t> assocs;
entity_triples = input.filter_triples(turtle_input::filter::contains("SBS_"), turtle_input::filter());
for (const auto& entity : entity_triples) {
auto& m = entity.second;
auto sub_it = m.find("rel:pointSubsetOf");
auto rep_it = m.find("rel:subsetRepOf");
auto idx_it = m.find("rel:pointSubsetContains");
auto poss_it = m.find("rel:possibleScanHits");
if (sub_it != m.end() && rep_it != m.end() && idx_it != m.end()) {
subset_association_t assoc;
assoc.ifc_object_guid = rep_it->second;
assoc.pointcloud_guid = pc_guids[sub_it->second];
assoc.point_indices = parse_index_list_(idx_it->second);
uint32_t poss_hits = 0;
if (poss_it != m.end()) {
std::stringstream sstr_conv;
sstr_conv << poss_it->second;
sstr_conv >> poss_hits;
}
possible_hits[rep_it->second] = poss_hits;
assocs.push_back(assoc);
}
}
return assocs;
}
} // duraark_rdf
| 36.697368 | 180 | 0.596988 | [
"object",
"vector",
"transform"
] |
d7dab3a309fb346d0ed3bead6e0b16a5725780c3 | 9,394 | cpp | C++ | src/model_data.cpp | Kotuon/pEngine | a80e268b8cfc99e212e5a0edd41991854adccd78 | [
"BSD-3-Clause"
] | null | null | null | src/model_data.cpp | Kotuon/pEngine | a80e268b8cfc99e212e5a0edd41991854adccd78 | [
"BSD-3-Clause"
] | null | null | null | src/model_data.cpp | Kotuon/pEngine | a80e268b8cfc99e212e5a0edd41991854adccd78 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file model_data.cpp
* @author Kelson Wysocki (kelson.wysocki@gmail.com)
* @brief
* @version 0.1
* @date 2021-06-06
*
* @copyright Copyright (c) 2021
*
*/
// std includes //
#include <cstdio>
#include <cstring>
// Library includes //
#include <glew.h>
#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <gtx/transform.hpp>
// Engine includes //
#include "engine.hpp"
#include "model.hpp"
#include "model_data.hpp"
#include "trace.hpp"
#include "shader.hpp"
/**
* @brief Default constructor
*
*/
Model_Data::Model_Data() {}
/**
* @brief Copy constructor
*
* @param other
*/
Model_Data::Model_Data(const Model_Data& other) {
for (float vert : other.vertices) {
vertices.emplace_back(vert);
}
for (float norm : other.normals) {
normals.emplace_back(norm);
}
for (float uv : other.uvs) {
uvs.emplace_back(uv);
}
vertexbuffer = other.vertexbuffer;
normalbuffer = other.normalbuffer;
uvbuffer = other.uvbuffer;
}
/**
* @brief Deletes all buffers of the model
*
*/
Model_Data::~Model_Data() {
glDeleteBuffers(1, &vertexbuffer);
glDeleteBuffers(1, &uvbuffer);
glDeleteBuffers(1, &normalbuffer);
}
/**
* @brief Loads data of a model from given file
*
* @param reader File_Reader object containing the model data
* @return true
* @return false
*/
bool Model_Data::Load(File_Reader& reader) {
std::string modelName_ = reader.Read_String("modelToLoad");
return Read(modelName_);
}
/**
* @brief Loads in model using given filename
*
* @param modelName_ Model's filename
* @return true
* @return false
*/
bool Model_Data::Load(std::string modelName_) { return Read(modelName_); }
/**
* @brief Reads model data from file
*
* @param modelName_ Model's filename
* @return true
* @return false
*/
bool Model_Data::Read(std::string modelName_) {
// Opening the file
std::string fileToOpen = std::string(getenv("USERPROFILE")) + "/Documents/pEngine/models/" + modelName_;
// Setting the name of the file (used in model_data_manager)
modelName = fileToOpen;
FILE* file = fopen(fileToOpen.c_str(), "r");
if (!file) {
file = fopen(modelName_.c_str(), "r");
if (!file) {
return false;
}
else {
modelName = modelName_;
}
}
// Creating variables for reading
std::vector<unsigned> vertex_indices, uv_indices, normal_indices;
std::vector<glm::vec3> temp_vertices;
std::vector<glm::vec2> temp_uvs;
std::vector<glm::vec3> temp_normals;
// Until the whole file is read
while (true) {
char line_header[256];
// Getting next line of the file
int res = fscanf(file, "%s", line_header);
if (res == EOF) break;
// Checking for which data needs to be read in
if (strcmp(line_header,"v") == 0) {
glm::vec3 vertex;
fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
temp_vertices.emplace_back(vertex);
continue;
}
if (strcmp(line_header, "vt") == 0) {
glm::vec2 uv;
fscanf(file, "%f %f\n", &uv.x, &uv.y);
temp_uvs.emplace_back(uv);
continue;
}
if (strcmp(line_header, "vn") == 0) {
glm::vec3 normal;
fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z);
temp_normals.emplace_back(normal);
continue;
}
if (strcmp(line_header, "f") == 0) {
// Connecting face to previous read vertices, uvs, and normals
unsigned vertex_index[3], uv_index[3], normal_index[3];
int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertex_index[0], &uv_index[0], &normal_index[0],
&vertex_index[1], &uv_index[1], &normal_index[1], &vertex_index[2], &uv_index[2], &normal_index[2]);//,
// Expects models split into triangles
if (matches != 9) {
Trace::Message("File is incompatible with this parser. Export using different settings.");
return false;
}
// Setting vertices for current face
vertices.emplace_back((temp_vertices[vertex_index[0] - 1]).x);
vertices.emplace_back((temp_vertices[vertex_index[0] - 1]).y);
vertices.emplace_back((temp_vertices[vertex_index[0] - 1]).z);
vertices.emplace_back((temp_vertices[vertex_index[1] - 1]).x);
vertices.emplace_back((temp_vertices[vertex_index[1] - 1]).y);
vertices.emplace_back((temp_vertices[vertex_index[1] - 1]).z);
vertices.emplace_back((temp_vertices[vertex_index[2] - 1]).x);
vertices.emplace_back((temp_vertices[vertex_index[2] - 1]).y);
vertices.emplace_back((temp_vertices[vertex_index[2] - 1]).z);
// Setting uvs for current face
uvs.emplace_back((temp_uvs[uv_index[0] - 1]).x);
uvs.emplace_back((temp_uvs[uv_index[0] - 1]).y);
uvs.emplace_back((temp_uvs[uv_index[1] - 1]).x);
uvs.emplace_back((temp_uvs[uv_index[1] - 1]).y);
uvs.emplace_back((temp_uvs[uv_index[2] - 1]).x);
uvs.emplace_back((temp_uvs[uv_index[2] - 1]).y);
// Setting normals for current face
normals.emplace_back((temp_normals[normal_index[0] - 1]).x);
normals.emplace_back((temp_normals[normal_index[0] - 1]).y);
normals.emplace_back((temp_normals[normal_index[0] - 1]).z);
normals.emplace_back((temp_normals[normal_index[1] - 1]).x);
normals.emplace_back((temp_normals[normal_index[1] - 1]).y);
normals.emplace_back((temp_normals[normal_index[1] - 1]).z);
normals.emplace_back((temp_normals[normal_index[2] - 1]).x);
normals.emplace_back((temp_normals[normal_index[2] - 1]).y);
normals.emplace_back((temp_normals[normal_index[2] - 1]).z);
}
}
// Bind vertex data to buffers
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), &vertices[0], GL_STATIC_DRAW);
// Bind uv data to buffers
glGenBuffers(1, &uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(float), &uvs[0], GL_STATIC_DRAW);
// Bind normals data to buffers
glGenBuffers(1, &normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(float), &normals[0], GL_STATIC_DRAW);
return true;
}
/**
* @brief Draws the models
*
* @param parent Model component
* @param transform Transform component
* @param projection Projection matrix of the scene
* @param view View matrix of the scene
*/
void Model_Data::Draw(Model* parent, Transform* transform, glm::mat4 projection, glm::mat4 view) {
// Creating the MVP (Model * View * Projection) matrix
glm::mat4 model = glm::mat4(1.f);
model = glm::translate(model, transform->GetPosition());
model = glm::rotate(model, (transform->GetRotation().x / 180.f) * glm::pi<float>(), glm::vec3(1, 0, 0));
model = glm::rotate(model, (transform->GetRotation().y / 180.f) * glm::pi<float>(), glm::vec3(0, 1, 0));
model = glm::rotate(model, (transform->GetRotation().z / 180.f) * glm::pi<float>(), glm::vec3(0, 0, 1));
model = glm::scale(model, transform->GetScale());
// Sending data to the shaders
glm::mat4 MVP = projection * view * model;
glUniformMatrix4fv(Shader::GetMatrixId(), 1, GL_FALSE, &MVP[0][0]);
glUniformMatrix4fv(Shader::GetModelMatrixId(), 1, GL_FALSE, &model[0][0]);
glUniformMatrix4fv(Shader::GetViewMatrixId(), 1, GL_FALSE, &view[0][0]);
// Sending light data to the shaders
glm::vec3 lightPos = Engine::GetLightPos();
glUniform3f(Shader::GetLightId(), lightPos.x, lightPos.y, lightPos.z);
glUniform1f(Shader::GetLightPowerId(), Engine::GetLightPower());
// Setup texture for drawing if it exists
if (parent->GetTexture())
parent->GetTexture()->Display();
// Setup the model vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0,
3,
GL_FLOAT,
GL_FALSE,
0,
(void*)0
);
// Setup the model uv
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glVertexAttribPointer(
1,
2,
GL_FLOAT,
GL_FALSE,
0,
(void*)0
);
// Setup the model normals
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glVertexAttribPointer(
2,
3,
GL_FLOAT,
GL_FALSE,
0,
(void*)0
);
// Draw the object
glDrawArrays(GL_TRIANGLES, 0, vertices.size());
// Disable data sent to shaders
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
}
/**
* @brief Returns the filename that the models data was gotten from
*
* @return string Name of the file that contains model data
*/
std::string Model_Data::GetModelName() const { return modelName; }
| 31.313333 | 120 | 0.614435 | [
"object",
"vector",
"model",
"transform"
] |
d7e35c9e9029e7c912587eb4965c2bf84827bdde | 6,516 | cpp | C++ | GUI.cpp | IndriesGeorge/MovieRentalApp | d89f6520d8c8644ab274116e8f908bc1a29b73ec | [
"MIT"
] | null | null | null | GUI.cpp | IndriesGeorge/MovieRentalApp | d89f6520d8c8644ab274116e8f908bc1a29b73ec | [
"MIT"
] | null | null | null | GUI.cpp | IndriesGeorge/MovieRentalApp | d89f6520d8c8644ab274116e8f908bc1a29b73ec | [
"MIT"
] | null | null | null | #include "GUI.h"
void GUI::initGUIComponents()
{
QHBoxLayout* mainLy = new QHBoxLayout{};
setLayout(mainLy);
QGridLayout* gridLy = new QGridLayout;
gridLy->addWidget(table);
mainLy->addLayout(gridLy);
QVBoxLayout* rightLy = new QVBoxLayout;
QFormLayout* formsLy = new QFormLayout;
formsLy->addRow("Movie ID: ", idTxt);
formsLy->addRow("Movie Title: ", titleTxt);
formsLy->addRow("Movie Genre: ", genreCombo);
genreCombo->addItems(genresList);
yearSpin->setRange(1895, 2030);
formsLy->addRow("Release Year: ", yearSpin);
formsLy->addRow("Main Actor: ", protagonistTxt);
rightLy->addLayout(formsLy);
QHBoxLayout* buttonsLy = new QHBoxLayout;
buttonsLy->addWidget(addButton);
buttonsLy->addWidget(deleteButton);
buttonsLy->addWidget(updateButton);
rightLy->addLayout(buttonsLy);
QHBoxLayout* buttonsLy2 = new QHBoxLayout;
buttonsLy2->addWidget(ReloadButton);
buttonsLy2->addWidget(UndoButton);
rightLy->addLayout(buttonsLy2);
QHBoxLayout* buttonsLy3 = new QHBoxLayout;
buttonsLy3->addWidget(openCartButton);
buttonsLy3->addWidget(filterByProtagonist);
buttonsLy3->addWidget(sortByTitle);
rightLy->addLayout(buttonsLy3);
mainLy->addLayout(rightLy);
checkBoxesLy->addWidget(filterByGenreButton);
checkBoxesWidget->setLayout(checkBoxesLy);
mainLy->addWidget(checkBoxesWidget);
}
void GUI::initConnect()
{
QObject::connect(addButton, &QPushButton::clicked, [&]() {
auto id = idTxt->text().toInt();
auto title = titleTxt->text().toStdString();
auto genre = genreCombo->currentText().toStdString();
auto year = yearSpin->value();
auto protagonist = protagonistTxt->text().toStdString();
try
{
serv.service_add_movie(id, title, genre, year, protagonist);
}
catch (RepoException ex)
{
string message = ex.get_exception_message();
QString warning_message = QString::fromStdString(message);
QMessageBox::warning(nullptr, "Warning!\n", warning_message);
}
catch (Exception ex)
{
string message = ex.get_validation_messages();
QString warning_message = QString::fromStdString(message);
QMessageBox::warning(nullptr, "Warning!\n", warning_message);
}
reloadTable(serv.service_get_all_movies());
});
QObject::connect(updateButton, &QPushButton::clicked, [&]() {
auto id = idTxt->text().toInt();
auto title = titleTxt->text().toStdString();
auto genre = genreCombo->currentText().toStdString();
auto year = yearSpin->value();
auto protagonist = protagonistTxt->text().toStdString();
try
{
serv.service_update_movie(id, title, genre, year, protagonist);
}
catch (RepoException ex)
{
string message = ex.get_exception_message();
QString warning_message = QString::fromStdString(message);
QMessageBox::warning(nullptr, "Warning!\n", warning_message);
}
catch (Exception ex)
{
string message = ex.get_validation_messages();
QString warning_message = QString::fromStdString(message);
QMessageBox::warning(nullptr, "Warning!\n", warning_message);
}
reloadTable(serv.service_get_all_movies());
});
QObject::connect(deleteButton, &QPushButton::clicked, [&]() {
auto id = idTxt->text().toInt();
try
{
serv.service_delete_movie(id);
}
catch (RepoException ex)
{
string message = ex.get_exception_message();
QString warning_message = QString::fromStdString(message);
QMessageBox::warning(nullptr, "Warning!\n", warning_message);
}
reloadTable(serv.service_get_all_movies());
});
QObject::connect(table->selectionModel(), &QItemSelectionModel::selectionChanged, [this]() {
if (table->selectionModel()->selectedIndexes().isEmpty())
{
idTxt->setText("");
titleTxt->setText("");
genreCombo->setCurrentText("Action");
yearSpin->setValue(1895);
protagonistTxt->setText("");
}
else
{
auto selectedRow = table->selectionModel()->selectedIndexes().at(0).row();
auto column0 = table->model()->index(selectedRow, 0);
auto id = table->model()->data(column0, Qt::UserRole).toInt();
auto movie = serv.service_find_movie(id);
idTxt->setText(QString::number(movie.get_id()));
titleTxt->setText(QString::fromStdString(movie.get_title()));
genreCombo->setCurrentText(QString::fromStdString(movie.get_genre()));
yearSpin->setValue(movie.get_year());
protagonistTxt->setText(QString::fromStdString(movie.get_protagonist()));
}
});
QObject::connect(UndoButton, &QPushButton::clicked, [&]() {
try
{
serv.undo();
}
catch (RepoException ex)
{
string message = ex.get_exception_message();
QString warning_message = QString::fromStdString(message);
QMessageBox::warning(nullptr, "Warning!\n", warning_message);
}
reloadTable(serv.service_get_all_movies());
});
QObject::connect(ReloadButton, &QPushButton::clicked, [&]() {
reloadTable(serv.service_get_all_movies());
});
QObject::connect(openCartButton, &QPushButton::clicked, [&]() {
CartGUI* cartGui = new CartGUI{ serv.get_cart() };
cartGui->show();
});
QObject::connect(filterByProtagonist, &QPushButton::clicked, [&]() {
auto protagonist = protagonistTxt->text().toStdString();
reloadTable(serv.filter_by_protagonist(protagonist));
});
QObject::connect(sortByTitle, &QPushButton::clicked, [&]() {
reloadTable(serv.sort_by_title());
});
}
void GUI::reloadTable(vector<Movie> movies)
{
model->setMovies(movies);
model->refresh();
}
void GUI::generateCheckBoxes(vector<Movie> movies)
{
auto all_genres = serv.get_all_genres();
for (const auto& g : all_genres)
{
QCheckBox* checkBox = new QCheckBox;
checkBox->setText(QString::fromStdString(g));
checkBoxesLy->addWidget(checkBox);
}
QPushButton::connect(filterByGenreButton, &QPushButton::clicked, [&]() {
// We take all children from checkBoxesWidget which were generated above
QList<QCheckBox*> widgets = checkBoxesWidget->findChildren<QCheckBox*>();
// We iterate these widgets(checkboxes in this case)
for (auto checkBox : widgets)
{
if (checkBox->isChecked())
{
for (int index = 0; index < table->model()->rowCount(); index++)
{
auto rowindexColumn0 = table->model()->index(index, 0); // We want to take the id of the movie
auto id = table->model()->data(rowindexColumn0, Qt::UserRole).toInt();
auto movie = serv.service_find_movie(id);
if (movie.get_genre() == checkBox->text().toStdString())
{
QModelIndex idx = model->index(index, 3);
model->setData(idx, QColor(Qt::red), Qt::TextColorRole);
model->refresh();
}
}
}
}
});
}
| 26.704918 | 99 | 0.701351 | [
"vector",
"model"
] |
d7e44e103f523379b2d3069aa0c783b8c011ea07 | 1,243 | cc | C++ | leetcode/leetcode_393.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | leetcode/leetcode_393.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | leetcode/leetcode_393.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | #include <iostream>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <cstdint>
using namespace std;
int validbyte(uint8_t d[4], int n) {
auto is_valid = [](const uint8_t t) ->bool {
return (t & 0xc0 ) ^ 0x80 == 0;
};
uint8_t data = d[0];
if (!((data & 0xf8) ^ 0xf0)) {
if ((n >= 4) && is_valid(d[1]) && is_valid(d[2]) && is_valid(d[3])){
return 4;
}
}
if (!((data & 0xf0) ^ 0xe0)) {
if ((n>=3) && is_valid(d[1]) && is_valid(d[2])){
return 3;
}
}
if (!((data & 0xe0) ^ 0xc0)) {
if ((n>=2) && is_valid(d[1])){
return 2;
}
}
if (!((data & 0x80) ^ 0x00)) {
return 1;
}
return 0;
}
bool validUtf8(vector<int>& data) {
uint8_t w[4];
for (int idx = 0; idx < data.size(); ) {
uint8_t d = data[idx];
w[0] = 0; w[1] = 0; w[2] = 0; w[3] = 0;
for (int i = 0; i < 4 && idx + i < data.size(); ++i) {
w[i] = data[idx+i];
}
int n = validbyte(w, data.size() - idx);
if (n > 0) {
idx += n;
} else {
return false;
}
}
return true;
}
void test() {
vector<int> data = {197, 130, 1};
cout << validUtf8(data) << endl;
}
int main (int argc, char **argv) {
test();
return 0;
}
| 18.552239 | 70 | 0.531778 | [
"vector"
] |
d7fb460f2592d591d0963b1856d51922609eb94e | 818 | hpp | C++ | SickzilSFMLUI/includes/main_window.hpp | 0x00000FF/SickzilSFMLUI | a4c227ff8173f15742593b8d91fb1c9c575ab826 | [
"MIT"
] | 3 | 2019-08-16T05:48:40.000Z | 2019-08-19T13:22:48.000Z | SickzilSFMLUI/includes/main_window.hpp | 0x00000FF/SickzilSFMLUI | a4c227ff8173f15742593b8d91fb1c9c575ab826 | [
"MIT"
] | 4 | 2019-08-17T07:15:05.000Z | 2019-08-17T21:15:57.000Z | SickzilSFMLUI/includes/main_window.hpp | 0x00000FF/SickzilSFMLUI | a4c227ff8173f15742593b8d91fb1c9c575ab826 | [
"MIT"
] | null | null | null | #ifndef __MAIN_WINDOW_HPP__
#define __MAIN_WINDOW_HPP__
#include <SFML/Graphics.hpp>
#include <memory>
#include <draw_object.hpp>
using namespace sf;
struct ui_options
{
int width = 400;
int height = 500;
std::string title = "SickzilMachine";
};
using up_options = std::unique_ptr<ui_options>;
using up_object = std::unique_ptr<draw_object>;
class main_window : public sf::RenderWindow
{
public:
main_window(const ui_options& _options)
: RenderWindow(VideoMode(_options.width, _options.height), _options.title)
{
begin_window_loop();
}
int get_exit_code() const;
void begin_window_loop();
void dispatch_event_to_children(const Event& event);
private:
int exit_code = 0;
up_options m_options;
std::vector<up_object> m_objects;
};
#endif | 19.023256 | 75 | 0.705379 | [
"vector"
] |
cc091cbe9ad457369569736629ee8bec002e4f4f | 414 | hpp | C++ | algorithms/contiguous-data/rectangle-in-histogram/aim.hpp | dubzzz/various-algorithms | 16af4c05acfcb23d199df0851402b0da3ebba91c | [
"MIT"
] | 1 | 2017-04-17T18:32:46.000Z | 2017-04-17T18:32:46.000Z | algorithms/contiguous-data/rectangle-in-histogram/aim.hpp | dubzzz/various-algorithms | 16af4c05acfcb23d199df0851402b0da3ebba91c | [
"MIT"
] | 10 | 2016-12-25T04:42:56.000Z | 2017-03-30T20:42:25.000Z | algorithms/contiguous-data/rectangle-in-histogram/aim.hpp | dubzzz/various-algorithms | 16af4c05acfcb23d199df0851402b0da3ebba91c | [
"MIT"
] | 1 | 2022-03-25T17:39:05.000Z | 2022-03-25T17:39:05.000Z | /*
The aim of this topic is:
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Taken from: http://www.programcreek.com/2014/05/leetcode-largest-rectangle-in-histogram-java/
*/
#include <cstddef>
#include <vector>
// Algorithm to be tested
std::size_t largest(std::vector<unsigned> const& in);
| 29.571429 | 160 | 0.743961 | [
"vector"
] |
cc0bf6c35b0af5e600993ed643da1839fad4f87d | 6,442 | cpp | C++ | OOModel/src/CodeGenerationVisitor.cpp | dimitar-asenov/Envision | 1ab5c846fca502b7fe73ae4aff59e8746248446c | [
"BSD-3-Clause"
] | 75 | 2015-01-18T13:29:43.000Z | 2022-01-14T08:02:01.000Z | OOModel/src/CodeGenerationVisitor.cpp | dimitar-asenov/Envision | 1ab5c846fca502b7fe73ae4aff59e8746248446c | [
"BSD-3-Clause"
] | 364 | 2015-01-06T10:20:21.000Z | 2018-12-17T20:12:28.000Z | OOModel/src/CodeGenerationVisitor.cpp | dimitar-asenov/Envision | 1ab5c846fca502b7fe73ae4aff59e8746248446c | [
"BSD-3-Clause"
] | 14 | 2015-01-09T00:44:24.000Z | 2022-02-22T15:01:44.000Z | /***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "CodeGenerationVisitor.h"
#include "declarations/MetaDefinition.h"
#include "expressions/BooleanLiteral.h"
#include "expressions/StringLiteral.h"
#include "expressions/ReferenceExpression.h"
#include "expressions/MetaCallExpression.h"
#include "ModelBase/src/nodes/NameText.h"
#include "OOModel/src/elements/FormalResult.h"
namespace OOModel {
CodeGenerationVisitor::CodeGenerationVisitor(QMap<QString, Model::Node *> args) : args_{args} {}
void CodeGenerationVisitor::init()
{
addType<ReferenceExpression>(visitReferenceExpression);
addType<Model::NameText>(visitNameText);
addType<MetaCallExpression>(visitMetaCallExpression);
}
void CodeGenerationVisitor::visitReferenceExpression(CodeGenerationVisitor* v, OOModel::ReferenceExpression* n)
{
auto input = n->name();
if (!input.contains("##"))
{
if (input.startsWith("#"))
{
if (auto argument = v->args_[input.right(input.length() - 1)])
if (auto argumentReference = DCast<ReferenceExpression>(argument))
n->parent()->replaceChild(n, new OOModel::StringLiteral{argumentReference->name()});
}
else
if (auto argument = v->args_[input])
{
if (auto argumentReference = DCast<ReferenceExpression>(argument))
{
// case: there exists a replacement and it is another ReferenceExpression
// -> copy name (replacing it would cause child nodes of n to disappear)
n->setName(argumentReference->name());
}
else
{
// case: there exists a replacement and it is not a ReferenceExpression
// -> replace node
Model::Node* cloned = nullptr;
if (DCast<OOModel::Expression>(n) && DCast<OOModel::FormalResult>(argument))
{
// n is an expression but the argument is a formal result so we have to use
// the expression inside the formal result
cloned = DCast<OOModel::FormalResult>(argument)->typeExpression()->clone();
}
else // default case: use whole argument
cloned = argument->clone();
n->parent()->replaceChild(n, cloned);
// visit the cloned tree and return to avoid visiting the children of n
v->visitChildren(cloned);
return;
}
}
}
else
{
// case: n's name is a concatenated identifier (a##b)
// -> build identifier
QStringList parts = input.split("##");
bool modified = false;
for (auto i = 0; i < parts.size(); i++)
if (auto argument = DCast<ReferenceExpression>(v->args_[parts[i]]))
{
parts[i] = argument->name();
modified = true;
}
if (modified) n->setName(parts.join(""));
}
v->visitChildren(n);
}
void CodeGenerationVisitor::visitNameText(CodeGenerationVisitor* v, Model::NameText* n)
{
auto input = n->get();
if (!input.contains("##"))
{
if (auto argument = DCast<ReferenceExpression>(v->args_[input]))
{
// case: n's name is an existing argument of type ReferenceExpression
// -> copy name as new text
n->set(argument->name());
}
}
else
{
// case: n's text is a concatenated text (a##b)
// -> build text
QStringList parts = input.split("##");
bool modified = false;
for (auto i = 0; i < parts.size(); i++)
if (auto argument = DCast<ReferenceExpression>(v->args_[parts[i]]))
{
parts[i] = argument->name();
modified = true;
}
if (modified) n->set(parts.join(""));
}
v->visitChildren(n);
}
void CodeGenerationVisitor::visitMetaCallExpression(CodeGenerationVisitor* v, MetaCallExpression* n)
{
/*
* process arguments before generating.
* this ensures proper argument propagation.
*/
v->visitChildren(n);
if (!n->metaDefinition())
{
// case: unresolved meta definition
// -> check if it is a predefined meta function
if (auto metaDef = DCast<ReferenceExpression>(n->callee()))
v->handlePredefinedFunction(metaDef->name(), n);
}
else
{
// case: resolved meta definition
// -> generate recursively
n->generatedTree();
}
}
void CodeGenerationVisitor::handlePredefinedFunction(QString function, MetaCallExpression* n)
{
/*
* only handle predefined functions if they are nested in another meta call.
* this helps preventing unintentional modification of parents which are not generated nodes.
*/
if (!n->firstAncestorOfType<MetaCallExpression>()) return;
if (function == "SET_OVERRIDE_FLAG")
{
if (n->arguments()->size() != 1)
{
qDebug() << function << "#arguments != 1";
return;
}
if (auto argument = DCast<ReferenceExpression>(n->arguments()->first()))
if (auto flag = DCast<BooleanLiteral>(args_[argument->name()]))
if (auto p = n->firstAncestorOfType<Declaration>())
p->modifiers()->set(Modifier::Override, flag->value());
}
}
}
| 32.535354 | 120 | 0.672928 | [
"model"
] |
cc13c1a327fa42345d0e034d5581384d9a5536bb | 2,329 | cpp | C++ | Codeforces Round 375/st-Spanning Tree/main.cpp | sqc1999-oi/Codeforces | 5551e0e4b9dc66bb77c697568f0584aac3dbefae | [
"MIT"
] | 1 | 2016-07-18T12:05:56.000Z | 2016-07-18T12:05:56.000Z | Codeforces Round 375/st-Spanning Tree/main.cpp | sqc1999/Codeforces | 5551e0e4b9dc66bb77c697568f0584aac3dbefae | [
"MIT"
] | null | null | null | Codeforces Round 375/st-Spanning Tree/main.cpp | sqc1999/Codeforces | 5551e0e4b9dc66bb77c697568f0584aac3dbefae | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 2e5, M = 4e5;
pair<int, int> e[M], es[N], et[N];
int f[N];
bool cs[N], ct[N];
int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); }
int main()
{
ios::sync_with_stdio(false);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++)
{
cin >> e[i].first >> e[i].second;
e[i].first--;
e[i].second--;
}
int s, t, ds, dt;
cin >> s >> t >> ds >> dt;
s--;
t--;
for (int i = 0; i < n; i++) f[i] = i;
vector<pair<int, int>> ans;
bool flag = false;
for (int i = 0; i < m; i++)
{
int u = e[i].first, v = e[i].second;
if (u == s&&v == t || u == t&&v == s) flag = true;
if (u != s&&u != t&&v != s&&v != t)
{
int x = find(u), y = find(v);
if (x != y)
{
f[x] = y;
ans.push_back({ u,v });
}
}
}
for (int i = 0; i < m; i++)
{
int u = e[i].first, v = e[i].second;
if (v == s) swap(u, v);
if (u == s&&v != t)
{
int x = find(v);
cs[x] = true;
es[x] = { u,v };
}
if (v == t) swap(u, v);
if (u == t&&v != s)
{
int x = find(v);
ct[x] = true;
et[x] = { u,v };
}
}
int cnt = 0;
for (int i = 0; i < n; i++)
{
if (cs[i] && ct[i]) cnt++;
else if (cs[i])
{
if (--ds == 0) break;
ans.push_back(es[i]);
}
else if (ct[i])
{
if (--dt == 0) break;
ans.push_back(et[i]);
}
}
if (ds <= 0 || dt <= 0) cout << "No" << endl;
else if (ds + dt - 2 >= cnt&&flag)
{
ans.push_back({ s,t });
for (int i = 0; i < n; i++)
if (cs[i] && ct[i])
{
if (ds > 0)
{
ds--;
ans.push_back(es[i]);
}
else ans.push_back(et[i]);
}
cout << "Yes" << endl;
for (const auto &p : ans)
cout << p.first + 1 << ' ' << p.second + 1 << endl;
}
else if (ds + dt >= cnt + 1)
{
bool flag = true;
for (int i = 0; i < n; i++)
if (cs[i] && ct[i])
{
if (flag)
{
ds--;
flag = false;
ans.push_back(es[i]);
ans.push_back(et[i]);
}
else if (ds > 0)
{
ds--;
ans.push_back(es[i]);
}
else ans.push_back(et[i]);
}
cout << "Yes" << endl;
for (const auto &p : ans)
cout << p.first + 1 << ' ' << p.second + 1 << endl;
}
else cout << "No" << endl;
}
| 19.571429 | 62 | 0.406612 | [
"vector"
] |
cc406974e61e6eadffd0842a07631dd1ead8fa23 | 1,537 | cc | C++ | dataworks-public/src/model/GetMetaTableIntroWikiRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | dataworks-public/src/model/GetMetaTableIntroWikiRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | dataworks-public/src/model/GetMetaTableIntroWikiRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/dataworks-public/model/GetMetaTableIntroWikiRequest.h>
using AlibabaCloud::Dataworks_public::Model::GetMetaTableIntroWikiRequest;
GetMetaTableIntroWikiRequest::GetMetaTableIntroWikiRequest() :
RpcServiceRequest("dataworks-public", "2020-05-18", "GetMetaTableIntroWiki")
{
setMethod(HttpRequest::Method::Post);
}
GetMetaTableIntroWikiRequest::~GetMetaTableIntroWikiRequest()
{}
long GetMetaTableIntroWikiRequest::getWikiVersion()const
{
return wikiVersion_;
}
void GetMetaTableIntroWikiRequest::setWikiVersion(long wikiVersion)
{
wikiVersion_ = wikiVersion;
setParameter("WikiVersion", std::to_string(wikiVersion));
}
std::string GetMetaTableIntroWikiRequest::getTableGuid()const
{
return tableGuid_;
}
void GetMetaTableIntroWikiRequest::setTableGuid(const std::string& tableGuid)
{
tableGuid_ = tableGuid;
setParameter("TableGuid", tableGuid);
}
| 29.557692 | 78 | 0.770332 | [
"model"
] |
cc439fab4cf4194050e20d68991f836ce04c6fdf | 3,014 | cc | C++ | plugins/behavior/testing/mutable_behavior_bench.cc | kstepanmpmg/mldb | f78791cd34d01796705c0f173a14359ec1b2e021 | [
"Apache-2.0"
] | 665 | 2015-12-09T17:00:14.000Z | 2022-03-25T07:46:46.000Z | plugins/behavior/testing/mutable_behavior_bench.cc | tomzhang/mldb | a09cf2d9ca454d1966b9e49ae69f2fe6bf571494 | [
"Apache-2.0"
] | 797 | 2015-12-09T19:48:19.000Z | 2022-03-07T02:19:47.000Z | plugins/behavior/testing/mutable_behavior_bench.cc | matebestek/mldb | f78791cd34d01796705c0f173a14359ec1b2e021 | [
"Apache-2.0"
] | 103 | 2015-12-25T04:39:29.000Z | 2022-02-03T02:55:22.000Z | // This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "mldb/utils/testing/benchmarks.h"
#include "mldb/utils/testing/print_utils.h"
#include "mldb/plugins/behavior/mutable_behavior_domain.h"
using namespace std;
using namespace MLDB;
vector<Id>
genIds(int numIds)
{
vector<Id> ids;
ids.reserve(numIds);
for (int i = 0; i < numIds; i++) {
ids.push_back(Id(randomString(20)));
}
return ids;
}
int main(int argc, char * argv[])
{
int nThreads(1);
int numSubjects(1);
int numBehs(1);
{
using namespace boost::program_options;
options_description all_opt;
all_opt.add_options()
("num-threads,t", value(&nThreads),
"default: 1")
("num-subjects,s", value(&numSubjects),
"default: 1")
("num-behaviors,b", value(&numBehs),
"default: 1")
("help,H", "show help");
if (argc == 1) {
return 0;
}
variables_map vm;
store(command_line_parser(argc, argv)
.options(all_opt)
.run(),
vm);
notify(vm);
if (vm.count("help")) {
cerr << all_opt << endl;
return 1;
}
}
cerr << "subjects: " << numSubjects
<< "; behaviors: " << numBehs
<< "; threads: " << nThreads
<< endl;
vector<Id> subjects = genIds(numSubjects);
vector<Id> behaviors = genIds(numBehs);
MutableBehaviorDomain behDom;
int sliceSize = numSubjects / nThreads;
if (sliceSize * nThreads < numSubjects) {
sliceSize++;
}
vector<MutableBehaviorDomain::ManyEntryId> behEntries(numBehs);
Date behDate = Date::now();
for (int i = 0; i < numBehs; i++) {
auto & entry = behEntries[i];
entry.behavior = behaviors[i];
entry.timestamp = behDate;
behDate.addSeconds(-123.321);
}
Benchmarks bms;
auto populate = [&] (int threadNum) {
Benchmark bm(bms, "record-" + to_string(threadNum));
int start = threadNum * sliceSize;
int end = min(start + sliceSize, numSubjects);
for (int i = start; i < end; i++) {
const Id & subject = subjects[i];
behDom.recordMany(subject, &behEntries[0], numBehs);
}
};
{
Benchmark bm(bms, "record");
vector<thread> threads;
for (int i = 1; i < nThreads; i++) {
threads.emplace_back(populate, i);
}
std::atomic_thread_fence(std::memory_order_release);
populate(0);
for (auto & th: threads) {
th.join();
}
}
bms.dumpTotals();
return 0;
}
| 24.112 | 78 | 0.56503 | [
"vector"
] |
cc44284e0940563cedf9f4e0cd7907aaf9cffdbe | 2,317 | cpp | C++ | tools/benchmark/saga/saga_random_order_gtest_dense.cpp | timleathart/tick | 97e8fdc759358f377d414e09d2260454136911a2 | [
"BSD-3-Clause"
] | null | null | null | tools/benchmark/saga/saga_random_order_gtest_dense.cpp | timleathart/tick | 97e8fdc759358f377d414e09d2260454136911a2 | [
"BSD-3-Clause"
] | null | null | null | tools/benchmark/saga/saga_random_order_gtest_dense.cpp | timleathart/tick | 97e8fdc759358f377d414e09d2260454136911a2 | [
"BSD-3-Clause"
] | null | null | null | #include <chrono>
#include "tick/array/serializer.h"
#include "tick/random/test_rand.h"
#include "tick/optim/solver/saga.h"
#include "tick/optim/model/logreg.h"
#include "tick/optim/model/linreg.h"
#include "tick/optim/prox/prox_zero.h"
#ifdef _MKN_WITH_MKN_KUL_
#include "kul/os.hpp"
#endif
const constexpr size_t SEED = 1933;
const constexpr size_t N_ITER = 30;
const constexpr size_t N_FEATURES = 200;
int main(int argc, char *argv[]) {
ulong n_samples = 750000;
if (argc == 2) {
std::istringstream ss(argv[1]);
if (!(ss >> n_samples))
std::cerr << "Invalid number for n_samples: " << argv[1] << '\n';
}
{
n_samples = 750000;
const auto sample = test_uniform(n_samples * N_FEATURES, SEED);
ArrayDouble2d sample2d(n_samples, N_FEATURES, sample->data());
const auto features = SArrayDouble2d::new_ptr(sample2d);
const auto int_sample = test_uniform_int(0, 2, n_samples, SEED);
SArrayDoublePtr labels = SArrayDouble::new_ptr(n_samples);
for (int i = 0; i < n_samples; ++i) (*labels)[i] = (*int_sample)[i] - 1;
using milli = std::chrono::microseconds;
{
auto model = std::make_shared<ModelLogReg>(features, labels, false);
SAGA saga(n_samples, 0, RandType::unif, 1e-3);
saga.set_rand_max(n_samples);
saga.set_model(model);
saga.set_prox(std::make_shared<ProxZero>(0, 0, 1));
auto start = std::chrono::high_resolution_clock::now();
for (int j = 0; j < N_ITER; ++j) saga.solve();
auto finish = std::chrono::high_resolution_clock::now();
std::cout << argv[0] << " "
<< std::chrono::duration_cast<milli>(finish - start).count() / 1e6
<< std::endl;
}
{
auto model = std::make_shared<ModelLinReg>(features, labels, false);
SAGA saga(n_samples, 0, RandType::unif, 1e-3);
saga.set_rand_max(n_samples);
saga.set_model(model);
saga.set_prox(std::make_shared<ProxZero>(0, 0, 1));
auto start = std::chrono::high_resolution_clock::now();
for (int j = 0; j < N_ITER; ++j) saga.solve();
auto finish = std::chrono::high_resolution_clock::now();
std::cout << argv[0] << " "
<< std::chrono::duration_cast<milli>(finish - start).count() / 1e6
<< std::endl;
}
}
return 0;
} | 35.646154 | 83 | 0.627104 | [
"model"
] |
cc4b046ed862439618da5607b0b294c25788fc9d | 1,227 | cpp | C++ | src/daily/NC15.cpp | hewei-nju/LeetCode | 39aafffa9cc260056435ef4611e305f402b32223 | [
"MIT"
] | null | null | null | src/daily/NC15.cpp | hewei-nju/LeetCode | 39aafffa9cc260056435ef4611e305f402b32223 | [
"MIT"
] | null | null | null | src/daily/NC15.cpp | hewei-nju/LeetCode | 39aafffa9cc260056435ef4611e305f402b32223 | [
"MIT"
] | null | null | null |
/*给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
该二叉树层序遍历的结果是
[
[3],
[9,20],
[15,7]
]
*/
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int>> res;
vector<int> tmp;
queue<TreeNode*> oldQ;
queue<TreeNode*> newQ;
if (root != nullptr)
oldQ.push(root);
while (!oldQ.empty() || !newQ.empty()) {
if (!oldQ.empty()) {
auto node = oldQ.front();
cout << node->val << " ";
oldQ.pop();
tmp.push_back(node->val);
if (node->left != nullptr)
newQ.push(node->left);
if (node->right != nullptr)
newQ.push(node->right);
} else {
res.push_back(tmp);
tmp.clear();
oldQ.swap(newQ);
}
}
if (!tmp.empty())
res.push_back(tmp);
return res;
}
}; | 21.910714 | 53 | 0.449063 | [
"vector"
] |
cc4efb4cff32d82e17dba5bd80e3aa6a02bbb996 | 9,443 | cpp | C++ | Viewer/ecflowUI/src/ViewerUtil.cpp | ecmwf/ecflow | 2498d0401d3d1133613d600d5c0e0a8a30b7b8eb | [
"Apache-2.0"
] | 11 | 2020-08-07T14:42:45.000Z | 2021-10-21T01:59:59.000Z | Viewer/ecflowUI/src/ViewerUtil.cpp | CoollRock/ecflow | db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d | [
"Apache-2.0"
] | 10 | 2020-08-07T14:36:27.000Z | 2022-02-22T06:51:24.000Z | Viewer/ecflowUI/src/ViewerUtil.cpp | CoollRock/ecflow | db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d | [
"Apache-2.0"
] | 6 | 2020-08-07T14:34:38.000Z | 2022-01-10T12:06:27.000Z | //============================================================================
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================
#include "ViewerUtil.hpp"
#include <QtGlobal>
#include <QAbstractButton>
#include <QAbstractItemModel>
#include <QAction>
#include <QButtonGroup>
#include <QClipboard>
#include <QComboBox>
#include <QDebug>
#include <QFontDatabase>
#include <QFontMetrics>
#include <QLabel>
#include <QLinearGradient>
#include <QStackedWidget>
#include <QTabBar>
#include <QTabWidget>
#include <QTreeView>
#include <QRegularExpression>
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <QGuiApplication>
#else
#include <QApplication>
#endif
void ViewerUtil::initComboBox(QSettings& settings,QString key,QComboBox* cb)
{
Q_ASSERT(cb);
QString txt=settings.value(key).toString();
for(int i=0; i < cb->count(); i++)
{
if(cb->itemText(i) == txt)
{
cb->setCurrentIndex(i);
return;
}
}
if(cb->currentIndex() == -1)
cb->setCurrentIndex(0);
}
void ViewerUtil::initComboBoxByData(QString dataValue,QComboBox* cb)
{
Q_ASSERT(cb);
for(int i=0; i < cb->count(); i++)
{
if(cb->itemData(i).toString() == dataValue)
{
cb->setCurrentIndex(i);
return;
}
}
if(cb->currentIndex() == -1)
cb->setCurrentIndex(0);
}
bool ViewerUtil::initTreeColumnWidth(QSettings& settings,QString key,QTreeView *tree)
{
Q_ASSERT(tree);
QStringList dataColumns=settings.value(key).toStringList();
for(int i=0; i < tree->model()->columnCount()-1 && i < dataColumns.size(); i++)
{
tree->setColumnWidth(i,dataColumns[i].toInt());
}
return (dataColumns.size() >= tree->model()->columnCount()-1);
}
void ViewerUtil::saveTreeColumnWidth(QSettings& settings,QString key,QTreeView *tree)
{
QStringList dataColumns;
for(int i=0; i < tree->model()->columnCount()-1; i++)
{
dataColumns << QString::number(tree->columnWidth(i));
}
settings.setValue(key,dataColumns);
}
void ViewerUtil::initStacked(QSettings& settings,QString key,QStackedWidget *stacked)
{
Q_ASSERT(stacked);
int v=settings.value(key).toInt();
if(v >= 0 && v < stacked->count())
stacked->setCurrentIndex(v);
}
void ViewerUtil::initButtonGroup(QSettings& settings,QString key,QButtonGroup *bg)
{
Q_ASSERT(bg);
int v=settings.value(key).toInt();
if(v >= 0 && v < bg->buttons().count())
{
bg->buttons().at(v)->setChecked(true);
bg->buttons().at(v)->click();
}
}
void ViewerUtil::initCheckableAction(QSettings& settings,QString key,QAction *ac)
{
Q_ASSERT(ac);
if(settings.contains(key))
{
ac->setChecked(settings.value(key).toBool());
}
}
QBrush ViewerUtil::lineEditGreenBg()
{
//return lineEditBg(QColor(189,239,205));
return lineEditBg(QColor(210,255,224));
}
QBrush ViewerUtil::lineEditRedBg()
{
return lineEditBg(QColor(234,215,214));
}
QBrush ViewerUtil::lineEditBg(QColor col)
{
QLinearGradient grad;
grad.setCoordinateMode(QGradient::ObjectBoundingMode);
grad.setStart(0,0);
grad.setFinalStop(0,1);
grad.setColorAt(0,col);
grad.setColorAt(0.1,col.lighter(105));
grad.setColorAt(0.1,col.lighter(108));
grad.setColorAt(0.9,col.lighter(108));
grad.setColorAt(0.9,col.lighter(105));
grad.setColorAt(1,col);
return QBrush(grad);
}
void ViewerUtil::toClipboard(QString txt)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
QClipboard* cb=QGuiApplication::clipboard();
cb->setText(txt, QClipboard::Clipboard);
cb->setText(txt, QClipboard::Selection);
#else
QClipboard* cb=QApplication::clipboard();
cb->setText(txt, QClipboard::Clipboard);
cb->setText(txt, QClipboard::Selection);
#endif
}
QString ViewerUtil::fromClipboard()
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
return QGuiApplication::clipboard()->text();
#else
return QApplication::clipboard()->text();
#endif
}
void ViewerUtil::setOverrideCursor(QCursor cursor)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
QGuiApplication::setOverrideCursor(cursor);
#else
QApplication::setOverrideCursor(cursor);
#endif
}
void ViewerUtil::restoreOverrideCursor()
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
QGuiApplication::restoreOverrideCursor();
#else
QApplication::restoreOverrideCursor();
#endif
}
QString ViewerUtil::formatDuration(unsigned int delta) //in seconds
{
int day=delta/86400;
int hour=(delta%86400)/3600;
int min=(delta % 3600)/60;
int sec=delta % 60;
QString s;
if(day > 0)
{
s+=QString::number(day) + "d ";
}
if(hour > 0)
{
s+=QString::number(hour) + "h ";
}
if(min > 0)
{
s+=QString::number(min) + "m ";
}
if(sec > 0 || s.isEmpty())
{
s+=QString::number(sec) + "s";
}
return s;
}
int ViewerUtil::textWidth(const QFontMetrics& fm, QString txt, int len)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
return fm.horizontalAdvance(txt, len);
#else
return fm.width(txt, len);
#endif
}
int ViewerUtil::textWidth(const QFontMetrics& fm, QChar ch)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
return fm.horizontalAdvance(ch);
#else
return fm.width(ch);
#endif
}
// Taken from the qt-everywhere-opensource-4.8.3 source code:
// src/corelib/tools/qregexp.cpp:wc2rx()
// See JIRA issue ECFLOW-1753.
QString ViewerUtil::wildcardToRegex(const QString &wc_str)
{
const bool enableEscaping = true;
const int wclen = wc_str.length();
QString rx;
int i = 0;
bool isEscaping = false; // the previous character is '\'
const QChar *wc = wc_str.unicode();
while (i < wclen) {
const QChar c = wc[i++];
switch (c.unicode()) {
case '\\':
if (enableEscaping) {
if (isEscaping) {
rx += QLatin1String("\\\\");
} // we insert the \\ later if necessary
if (i == wclen) { // the end
rx += QLatin1String("\\\\");
}
} else {
rx += QLatin1String("\\\\");
}
isEscaping = true;
break;
case '*':
if (isEscaping) {
rx += QLatin1String("\\*");
isEscaping = false;
} else {
rx += QLatin1String(".*");
}
break;
case '?':
if (isEscaping) {
rx += QLatin1String("\\?");
isEscaping = false;
} else {
rx += QLatin1Char('.');
}
break;
case '$':
case '(':
case ')':
case '+':
case '.':
case '^':
case '{':
case '|':
case '}':
if (isEscaping) {
isEscaping = false;
rx += QLatin1String("\\\\");
}
rx += QLatin1Char('\\');
rx += c;
break;
case '[':
if (isEscaping) {
isEscaping = false;
rx += QLatin1String("\\[");
} else {
rx += c;
if (wc[i] == QLatin1Char('^'))
rx += wc[i++];
if (i < wclen) {
if (rx[i] == QLatin1Char(']'))
rx += wc[i++];
while (i < wclen && wc[i] != QLatin1Char(']')) {
if (wc[i] == QLatin1Char('\\'))
rx += QLatin1Char('\\');
rx += wc[i++];
}
}
}
break;
case ']':
if(isEscaping){
isEscaping = false;
rx += QLatin1String("\\");
}
rx += c;
break;
default:
if(isEscaping){
isEscaping = false;
rx += QLatin1String("\\\\");
}
rx += c;
}
}
return rx;
}
QFont ViewerUtil::findMonospaceFont()
{
QStringList lst{"Monospace","Courier New", "Menlo", "Courier", "Monaco"};
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
auto fLst = QFontDatabase::families();
#else
QFontDatabase db = QFontDatabase();
auto fLst = db.families();
#endif
for(auto s: lst) {
for(auto fMem: fLst) {
if (fMem == s || fMem.startsWith(s + "[")) {
QFont f(fMem);
f.setFixedPitch(true);
f.setPointSize(10);
return f;
}
}
}
QFont fr;
fr.setPointSize(10);
return fr;
}
QIcon ViewerUtil::makeExpandIcon(bool targetOnRight)
{
QIcon ic;
ic.addPixmap(QPixmap(":/viewer/expand_left.svg"), QIcon::Normal, (targetOnRight?QIcon::On:QIcon::Off));
ic.addPixmap(QPixmap(":/viewer/expand_right.svg"), QIcon::Normal, (targetOnRight?QIcon::Off:QIcon::On));
return ic;
}
| 24.915567 | 108 | 0.550037 | [
"model"
] |
cc50e9843ffd0bb6343de684c7ec8d376395bb19 | 11,399 | cpp | C++ | src/qttypes/qtprotobufqttypes.cpp | pontaoski/qtprotobuf | 7225e6e324aa38c1bbeac1c0829cef73650e9d6f | [
"MIT"
] | 139 | 2019-06-28T10:35:07.000Z | 2022-03-23T05:54:26.000Z | src/qttypes/qtprotobufqttypes.cpp | pontaoski/qtprotobuf | 7225e6e324aa38c1bbeac1c0829cef73650e9d6f | [
"MIT"
] | 165 | 2019-10-22T14:51:10.000Z | 2022-02-24T22:46:56.000Z | src/qttypes/qtprotobufqttypes.cpp | pontaoski/qtprotobuf | 7225e6e324aa38c1bbeac1c0829cef73650e9d6f | [
"MIT"
] | 29 | 2019-08-06T11:15:41.000Z | 2022-01-04T02:51:43.000Z | /*
* MIT License
*
* Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
*
* This file is part of qtprotobuf project https://git.semlanik.org/semlanik/qtprotobuf
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <QUrl>
#include <QChar>
#include <QUuid>
#include <QColor>
#include <QTime>
#include <QDate>
#include <QTimeZone>
#include <QDateTime>
#include <QDataStream>
#include <QSize>
#include <QSizeF>
#include <QPoint>
#include <QPointF>
#include <QRect>
#include <QRectF>
#include <QPolygon>
#include <QPolygonF>
#include <QMatrix4x4>
#include <QVector2D>
#include <QVector3D>
#include <QVector4D>
#include <QTransform>
#include <QQuaternion>
#include <QImage>
#include <QBuffer>
#include <qtprotobuftypes.h>
#include <qtprotobufqttypes.h>
#include "qabstractprotobufserializer.h"
#include "qabstractprotobufserializer_p.h"
#include "QtProtobuf/QtCore.qpb.h"
#include "QtProtobuf/QtGui.qpb.h"
namespace QtProtobuf {
::QUrl convert(const ::QtProtobuf::QUrl &from) {
return ::QUrl(from.url());
}
::QtProtobuf::QUrl convert(const ::QUrl &from) {
return ::QtProtobuf::QUrl(from.url());
}
::QChar convert(const ::QtProtobuf::QChar &from) {
QDataStream stream(from.character());
::QChar ret;
stream >> ret;
return ret;
}
::QtProtobuf::QChar convert(const ::QChar &from) {
QByteArray out;
QDataStream stream(&out, QIODevice::WriteOnly);
stream << from;
return ::QtProtobuf::QChar(out);
}
::QUuid convert(const ::QtProtobuf::QUuid &from) {
return ::QUuid(from.uuid());
}
::QtProtobuf::QUuid convert(const ::QUuid &from) {
return ::QtProtobuf::QUuid(from.toString());
}
::QColor convert(const ::QtProtobuf::QColor &from) {
return ::QColor::fromRgba(from.rgba());
}
::QtProtobuf::QColor convert(const ::QColor &from) {
return ::QtProtobuf::QColor(from.rgba());
}
::QTime convert(const ::QtProtobuf::QTime &from) {
return ::QTime::fromMSecsSinceStartOfDay(from.msec());
}
::QtProtobuf::QTime convert(const ::QTime &from) {
return ::QtProtobuf::QTime(from.msecsSinceStartOfDay());
}
::QDate convert(const ::QtProtobuf::QDate &from) {
return ::QDate(from.year(), from.month(), from.day());
}
::QtProtobuf::QDate convert(const ::QDate &from) {
return ::QtProtobuf::QDate(from.year(), from.month(), from.day());
}
::QDateTime convert(const ::QtProtobuf::QDateTime &from) {
return ::QDateTime(convert(from.date()), convert(from.time()));
}
::QtProtobuf::QDateTime convert(const ::QDateTime &from) {
return ::QtProtobuf::QDateTime(convert(from.date()), convert(from.time()));
}
::QSize convert(const ::QtProtobuf::QSize &from) {
return ::QSize(from.width(), from.height());
}
::QtProtobuf::QSize convert(const ::QSize &from) {
return ::QtProtobuf::QSize(from.width(), from.height());
}
::QSizeF convert(const ::QtProtobuf::QSizeF &from) {
return ::QSizeF(from.width(), from.height());
}
::QtProtobuf::QSizeF convert(const ::QSizeF &from) {
return ::QtProtobuf::QSizeF(from.width(), from.height());
}
::QPoint convert(const ::QtProtobuf::QPoint &from) {
return ::QPoint(from.x(), from.y());
}
::QtProtobuf::QPoint convert(const ::QPoint &from) {
return ::QtProtobuf::QPoint(from.x(), from.y());
}
::QPointF convert(const ::QtProtobuf::QPointF &from) {
return ::QPointF(from.x(), from.y());
}
::QtProtobuf::QPointF convert(const ::QPointF &from) {
return ::QtProtobuf::QPointF(from.x(), from.y());
}
::QRect convert(const ::QtProtobuf::QRect &from) {
return ::QRect(convert(from.position()), convert(from.size()));
}
::QtProtobuf::QRect convert(const ::QRect &from) {
return ::QtProtobuf::QRect(convert(from.topLeft()), convert(from.size()));
}
::QRectF convert(const ::QtProtobuf::QRectF &from) {
return ::QRectF(convert(from.position()), convert(from.size()));
}
::QtProtobuf::QRectF convert(const ::QRectF &from) {
return ::QtProtobuf::QRectF(convert(from.topLeft()), convert(from.size()));
}
::QPolygon convert(const ::QtProtobuf::QPolygon &from) {
::QPolygon polygon;
for (auto point : from.points()) {
polygon.append(convert(*point));
}
return polygon;
}
::QtProtobuf::QPolygon convert(const ::QPolygon &from) {
::QtProtobuf::QPolygon polygon;
for (auto point : from) {
polygon.points().append(QSharedPointer<::QtProtobuf::QPoint>(new ::QtProtobuf::QPoint(convert(point))));
}
return polygon;
}
::QPolygonF convert(const ::QtProtobuf::QPolygonF &from) {
::QPolygonF polygon;
for (auto point : from.points()) {
polygon.append(convert(*point));
}
return polygon;
}
::QtProtobuf::QPolygonF convert(const ::QPolygonF &from) {
::QtProtobuf::QPolygonF polygon;
for (auto point : from) {
polygon.points().append(QSharedPointer<::QtProtobuf::QPointF>(new ::QtProtobuf::QPointF(convert(point))));
}
return polygon;
}
::QMatrix4x4 convert(const ::QtProtobuf::QMatrix4x4 &from) {
return ::QMatrix4x4(from.m11(), from.m12(), from.m13(), from.m14(),
from.m21(), from.m22(), from.m23(), from.m24(),
from.m31(), from.m32(), from.m33(), from.m34(),
from.m41(), from.m42(), from.m43(), from.m44());
}
::QtProtobuf::QMatrix4x4 convert(const ::QMatrix4x4 &from) {
//QMatrix4x4::data returned in column-major format
return ::QtProtobuf::QMatrix4x4(from.data()[0], from.data()[4], from.data()[8], from.data()[12],
from.data()[1], from.data()[5], from.data()[9], from.data()[13],
from.data()[2], from.data()[6], from.data()[10], from.data()[14],
from.data()[3], from.data()[7], from.data()[11], from.data()[15]);
}
::QVector2D convert(const ::QtProtobuf::QVector2D &from) {
return ::QVector2D(from.xpos(), from.ypos());
}
::QtProtobuf::QVector2D convert(const ::QVector2D &from) {
return ::QtProtobuf::QVector2D(from.x(), from.y());
}
::QVector3D convert(const ::QtProtobuf::QVector3D &from) {
return ::QVector3D(from.xpos(), from.ypos(), from.zpos());
}
::QtProtobuf::QVector3D convert(const ::QVector3D &from) {
return ::QtProtobuf::QVector3D(from.x(), from.y(), from.z());
}
::QVector4D convert(const ::QtProtobuf::QVector4D &from) {
return ::QVector4D(from.xpos(), from.ypos(), from.zpos(), from.wpos());
}
::QtProtobuf::QVector4D convert(const ::QVector4D &from) {
return ::QtProtobuf::QVector4D(from.x(), from.y(), from.z(), from.w());
}
::QTransform convert(const ::QtProtobuf::QTransform &from) {
return ::QTransform(from.m11(), from.m12(), from.m13(),
from.m21(), from.m22(), from.m23(),
from.m31(), from.m32(), from.m33());
}
::QtProtobuf::QTransform convert(const ::QTransform &from) {
return ::QtProtobuf::QTransform(from.m11(), from.m12(), from.m13(),
from.m21(), from.m22(), from.m23(),
from.m31(), from.m32(), from.m33());
}
::QQuaternion convert(const ::QtProtobuf::QQuaternion &from) {
return ::QQuaternion(from.scalar(), convert(from.vector()));
}
::QtProtobuf::QQuaternion convert(const ::QQuaternion &from) {
return ::QtProtobuf::QQuaternion(from.scalar(), convert(from.vector()));
}
::QImage convert(const ::QtProtobuf::QImage &from) {
return ::QImage::fromData(from.data(), from.format().toLatin1().data());
}
::QtProtobuf::QImage convert(const ::QImage &from) {
QByteArray data;
QBuffer buffer(&data);
buffer.open(QIODevice::WriteOnly);
from.save(&buffer, "PNG");
qProtoWarning() << "QImage always is sent in PNG format";
return ::QtProtobuf::QImage(data, "PNG");
}
template <typename QType, typename PType>
void registerQtTypeHandler() {
QtProtobufPrivate::registerHandler(qMetaTypeId<QType>(), {
[](const QtProtobuf::QAbstractProtobufSerializer *serializer, const QVariant &value, const QtProtobuf::QProtobufMetaProperty &property, QByteArray &buffer) {
PType object(convert(value.value<QType>()));
buffer.append(serializer->serializeObject(&object, PType::protobufMetaObject, property));
},
[](const QtProtobuf::QAbstractProtobufSerializer *serializer, QtProtobuf::QProtobufSelfcheckIterator &it, QVariant &value) {
PType object;
serializer->deserializeObject(&object, PType::protobufMetaObject, it);
value = QVariant::fromValue<QType>(convert(object));
}, QtProtobufPrivate::ObjectHandler });
}
void qRegisterProtobufQtTypes() {
registerQtTypeHandler<::QUrl, ::QtProtobuf::QUrl>();
registerQtTypeHandler<::QChar, ::QtProtobuf::QChar>();
registerQtTypeHandler<::QUuid, ::QtProtobuf::QUuid>();
registerQtTypeHandler<::QTime, ::QtProtobuf::QTime>();
registerQtTypeHandler<::QDate, ::QtProtobuf::QDate>();
registerQtTypeHandler<::QDateTime, ::QtProtobuf::QDateTime>();
registerQtTypeHandler<::QDateTime, ::QtProtobuf::QDateTime>();
registerQtTypeHandler<::QSize, ::QtProtobuf::QSize>();
registerQtTypeHandler<::QSizeF, ::QtProtobuf::QSizeF>();
registerQtTypeHandler<::QPoint, ::QtProtobuf::QPoint>();
registerQtTypeHandler<::QPointF, ::QtProtobuf::QPointF>();
registerQtTypeHandler<::QRect, ::QtProtobuf::QRect>();
registerQtTypeHandler<::QRectF, ::QtProtobuf::QRectF>();
registerQtTypeHandler<::QPolygon, ::QtProtobuf::QPolygon>();
registerQtTypeHandler<::QPolygonF, ::QtProtobuf::QPolygonF>();
registerQtTypeHandler<::QColor, ::QtProtobuf::QColor>();
registerQtTypeHandler<::QMatrix4x4, ::QtProtobuf::QMatrix4x4>();
registerQtTypeHandler<::QVector2D, ::QtProtobuf::QVector2D>();
registerQtTypeHandler<::QVector3D, ::QtProtobuf::QVector3D>();
registerQtTypeHandler<::QVector4D, ::QtProtobuf::QVector4D>();
registerQtTypeHandler<::QTransform, ::QtProtobuf::QTransform>();
registerQtTypeHandler<::QQuaternion, ::QtProtobuf::QQuaternion>();
registerQtTypeHandler<::QImage, ::QtProtobuf::QImage>();
}
}
| 35.621875 | 200 | 0.649004 | [
"object",
"vector"
] |
cc5124131a8b7790ba5c5904bc49fc15fa4a968a | 1,878 | cpp | C++ | bfs_network_delay.cpp | MeredithCL/Algorithms-Basic-Exercises | c9cadfbe3cf5a0d6fabb34aa6ff170e97f1e4e83 | [
"MIT"
] | null | null | null | bfs_network_delay.cpp | MeredithCL/Algorithms-Basic-Exercises | c9cadfbe3cf5a0d6fabb34aa6ff170e97f1e4e83 | [
"MIT"
] | null | null | null | bfs_network_delay.cpp | MeredithCL/Algorithms-Basic-Exercises | c9cadfbe3cf5a0d6fabb34aa6ff170e97f1e4e83 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
int size = times.size();
if (!size && n > 0)
{
return -1;
}
int edges[n + 1][n + 1];
int been[n + 1];
for (int i = 1; i <= n; ++ i)
{
been[i] = -1;
for (int j = 1; j <= n; ++ j)
{
edges[i][j] = INT_MAX;
}
}
for (int i = 0; i < size; ++ i)
{
edges[times[i][0]][times[i][1]] = times[i][2];
}
been[k] = 0;
queue<int> q;
q.push(k);
while (!q.empty())
{
int size = q.size();
for (int j = 0; j < size; ++ j)
{
int index = q.front();
q.pop();
for (int i = 1; i <= n; ++ i)
{
if (i != index && i != k && edges[index][i] != INT_MAX)
{
if (been[i] == -1)
{
been[i] = been[index] + edges[index][i];
q.push(i);
}
else
{
if (been[i] > been[index] + edges[index][i])
{
been[i] = been[index] + edges[index][i];
q.push(i);
}
}
}
}
}
}
int maxi = INT_MIN;
for (int i = 1; i <= n; ++ i)
{
if (been[i] == -1 && i != k)
{
return -1;
}
maxi = max(been[i], maxi);
}
return maxi;
}
};
| 27.617647 | 75 | 0.275293 | [
"vector"
] |
7fe230046cd066de666ba97a2feec94925e73fbf | 4,233 | cpp | C++ | samples/CastorDvpTD/MainFrame.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 245 | 2015-10-29T14:31:45.000Z | 2022-03-31T13:04:45.000Z | samples/CastorDvpTD/MainFrame.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 64 | 2016-03-11T19:45:05.000Z | 2022-03-31T23:58:33.000Z | samples/CastorDvpTD/MainFrame.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 11 | 2018-05-24T09:07:43.000Z | 2022-03-21T21:05:20.000Z | #include "MainFrame.hpp"
#include "RenderPanel.hpp"
#include "CastorDvpTD.hpp"
#include "Game.hpp"
#include <Castor3D/Event/Frame/CpuFunctorEvent.hpp>
#include <Castor3D/Render/RenderLoop.hpp>
#include <Castor3D/Render/RenderTarget.hpp>
#include <Castor3D/Render/RenderWindow.hpp>
#include <wx/sizer.h>
using namespace castor;
using namespace castor3d;
namespace castortd
{
namespace
{
static const wxSize MainFrameSize{ 1024, 768 };
typedef enum eID
{
eID_RENDER_TIMER,
} eID;
void doUpdate( Game & p_game )
{
auto & engine = *wxGetApp().getCastor();
if ( !engine.isCleaned() )
{
p_game.update();
engine.postEvent( makeCpuFunctorEvent( EventType::ePostRender, [&p_game]()
{
doUpdate( p_game );
} ) );
}
}
}
MainFrame::MainFrame()
: wxFrame{ nullptr, wxID_ANY, ApplicationName, wxDefaultPosition, MainFrameSize, wxSYSTEM_MENU | wxCAPTION | wxCLOSE_BOX | wxCLIP_CHILDREN | wxRESIZE_BORDER | wxMAXIMIZE_BOX }
{
SetClientSize( MainFrameSize );
Show( true );
try
{
doLoadScene();
wxBoxSizer * sizer{ new wxBoxSizer{ wxHORIZONTAL } };
sizer->Add( m_panel.get(), wxSizerFlags( 1 ).Shaped().Centre() );
sizer->SetSizeHints( this );
SetSizer( sizer );
}
catch ( std::exception & p_exc )
{
wxMessageBox( p_exc.what() );
}
}
void MainFrame::doLoadScene()
{
auto & engine = *wxGetApp().getCastor();
auto target = GuiCommon::loadScene( engine
, File::getExecutableDirectory().getPath() / cuT( "share" ) / cuT( "CastorDvpTD" ) / cuT( "Data.zip" )
, nullptr );
if ( target )
{
m_game = std::make_unique< Game >( *target->getScene() );
m_panel = wxMakeWindowPtr< RenderPanel >( this, MainFrameSize, *m_game );
m_panel->setRenderTarget( target );
auto & window = m_panel->getRenderWindow();
if ( window.isFullscreen() )
{
ShowFullScreen( true, wxFULLSCREEN_ALL );
}
if ( !IsMaximized() )
{
SetClientSize( int( window.getSize().getWidth() )
, int( window.getSize().getHeight() ) );
}
else
{
Maximize( false );
SetClientSize( int( window.getSize().getWidth() )
, int( window.getSize().getHeight() ) );
Maximize();
}
Logger::logInfo( cuT( "Scene file read" ) );
#if wxCHECK_VERSION( 2, 9, 0 )
wxSize size = GetClientSize();
SetMinClientSize( size );
#endif
if ( engine.isThreaded() )
{
engine.getRenderLoop().beginRendering();
engine.postEvent( makeCpuFunctorEvent( EventType::ePostRender
, [this]()
{
doUpdate( *m_game );
} ) );
}
else
{
m_timer = new wxTimer( this, eID_RENDER_TIMER );
m_timer->Start( 1000 / int( engine.getRenderLoop().getWantedFps() ), true );
}
}
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
BEGIN_EVENT_TABLE( MainFrame, wxFrame )
EVT_PAINT( MainFrame::OnPaint )
EVT_CLOSE( MainFrame::OnClose )
EVT_ERASE_BACKGROUND( MainFrame::OnEraseBackground )
EVT_TIMER( eID_RENDER_TIMER, MainFrame::OnRenderTimer )
END_EVENT_TABLE()
#pragma GCC diagnostic pop
void MainFrame::OnPaint( wxPaintEvent & p_event )
{
wxPaintDC paintDC( this );
p_event.Skip();
}
void MainFrame::OnClose( wxCloseEvent & p_event )
{
Hide();
if ( m_timer )
{
m_timer->Stop();
delete m_timer;
m_timer = nullptr;
}
auto & engine = *wxGetApp().getCastor();
if ( m_panel )
{
if ( engine.isThreaded() )
{
engine.getRenderLoop().pause();
}
m_panel->reset();
if ( engine.isThreaded() )
{
engine.getRenderLoop().resume();
}
}
if ( wxGetApp().getCastor() )
{
engine.cleanup();
}
if ( m_panel )
{
m_panel->Close( true );
m_panel = nullptr;
}
DestroyChildren();
p_event.Skip();
}
void MainFrame::OnEraseBackground( wxEraseEvent & p_event )
{
p_event.Skip();
}
void MainFrame::OnRenderTimer( wxTimerEvent & p_event )
{
if ( wxGetApp().getCastor() )
{
auto & castor = *wxGetApp().getCastor();
if ( !castor.isCleaned() )
{
if ( !castor.isThreaded() )
{
castor.getRenderLoop().renderSyncFrame();
m_game->update();
m_timer->Start( 1000 / int( castor.getRenderLoop().getWantedFps() ), true );
}
}
}
}
}
| 20.852217 | 177 | 0.640917 | [
"render"
] |
7febb1745428654871f2b027ff2adbefa7d4bb10 | 26,500 | cpp | C++ | sourcedata/jedit40source/jEdit/jeditshell/jedinstl/JELRegInstaller.cpp | DXYyang/SDP | 6ad0daf242d4062888ceca6d4a1bd4c41fd99b63 | [
"Apache-2.0"
] | 6 | 2020-10-27T06:11:59.000Z | 2021-09-09T13:52:42.000Z | sourcedata/jedit41source/jEdit/jeditshell/jedinstl/JELRegInstaller.cpp | DXYyang/SDP | 6ad0daf242d4062888ceca6d4a1bd4c41fd99b63 | [
"Apache-2.0"
] | 8 | 2020-11-16T20:41:38.000Z | 2022-02-01T01:05:45.000Z | sourcedata/jedit41source/jEdit/jeditshell/jedinstl/JELRegInstaller.cpp | DXYyang/SDP | 6ad0daf242d4062888ceca6d4a1bd4c41fd99b63 | [
"Apache-2.0"
] | null | null | null | /*
* JELRegInstaller.cpp - part of jEditLauncher package
* Copyright (C) 2001 John Gellene
* jgellene@nyc.rr.com
*
* Notwithstanding the terms of the General Public License, the author grants
* permission to compile and link object code generated by the compilation of
* this program with object code and libraries that are not subject to the
* GNU General Public License, provided that the executable output of such
* compilation shall be distributed with source code on substantially the
* same basis as the jEditLauncher package of which this program is a part.
* By way of example, a distribution would satisfy this condition if it
* included a working makefile for any freely available make utility that
* runs on the Windows family of operating systems. This condition does not
* require a licensee of this software to distribute any proprietary software
* (including header files and libraries) that is licensed under terms
* prohibiting redistribution to third parties.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id: JELRegInstaller.cpp,v 1.14 2002/02/19 03:33:44 jgellene Exp $
*/
#include "stdafx.h"
#include <string.h>
#include "InstallData.h"
#include "StringPtr.h"
#include "InstallerLog.h"
#include "JELRegInstaller.h"
#include <assert.h>
#include <stdlib.h> // for itoa in debug
/* Implementation of JELRegistryInstaller */
JELRegistryInstaller::JELRegistryInstaller(const InstallData *ptrData,
Installer *ptrOwner)
: pData(ptrData), pOwner(ptrOwner) {}
JELRegistryInstaller::~JELRegistryInstaller() {}
HRESULT JELRegistryInstaller::Install()
{
InstallerLog::Log(Message, "Commencing installation of registry entires. . . .\n");
HRESULT hr;
// register proxy/stub DLL
CString strPath(pData->strInstallDir);
strPath += _T("\\jeservps.dll");
if(FAILED(hr = RegisterDLL(strPath, TRUE)))
return hr;
// registration of unlaunch for "Add/Remove Programs" applet
// other data added by COM server
RegisterUninstall();
// register COM server
strPath = pData->strInstallDir;
strPath += _T("\\jeditsrv.exe");
if(FAILED(hr = RegisterEXE(strPath)))
{
// TODO: try to restore former setting
return hr;
}
// register the context menu handler
strPath = pData->strInstallDir;
strPath += pData->bUsingTempFileName ?
_T("\\jeshlstb.dl_") : _T("\\jeshlstb.dll");
if(FAILED(hr = RegisterDLL(strPath, TRUE)))
return hr;
// if we are still using the temporary file name, fix the
// registration entry so it will be correct after rebooting
if(pData->bUsingTempFileName)
{
if(FAILED(hr = CorrectTempCtxReg()))
{
InstallerLog::Log(Debug,
"Registration of context menu handler could not be corrected.\n");
return hr;
}
}
RegisterPrimaryVersion();
RegisterCmdLineParameters();
return hr;
}
HRESULT JELRegistryInstaller::RegisterDLL(LPCTSTR szPath, BOOL bRegister)
{
if(bRegister)
{
InstallerLog::Log(Message, "Registering %s. . .\n", szPath);
}
FARPROC proc = 0;
HRESULT hr;
LPCTSTR szProc = bRegister ? _T("DllRegisterServer") :
_T("DllUnregisterServer");
HMODULE hModule = ::LoadLibrary(szPath);
if(hModule == 0)
{
InstallerLog::Log(Error, "Could not load library in %s\n.",
szPath);
return E_FAIL;
}
proc = GetProcAddress(hModule, szProc);
if(proc == 0)
{
InstallerLog::Log(Error, "Could not get address for %s in %s\n.",
szProc, szPath);
hr = E_FAIL;
}
else
{
hr = (proc)();
if(hr != S_OK)
{
if(bRegister)
{
InstallerLog::Log(Error, "Registration failed; error code 0x%08x.\n");
}
hr = E_FAIL;
}
else
{
InstallerLog::Log(Message, "Registration succeeded.\n");
}
}
if(hModule != 0)
FreeLibrary(hModule);
return hr;
}
HRESULT JELRegistryInstaller::RegisterEXE(LPCTSTR szPath, BOOL bRegister)
{
if(bRegister)
{
InstallerLog::Log(Message, "Registering %s. . .\n", szPath);
}
CString strCmdLine(szPath);
strCmdLine += (bRegister ? _T(" /RegServer") : _T(" /UnregServer"));
CStringBuf<> bufCmdLine(strCmdLine);
STARTUPINFO si;
::ZeroMemory(&si, sizeof(si));
PROCESS_INFORMATION pi;
BOOL bReturn = CreateProcess(0, bufCmdLine, 0, 0, 0, 0, 0, 0, &si, &pi);
if(!bReturn)
{
if(bRegister)
InstallerLog::Log(Error, "Registration failed.\n");
DWORD swError = GetLastError();
}
else
{
if(bRegister)
InstallerLog::Log(Message, "Registration succeeded.\n");
}
return bReturn ? S_OK : E_FAIL;
}
HRESULT JELRegistryInstaller::CorrectTempCtxReg()
{
HKEY hKey = 0;
CString strClassKeyPath((LPCSTR)IDS_REG_CTX_SERVER_KEY);
int nResult = RegOpenKeyEx(HKEY_CLASSES_ROOT,
strClassKeyPath, 0, KEY_SET_VALUE, &hKey);
if(nResult == ERROR_SUCCESS)
{
nResult = RegSetValueEx(hKey, 0, 0, REG_SZ,
(const LPBYTE)(LPCTSTR)pData->strInstallFinalPath,
InstallData::GetBufferByteLen(pData->strInstallFinalPath));
}
RegCloseKey(hKey);
return nResult == ERROR_SUCCESS ? S_OK : E_FAIL;
}
HRESULT JELRegistryInstaller::RegisterUninstall()
{
InstallerLog::Log(Message, "Registering uninstall data for Add/Remove programs...\n");
HKEY hKey;
CString strUninstallKey((LPCSTR)IDS_REG_UNINSTALL_KEY);
strUninstallKey += pData->strInstallVersion;
::OutputDebugString(strUninstallKey);
int nResult = RegCreateKeyEx(HKEY_CURRENT_USER,
strUninstallKey, 0, 0, REG_OPTION_NON_VOLATILE,
KEY_WRITE, 0, &hKey, 0);
if(nResult == ERROR_SUCCESS)
{
InstallerLog::Log(Debug, "Found uninstall key\n");
CString strUninstall(pData->strInstallDir);
strUninstall += "\\unlaunch.exe";
nResult = RegSetValueEx(hKey, "UninstallString", 0, REG_SZ,
(const LPBYTE)(LPCTSTR)strUninstall,
InstallData::GetBufferByteLen(strUninstall));
InstallerLog::Log(Debug, "UninstallString %s.\n",
nResult == ERROR_SUCCESS ? "OK" : "error");
CString strInstall(pData->strInstallDir);
strInstall += "\\jedit.exe /i ";
strInstall += pData->strJavaHome;
nResult = RegSetValueEx(hKey, "InstallPath", 0, REG_SZ,
(const LPBYTE)(LPCTSTR)strInstall,
InstallData::GetBufferByteLen(strInstall));
InstallerLog::Log(Debug, "Install Path %s.\n",
nResult == ERROR_SUCCESS ? "OK" : "error");
CString strDisplayIcon(pData->strInstallDir);
strDisplayIcon += "\\jedit.exe, 0";
nResult = RegSetValueEx(hKey, "DisplayIcon", 0, REG_SZ,
(const LPBYTE)(LPCTSTR)strDisplayIcon,
InstallData::GetBufferByteLen(strDisplayIcon));
InstallerLog::Log(Debug, "Display Icon %s.\n",
nResult == ERROR_SUCCESS ? "OK" : "error");
}
else
InstallerLog::Log(Error, "Could not find uninstall registry key.\n");
RegCloseKey(hKey);
InstallerLog::Log(Message, "Uninstall registration %s.\n",
nResult == ERROR_SUCCESS ? "succeeded" : "failed");
return (nResult == ERROR_SUCCESS ? S_OK : E_FAIL);
}
HRESULT JELRegistryInstaller::RegisterPrimaryVersion()
{
// register scripting object and designated context menu handler
// get default value for GUID
// get ProgID under GUID
// default value becomes default value for class 'JEdit.JEditLauncher'
// CLSID is GUID
// CurVer is ProgID
CString strClassKey(_T("CLSID\\"));
const CString& strGUID = pData->strInstallGUID;
strClassKey += strGUID;
CString strClassName;
CString strCurVer;
CString strCurVerDir;
HKEY hKey;
int nResult;
int nCounter = 20;
// waiting for possible registration of new server in separate thread
do
{
Sleep(50);
nResult = RegOpenKeyEx(HKEY_CLASSES_ROOT, strClassKey, 0,
KEY_READ | KEY_QUERY_VALUE, &hKey);
} while(nResult != ERROR_SUCCESS && --nCounter != 0);
if(nResult == ERROR_SUCCESS)
{
CStringBuf<>pClassBuf(strClassName);
DWORD dwLength = pClassBuf.Size();
RegQueryValueEx(hKey, 0, 0, 0, (LPBYTE)pClassBuf, &dwLength);
HKEY hSubkey;
nResult = RegOpenKeyEx(hKey, _T("ProgID"), 0, KEY_READ, &hSubkey);
if(nResult == ERROR_SUCCESS)
{
CStringBuf<>pCurVerBuf(strCurVer);
dwLength = pCurVerBuf.Size();
RegQueryValueEx(hSubkey, 0, 0, 0, (LPBYTE)pCurVerBuf, &dwLength);
}
RegCloseKey(hSubkey);
nResult = RegOpenKeyEx(hKey, _T("LocalServer32"), 0, KEY_READ, &hSubkey);
if(nResult == ERROR_SUCCESS)
{
CStringBuf<>pCurVerDirBuf(strCurVerDir);
dwLength = pCurVerDirBuf.Size();
RegQueryValueEx(hSubkey, 0, 0, 0, (LPBYTE)pCurVerDirBuf, &dwLength);
InstallData::ShortenToDirectory(pCurVerDirBuf);
}
RegCloseKey(hSubkey);
}
RegCloseKey(hKey);
nResult = RegCreateKeyEx(HKEY_CLASSES_ROOT, _T("JEdit.JEditLauncher"), 0, 0, 0,
KEY_ALL_ACCESS, 0, &hKey, 0);
if(nResult == ERROR_SUCCESS)
{
RegSetValueEx(hKey, 0, 0, REG_SZ, (LPBYTE)(LPCTSTR)strClassName,
InstallData::GetBufferByteLen(strClassName));
HKEY hSubkey;
nResult = RegCreateKeyEx(hKey, _T("CLSID"), 0, 0, 0, KEY_ALL_ACCESS,
0, &hSubkey, 0);
if(nResult == ERROR_SUCCESS)
{
RegSetValueEx(hSubkey, 0, 0, REG_SZ, (LPBYTE)(LPCTSTR)strGUID,
InstallData::GetBufferByteLen(strGUID));
}
RegCloseKey(hSubkey);
nResult = RegCreateKeyEx(hKey, _T("CurVer"), 0, 0, 0, KEY_ALL_ACCESS,
0, &hSubkey, 0);
if(nResult == ERROR_SUCCESS)
{
RegSetValueEx(hSubkey, 0, 0, REG_SZ, (LPBYTE)(LPCTSTR)strCurVer,
InstallData::GetBufferByteLen(strCurVer));
}
RegCloseKey(hSubkey);
}
RegCloseKey(hKey);
// unregister uninstall information for jEdit 3.2
int nResultDel = RegOpenKeyEx(HKEY_CURRENT_USER,
_T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"),
0, KEY_WRITE, &hKey);
if(nResultDel == ERROR_SUCCESS)
RegDeleteKey(hKey, _T("jEdit 3.2"));
RegCloseKey(hKey);
if(nResult != ERROR_SUCCESS)
return E_FAIL;
return S_OK;
}
HRESULT JELRegistryInstaller::RegisterCmdLineParameters()
{
bool bResult = true;
InstallerLog::Log(Message, "Registering command line parameters. . . .\n");
HKEY hLauncherKey, hVersionKey;
DWORD dwDisp;
int nResult;
DWORD dwValueSize;
TCHAR szBuf[MAX_PATH];
TCHAR* arszValues[] = { _T("Java Executable"),
_T("Java Options"),
_T("jEdit Target"),
_T("jEdit Options"),
_T("jEdit Working Directory"),
_T("Launcher GUID"),
_T("Installation Directory"),
_T("Launcher Log Level") };
ZeroMemory(szBuf, MAX_PATH);
/*
enum { JavaExec, JavaOptions, jEditTarget, jEditOptions,
Server, WorkingDir, GUID, InstallDir };
*/
// ask if parameters should be retained from last installation
bool bUseOldParameters = false;
if((pData->bIs32 || pData->bIs40) && IDYES == MessageBox(0,
"Do you wish to retain command line parameters from your existing installation of jEditLauncher?",
"jEditLauncher", MB_ICONQUESTION | MB_YESNO))
{
InstallerLog::Log(Message, "Using parameters from existing installation.\n");
bUseOldParameters = true;
}
else
{
InstallerLog::Log(Message, "Writing default parameters.\n");
}
CString strLauncherParamKeyPath((LPCSTR)IDS_REG_LAUNCHER_PARAM_KEY);
RegCreateKeyEx(HKEY_CURRENT_USER, strLauncherParamKeyPath, 0, 0, 0,
KEY_ALL_ACCESS, 0, &hLauncherKey, 0);
CString strVersion(pData->strInstallVersion);
RegCreateKeyEx(hLauncherKey, strVersion, 0, 0, 0,
KEY_ALL_ACCESS, 0, &hVersionKey, &dwDisp);
// rewrite key from 3.2 to 4.0
if(bUseOldParameters && pData->bIs32 && !pData->bIs40)
{
HKEY hKey32;
int nResult32 = RegOpenKeyEx(hLauncherKey,
"3.2", 0, KEY_READ, &hKey32);
if(nResult32 == ERROR_SUCCESS)
{
nResult32 = RegCopyKey(hKey32, hLauncherKey, "4.0");
RegCloseKey(hKey32);
if(nResult32 == ERROR_SUCCESS)
{
InstallerLog::Log(Debug,
"Copied key information from version 3.2 to 4.0.\n");
nResult32 = RegDeleteKey(hLauncherKey, _T("3.2"));
InstallerLog::Log(Debug, "version 3.2 parameters %s\n",
nResult32 == ERROR_SUCCESS ? "deleted" : "not deleted");
}
else
{
bUseOldParameters = false;
InstallerLog::Log(Error,
"Could not copy parameters from version 3.2 to 4.0, new parameters must be supplied.\n");
}
}
else
{
RegCloseKey(hKey32);
bUseOldParameters = false;
InstallerLog::Log(Error,
"Could not find parameters from version 3.2 to copy, new parameters must be supplied.\n");
}
}
// "Java Executable" - set if old parameter or if not available;
// do not update if user elects to retain old parameters
dwValueSize = MAX_PATH;
nResult = RegQueryValueEx(hVersionKey, arszValues[0], 0, 0, (LPBYTE)szBuf, &dwValueSize);
if(!bUseOldParameters || nResult != ERROR_SUCCESS || dwValueSize == 0)
{
CString strJavaExec(pData->strJavaHome);
strJavaExec += _T("\\javaw.exe");
nResult = RegSetValueEx(hVersionKey, arszValues[0], 0,
REG_SZ, (LPBYTE)(LPCTSTR)strJavaExec,
InstallData::GetBufferByteLen(strJavaExec));
if(ERROR_SUCCESS == nResult)
{
InstallerLog::Log(Debug,
"Writing \"Java Executable\" registry parameter: %s\n",
(LPCSTR)strJavaExec);
}
else
{
InstallerLog::Log(Error,
"Could not write \"Java Executable\" registry parameter.\n");
bResult &= false;
}
}
// "Java Options" - set if new parameters of if unavailable;
// update regardless whenther user elects to retain old parameters
dwValueSize = MAX_PATH;
nResult = RegQueryValueEx(hVersionKey, arszValues[1], 0, 0, (LPBYTE)szBuf, &dwValueSize);
if(!bUseOldParameters || nResult != ERROR_SUCCESS || dwValueSize == 0)
{
bUseOldParameters = false;
CString strJavaOptions(_T("-mx32m -jar"));
// strJavaOptions.Format(IDS_REG_JAVAPARAM_DEFAULT,
// pData->arPathNames[pData->nIndexSubjectVer]);
nResult = RegSetValueEx(hVersionKey, arszValues[1], 0,
REG_SZ, (LPBYTE)(LPCTSTR)strJavaOptions,
InstallData::GetBufferByteLen(strJavaOptions));
if(ERROR_SUCCESS == nResult)
{
InstallerLog::Log(Debug,
"Writing \"Java Options\" registry parameter: %s\n",
(LPCSTR)strJavaOptions);
}
else
{
InstallerLog::Log(Error,
"Could not write \"Java Options\" registry parameter.\n");
bResult &= false;
}
}
else
{
UpdateJarParameter(szBuf);
nResult = RegSetValueEx(hVersionKey, arszValues[1], 0,
REG_SZ, (LPBYTE)szBuf,
(_tcslen(szBuf) + 1) * sizeof(TCHAR));
if(ERROR_SUCCESS == nResult)
{
InstallerLog::Log(Debug,
"Updating \"Java Options\" registry parameter: %s\n",
(LPCSTR)szBuf);
}
else
{
InstallerLog::Log(Error,
"Could not write \"Java Options\" registry parameter.\n");
bResult &= false;
}
}
// "jEdit Target" -- must always be set
CString strJEditTarget;
dwValueSize = MAX_PATH;
nResult = RegQueryValueEx(hVersionKey, arszValues[2], 0, 0, (LPBYTE)szBuf, &dwValueSize);
if(nResult != ERROR_SUCCESS || dwValueSize == 0
|| strstr(szBuf, "jedit.jar") != 0)
{
strJEditTarget = _T("\"");
strJEditTarget += pData->strInstallDir;
strJEditTarget += _T("\\jedit.jar\"");
}
else
{
strJEditTarget = _T("org.gjt.sp.jedit.jEdit");
}
nResult = RegSetValueEx(hVersionKey, arszValues[2], 0,
REG_SZ, (LPBYTE)(LPCTSTR)strJEditTarget,
InstallData::GetBufferByteLen(strJEditTarget));
if(ERROR_SUCCESS == nResult)
{
InstallerLog::Log(Debug,
"Writing \"jEdit Target\" registry parameter: %s\n",
(LPCSTR)strJEditTarget);
}
else
{
InstallerLog::Log(Error,
"Could not write \"jEdit Target\" registry parameter.\n");
bResult &= false;
}
// "jEdit Options" - default is no options;
// make sure an empty item is written
dwValueSize = MAX_PATH;
nResult = RegQueryValueEx(hVersionKey, arszValues[3], 0, 0, (LPBYTE)szBuf, &dwValueSize);
if(!bUseOldParameters || nResult != ERROR_SUCCESS)
{
// "jEdit Options"
char szBuf = 0;
nResult = RegSetValueEx(hVersionKey, arszValues[3], 0,
REG_SZ, (LPBYTE)&szBuf, sizeof(TCHAR));
if(ERROR_SUCCESS == nResult)
{
InstallerLog::Log(Debug,
"Writing empty \"jEdit Options\" registry parameter.\n");
}
else
{
InstallerLog::Log(Error,
"Could not write \"jEdit Options\" registry parameter.\n");
bResult &= false;
}
}
// "jEdit Working Directory"
// always change working directory, so you can't get
// an orphan entry following an uninstall of another version
CString strWorkingDir(pData->strInstallDir);
nResult = RegSetValueEx(hVersionKey, arszValues[4], 0,
REG_SZ, (LPBYTE)(LPCTSTR)strWorkingDir,
InstallData::GetBufferByteLen(strWorkingDir));
if(ERROR_SUCCESS == nResult)
{
InstallerLog::Log(Debug,
"Writing \"jEdit Working Directory\" registry parameter: %s\n",
(LPCTSTR)strWorkingDir);
}
else
{
InstallerLog::Log(Error,
"Could not write \"jEdit Working Directory\" registry parameter.\n");
bResult &= false;
}
// "Launcher GUID"
nResult = RegSetValueEx(hVersionKey, arszValues[5], 0,
REG_SZ, (LPBYTE)(LPCTSTR)pData->strInstallGUID,
InstallData::GetBufferByteLen(pData->strInstallGUID));
if(ERROR_SUCCESS == nResult)
{
InstallerLog::Log(Debug,
"Writing \"Launcher GUID\" registry parameter: %s\n",
(LPCTSTR)pData->strInstallGUID);
}
else
{
InstallerLog::Log(Error,
"Could not write \"Launcher GUID\" registry parameter.\n");
bResult &= false;
}
// "Installation Dir"
nResult = RegSetValueEx(hVersionKey, arszValues[6], 0,
REG_SZ, (LPBYTE)(LPCTSTR)pData->strInstallDir,
InstallData::GetBufferByteLen(pData->strInstallDir));
if(ERROR_SUCCESS == nResult)
{
InstallerLog::Log(Debug,
"Writing \"Installation Dir\" registry parameter: %s\n",
(LPCTSTR)pData->strInstallDir);
}
else
{
InstallerLog::Log(Error,
"Could not write \"Installation Dir\" registry parameter.\n");
bResult &= false;
}
// "Launcher Log Level": set to -1 if not previously set
dwValueSize = MAX_PATH;
nResult = RegQueryValueEx(hVersionKey, arszValues[7], 0, 0, (LPBYTE)szBuf, &dwValueSize);
if(!bUseOldParameters || nResult != ERROR_SUCCESS || dwValueSize == 0)
{
DWORD dwDebug = (DWORD)-1;
nResult = RegSetValueEx(hVersionKey, arszValues[7], 0,
REG_DWORD, (LPBYTE)&dwDebug, sizeof(DWORD));
if(ERROR_SUCCESS == nResult)
{
InstallerLog::Log(Debug,
"Writing \"Launcher Log Level\" registry parameter: %d\n",
dwDebug);
}
else
{
InstallerLog::Log(Error,
"Could not write \"Launcher Log Level\" registry parameter.\n");
bResult &= false;
}
}
RegCloseKey(hVersionKey);
RegCloseKey(hLauncherKey);
InstallerLog::Log(Message, "Registration of command line parameters %s.\n",
bResult ? "succeeded" : "failed");
return S_OK;
}
// if "jEdit.jar" appears in the parameter,
// get the associated directory and change to the
// current install directory
void JELRegistryInstaller::UpdateJarParameter(LPTSTR lpszParam)
{
CString strLCParam(lpszParam);
strLCParam.MakeLower();
const TCHAR *pJar = lpszParam + strLCParam.Find(_T("jedit.jar"));
if(pJar <= lpszParam) return;
bool quoted = false;
const TCHAR *pStart = lpszParam;
const TCHAR *p;
for(p = lpszParam; p < pJar; ++p)
{
switch (*p)
{
case _T(';'): pStart = p; break;
case _T(' '): if(!quoted) pStart = p; break;
case _T('\"'): quoted = !quoted; if(quoted) pStart = p; break;
default: break;
}
}
// now pStart points to the beginning of the jedit.jar path,
// or a leading space, quote or semicolon; next we trim
bool bContinue = true;
for(p = pStart; bContinue && p < pJar; ++p)
{
switch(*p)
{
case _T(';'):
case _T(' '):
case _T('\"'): pStart = p; break;
default: bContinue = false; break;
}
}
// now we replace from pStart to pJar with the new install dir
char szNewParam[MAX_PATH];
ZeroMemory(szNewParam, MAX_PATH);
lstrcpyn(szNewParam, lpszParam, pStart - lpszParam);
lstrcat(szNewParam, pData->strInstallDir);
lstrcat(szNewParam, _T("\\"));
lstrcat(szNewParam, pJar);
lstrcpy(lpszParam, szNewParam);
}
HRESULT JELRegistryInstaller::Uninstall()
{
UnregisterCmdLineParameters();
CString strDir(pData->strInstallDir);
// unregister proxy/stub DLL
CString strPath(strDir);
strPath += _T("\\jeservps.dll");
RegisterDLL(strPath, FALSE);
// clean up proxy/stub; this is interface GUID
CString strPxStubCLSID(_T("CLSID\\{E53269FA-8A5C-42B0-B3BC-82254F4FCED4}"));
RegDeleteKey(HKEY_CLASSES_ROOT, strPxStubCLSID + _T("\\InProcServer32"));
RegDeleteKey(HKEY_CLASSES_ROOT, strPxStubCLSID);
// unregister COM Server
strPath = strDir;
strPath += _T("\\jeditsrv.exe");
RegisterEXE(strPath, FALSE);
CheckUnregisterCtxMenu();
// delete HKEY_CLASSES_ROOT\JEdit.JEditLauncher and interface key if nothing is left
HKEY hLauncherKey;
if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, _T("JEdit.JEditLauncher"),
0, KEY_ALL_ACCESS, &hLauncherKey))
{
RegDeleteKey(hLauncherKey, _T("CLSID"));
RegDeleteKey(hLauncherKey, _T("CurVer"));
RegCloseKey(hLauncherKey);
RegDeleteKey(HKEY_CLASSES_ROOT, _T("JEdit.JEditLauncher"));
}
CString strInterfaceKey(_T("Interface\\{E53269FA-8A5C-42B0-B3BC-82254F4FCED4}"));
if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, strInterfaceKey,
0, KEY_ALL_ACCESS, &hLauncherKey))
{
RegDeleteKey(hLauncherKey, _T("NumMethods"));
RegDeleteKey(hLauncherKey, _T("ProxyStubClsid"));
RegDeleteKey(hLauncherKey, _T("ProxyStubClsid32"));
RegDeleteKey(hLauncherKey, _T("TypeLib"));
RegCloseKey(hLauncherKey);
RegDeleteKey(HKEY_CLASSES_ROOT, strInterfaceKey);
}
return S_OK;
}
HRESULT JELRegistryInstaller::UnregisterCmdLineParameters()
{
HKEY hKey;
// delete command line parameters and any empty parent keys
CString strLauncherParamKey((LPCSTR)IDS_REG_LAUNCHER_PARAM_KEY);
int nResult = RegOpenKeyEx(HKEY_CURRENT_USER, strLauncherParamKey,
0, KEY_ALL_ACCESS, &hKey);
if(nResult == ERROR_SUCCESS)
{
CString strVersion(pData->strInstallVersion);
RegDeleteKey(hKey, strVersion);
DWORD dwSubkeys;
RegQueryInfoKey(hKey, 0, 0, 0, &dwSubkeys, 0, 0, 0, 0, 0, 0, 0);
if(dwSubkeys == 0)
{
RegCloseKey(hKey);
if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_CURRENT_USER,
_T("Software\\www.jedit.org"), 0, KEY_ALL_ACCESS, &hKey))
{
RegDeleteKey(hKey, _T("jEditLauncher"));
RegQueryInfoKey(hKey, 0, 0, 0, &dwSubkeys, 0, 0, 0, 0, 0, 0, 0);
if(dwSubkeys == 0)
{
RegCloseKey(hKey);
if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_CURRENT_USER,
_T("Software"), 0, KEY_ALL_ACCESS, &hKey))
{
RegDeleteKey(hKey, _T("www.jedit.org"));
}
}
}
}
}
RegCloseKey(hKey);
return S_OK;
}
// Unregisters ctx menu handler if the current version is installed
HRESULT JELRegistryInstaller::CheckUnregisterCtxMenu()
{
// first get the CLSID of the installed handler
CString strCtxMenuKey((LPCSTR)IDS_REG_CTXMENU_KEY);
CString strCurCtxMenuCLSID;
HKEY hCtxMenuKey;
int nResult = RegOpenKeyEx(HKEY_CLASSES_ROOT, strCtxMenuKey, 0,
KEY_ALL_ACCESS, &hCtxMenuKey);
if(nResult == ERROR_SUCCESS)
{
CStringBuf<>buf(strCurCtxMenuCLSID);
DWORD dwlength = buf * sizeof(TCHAR);
nResult = RegQueryValueEx(hCtxMenuKey, 0, 0, 0,
(LPBYTE)buf, &dwlength);
}
RegCloseKey(hCtxMenuKey);
// now get the path to the handler module from the CLSID
CString strCurCtxMenuPath;
CString strServerKey(_T("CLSID\\"));
strServerKey += strCurCtxMenuCLSID;
strServerKey += _T("\\InprocServer32");
nResult = RegOpenKeyEx(HKEY_CLASSES_ROOT, strServerKey, 0,
KEY_ALL_ACCESS, &hCtxMenuKey);
if(nResult == ERROR_SUCCESS)
{
CStringBuf<>buf(strCurCtxMenuPath);
DWORD dwlength = buf * sizeof(TCHAR);
nResult = RegQueryValueEx(hCtxMenuKey, 0, 0, 0,
(LPBYTE)buf, &dwlength);
}
RegCloseKey(hCtxMenuKey);
// NOTE: Ctx menu now always installed
// now compare the installed handler's path to
// the path in this version and delete the key if they match
// CString strPath(pData->arPathNames[pData->nIndexSubjectVer]);
// strPath += _T("\\jeshlstb.dll");
// TCHAR szInstalledPath[MAX_PATH], szCurPath[MAX_PATH];
// GetShortPathName(strCurCtxMenuPath, szInstalledPath, MAX_PATH);
// GetShortPathName(strPath, szCurPath, MAX_PATH);
// HRESULT hr = S_OK;
// if(_tcsicmp(szInstalledPath, szCurPath) == 0)
// {
RegDeleteKey(HKEY_CLASSES_ROOT, strCtxMenuKey);
RegisterDLL(strCurCtxMenuPath, FALSE);
// }
// else hr = S_FALSE;
return S_OK;
}
HRESULT JELRegistryInstaller::SendMessage(LPVOID p)
{
p;
return E_NOTIMPL;
}
LONG JELRegistryInstaller::RegCopyKey(HKEY SrcKey, HKEY TrgKey, TCHAR* TrgSubKeyName)
{
HKEY SrcSubKey;
HKEY TrgSubKey;
int ValEnumIndx=0;
int KeyEnumIndx=0;
char ValName[MAX_PATH+1];
char KeyName[MAX_PATH+1];
DWORD size;
DWORD VarType;
LONG nResult;
DWORD KeyDisposition;
FILETIME LastWriteTime;
CString strBuffer;
// create target key
nResult = RegCreateKeyEx(TrgKey, TrgSubKeyName, NULL, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &TrgSubKey,
&KeyDisposition);
if(nResult != ERROR_SUCCESS)
return nResult;
do {
do {
// read value from source key
CStringBuf<1024> buffer(strBuffer);
ULONG buffSize = (ULONG)buffer.Size();
size=MAX_PATH+1;
nResult = RegEnumValue(SrcKey, ValEnumIndx, ValName, &size,
NULL, &VarType, buffer, &buffSize);
// done copying this key
if (nResult == ERROR_NO_MORE_ITEMS)
{
nResult = ERROR_SUCCESS;
break;
}
if(nResult != ERROR_SUCCESS)
break;
// write value to target key
nResult = RegSetValueEx(TrgSubKey, ValName, NULL, VarType,
buffer, buffSize);
if(nResult != ERROR_SUCCESS)
break;
// read next value
ValEnumIndx++;
} while (nResult == ERROR_SUCCESS);
// if copying under the same key avoid endless recursions
TCHAR TrgSubKeyNameRoot[1024];
do {
// enum sub keys
size=MAX_PATH+1;
nResult = RegEnumKeyEx(SrcKey, KeyEnumIndx++, KeyName, &size,
NULL, NULL, NULL, &LastWriteTime);
lstrcpyn(TrgSubKeyNameRoot, TrgSubKeyName, lstrlen(TrgSubKeyName) + 1);
} while ((SrcKey == TrgKey) &&
(nResult == ERROR_SUCCESS) &&
!lstrcmpi(KeyName, TrgSubKeyNameRoot));
// done copying this key
if (nResult == ERROR_NO_MORE_ITEMS)
break;
// unknown error return
if (nResult != ERROR_SUCCESS)
break;
// open the source subkey
InstallerLog::Log(Debug, "Opening sub key %s\n", KeyName);
nResult = RegOpenKeyEx(SrcKey, KeyName, NULL, KEY_ALL_ACCESS,
&SrcSubKey);
if(nResult != ERROR_SUCCESS)
break;
// recurs with the subkey
nResult = RegCopyKey(SrcSubKey, TrgSubKey, KeyName);
if(nResult != ERROR_SUCCESS)
break;
nResult = RegCloseKey(SrcSubKey);
if(nResult != ERROR_SUCCESS)
break;
} while (true);
RegCloseKey(TrgSubKey);
if (nResult == ERROR_NO_MORE_ITEMS)
return ERROR_SUCCESS;
else
return nResult;
}
| 29.608939 | 101 | 0.709396 | [
"object"
] |
7feca11c06b3a5c0220a461919833275e5f72faa | 2,251 | cpp | C++ | ho.cpp | e-eight/basis_func | 5374e4c034c4d25c019d9338ac9c0ec39929dd70 | [
"MIT"
] | null | null | null | ho.cpp | e-eight/basis_func | 5374e4c034c4d25c019d9338ac9c0ec39929dd70 | [
"MIT"
] | null | null | null | ho.cpp | e-eight/basis_func | 5374e4c034c4d25c019d9338ac9c0ec39929dd70 | [
"MIT"
] | null | null | null | #include "ho.h"
#include <cmath>
#include <stdexcept>
namespace basis_func {
namespace ho {
void WaveFunctionsUptoMaxN(Eigen::ArrayXXd& vals, const Eigen::ArrayXd& pts,
const std::size_t& max_n, const std::size_t& l,
const double& length, const Space& space)
{
if (space != Space::coordinate && space != Space::momentum) {
throw std::runtime_error("space must be coordinate or momentum.");
}
int npts = pts.size();
int ni = static_cast<int>(max_n);
int li = static_cast<int>(l);
if (vals.rows() != ni + 1 || vals.cols() != npts) {
throw std::runtime_error(
"vals must have the dimensions (max_n + 1, pts.size())");
}
Eigen::ArrayXd x(npts), x2(npts);
x = pts;
if (space == Space::coordinate) {
x /= length;
}
else {
x *= length;
}
x2 = x.square();
double jac = 0;
if (space == Space::coordinate) {
jac = std::pow(length, -1.5);
}
else {
jac = std::pow(length, 1.5);
}
Eigen::ArrayXd psi_i(npts), psi_im1(npts), psi_im2(npts);
// n = 0
psi_im2 = (jac * Eigen::pow(x, li) * std::sqrt(2.0 / std::tgamma(li + 1.5))
* Eigen::exp(-0.5 * x2));
// n = 1
psi_im1 = (jac * Eigen::pow(x, li) * std::sqrt(2.0 / std::tgamma(li + 2.5))
* (1.5 + li - x2) * Eigen::exp(-0.5 * x2));
vals.row(0) = psi_im2;
vals.row(1) = psi_im1;
for (int i = 2; i <= ni; ++i) {
psi_i = ((std::sqrt(2. * i / (1. + 2. * (li + i)))
* (2. + (li - 0.5 - x2) / i) * psi_im1)
- (std::sqrt(4. * i * (i - 1) / (4. * (i + li) * (i + li) - 1.))
* (1. + (li - 0.5) / i) * psi_im2));
psi_im2 = psi_im1;
psi_im1 = psi_i;
vals.row(i) = psi_i;
}
}
void WaveFunctionsUptoMaxL(std::vector<Eigen::ArrayXXd>& wfs,
const Eigen::ArrayXd& pts, const std::size_t& max_n,
const std::size_t& max_l, const double& length,
const Space& space)
{
int npts = pts.size();
Eigen::ArrayXXd psi(max_n + 1, npts);
for (std::size_t l = 0; l <= max_l; ++l) {
WaveFunctionsUptoMaxN(psi, pts, max_n, l, length, space);
wfs.push_back(psi);
}
}
} // namespace ho
} // namespace basis_func
| 27.790123 | 79 | 0.522434 | [
"vector"
] |
7ff0ad1b2b7817ec50269b998199fb63fcfbaf67 | 1,675 | cpp | C++ | aws-cpp-sdk-sso-oidc/source/model/StartDeviceAuthorizationResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-sso-oidc/source/model/StartDeviceAuthorizationResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-sso-oidc/source/model/StartDeviceAuthorizationResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/sso-oidc/model/StartDeviceAuthorizationResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::SSOOIDC::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
StartDeviceAuthorizationResult::StartDeviceAuthorizationResult() :
m_expiresIn(0),
m_interval(0)
{
}
StartDeviceAuthorizationResult::StartDeviceAuthorizationResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_expiresIn(0),
m_interval(0)
{
*this = result;
}
StartDeviceAuthorizationResult& StartDeviceAuthorizationResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("deviceCode"))
{
m_deviceCode = jsonValue.GetString("deviceCode");
}
if(jsonValue.ValueExists("userCode"))
{
m_userCode = jsonValue.GetString("userCode");
}
if(jsonValue.ValueExists("verificationUri"))
{
m_verificationUri = jsonValue.GetString("verificationUri");
}
if(jsonValue.ValueExists("verificationUriComplete"))
{
m_verificationUriComplete = jsonValue.GetString("verificationUriComplete");
}
if(jsonValue.ValueExists("expiresIn"))
{
m_expiresIn = jsonValue.GetInteger("expiresIn");
}
if(jsonValue.ValueExists("interval"))
{
m_interval = jsonValue.GetInteger("interval");
}
return *this;
}
| 22.333333 | 128 | 0.740299 | [
"model"
] |
7ff4d945e8146d90ca92591dabc82a0871684b74 | 1,758 | cpp | C++ | NinjaGaiden/Ninja/CrouchingState.cpp | Kaos1105/Ninja-Gaiden-NES | 4d1cfd5ca045587ac6b14b738a46e78951f54bbe | [
"MIT"
] | null | null | null | NinjaGaiden/Ninja/CrouchingState.cpp | Kaos1105/Ninja-Gaiden-NES | 4d1cfd5ca045587ac6b14b738a46e78951f54bbe | [
"MIT"
] | null | null | null | NinjaGaiden/Ninja/CrouchingState.cpp | Kaos1105/Ninja-Gaiden-NES | 4d1cfd5ca045587ac6b14b738a46e78951f54bbe | [
"MIT"
] | 1 | 2019-05-15T07:37:00.000Z | 2019-05-15T07:37:00.000Z | #include "CrouchingState.h"
CrouchingState::CrouchingState(StateGameObject * gameObject)
{
this->gameObject = gameObject;
}
void CrouchingState::Idle()
{
gameObject->SetIsCrouching(false);
gameObject->SetState(gameObject->GetIdleState());
}
void CrouchingState::Attack()
{
//Tiếng kiếm kêu
if (this->gameObject->GetID() == GAME_OBJ_ID_NINJA)
GameSound::GetInstance()->Play(IDSound::SWORD);
gameObject->SetState(gameObject->GetAttackingState());
}
void CrouchingState::Walk()
{
}
void CrouchingState::Climb()
{
}
void CrouchingState::Throw()
{
gameObject->SetState(gameObject->GetThrowingState());
}
void CrouchingState::Jump()
{
}
void CrouchingState::Crouch()
{
}
void CrouchingState::Hurt()
{
float vx = gameObject->GetDefaultWalkSpeed() * (gameObject->IsLeft() ? 1 : -1) / 1.25f;
float vy = gameObject->GetDefautJumpSpeed() / 1.5f;
gameObject->SetSpeedY(vx);
gameObject->SetSpeedY(vy);
if (gameObject->GetID() == GAME_OBJ_ID_NINJA)
{
gameObject->SetIsInvincible(true);
gameObject->ResetInvincibleTimer();
}
gameObject->SetIsGrounded(false);
gameObject->SetIsHurt(true);
gameObject->SetState(gameObject->GetHurtState());
}
void CrouchingState::Update(DWORD dt)
{
State::Update(dt);
}
void CrouchingState::Render()
{
State::Render();
if (gameObject->GetCrouchAnimID() != -1)
{
SpriteData spriteData;
spriteData.width = gameObject->GetWidth();
spriteData.height = gameObject->GetHeight();
spriteData.x = gameObject->GetPositionX();
spriteData.y = gameObject->GetPositionY();
spriteData.scale = 1;
spriteData.angle = 0;
spriteData.isLeft = gameObject->IsLeft();
spriteData.isFlipped = gameObject->IsFlipped();
gameObject->GetAnimationsList()[gameObject->GetCrouchAnimID()]->Render(spriteData);
}
} | 21.975 | 88 | 0.726962 | [
"render"
] |
3d15aa52852114582da3a1ce862b75a8afd86ad1 | 5,070 | cpp | C++ | light.cpp | block8437/GameEngine | e4b452c33781566e55e9339efee9441ddb924f58 | [
"MIT"
] | null | null | null | light.cpp | block8437/GameEngine | e4b452c33781566e55e9339efee9441ddb924f58 | [
"MIT"
] | 1 | 2017-04-05T00:58:21.000Z | 2017-04-05T00:58:21.000Z | light.cpp | block8437/GameEngine | e4b452c33781566e55e9339efee9441ddb924f58 | [
"MIT"
] | null | null | null | #include "light.h"
static float ratio = 40.0f;
b2Vec2 b2Scale(b2Vec2 vector, float scale ) {
return b2Vec2(vector.x * scale, vector.y * scale);
}
namespace GameEngine {
Light::Light(World* _world, int _x, int _y, float _r, float _g, float _b, int _windowWidth, int _windowHeight, GLuint _shader) {
world = _world;
x = _x;
y = _y;
r = _r;
g = _g;
b = _b;
windowWidth = _windowWidth;
windowHeight = _windowHeight;
shader = _shader;
}
/*
I feel like I should explain what I am doing in this function.
Light::render does not do what you would expect it to do
it renders lights. You probably didn't guess that. Ik, pretty mysterious.
All the way up to b2Vec2 vertex = poly->GetVertex(i); is just getting the vertices of the shapes of the fixture of the object.
First we loop over every fixture, we get the shape, and we make sure it is a polygon.
Then we loop over every vertex.
Credits to https://github.com/jacobbrunson/BasicLighting/blob/master/src/Main.java#L32-L73
for shadow algo. Credits to that one youtube video for the lighting shader.
*/
void Light::render() {
glEnable(GL_BLEND);
glEnable(GL_STENCIL_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColorMask(false, false, false, false);
glStencilFunc(GL_ALWAYS, 1, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
//glStencilMask(1);
std::vector<DynamicObject*> dynamicObjects = *world->getRenderList()->getDynamicObjects();
std::vector<StaticObject*> staticObjects = *world->getRenderList()->getStaticObjects();
DynamicObject* dynObj;
StaticObject* statObj;
b2Body* body;
b2Shape* shape;
b2Vec2 lightLoc = b2Vec2(x, y);
for (unsigned int i = 0; i < dynamicObjects.size(); i++) {
dynObj = dynamicObjects[i];
body = dynObj->getBody();
for(b2Fixture* f = body->GetFixtureList(); f; f = f->GetNext()) {
shape = f->GetShape();
if(shape->GetType() == b2Shape::e_polygon) {
b2PolygonShape* poly = (b2PolygonShape*)shape;
int count = poly->GetVertexCount();
for(int i = 0; i < count; i++) {
b2Vec2 vertex = poly->GetVertex(i);
vertex = b2Vec2(vertex.x * ratio, vertex.y * ratio);
b2Vec2 nextvertex = poly->GetVertex((i + 1) % count);
nextvertex = b2Vec2(nextvertex.x * ratio, nextvertex.y * ratio);
b2Vec2 edge = nextvertex - vertex;
b2Vec2 normal = b2Vec2(edge.y, -edge.x);
b2Vec2 lightToCurrent = vertex - lightLoc;
if(b2Dot(normal, lightToCurrent) > 0.0f) {
b2Vec2 point1 = vertex + b2Scale(lightToCurrent, 800.0f);
b2Vec2 point2 = vertex + b2Scale(nextvertex - lightLoc, 800.0f);
glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
glBegin(GL_QUADS); {
glVertex2f(vertex.x, vertex.y);
glVertex2f(point1.x, point1.y);
glVertex2f(point2.x, point2.y);
glVertex2f(nextvertex.x, nextvertex.y);
} glEnd();
}
}
}
}
}
for (unsigned int i = 0; i < staticObjects.size(); i++) {
statObj = staticObjects[i];
body = statObj->getBody();
for(b2Fixture* f = body->GetFixtureList(); f; f = f->GetNext()) {
shape = f->GetShape();
if(shape->GetType() == b2Shape::e_polygon) {
b2PolygonShape* poly = (b2PolygonShape*)shape;
int count = poly->GetVertexCount();
for(int i = 0; i < count; i++) {
b2Vec2 vertex = poly->GetVertex(i);
vertex = b2Vec2(vertex.x * ratio, vertex.y * ratio);
b2Vec2 nextvertex = poly->GetVertex((i + 1) % count);
nextvertex = b2Vec2(nextvertex.x * ratio, nextvertex.y * ratio);
b2Vec2 edge = nextvertex - vertex;
b2Vec2 normal = b2Vec2(edge.y, -edge.x);
b2Vec2 lightToCurrent = vertex - lightLoc;
if(b2Dot(normal, lightToCurrent) > 0.0f) {
b2Vec2 point1 = vertex + b2Scale(lightToCurrent, 80.0f);
b2Vec2 point2 = vertex + b2Scale(nextvertex - lightLoc, 80.0f);
float offsetX = body->GetPosition().x * ratio;
float offsetY = body->GetPosition().y * ratio;
glBegin(GL_QUADS); {
glVertex2f(vertex.x + offsetX, vertex.y + offsetY);
glVertex2f(point1.x + offsetX, point1.y + offsetY);
glVertex2f(point2.x + offsetX, point2.y + offsetY);
glVertex2f(nextvertex.x + offsetX, nextvertex.y + offsetY);
} glEnd();
}
}
}
}
}
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glStencilFunc(GL_EQUAL, 0, 1);
glColorMask(true, true, true, true);
glUseProgram(shader);
glUniform2f(glGetUniformLocation(shader,"lightpos"), x, y);
glUniform3f(glGetUniformLocation(shader,"lightColor"), 1.0, 0.0, 1.0);
glUniform1f(glGetUniformLocation(shader,"screenHeight"), windowHeight);
glUniform1f(glGetUniformLocation(shader,"radius"), 10);
glBegin(GL_QUADS); {
glVertex2f(0, 0);
glVertex2f(0, windowHeight);
glVertex2f(windowWidth, windowHeight);
glVertex2f(windowWidth, 0);
} glEnd();
glUseProgram(0);
glClear(GL_STENCIL_BUFFER_BIT);
glDisable(GL_STENCIL_TEST);
glDisable(GL_BLEND);
}
void Light::clean() {
}
} | 31.296296 | 129 | 0.649112 | [
"render",
"object",
"shape",
"vector"
] |
3d1a70d80798bc7385c222baa98ed2b3ac55b7fb | 793 | cpp | C++ | VNOJ/Dynamic_Programming/DP_on_Trees/mtree.cpp | hoanghai1803/CP_Training | 03495a21509fb3ab7fc64674b9a1b0c7d4327ecb | [
"MIT"
] | 4 | 2021-08-25T10:53:32.000Z | 2021-09-30T03:25:50.000Z | VNOJ/Dynamic_Programming/DP_on_Trees/mtree.cpp | hoanghai1803/CP_Training | 03495a21509fb3ab7fc64674b9a1b0c7d4327ecb | [
"MIT"
] | null | null | null | VNOJ/Dynamic_Programming/DP_on_Trees/mtree.cpp | hoanghai1803/CP_Training | 03495a21509fb3ab7fc64674b9a1b0c7d4327ecb | [
"MIT"
] | null | null | null | // Author: __BruteForce__
#include <bits/stdc++.h>
using namespace std;
typedef long long int64;
typedef pair<int, int> ii;
#define MAX_N 100005
#define MOD 1000000007
int n;
vector<ii> adj[MAX_N];
int64 sum[MAX_N], res = 0;
void dfs(int u, int par) {
for (auto e: adj[u]) {
int v = e.first, w = e.second;
if (v == par) continue;
dfs(v, u);
res = (res + (w * sum[v] + w) % MOD * sum[u]) % MOD;
sum[u] = (sum[u] + w * sum[v] + w) % MOD;
}
res = (res + sum[u]) % MOD;
}
int main() {
cin.tie(0)->sync_with_stdio(false);
cin >> n;
for (int i = 1; i < n; i++) {
int u, v, w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
dfs(1, 0);
cout << res << "\n";
} | 19.825 | 60 | 0.48802 | [
"vector"
] |
3d1de0cb8f134e37cbc1b7a3a30b81bcfc9b5c96 | 332 | hpp | C++ | include/awl/cursor/const_optional_object_ref_fwd.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | include/awl/cursor/const_optional_object_ref_fwd.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | include/awl/cursor/const_optional_object_ref_fwd.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | #ifndef AWL_CURSOR_CONST_OPTIONAL_OBJECT_REF_FWD_HPP_INCLUDED
#define AWL_CURSOR_CONST_OPTIONAL_OBJECT_REF_FWD_HPP_INCLUDED
#include <awl/cursor/object_fwd.hpp>
#include <fcppt/optional/reference_fwd.hpp>
namespace awl::cursor
{
using const_optional_object_ref = fcppt::optional::reference<awl::cursor::object const>;
}
#endif
| 22.133333 | 88 | 0.837349 | [
"object"
] |
3d2ad388c658ffb4e4e4bdc5d370b47177a53f59 | 49,873 | cpp | C++ | vlib/ssci/bio/randseq.cpp | syntheticgio/fda-hive | 5e645c6a5b76b5a437635631819a1c934c7fd7fc | [
"Unlicense",
"MIT"
] | null | null | null | vlib/ssci/bio/randseq.cpp | syntheticgio/fda-hive | 5e645c6a5b76b5a437635631819a1c934c7fd7fc | [
"Unlicense",
"MIT"
] | null | null | null | vlib/ssci/bio/randseq.cpp | syntheticgio/fda-hive | 5e645c6a5b76b5a437635631819a1c934c7fd7fc | [
"Unlicense",
"MIT"
] | null | null | null | /*
* ::718604!
*
* Copyright(C) November 20, 2014 U.S. Food and Drug Administration
* Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al
* Affiliation: Food and Drug Administration (1), George Washington University (2)
*
* All rights Reserved.
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <slib/core/def.hpp>
#include <slib/core/dic.hpp>
#include <slib/core/mex.hpp>
#include <slib/core/str.hpp>
#include <slib/core/var.hpp>
#include <slib/std/file.hpp>
#include <slib/std/string.hpp>
#include <ssci/bio/randseq.hpp>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <ctime>
//#define RAND1 (real)rand()/RAND_MAX
#define PROGRESS(items,cur,max,perc) (m_callback && !m_callback(m_callbackParam, items, ((cur) * 1.0 / (max)) * perc, 100))
using namespace slib;
idx sRandomSeq::validate(idx num, idx low, idx high)
{
if( num >= low && (high < 0 ? true : num <= high) ) {
return true;
}
return false;
}
bool sRandomSeq::validate(const char * str)
{
if( sLen(str) != 0 ) {
return true;
}
return false;
}
void sRandomSeq::translateRevComp(idx orientation, bool *isrev, bool *iscomp)
{
switch(orientation) {
case 0:
*isrev = false;
*iscomp = false;
break;
case 1:
*isrev = true;
*iscomp = false;
break;
case 2:
*isrev = false;
*iscomp = true;
break;
case 3:
*isrev = true;
*iscomp = true;
break;
}
}
idx sRandomSeq::preparePrimers()
{
// Understand the primers String and get the sequences separated by 00
sStr temp;
temp.add(primersString.ptr(0), primersString.length());
primersString.cut(0);
sString::searchAndReplaceSymbols(&primersString, temp, 0, ";" sString_symbolsEndline, 0, 0, true, true, false, false);
primersCnt = sString::cnt00(primersString);
return primersCnt;
}
idx sRandomSeq::prepareLowComplexity()
{
// Understand the primers String and get the sequences separated by 00
sStr temp;
temp.add(lowComplexityString.ptr(0), lowComplexityString.length());
lowComplexityString.cut(0);
sString::searchAndReplaceSymbols(&lowComplexityString, temp, 0, ";" sString_symbolsEndline, 0, 0, true, true, false, false);
lowComplexityCnt = sString::cnt00(lowComplexityString);
return lowComplexityCnt;
}
void sRandomSeq::applyNoise(sStr &buf, idx buflen)
{
char *let = buf.ptr(0);
real randNum;
idx j;
for(idx i = 0; i < buflen; ++i) {
if( flipCoin(noisePercentage, 100) ) {
randNum = randDist(0, 100);
idx row = sBioseq::mapATGC[(idx) let[i]];
for(j = 0; j < 4; j++) {
if( (randNum < noiseAccumTable[row][j]) ) {
break;
}
}
if( (j < 4) && (row != j) ) {
let[i] = sBioseq::mapRevATGC[j];
} else if( j == 4 ) {
// Insertion
// memmove (buf.ptr(posinbuf+mutation->mutation.length()), buf.ptr(posinbuf), mutation->mutation.length());
} else if( j == 5 ) {
// Deletion
// memmove (buf.ptr(posinbuf+mutation->mutation.length()), buf.ptr(posinbuf), mutation->mutation.length()); }
}
}
}
}
bool sRandomSeq::addPrimers(sStr &buf, idx buflen)
{
if( flipCoin(primersFreq, 100) ) {
idx getPrimerNum = randDist(0, primersCnt);
const char *primerS = sString::next00(primersString.ptr(), getPrimerNum);
if( !primerS ) {
return false;
}
idx prLen = sLen(primerS);
// Need start and length to put at the beginning of buf
idx primDist = randDist(primersMin, prLen);
if( primDist > buflen ) {
primDist = buflen;
}
idx primStart = randDist(0, prLen - primDist);
// Check that it will not go outbounds;
if( (primDist + primStart) > buflen ) {
primDist = buflen - primStart;
}
strncpy(buf.ptr(0), primerS + primStart, primDist);
return true;
}
return false;
}
// void applyMutations(sStr &buf, sStr &qua, idx buflen, idx irow, idx seqStart, sStr *id)
// {
// idx randAllele = randDist(0, refSeqs[irow].diploidicity) + 1;
// for(idx imut = 0; imut < refSeqs[irow].mutcnt; ++imut) {
// RefMutation * mutation = mutContainer.ptr(refSeqs[irow].rangeseqsOffset + imut);
// if( (seqStart < mutation->position) && (mutation->position < (seqStart + buflen)) ) {
// // Apply mutation based on the frequency and taking into consideration
// // the allele (0 it means that it goes to all strands)
// idx posinbuf = mutation->position - seqStart;
// if( flipCoin(mutation->frequency, 100) && ( (mutation->allele==0) || randAllele == mutation->allele)) {
// if( id ) {
// id->printf(" mut=%" DEC " %c>%c", mutation->position + 1, buf.ptr(posinbuf)[0], mutation->mutation.ptr()[0]);
// }
// if( mutation->mutation.length() > 1 ) {
// // We must move from posinbuf to make space mutation.length() spaces
// memmove(buf.ptr(posinbuf + mutation->mutation.length()), buf.ptr(posinbuf), mutation->mutation.length());
// }
// // Copy
// strncpy(buf.ptr(posinbuf), mutation->mutation.ptr(), mutation->mutation.length());
//// char init=sBioseq::mapRevATGC[(sBioseq::mapATGC[(idx)tt[0]])%4];
//// tt[0]=sBioseq::mapRevATGC[(sBioseq::mapATGC[(idx)tt[0]]+*mut)%4];
// //hdr.printf(" mut=%" DEC "%c>%c",curpos+1,init,tt[0]);
// }
// }
// }
// }
int sRandomSeq::applySortMutations(sStr &buf, sStr &qua, idx buflen, idx irow, idx seqStart, sStr *id, idx seqlenDump)
{
idx ploidy = 2;
if (!seqlenDump){
seqlenDump = buflen;
}
if( irow < refSeqs.dim() ) {
ploidy = refSeqs[irow].diploidicity;
}
idx randAllele = randDist(0, ploidy) + 1;
idx posMut = binarySearchMutation(seqStart);
idx mlen;
idx refposoffset = 0; // keeps track of the reference offset for indels
idx blen, restlen;
RefMutation * mutation;
mutation = mutContainer.ptr(mutSortList[posMut]);
idx prevgroupMut = mutation->groupid;
bool coinResult = flipCoin(mutation->frequency, 100);
while( (mutation->refNumSeq == irow) && (seqStart < (mutation->position + refposoffset)) && ((mutation->position + refposoffset) < (seqStart + buflen)) ) {
// Apply mutation based on the frequency and taking into consideration
// the allele (0 it means that it goes to all strands)
idx posinbuf = refposoffset + mutation->position - seqStart;
coinResult = (prevgroupMut == mutation->groupid) ? coinResult : flipCoin(mutation->frequency, 100);
if( coinResult && ((mutation->allele == 0) || (randAllele == mutation->allele)) ) {
blen = buf.length();
if( id && (posinbuf < seqlenDump)) {
id->printf(" mut=%" DEC " %c>%s", mutation->position + 1, buf.ptr(posinbuf)[0], mutationStringContainer.ptr(mutation->mutationOffset));
}
mutation->count++;
mlen = sLen(mutationStringContainer.ptr(mutation->mutationOffset));
if( mlen > 1 ) {
// We must move from posinbuf to make space mutation.length() spaces
restlen = blen - (posinbuf + mlen - 1) - 1;
// memmove(buf.ptr(posinbuf + mlen - 1), buf.ptr(posinbuf), restlen);
const char *src = buf.ptr(posinbuf);
char *dest = buf.ptr(posinbuf+mlen-1);
for (idx imove = restlen-1; 0 <= imove && src[imove] != '\0'; --imove){
dest[imove] = src[imove];
}
refposoffset += (mlen - 1);
}
if( mutationStringContainer.ptr(mutation->mutationOffset)[0] == '-' ) {
// It is a deletion
restlen = blen - (posinbuf + mlen - 1) - 1; // last -1 is to avoid going outbounds
// memmove(buf.ptr(posinbuf), buf.ptr(posinbuf + 1), restlen-1);
const char *src = buf.ptr(posinbuf+1);
char *dest = buf.ptr(posinbuf);
for (idx imove = 0; imove < restlen && src[imove] != '\0'; ++imove){
dest[imove] = src[imove];
}
buf.cut(blen - 1);
refposoffset -= (mlen);
} else {
// Copy
strncpy(buf.ptr(posinbuf), mutationStringContainer.ptr(mutation->mutationOffset), mlen);
// Set qualities according to the mutation
if ((mutation->quality > 0) && (qua.length()>0)){
for(idx i = 0; i < mlen; ++i) {
qua[posinbuf + i] = mutation->quality + 33;
}
}
}
// char init=sBioseq::mapRevATGC[(sBioseq::mapATGC[(idx)tt[0]])%4];
// tt[0]=sBioseq::mapRevATGC[(sBioseq::mapATGC[(idx)tt[0]]+*mut)%4];
//hdr.printf(" mut=%" DEC "%c>%c",curpos+1,init,tt[0]);
} else {
mutation->miss++;
}
++posMut;
if( (posMut == mutContainer.dim()) ) {
break;
}
prevgroupMut = mutation->groupid;
mutation = mutContainer.ptr(mutSortList[posMut]);
}
return 1;
}
bool sRandomSeq::addLowComplexity(sStr &buf, idx buflen)
{
if( flipCoin(lowComplexityFreq, 100) ) {
idx getlowCNum = randDist(0, lowComplexityCnt);
const char *lowCstring = sString::next00(lowComplexityString.ptr(), getlowCNum);
if( !lowCstring ) {
return false;
}
idx lCLen = sLen(lowCstring);
if( lowComplexityMin == -1 ) {
lowComplexityMin = lCLen;
}
if( lowComplexityMax == -1 ) {
lowComplexityMax = lCLen;
}
if( lCLen < lowComplexityMin ) {
return false;
}
// Get the distance from lowComplexityMin and Max (lCLen, lowCompMax)
idx randlowCLen = randDist(lowComplexityMin, lowComplexityMax > lCLen ? lCLen : lowComplexityMax);
if( randlowCLen > buflen ) {
randlowCLen = buflen;
}
idx seqStart = randDist(0, buflen - randlowCLen);
strncpy(buf.ptr(seqStart), lowCstring, randlowCLen);
return true;
}
return false;
}
bool sRandomSeq::printFastXData(sFil * outFile, idx seqlen, const char *seqid, const char *seq, const char *seqqua, idx subrpt)
{
char initChar = seqqua ? '@' : '>';
outFile->printf("%c%s", initChar, seqid);
if( subrpt > 1 ) {
outFile->printf(" H#=%" DEC, subrpt);
}
outFile->printf("\n%.*s\n", (int) seqlen, seq);
if( seqqua ) {
outFile->printf("+\n%.*s\n", (int) seqlen, seqqua);
}
return true;
}
real sRandomSeq::randDist(real rmin, real rmax, void *dist)
{
if( !dist ) {
return rmin + sRand::ran0(&idum) * (rmax - rmin);
}
return 0;
}
bool sRandomSeq::flipCoin(real pr, idx maxValue)
{
bool valid = randDist(0, maxValue) < pr ? true : false;
return valid;
}
const char * sRandomSeq::generateRandString(sStr &auxbuf, idx randlength, idx tabu)
{
auxbuf.cut(0);
if( (tabu != -1) && (randlength == 1) ) {
auxbuf.printf("%c", sBioseq::mapRevATGC[(tabu + (idx) randDist(1, 4)) % 4]);
} else {
for(idx i = 0; i < randlength; ++i) {
auxbuf.printf("%c", sBioseq::mapRevATGC[(idx) randDist(0, 4)]);
}
}
return auxbuf.ptr();
}
sTxtTbl * sRandomSeq::tableParser(const char * tblDataPath, const char * colsep, bool header, idx parseCnt)
{
sFil tblDataFil(tblDataPath);
idx offset = 0;
while( offset < tblDataFil.length() && tblDataFil[offset] == '#' ) {
// skip to next line
while( offset < tblDataFil.length() && tblDataFil[offset] != '\r' && tblDataFil[offset] != '\n' )
offset++;
while( offset < tblDataFil.length() && (tblDataFil[offset] == '\r' || tblDataFil[offset] == '\n') )
offset++;
}
sTxtTbl *tbl = new sTxtTbl();
tbl->borrowFile(&tblDataFil, sFile::time(tblDataPath));
idx flags = sTblIndex::fColsepCanRepeat | sTblIndex::fLeftHeader;
flags |= header ? sTblIndex::fTopHeader : 0;
tbl->parseOptions().flags = flags;
tbl->parseOptions().colsep = colsep ? colsep : " ";
tbl->parseOptions().comment = "#";
tbl->parseOptions().initialOffset = offset;
tbl->parse(); //(flags, " ", "\r\n", "\"", 0, 0, sIdxMax, sIdxMax, 1, 1, offset);
tbl->remapReadonly();
return tbl;
}
void sRandomSeq::addMutation(RefMutation *dst, RefMutation *src, idx pos)
{
memcpy(dst, src, sizeof(RefMutation));
dst->position = pos;
}
bool sRandomSeq::readTableMutations(const char * tblDataPath, sBioseq *sub, sStr *errmsg)
{
// idx filetype = 0; // csv = 0, vcf = 1
bool isHeader = true;
// Row content:
// csv - chrom, Position start, position end, reference, mutation, frequency, quality, zygosity, note
// Note: zygosity (hete = 1 or 2, homo = 0)
// vcf - chrom, position, ID, REF, ALT, QUAL, FILTER, INFO, FORMAT, NA12878
sFilePath flnm3 (tblDataPath, "%%ext");
char default_colsep[] = ",";
if (flnm3.cmp("vcf", 3) == 0){
default_colsep[0] = '\t';
// filetype=1;
isHeader = false;
}
sTxtTbl * table = tableParser(tblDataPath, default_colsep, isHeader, 0);
enum
{
};
idx dimTable = table->rows();
if( dimTable <= 0 ) {
errmsg->printf("Can't open Mutation table file");
return false;
}
mutationStringContainer.cut(0);
idx mutCount = 0;
sStr cbuf;
sStr auxString;
idx irow, icol;
idx endrange;
idx refoffset, mutoffset, zygoffset;
RefMutation mutAux;
for(idx j = 0; j < dimTable; ++j) {
// extract seqpos
cbuf.cut(0);
table->printCell(cbuf, j, -1);
irow = sFilterseq::getrownum(idlist, cbuf.ptr());
if( irow >= 0 && irow < sub->dim() ) {
// table->printCell(cbuf, i, 2);
icol = 0;
RefMutation *mutInfo = &mutAux;
// Read Position Start
mutInfo->position = table->ival(j, icol++) - 1;
// For now, we will ignore the end column position
// Read Position End
endrange = table->ival(j, icol++) - 1;
cbuf.add(0);
// Read Reference
refoffset = cbuf.length();
table->printCell(cbuf, j, icol++);
if (endrange <= 0){
endrange = (mutInfo->position - 1) + (cbuf.length() - refoffset);
}
cbuf.add(0);
// Read mutation
mutoffset = cbuf.length();
table->printCell(cbuf, j, icol++);
mutInfo->refNumSeq = irow;
mutInfo->refLength = 1;
// Read frequency column
mutInfo->frequency = table->ival(j, icol);
if (mutInfo->frequency > 100){
mutInfo->frequency = -1;
}
icol++;
// Read quality
idx qual = table->ival(j, icol);
mutInfo->quality = (qual == -1) ? (idx) randDist(quaMinValue, quaMaxValue) : 0;
icol++;
cbuf.add(0);
// Read Zygosity
zygoffset = cbuf.length();
table->printCell(cbuf, j, icol++);
const char *zygo = cbuf.ptr(zygoffset);
idx heterohomozygous = 0; // -1 is heterozygous, 0 is not determined and 1 is homozygous
if ((zygo && *zygo) && isdigit(zygo[0]) ) {
mutInfo->allele = atoidx(zygo);
if (mutInfo->allele > 10){
mutInfo->allele = 0;
}
}
else {
mutInfo->allele = 0; // default
}
if( (zygo && *zygo) && !isdigit(zygo[0]) ) {
// It is either 'hete' OR 'homo' zygous
auxString.cut(0);
sString::changeCase(&auxString, zygo, sMin(sLen(zygo), (idx)4), sString::eCaseLo);
if( strncmp(auxString.ptr(0), "hete", 4) == 0 ) {
heterohomozygous = -1;
} else if( strncmp(auxString.ptr(0), "homo", 4) == 0 ) {
heterohomozygous = 1;
}
}
if (heterohomozygous == 0){
// Check the last column and look for "d1/d2",
// if d1 == d2 it will be homozygous
// if d1 != d2 it will be heterozygous
idx lastColumn = table->cols() - 1;
const char *cell = table->printCell(cbuf, j, lastColumn);
if (cell && (sLen(cell) > 3) && cell[1] == '/'){
if (cell[0] != cell[2]){
heterohomozygous = -1;
}
else {
heterohomozygous = 1;
}
}
}
if (mutInfo->frequency < 0 ){
if( heterohomozygous == -1 ) {
mutInfo->frequency = (idx) randDist(50, 100);
if (mutInfo->allele == 0){
mutInfo->allele = (idx) randDist(0, 2) + 1; // either 1 or 2
}
} else {
mutInfo->frequency = (idx) randDist(75, 100);
mutInfo->allele = 0;
}
}
mutInfo->mutBiasStart = 0;
mutInfo->mutBiasEnd = 0;
mutInfo->groupid = mutCount;
char *charmut = cbuf.ptr(mutoffset);
idx pos, ipos = 0;
// validate the mutation
for ( idx is=0; charmut[is] != 0; ++is) {
unsigned char let = sBioseq::mapATGC[(idx)(charmut[is])];
if(let == 0xFF) {
charmut[is] = 0;
break;
}
}
for(pos = mutInfo->position; pos <= (endrange); ++pos, ++ipos) {
if( !*charmut ) {
charmut--;
*charmut = '-';
}
RefMutation *mut = mutContainer.add(1);
*mut = *mutInfo; // operator '=' is overloaded
mut->position = pos;
mut->refBase = 0; //*cbuf.ptr(refoffset+ipos);
mut->mutationOffset = mutationStringContainer.length();
mut->count = 0;
mut->miss = 0;
if( pos == endrange ) {
mutationStringContainer.printf("%s", charmut);
} else {
mutationStringContainer.printf("%c", *charmut);
}
mutationStringContainer.add0();
++charmut;
++mutCount;
}
}
}
// mutContainer.resize(mutCount);
if( mutCount != 0 ) {
inSilicoFlags |= eSeqMutations;
}
delete table;
return true;
}
// Ascendent Order:
// 1, if i1 is better than i2
// -1, if i2 is better than i1
idx sRandomSeq::mutationComparator(sRandomSeq * myThis, void * arr, udx i1, udx i2)
{
idx fit1 = myThis->mutContainer[i1].position;
idx fit2 = myThis->mutContainer[i2].position;
if( fit1 > fit2 ) {
return 1;
} else if( fit1 < fit2 ) {
return -1;
}
return 0;
}
idx sRandomSeq::binarySearch(real * array, idx num, real target, bool returnIndexbeforeTarget)
{
idx lo = 0, mid = 0, hi = num - 1;
real aux;
while( lo <= hi ) {
mid = lo + (hi - lo) / 2;
aux = array[mid];
if( aux == target ) {
break;
} else if( aux < target ) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
while( returnIndexbeforeTarget && (mid > 0) && (array[mid] >= target) ) {
mid -= 1;
}
return mid;
}
idx sRandomSeq::binarySearchMutation(idx target)
{
// Find in mutSortList the position
idx lo = 0, mid = 0, hi = mutSortList.dim() - 1;
idx aux;
while( lo <= hi ) {
mid = lo + (hi - lo) / 2;
aux = mutContainer[mutSortList[mid]].position;
if( aux == target ) {
break;
} else if( aux < target ) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if( (mid < mutSortList.dim() - 1) && (mutContainer[mutSortList[mid]].position < target) ) {
mid += 1;
}
while( (mid > 0) && (mutContainer[mutSortList[mid-1]].position >= target) ) {
mid -= 1;
}
return mid;
}
bool sRandomSeq::mutationCSVoutput(sFil *out, sBioseq &sub, sStr &err)
{
// Print the header
out->printf("id, position start, position end, reference, variation, frequency, quality, allele, bias_start, bias_end, count, miss\n");
idx irow;
for(idx imut = 0; imut < mutContainer.dim(); ++imut) {
RefMutation * mutation = mutContainer.ptr(imut);
if( !mutation ) {
err.printf("error while reading mutation vector");
return false;
}
irow = mutation->refNumSeq;
out->printf("\"%s\",%" DEC ",%" DEC ",%c,%s,%" DEC ",%" DEC ",%" DEC ",%" DEC ",%" DEC ",%" DEC ",%" DEC "\n", sub.id(irow), mutation->position + 1, mutation->position + 1, mutation->refBase, mutationStringContainer.ptr(mutation->mutationOffset), mutation->frequency,
mutation->quality, mutation->allele, mutation->mutBiasStart, mutation->mutBiasEnd, mutation->count, mutation->miss);
}
return true;
}
bool sRandomSeq::mutationVCFoutput(sFil *out, const char *refID, sBioseq &sub, sStr &err)
{
// Print the header
time_t t = time(0); // Current time
tm * now = localtime(&t); // Use the simple tm structure
idx threshold = 10;
out->printf("##fileformat=VCFv4.2\n"
"##fileDate=%d%d%d\n"
"##source=HIVE\n", (now->tm_year + 1900), (now->tm_mon + 1), now->tm_mday);
out->printf("##reference=%s\n", refID);
out->printf(
// "##INFO=<ID=AC,Number=.,Type=Integer,Description=\"Allele count in genotypes, for each ALT allele, in the same order as listed\">\n"
"##INFO=<ID=AF,Number=.,Type=Float,Description=\"Allele Frequency\">\n"
// "##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Read Depth\">\n"
// "##INFO=<ID=CG,Number=1,Type=Integer,Description=\"Consensus Genotype\">\n"
"##FILTER=<ID=PASS,Description=\"Coverage Threshold level of at least %" DEC "\">\n"
"#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n", threshold);
sStr info;
idx irow;
for(idx imut = 0; imut < mutContainer.dim(); ++imut) {
RefMutation * mutation = mutContainer.ptr(imut);
if( !mutation ) {
err.printf("error while reading mutation vector");
return false;
}
irow = mutation->refNumSeq;
info.printf(0, "AF=%" DEC, mutation->frequency);
out->printf("%s\t%" DEC "\t%s\t%c\t%s\t%" DEC "\tPASS\t%s\n", sub.id(irow), mutation->position + 1, sub.id(irow), mutation->refBase, mutationStringContainer.ptr(mutation->mutationOffset), mutation->quality, info.ptr());
}
return true;
}
bool sRandomSeq::normalizeTable()
{
idx irow = 5, jcol = 6;
real sum;
for(idx i = 0; i < irow; ++i) {
sum = 0;
for(idx j = 0; j < jcol; ++j) {
sum += noiseOriginalTable[i][j];
}
if( sum == 0 ) {
return false;
}
noiseAccumTable[i][0] = (noiseOriginalTable[i][0] * 100) / sum;
for(idx j = 1; j < jcol; ++j) {
noiseAccumTable[i][j] = noiseAccumTable[i][j - 1] + (noiseOriginalTable[i][j] * 100) / sum;
}
}
return true;
}
bool sRandomSeq::noiseDefaults ()
{
noiseOriginalTable[0][0] = 1;
noiseOriginalTable[0][1] = 1;
noiseOriginalTable[0][2] = 1;
noiseOriginalTable[0][3] = 1;
noiseOriginalTable[0][4] = 0;
noiseOriginalTable[0][5] = 0;
noiseOriginalTable[1][0] = 1;
noiseOriginalTable[1][1] = 1;
noiseOriginalTable[1][2] = 1;
noiseOriginalTable[1][3] = 1;
noiseOriginalTable[1][4] = 0;
noiseOriginalTable[1][5] = 0;
noiseOriginalTable[2][0] = 1;
noiseOriginalTable[2][1] = 1;
noiseOriginalTable[2][2] = 1;
noiseOriginalTable[2][3] = 1;
noiseOriginalTable[2][4] = 0;
noiseOriginalTable[2][5] = 0;
noiseOriginalTable[3][0] = 1;
noiseOriginalTable[3][1] = 1;
noiseOriginalTable[3][2] = 1;
noiseOriginalTable[3][3] = 1;
noiseOriginalTable[3][4] = 1;
noiseOriginalTable[3][5] = 1;
noiseOriginalTable[4][0] = 1;
noiseOriginalTable[4][1] = 1;
noiseOriginalTable[4][2] = 1;
noiseOriginalTable[4][3] = 1;
noiseOriginalTable[4][4] = 0;
noiseOriginalTable[4][5] = 0;
return true;
}
bool sRandomSeq::loadParticularAttributes (sVar &options, sStr *err, sBioseq &qry, bool useMutFile, bool useIonAnnot)
{
inSilicoFlags |= eSeqPrintRandomReads;
idx format=1;
sString::xscanf(options.value("outformat", 0),"%n=0^0^fasta^1^fq^fastq", &format);
inSilicoFlags |= (format < 2) ? eSeqFastA : eSeqFastQ;
sString::xscanf(options.value("showId", 0),"%n=0^0^false^off^no^1^true^on^yes", &format);
inSilicoFlags |= (format < 4) ? eSeqNoId : 0;
numReads = options.ivalue("numReads", 1000);
if( !validate(numReads, 1, -1) ) {
err->printf("Invalid number of Reads");
return false;
}
minLength = options.ivalue("minLen", 100);
maxLength = options.ivalue("maxLen", 100);
lengthDistributionType = 0;
if( minLength > maxLength ) {
err->printf("Minimum length must be greater than Maximum Length");
return false;
}
if( !validate(minLength, 0, -1) && !validate(maxLength, 0, -1) ) {
err->printf("Invalid length");
return false;
}
lowComplexityMin = 0;
lowComplexityMax = 0;
lowComplexityFreq = 0;
primersMin = 0;
primersFreq = 0;
strandedness = options.ivalue("strand", 2);
idx pairedEnd = options.boolvalue("pairedEnd", 0);
if( pairedEnd ) {
minPEread = options.ivalue("pEndmin", 100);
maxPEread = options.ivalue("pEndmax", 500);
if( minPEread < minLength ) {
// err->printf("Please check your Paired end inputs, minimum Paired End (%" DEC " < minimum Length %" DEC ")", minPEread, minLength);
minPEread = minLength;
// return false;
}
if( (minPEread < maxPEread) && validate(minPEread, 0, -1) && validate(maxPEread, 0, -1) ) {
inSilicoFlags |= eSeqPrintPairedEnd;
} else {
err->printf("Please check the Paired end inputs, they are invalid");
return false;
}
} else {
minPEread = 0;
maxPEread = 0;
}
quaType = 0;
quaMinValue = options.ivalue("quaMin", 25);
quaMaxValue = options.ivalue("quaMax", 40);
// Filter Low complexity reads
complexityEntropy = options.rvalue("lowCompEntropy", 0);
complexityWindow = options.rvalue("lowCompWindow", 0);
if( complexityWindow && complexityEntropy ) {
inSilicoFlags |= eSeqComplexityFilter;
}
// Filter N Percentage
filterNperc = options.ivalue("filterN", -1);
if( validate(filterNperc, 0, 101) ) {
inSilicoFlags |= eSeqFilterNs;
}
inSilicoFlags |= eSeqPreloadedGenomeFile;
if( useMutFile && (qry.dim() > 0) ) {
qryFileCnt = qry.dim();
inSilicoFlags |= eSeqParseMutationFile;
}
idx randseed = options.ivalue("randSeed");
if( randseed == 0 ) {
// Initialize with rand0
} else {
// use the seed to initialize randomness
// sRand::ran0(&randSeed)
}
noiseDefaults ();
noisePercentage = options.rvalue("noisePerc", 0);
// noisePercentage = 50;
if( noisePercentage > 0 ) {
if( !normalizeTable() ) {
err->printf("error at normalizing noise table");
return false;
}
inSilicoFlags |= eSeqNoise;
}
// Generate Random Mutations
randMutNumber = options.ivalue("randMutations", 0);
if( validate(randMutNumber, 1, -1) ) {
inSilicoFlags |= eSeqGenerateRandomMut;
}
if( useIonAnnot ) { // Use all ranges in the file
useAllAnnotRanges = true;
inSilicoFlags |= eSeqParseAnnotFile;
}
randMutStringLen = 1; // one string mutation
randMutFreq = -1; // Random Frequency
return true;
}
idx sRandomSeq::ionWanderCallback(sIon * ion, sIonWander *ts, sIonWander::StatementHeader * traverserStatement, sIon::RecordResult * curResults)
{
// sVec<RangeSeq> *rs = (sVec<RangeSeq> *) ts->callbackFuncParam;
sRandomSeq *th = (sRandomSeq *) ts->callbackFuncParam;
// char *id, *type;
// idx pos;
idx seqlen;
const char *seqid = 0;
idx pos;
idx irow;
sIO *aux = &(th->auxbuf);
aux->cut(0);
idx ifCut = th->rangeContainer.dim();
if (th->Sub->dim() == 0){
return 0;
}
if( traverserStatement->label[0] == 'a' ) {
RangeSeq *range = th->rangeContainer.add();
sIon::RecordResult * p = curResults + 1; // extract seqID
// seqID|pos|record|type|id
if( p ) {
pos = aux->length();
sIon_outTextBody(aux, p->cType, p->body, p->size);
aux->add0();
seqid = aux->ptr(pos);
// seqid = atoidx(aux->ptr(pos));
}
p = curResults + 2; // extract pos
if( p ) {
range->sourceStartRange = (idx) (((int *) (p->body))[1]) - 1;
range->sourceEndRange = (idx) (((int *) (p->body))[0]) - 1;
}
p = curResults + 5; // extract id
if( p ) {
pos = aux->length();
sIon_outTextBody(aux, p->cType, p->body, p->size);
aux->add0();
// id = aux->ptr(pos);
}
p = curResults + 4; // extract type
if( p ) {
pos = aux->length();
sIon_outTextBody(aux, p->cType, p->body, p->size);
aux->add0();
// type = aux->ptr(pos);
}
irow = sFilterseq::getrownum(th->idlist, seqid);
if( (irow >= 0) && (irow < th->Sub->dim()) ) {
seqlen = th->Sub->len(irow);
// Manipulate the ranges
if( (range->sourceEndRange > 0) && (range->sourceStartRange > range->sourceEndRange) ) {
th->rangeContainer.cut(ifCut);
return 0;
}
if( range->sourceStartRange > seqlen ) {
th->rangeContainer.cut(ifCut);
return 0;
}
if( range->sourceStartRange < 0 ) {
range->sourceStartRange = 0;
}
if( (range->sourceEndRange == -1) || (range->sourceEndRange > seqlen) ) {
range->sourceEndRange = seqlen;
}
range->sourceSeqnum = irow;
range->destSeqnum = -1;
range->hiveseqListOffset = 0; //th->hiveseqListContainer.length();
range->orientation = 0; // Forward
range->coverage = 1;
}
else {
th->rangeContainer.cut(ifCut);
}
// th->hiveseqListContainer.printf("%" DEC ",%" DEC ",%" DEC, seqid, range->startRange, range->endRange);
// th->hiveseqListContainer.add0();
}
return 1;
}
bool sRandomSeq::addAnnotRange (AnnotQuery * annot, sStr &stringContainer, const char *seqid, const char *id, const char *type, idx tandem, idx before, idx after, void *ptr){
const char *notavailable = "na";
bool isValid = false;
if ((seqid == 0) || ( strncmp(seqid, notavailable, 2) == 0)){
annot->seqoffset = -1;
}
else {
annot->seqoffset = stringContainer.length();
stringContainer.add(seqid);
stringContainer.add0();
isValid = true;
}
if ((id == 0) || ( strncmp(id, notavailable, 2) == 0)){
annot->idoffset = -1;
}
else {
annot->idoffset = stringContainer.length();
stringContainer.add(id);
stringContainer.add0();
isValid = true;
}
if ((type == 0) || ( strncmp(type, notavailable, 2) == 0)){
annot->typeoffset = -1;
}
else {
annot->typeoffset = stringContainer.length();
stringContainer.add(type);
stringContainer.add0();
isValid = true;
}
annot->tandem = tandem;
annot->before = before;
annot->after = after;
annot->extraInfo = ptr;
if (ptr){
// Read the ranges and determine if it's valid
// const sUsrObjPropsNode *node = (const sUsrObjPropsNode *)ptr;
// idx start = node->findIValue("inSilicoCNVStartRange", 0);
// idx end = node->findIValue("inSilicoCNVEndRange", 0);
// if (end > start){
// isValid = true;
// }
}
return isValid;
}
bool sRandomSeq::generateQualities(const char *seq, sStr &qua, idx seqlen)
{
char ran;
char *quabuf = qua.add(0, seqlen);
if( quaType == 1 ) {
real a, b, c;
if( inSilicoFlags & eSeqPrintPairedEnd ) {
a = -(real) (quaMaxValue - quaMinValue) / (seqlen * seqlen);
b = 0;
c = quaMaxValue;
} else {
a = -(real) (quaMaxValue - quaMinValue) / (maxLength * maxLength);
b = 0;
c = quaMaxValue;
}
for(idx x = 0; x < seqlen; ++x) {
ran = (a * (x * x) + b * x + c) + randDist(-2, 2);
if( ran < 0 ) {
ran = 0;
}
quabuf[x] = ran + 33;
// qua.printf("%c", ran + 33);
}
} else if( quaType == 2 ) {
// Use the quality from the table
idx rows = qualityTable->rows();
idx irow;
real minQ, maxQ;
char let;
for(idx i = 0; i < seqlen; ++i) {
irow = (i * rows) / seqlen;
let = sBioseq::mapATGC[(idx) seq[i]];
minQ = qualityTable->rval(irow, 4 * let + 0);
maxQ = qualityTable->rval(irow, 4 * let + 2);
ran = randDist(minQ, maxQ);
if( ran < 0 ) {
ran = 0;
}
quabuf[i] = ran + 33;
// qua.printf("%c", ran + 33);
}
} else {
for(idx ll = 0; ll < seqlen; ++ll) {
ran = randDist(quaMinValue, quaMaxValue);
if( ran < 0 ) {
ran = 0;
}
quabuf[ll] = ran + 33;
// qua.printf("%c", ran + 33);
}
}
return true;
}
void sRandomSeq::mutationFillandFix(sBioseq &sub)
{
bool fixMutation;
sStr t;
for(idx imut = 0; imut < mutContainer.dim(); ++imut) {
RefMutation *mutInfo = mutContainer.ptr(imut);
fixMutation = (mutInfo->refBase == -1) ? true : false;
if( mutInfo->refBase <= 0 ) {
// Fill reference Base information
t.cut(0);
sBioseq::uncompressATGC(&t, sub.seq(mutInfo->refNumSeq), mutInfo->position, mutInfo->refLength, true, 0, 0, 0);
mutInfo->refBase = t[0];
}
if( fixMutation ) {
idx mutlen = sLen(mutationStringContainer.ptr(mutInfo->mutationOffset));
// Fix the mutation if it is required
char mutChar = mutationStringContainer.ptr(mutInfo->mutationOffset)[0];
if( (mutlen == 1) && (mutChar != '-') && (mutInfo->refBase == mutChar) ) {
t.cut(0);
generateRandString(t, mutlen, sBioseq::mapATGC[(idx) mutInfo->refBase]);
mutationStringContainer.ptr(mutInfo->mutationOffset)[0] = t[0];
}
}
}
}
bool sRandomSeq::generateRandomMutations(sBioseq &sub, sStr &err)
{
idx mutSize = mutContainer.dim();
idx refcount = 0;
sStr auxbuf, t;
for(idx imut = 0; imut < randMutNumber; ++imut) {
mutContainer.add();
RefMutation *mutInfo = mutContainer.ptr(mutSize + refcount);
mutInfo->refNumSeq = (idx) randDist(0, sub.dim());
mutInfo->position = (idx) randDist(0, sub.len(mutInfo->refNumSeq));
t.cut(0);
sBioseq::uncompressATGC(&t, sub.seq(mutInfo->refNumSeq), mutInfo->position, 1, true, 0, 0, 0);
mutInfo->refBase = t[0];
generateRandString(auxbuf, randMutStringLen, sBioseq::mapATGC[(idx) mutInfo->refBase]);
mutInfo->mutationOffset = mutationStringContainer.length();
mutationStringContainer.addString(auxbuf.ptr(), randMutStringLen);
mutationStringContainer.add0();
mutInfo->frequency = (randMutFreq == -1) ? (idx) randDist(0, 100) : randMutFreq;
mutInfo->quality = (idx) randDist(quaMinValue, quaMaxValue);
mutInfo->allele = 0; //(randallele == -1) ? (idx)randDist(0, 1+nodeEntry->findIValue("inSilicoDiploidicity")): randallele;
mutInfo->mutBiasStart = 0; //nodeMutRow->findIValue("inSilicoMutBiasStart");
mutInfo->mutBiasEnd = 0; //nodeMutRow->findIValue("inSilicoMutBiasEnd");
mutInfo->count = 0;
mutInfo->miss = 0;
++refcount;
}
return true;
}
bool sRandomSeq::launchParser(const char *outFile, const char *srcFile, sVioseq2 &v, sStr &errmsg)
{
// sVioseq2 v;
v.m_callback = m_callback;
v.m_callbackParam = m_callbackParam;
idx parseflags = sVioseq2::eTreatAsFastA | sVioseq2::eParseQuaBit;
idx ires = v.parseSequenceFile(outFile, srcFile, parseflags, 0, 0, 0, 0, 0, 0);
if( ires < 0 ) {
for(idx j = 0; v.listErrors[0].errN != 0; ++j) {
if( v.listErrors[j].errN == ires ) {
errmsg.printf("%s", v.listErrors[j].msg);
return false;
}
}
}
return true;
}
idx sRandomSeq::selectRandRow(real *prob, idx num, real ra)
{
idx ps = 0;
if( !ra ) {
ra = randDist();
}
// // find ra value in prob;
// while( (ra > prob[ps]) && (ps < prob.dim()) ) {
// ++ps;
//
ps = binarySearch(prob, num, ra, true);
return ps;
}
idx sRandomSeq::randomize(sFil *out, sBioseq &sub, sStr &err, sFil *out2, const char * lazyLenPath, sDic<idx> * cntProbabilityInfo)
{
// Calculate probabilities to select each row
idx maxNumberInfiniteLoop = 1000;
sStr id, t, revt;
sStr qua, revqua;
// Sub = ⊂
sVec<real> rowProb(lazyLenPath);
idx subdim = 0;
if( inSilicoFlags & eSeqParseAnnotFile ) {
// Use Ranges
rowProb.resizeM(1+rangeContainer.dim());
subdim = rangeContainer.dim();
rowProb[0] = 0;
// (real) (rangeContainer.ptr(0)->sourceEndRange - rangeContainer.ptr(0)->sourceStartRange) * rangeContainer.ptr(0)->coverage;
for(idx i = 0; i < subdim; ++i) {
rowProb[i+1] = rowProb[i] + ((rangeContainer.ptr(i)->sourceEndRange - rangeContainer.ptr(i)->sourceStartRange) * rangeContainer.ptr(i)->coverage);
}
} else {
// Use sBioseq
rowProb.resizeM(1+sub.dim());
idx refDim = refSeqs.dim();
subdim = sub.dim();
idx coverage = (0 < refDim) ? refSeqs[0].coverage : 1;
rowProb[0] = 0;
//(real) sub.len(0) * coverage;
for(idx i = 0; i < subdim; ++i) {
coverage = (i < refDim) ? refSeqs[i].coverage : 1;
rowProb[i+1] = rowProb[i] + (sub.len(i) * coverage);
}
}
real invAccumLength = 0;
invAccumLength = 1.0 / rowProb[subdim];
for(idx i = 0; i <= subdim; ++i) {
rowProb[i] *= invAccumLength;
}
// Sort the mutations array
if( inSilicoFlags & eSeqMutations ) {
mutSortList.resize(mutContainer.dim());
for(idx i = 0; i < mutContainer.dim(); ++i) {
mutSortList[i] = i;
}
sSort::sortSimpleCallback((sSort::sCallbackSorterSimple) mutationComparator, (void *) this, mutContainer.dim(), mutContainer.ptr(0), mutSortList.ptr(0));
}
idx seqlenDump = 0;
idx seqLen = 0;
idx totLen = 0;
idx iter = 0;
idx countInfiniteLoop = 0;
idx NCount;
idx temppos;
// Start the big loop to generate random reads
real ra = 0;
while( iter < numReads ) {
if( iter % 10000 == 0 ) {
if( PROGRESS(iter, iter, numReads, 100) ) {
err.printf("Process needs to be killed; terminating");
return 0;
}
}
// Select a random row from the File to use
ra = randDist();
idx irowProb = selectRandRow(rowProb.ptr(), rowProb.dim(), ra);
if( irowProb >= subdim || irowProb < 0 ) {
err.printf("random number is out of bounds to select row ID");
return -1;
}
seqLen = seqlenDump = randDist(minLength, maxLength);
if( inSilicoFlags & eSeqPrintPairedEnd ) {
seqLen = randDist(minPEread, maxPEread);
if( seqLen < seqlenDump ) {
seqLen = seqlenDump;
}
}
totLen = seqLen * 2; // add twice the distance to apply deletions in a later step
idx irow = irowProb;
idx seqStart = 0;
// Select the position to generate the random read from the irow
if (inSilicoFlags & eSeqParseAnnotFile){
// irow is the range that we need to use
// We will assume that ranges are valid in the sBioseq
RangeSeq *range = rangeContainer.ptr(irowProb);
irow = range->sourceSeqnum; // use the real irow from sBioseq
if( seqLen > (range->sourceEndRange - range->sourceStartRange) ) {
seqLen = range->sourceEndRange - range->sourceStartRange;
}
seqStart = (idx) randDist(range->sourceStartRange, range->sourceEndRange - seqLen);
if( totLen > (range->sourceEndRange - seqStart) ) {
totLen = range->sourceEndRange - seqStart;
}
}
else {
idx subLen = sub.len(irow);
if( seqLen > subLen ) {
seqLen = subLen;
}
seqStart = (idx) randDist(0, subLen - seqLen);
if( totLen > (seqStart + seqLen) ) {
totLen = seqStart + seqLen;
}
}
if( totLen < minLength ) {
if( countInfiniteLoop > maxNumberInfiniteLoop ) {
err.printf("we couldn't find reads with the specified length");
return 0;
}
++countInfiniteLoop;
continue;
}
//
// Get the output according to the parameters selected
const char * seq = sub.seq(irow);
qua.cut(0);
t.cut(0);
sBioseq::uncompressATGC(&t, seq, seqStart, totLen, true, 0);
// restore N based on quality 0
const char * seqqua = sub.qua(irow);
NCount = 0; // count all Ns in one read
if( seqqua ) {
bool quabit = sub.getQuaBit(irow);
for(idx i = seqStart, pos = 0; i < seqStart + seqLen; ++i, ++pos) {
if( sub.Qua(seqqua, i, quabit) == 0 ) {
t[pos] = 'N';
NCount++;
}
}
}
// Filter N's in the read
if( (inSilicoFlags & eSeqFilterNs) && (NCount > (seqLen * filterNperc / 100)) ) {
if( countInfiniteLoop > maxNumberInfiniteLoop ) {
err.printf("it didn't pass the filter N's stage to generate reads");
return 0;
}
++countInfiniteLoop;
continue;
}
id.printf(0, "%s%s pos=%" DEC " len=%" DEC, prefixID, sub.id(irow), seqStart + 1, seqlenDump);
// 1. Add primers first
if( inSilicoFlags & eSeqPrimers ) {
addPrimers(t, seqLen);
}
// 2. Add low complexity regions
if( inSilicoFlags & eSeqLowComplexity ) {
addLowComplexity(t, seqLen);
}
// 2. Apply General Noise first using the NOISE ARRAY TO ALL POSITIONS
if( inSilicoFlags & eSeqNoise ) {
applyNoise(t, seqLen);
}
// 3. Generate the quality string if necessary
if( inSilicoFlags & eSeqFastQ ) {
generateQualities(t, qua, seqLen);
}
// Change output due to mutations in certain positions
// 4. Apply mutations if necessary
if( inSilicoFlags & eSeqMutations ) {
applySortMutations(t, qua, seqLen, irow, seqStart, &id);
}
if( (inSilicoFlags & eSeqComplexityFilter) && ((temppos = sFilterseq::complexityFilter(t.ptr(), seqLen, complexityWindow, complexityEntropy, false)) != 0) ) {
// It failed the complexity Test
if( countInfiniteLoop > maxNumberInfiniteLoop ) {
err.printf("it didn't pass the complexity test to generate reads");
return 0;
}
++countInfiniteLoop;
continue;
}
countInfiniteLoop = 0;
// Print the output in correct format
if( inSilicoFlags & eSeqPrintPairedEnd ) {
sFil *file1, *file2;
if( flipCoin(0.5) ) {
file1 = out;
file2 = out2;
} else {
file1 = out2;
file2 = out;
}
if( inSilicoFlags & eSeqNoId ) {
id.printf(0, "%" DEC, iter + 1);
} else {
id.printf(" FragLength=%" DEC " Strand=fwd", seqLen);
}
printFastXData(file1, seqlenDump, id, t.ptr(), qua.length() ? qua.ptr() : 0, 1);
// reverse complement the sequence
// Improvement can be made by selecting two letters and exchange the position
// for all of them. And the temporary sStr is not needed
idx revll = seqLen - 1;
// revt.printf(0, "%s", t.ptr());
revt.cut(0);
revt.add(t.ptr(), seqlenDump);
// char * rev = revt.ptr(0);
// char * tt = t.ptr(0);
for(idx ll = 0; ll < seqlenDump; ++ll, --revll) {
revt[ll] = sBioseq::mapRevATGC[sBioseq::mapComplementATGC[sBioseq::mapATGC[(idx) t[revll]]]];
}
if (qua.length()){
revqua.cut(0);
revqua.add(qua.ptr(), seqlenDump);
idx revqlen = qua.length() - 1;
for(idx ll = 0; ll < seqlenDump; ++ll, --revqlen) {
revqua[ll] = qua[revqlen];
}
}
if( inSilicoFlags & eSeqNoId ) {
id.printf(0, "%" DEC, iter + 1);
} else {
id.cut(id.length() - 3);
id.addString("rev");
}
printFastXData(file2, seqlenDump, id, revt.ptr(), qua.length() ? revqua.ptr() : 0, 1);
} else {
// Apply Reverse Complement or Reverse due to strandedness
if( strandedness == 1 || (strandedness == 2 && (randDist() < 0.5)) ) {
// reverse complement the sequence
// Improvement can be made by selecting two letters and exchange the position
// for all of them. And the temporary sStr is not needed
id.printf(" Strand=rev");
idx revll = seqLen - 1;
revt.printf(0, "%s", t.ptr());
char * rev = revt.ptr(0);
char * tt = t.ptr(0);
for(idx ll = 0; ll < seqLen; ++ll, --revll) {
tt[ll] = sBioseq::mapRevATGC[sBioseq::mapComplementATGC[sBioseq::mapATGC[(idx) rev[revll]]]];
}
} else {
id.printf(" Strand=fwd");
}
if( inSilicoFlags & eSeqNoId ) {
id.printf(0, "%" DEC, iter + 1);
}
printFastXData(out, seqLen, id, t.ptr(), qua.length() ? qua.ptr() : 0, 1);
}
// Report into the dictionary if is asked
if( cntProbabilityInfo ) {
idx * unCnt = cntProbabilityInfo->get(&irowProb, sizeof(idx));
if( !unCnt ) {
unCnt = cntProbabilityInfo->set(&irowProb, sizeof(idx));
*unCnt = 0;
};
(*unCnt) = (*unCnt) + 1;
}
++iter;
}
return iter;
}
| 36.113686 | 275 | 0.536603 | [
"vector"
] |
3d31c4c60ff5a10098f5ebf9e6d9292a03b852ee | 85,426 | cpp | C++ | drivers/ksfilter/ks/shmisc.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | drivers/ksfilter/ks/shmisc.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | drivers/ksfilter/ks/shmisc.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (C) Microsoft Corporation, 1998 - 1999
Module Name:
shmisc.cpp
Abstract:
This module contains miscellaneous functions for the kernel streaming
filter .
Author:
Dale Sather (DaleSat) 31-Jul-1998
--*/
#include "ksp.h"
#include <kcom.h>
#ifdef ALLOC_DATA_PRAGMA
#pragma const_seg("PAGECONST")
#endif // ALLOC_DATA_PRAGMA
#ifdef ALLOC_PRAGMA
#pragma code_seg("PAGE")
#endif // ALLOC_PRAGMA
NTSTATUS
KspCreate(
IN PIRP Irp,
IN ULONG CreateItemsCount,
IN const KSOBJECT_CREATE_ITEM* CreateItems OPTIONAL,
IN const KSDISPATCH_TABLE* DispatchTable,
IN BOOLEAN RefParent,
IN PKSPX_EXT Ext,
IN PLIST_ENTRY SiblingListHead,
IN PDEVICE_OBJECT TargetDevice
)
/*++
Routine Description:
This routine performs generic processing relating to a create IRP. If
this function fails, it always cleans up by redispatching the IRP through
the object's close dispatch. The IRP will also get dispatched through
the close dispatch if the client pends the IRP and fails it later. This
allows the caller (the specific object) to clean up as required.
Arguments:
Irp -
Contains a pointer to the create IRP.
CreateItemsCount -
Contains a count of the create items for the new object. Zero is
permitted.
CreateItems -
Contains a pointer to the array of create items for the new object.
NULL is OK.
DispatchTable -
Contains a pointer to the IRP dispatch table for the new object.
RefParent -
Indicates whether the parent object should be referenced. If this
argument is TRUE and there is no parent object, this routine will
ASSERT.
Ext -
Contains a pointer to a generic extended structure.
SiblingListHead -
The head of the list to which this object should be added. There is
a list entry in *X for this purpose.
TargetDevice -
Contains a pointer to the optional target device. This is associated
with the created object for the purposes of stack depth calculation.
Return Value:
STATUS_SUCCESS, STATUS_PENDING or some indication of failure.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspCreate]"));
PAGED_CODE();
ASSERT(Irp);
ASSERT(DispatchTable);
ASSERT(Ext);
ASSERT(SiblingListHead);
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(Irp);
//
// Optionally reference the parent file object.
//
if (RefParent) {
ASSERT(irpSp->FileObject->RelatedFileObject);
ObReferenceObject(irpSp->FileObject->RelatedFileObject);
}
//
// Enlist in the sibling list.
//
InsertTailList(SiblingListHead,&Ext->SiblingListEntry);
Ext->SiblingListHead = SiblingListHead;
//
// Allocate the header if there isn't one already.
//
PKSIOBJECT_HEADER* fsContext =
(PKSIOBJECT_HEADER*)(irpSp->FileObject->FsContext);
PKSIOBJECT_HEADER objectHeader;
NTSTATUS status;
if (fsContext && *fsContext) {
//
// There already is one.
//
objectHeader = *fsContext;
status = STATUS_SUCCESS;
} else {
status =
KsAllocateObjectHeader(
(KSOBJECT_HEADER*)(&objectHeader),
CreateItemsCount,
const_cast<PKSOBJECT_CREATE_ITEM>(CreateItems),
Irp,
DispatchTable);
if (NT_SUCCESS(status)) {
if (! fsContext) {
//
// Use the header as the context.
//
fsContext = &objectHeader->Self;
irpSp->FileObject->FsContext = fsContext;
}
*fsContext = objectHeader;
} else {
//
// when alloc fails, make it
//
objectHeader = NULL;
}
}
if (NT_SUCCESS(status)) {
//
// Install a pointer to the structure in the object header.
//
objectHeader->Object = PVOID(Ext);
//
// Set the power dispatch function.
//
#if 0
KsSetPowerDispatch(objectHeader,KspDispatchPower,PVOID(Ext));
#endif
//
// Set the target device object if required.
//
if (TargetDevice) {
KsSetTargetDeviceObject(objectHeader,TargetDevice);
}
}
//
// Give the client a chance.
//
if (NT_SUCCESS(status) &&
Ext->Public.Descriptor->Dispatch &&
Ext->Public.Descriptor->Dispatch->Create) {
status = Ext->Public.Descriptor->Dispatch->Create(&Ext->Public,Irp);
}
if (! NT_SUCCESS(status) ) {
//
// If we fail, we clean up by calling the close dispatch function. It is
// prepared to handle failed creates. We set the IRP status to
// STATUS_MORE_PROCESSING_REQUIRED to let the close dispatch know we
// don't want it to complete the IRP. Eventually, the caller will put
// the correct status in the IRP and complete it.
//
Irp->IoStatus.Status = STATUS_MORE_PROCESSING_REQUIRED;
//
// Unfortunately, if the object header creation failed, we cannot
// close. It is the caller's responsibility to cleanup anything
// on this type of failure by detecting a non-successful status
// code returned and a more processing required in the irp status
//
if (objectHeader != NULL)
DispatchTable->Close(irpSp->DeviceObject,Irp);
}
return status;
}
NTSTATUS
KspClose(
IN PIRP Irp,
IN PKSPX_EXT Ext,
IN BOOLEAN DerefParent
)
/*++
Routine Description:
This routine performs generic processing related to a close IRP. It will
also handle completion of failed create IRPs.
Arguments:
Irp -
Contains a pointer to the close IRP requiring processing.
Ext -
Contains a pointer to a generic extended structure.
DerefParent -
Contains an indication of whether or not the parent object should be
dereferenced.
Return Value:
STATUS_SUCCESS or...
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspClose]"));
PAGED_CODE();
ASSERT(Irp);
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(Irp);
//
// Take the control mutex if this is not a filter to synchronize access to
// the object hierarchy. If it is a filter, synchronize access to the
// device-level hierarchy by taking the device mutex.
//
if (Irp->IoStatus.Status != STATUS_MORE_PROCESSING_REQUIRED) {
if (! irpSp->FileObject->RelatedFileObject) {
Ext->Device->AcquireDevice();
}
KeWaitForMutexObject (
Ext->FilterControlMutex,
Executive,
KernelMode,
FALSE,
NULL
);
}
//
// This function gets called synchronously with the dispatching of a close
// IRP, asynchronously when the client is done with a close IRP it has
// marked pending, synchronously with the failure of a create IRP, and
// asynchronously when the client is done with a create IRP it has marked
// pending and subsequently failed. The following test makes sure we are
// doing the first of the four.
//
if ((irpSp->MajorFunction == IRP_MJ_CLOSE) &&
! (irpSp->Control & SL_PENDING_RETURNED)) {
//
// Free all remaining events.
//
KsFreeEventList(
irpSp->FileObject,
&Ext->EventList.ListEntry,
KSEVENTS_SPINLOCK,
&Ext->EventList.SpinLock);
//
// Give the client a chance to clean up.
//
if (Ext->Public.Descriptor->Dispatch &&
Ext->Public.Descriptor->Dispatch->Close) {
NTSTATUS status = Ext->Public.Descriptor->Dispatch->Close(&Ext->Public,Irp);
//
// If the client pends the IRP, we will finish cleaning up when
// the IRP is redispatched for completion.
//
if (status == STATUS_PENDING) {
if (irpSp->FileObject->RelatedFileObject) {
KeReleaseMutex (
Ext->FilterControlMutex,
FALSE
);
} else {
Ext->Device->ReleaseDevice();
}
return status;
} else {
Irp->IoStatus.Status = status;
}
} else {
//
// Indicate a positive outcome.
//
Irp->IoStatus.Status = STATUS_SUCCESS;
}
}
//
// Defect from the sibling list.
//
RemoveEntryList(&Ext->SiblingListEntry);
//
// Release the control mutex if this is not a filter. If it is a filter,
// release the device mutex.
//
if (Irp->IoStatus.Status != STATUS_MORE_PROCESSING_REQUIRED) {
KeReleaseMutex (
Ext->FilterControlMutex,
FALSE
);
if (! irpSp->FileObject->RelatedFileObject) {
Ext->Device->ReleaseDevice();
}
}
//
// Free header and context if they still exist.
//
PKSIOBJECT_HEADER* fsContext =
(PKSIOBJECT_HEADER*)(irpSp->FileObject->FsContext);
if (fsContext) {
if (*fsContext) {
if (fsContext == &(*fsContext)->Self) {
//
// The context is the header. Just free it.
//
KsFreeObjectHeader(KSOBJECT_HEADER(*fsContext));
} else {
//
// The context is the header. Just free it.
//
KsFreeObjectHeader(KSOBJECT_HEADER(*fsContext));
ExFreePool(fsContext);
}
} else {
//
// Just a context...no object header.
//
ExFreePool(fsContext);
}
}
//
// Optionally dereference the parent object.
//
if (DerefParent) {
ASSERT(irpSp->FileObject->RelatedFileObject);
ObDereferenceObject(irpSp->FileObject->RelatedFileObject);
}
return Irp->IoStatus.Status;
}
NTSTATUS
KspDispatchClose(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
/*++
Routine Description:
This routine dispatches close IRPs.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspDispatchClose]"));
PAGED_CODE();
ASSERT(DeviceObject);
ASSERT(Irp);
//
// Get a pointer to the extended public structure.
//
PKSPX_EXT ext = KspExtFromIrp(Irp);
//
// Call the helper.
//
NTSTATUS status = KspClose(Irp,ext,FALSE);
if (status != STATUS_PENDING) {
//
// STATUS_MORE_PROCESSING_REQUIRED indicates we are using the close
// dispatch to synchronously fail a create. The create dispatch
// will do the completion.
//
if (status != STATUS_MORE_PROCESSING_REQUIRED) {
IoCompleteRequest(Irp,IO_NO_INCREMENT);
}
//
// Delete the object.
//
ext->Interface->Release();
}
return status;
}
void
KsWorkSinkItemWorker(
IN PVOID Context
)
/*++
Routine Description:
This routine calls a worker function on a work sink interface.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsWorkSinkItemWorker]"));
PAGED_CODE();
ASSERT(Context);
PIKSWORKSINK(Context)->Work();
}
NTSTATUS
KspRegisterDeviceInterfaces(
IN ULONG CategoriesCount,
IN const GUID* Categories,
IN PDEVICE_OBJECT PhysicalDeviceObject,
IN PUNICODE_STRING RefString,
OUT PLIST_ENTRY ListEntry
)
/*++
Routine Description:
This routine registers device classes based on a list of GUIDs and
creates a list of the registered classes which contains the generated
symbolic link names.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspRegisterDeviceInterfaces]"));
PAGED_CODE();
ASSERT(RefString);
NTSTATUS status = STATUS_SUCCESS;
for(; CategoriesCount--; Categories++) {
//
// Register the device interface.
//
UNICODE_STRING linkName;
status =
IoRegisterDeviceInterface(
PhysicalDeviceObject,
Categories,
RefString,
&linkName);
if (NT_SUCCESS(status)) {
//
// Save the symbolic link name in a list for cleanup.
//
PKSPDEVICECLASS deviceClass =
new(PagedPool,POOLTAG_DEVICEINTERFACE) KSPDEVICECLASS;
if (deviceClass) {
deviceClass->SymbolicLinkName = linkName;
deviceClass->InterfaceClassGUID = Categories;
InsertTailList(
ListEntry,
&deviceClass->ListEntry);
} else {
_DbgPrintF(DEBUGLVL_TERSE,("[KspRegisterDeviceInterfaces] failed to allocate device class list entry"));
RtlFreeUnicodeString(&linkName);
status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
} else {
_DbgPrintF(DEBUGLVL_TERSE,("[KspRegisterDeviceInterfaces] IoRegisterDeviceInterface failed (0x%08x)",status));
break;
}
}
return status;
}
NTSTATUS
KspSetDeviceInterfacesState(
IN PLIST_ENTRY ListHead,
IN BOOLEAN NewState
)
/*++
Routine Description:
This routine sets the state of device interfaces in a list.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspSetDeviceInterfacesState]"));
PAGED_CODE();
ASSERT(ListHead);
NTSTATUS status = STATUS_SUCCESS;
for(PLIST_ENTRY listEntry = ListHead->Flink;
listEntry != ListHead;
listEntry = listEntry->Flink) {
PKSPDEVICECLASS deviceClass = PKSPDEVICECLASS(listEntry);
status = IoSetDeviceInterfaceState(
&deviceClass->SymbolicLinkName,NewState);
}
return status;
}
void
KspFreeDeviceInterfaces(
IN PLIST_ENTRY ListHead
)
/*++
Routine Description:
This routine frees a list of device interfaces.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspFreeDeviceInterfaces]"));
PAGED_CODE();
ASSERT(ListHead);
while (! IsListEmpty(ListHead)) {
PKSPDEVICECLASS deviceClass =
(PKSPDEVICECLASS) RemoveHeadList(ListHead);
RtlFreeUnicodeString(&deviceClass->SymbolicLinkName);
delete deviceClass;
}
}
KSDDKAPI
void
NTAPI
KsAddEvent(
IN PVOID Object,
IN PKSEVENT_ENTRY EventEntry
)
/*++
Routine Description:
This routine adds events to an object's event list.
Arguments:
Object -
Contains a pointer to the object.
EventEntry -
Contains a pointer to the event to be added.
Return Value:
None.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsAddEvent]"));
PAGED_CODE();
ASSERT(Object);
ASSERT(EventEntry);
PKSPX_EXT ext = CONTAINING_RECORD(Object,KSPX_EXT,Public);
ExInterlockedInsertTailList(
&ext->EventList.ListEntry,
&EventEntry->ListEntry,
&ext->EventList.SpinLock);
}
KSDDKAPI
NTSTATUS
NTAPI
KsDefaultAddEventHandler(
IN PIRP Irp,
IN PKSEVENTDATA EventData,
IN OUT PKSEVENT_ENTRY EventEntry
)
/*++
Routine Description:
This routine handles connection event 'add' requests.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[CKsPin::KsDefaultAddEventHandler]"));
PAGED_CODE();
ASSERT(Irp);
ASSERT(EventData);
ASSERT(EventEntry);
//
// Get a pointer to the target object.
//
PKSPX_EXT ext = KspExtFromIrp(Irp);
ExInterlockedInsertTailList(
&ext->EventList.ListEntry,
&EventEntry->ListEntry,
&ext->EventList.SpinLock);
return STATUS_SUCCESS;
}
#ifdef ALLOC_PRAGMA
#pragma code_seg()
#endif // ALLOC_PRAGMA
KSDDKAPI
void
NTAPI
KsGenerateEvents(
IN PVOID Object,
IN const GUID* EventSet OPTIONAL,
IN ULONG EventId,
IN ULONG DataSize,
IN PVOID Data OPTIONAL,
IN PFNKSGENERATEEVENTCALLBACK CallBack OPTIONAL,
IN PVOID CallBackContext OPTIONAL
)
/*++
Routine Description:
This routine generates events.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsGenerateEvents]"));
ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
ASSERT(Object);
PKSPX_EXT ext = CONTAINING_RECORD(Object,KSPX_EXT,Public);
GUID LocalEventSet;
//
// NOTE:
//
// If EventSet is specified, copy it onto the stack. This field will
// be accessed with a spinlock held and is frequently a GUID specified
// through linkage with ksguid.lib. These are all pageconst!
//
if (EventSet)
{
LocalEventSet = *EventSet;
}
//
// Generate all events of the indicated type.
//
if (! IsListEmpty(&ext->EventList.ListEntry))
{
KIRQL oldIrql;
KeAcquireSpinLock(&ext->EventList.SpinLock,&oldIrql);
for(PLIST_ENTRY listEntry = ext->EventList.ListEntry.Flink;
listEntry != &ext->EventList.ListEntry;) {
PKSIEVENT_ENTRY eventEntry =
CONTAINING_RECORD(
listEntry,
KSIEVENT_ENTRY,
EventEntry.ListEntry);
//
// Get next before generating in case the event is removed.
//
listEntry = listEntry->Flink;
//
// Generate the event if...
// ...id matches, and
// ...no set was specified or the set matches, and
// ...no callback was specified or the callback says ok
//
if ((eventEntry->Event.Id == EventId) &&
((! EventSet) ||
IsEqualGUIDAligned(
LocalEventSet,
eventEntry->Event.Set)) &&
((! CallBack) ||
CallBack(CallBackContext,&eventEntry->EventEntry))) {
KsGenerateDataEvent(
&eventEntry->EventEntry,
DataSize,
Data);
}
}
KeReleaseSpinLock(&ext->EventList.SpinLock,oldIrql);
}
}
#ifdef ALLOC_PRAGMA
#pragma code_seg("PAGE")
#endif // ALLOC_PRAGMA
#if 0
NTSTATUS
KspDispatchPower(
IN PVOID Context,
IN PIRP Irp
)
/*++
Routine Description:
This routine dispatches power IRPs, passing control to the client's
handler.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspDispatchPower]"));
PAGED_CODE();
ASSERT(Context);
ASSERT(Irp);
//
// Get a pointer to the extended structure.
//
PKSPX_EXT ext = reinterpret_cast<PKSPX_EXT>(Context);
//
// If there's a client interface, call it.
//
NTSTATUS status = STATUS_SUCCESS;
if (ext->Public.Descriptor->Dispatch &&
ext->Public.Descriptor->Dispatch->Power) {
status = ext->Public.Descriptor->Dispatch->Power(&ext->Public,Irp);
#if DBG
if (status == STATUS_PENDING) {
_DbgPrintF(DEBUGLVL_ERROR,("CLIENT BUG: power management handler returned STATUS_PENDING"));
}
#endif
}
return status;
}
#endif
void
KspStandardConnect(
IN PIKSTRANSPORT NewTransport OPTIONAL,
OUT PIKSTRANSPORT *OldTransport OPTIONAL,
OUT PIKSTRANSPORT *BranchTransport OPTIONAL,
IN KSPIN_DATAFLOW DataFlow,
IN PIKSTRANSPORT ThisTransport,
IN PIKSTRANSPORT* SourceTransport,
IN PIKSTRANSPORT* SinkTransport
)
/*++
Routine Description:
This routine establishes a transport connection.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspStandardConnect]"));
PAGED_CODE();
ASSERT(ThisTransport);
ASSERT(SourceTransport);
ASSERT(SinkTransport);
if (BranchTransport) {
*BranchTransport = NULL;
}
//
// Make sure this object sticks around until we are done.
//
ThisTransport->AddRef();
PIKSTRANSPORT* transport =
(DataFlow & KSPIN_DATAFLOW_IN) ?
SourceTransport :
SinkTransport;
//
// Release the current source/sink.
//
if (*transport) {
//
// First disconnect the old back link. If we are connecting a back
// link for a new connection, we need to do this too. If we are
// clearing a back link (disconnecting), this request came from the
// component we're connected to, so we don't bounce back again.
//
switch (DataFlow) {
case KSPIN_DATAFLOW_IN:
(*transport)->Connect(NULL,NULL,NULL,KSP_BACKCONNECT_OUT);
break;
case KSPIN_DATAFLOW_OUT:
(*transport)->Connect(NULL,NULL,NULL,KSP_BACKCONNECT_IN);
break;
case KSP_BACKCONNECT_IN:
if (NewTransport) {
(*transport)->Connect(NULL,NULL,NULL,KSP_BACKCONNECT_OUT);
}
break;
case KSP_BACKCONNECT_OUT:
if (NewTransport) {
(*transport)->Connect(NULL,NULL,NULL,KSP_BACKCONNECT_IN);
}
break;
}
//
// Now release the old neighbor or hand it off to the caller.
//
if (OldTransport) {
*OldTransport = *transport;
} else {
(*transport)->Release();
}
} else if (OldTransport) {
*OldTransport = NULL;
}
//
// Copy the new source/sink.
//
*transport = NewTransport;
if (NewTransport) {
//
// Add a reference if necessary.
//
NewTransport->AddRef();
//
// Do the back connect if necessary.
//
switch (DataFlow) {
case KSPIN_DATAFLOW_IN:
NewTransport->Connect(ThisTransport,NULL,NULL,KSP_BACKCONNECT_OUT);
break;
case KSPIN_DATAFLOW_OUT:
NewTransport->Connect(ThisTransport,NULL,NULL,KSP_BACKCONNECT_IN);
break;
}
}
//
// Now this object may die if it has no references.
//
ThisTransport->Release();
}
#ifdef ALLOC_PRAGMA
#pragma code_seg()
#endif // ALLOC_PRAGMA
NTSTATUS
KspTransferKsIrp(
IN PIKSTRANSPORT NewTransport,
IN PIRP Irp
)
/*++
Routine Description:
This routine transfers a streaming IRP using the kernel streaming
transport.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspTransferKsIrp]"));
ASSERT(NewTransport);
ASSERT(Irp);
NTSTATUS status;
while (NewTransport) {
PIKSTRANSPORT nextTransport;
status = NewTransport->TransferKsIrp(Irp,&nextTransport);
ASSERT(NT_SUCCESS(status) || ! nextTransport);
NewTransport = nextTransport;
}
return status;
}
void
KspDiscardKsIrp(
IN PIKSTRANSPORT NewTransport,
IN PIRP Irp
)
/*++
Routine Description:
This routine discards a streaming IRP using the kernel streaming
transport.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspDiscardKsIrp]"));
ASSERT(NewTransport);
ASSERT(Irp);
while (NewTransport) {
PIKSTRANSPORT nextTransport;
NewTransport->DiscardKsIrp(Irp,&nextTransport);
NewTransport = nextTransport;
}
}
KSDDKAPI
KSOBJECTTYPE
NTAPI
KsGetObjectTypeFromIrp(
IN PIRP Irp
)
/*++
Routine Description:
This routine returns the object type from an IRP.
Arguments:
Irp -
Contains a pointer to an IRP which must have been sent to a file
object corresponding to a object.
Return Value:
The type of the object.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsGetObjectTypeFromIrp]"));
ASSERT(Irp);
//
// If FileObject == NULL, we assume that they've passed us a device level
// Irp.
//
if (IoGetCurrentIrpStackLocation (Irp)->FileObject == NULL)
return KsObjectTypeDevice;
PKSPX_EXT ext = KspExtFromIrp(Irp);
return KspExtFromIrp(Irp)->ObjectType;
}
KSDDKAPI
PVOID
NTAPI
KsGetObjectFromFileObject(
IN PFILE_OBJECT FileObject
)
/*++
Routine Description:
This routine returns the KS object associated with a file object.
Arguments:
FileObject -
Contains a pointer to the file object.
Return Value:
A pointer to the KS object.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsGetObjectFromFileObject]"));
ASSERT(FileObject);
return PVOID(&KspExtFromFileObject(FileObject)->Public);
}
KSDDKAPI
KSOBJECTTYPE
NTAPI
KsGetObjectTypeFromFileObject(
IN PFILE_OBJECT FileObject
)
/*++
Routine Description:
This routine returns the KS object type associated with a file object.
Arguments:
FileObject -
Contains a pointer to the file object.
Return Value:
The object type.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsGetObjectTypeFromFileObject]"));
ASSERT(FileObject);
return KspExtFromFileObject(FileObject)->ObjectType;
}
#ifdef ALLOC_PRAGMA
#pragma code_seg("PAGE")
#endif // ALLOC_PRAGMA
KSDDKAPI
void
NTAPI
KsAcquireControl(
IN PVOID Object
)
/*++
Routine Description:
This routine acquires the control mutex for an object.
Arguments:
Object -
Contains a pointer to an object.
Return Value:
None.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsAcquireControl]"));
PAGED_CODE();
ASSERT(Object);
PKSPX_EXT ext = CONTAINING_RECORD(Object,KSPX_EXT,Public);
KeWaitForMutexObject (
ext->FilterControlMutex,
Executive,
KernelMode,
FALSE,
NULL
);
}
KSDDKAPI
void
NTAPI
KsReleaseControl(
IN PVOID Object
)
/*++
Routine Description:
This routine releases the control mutex for an object.
Arguments:
Object -
Contains a pointer to an object.
Return Value:
None.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsReleaseControl]"));
PAGED_CODE();
ASSERT(Object);
PKSPX_EXT ext = CONTAINING_RECORD(Object,KSPX_EXT,Public);
KeReleaseMutex (
ext->FilterControlMutex,
FALSE
);
}
KSDDKAPI
PKSDEVICE
NTAPI
KsGetDevice(
IN PVOID Object
)
/*++
Routine Description:
This routine gets the device for any file object.
Arguments:
Object -
Contains a pointer to an object.
Return Value:
A pointer to the device.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsGetDevice]"));
PAGED_CODE();
ASSERT(Object);
PKSPX_EXT ext = CONTAINING_RECORD(Object,KSPX_EXT,Public);
return ext->Device->GetStruct();
}
KSDDKAPI
PUNKNOWN
NTAPI
KsRegisterAggregatedClientUnknown(
IN PVOID Object,
IN PUNKNOWN ClientUnknown
)
/*++
Routine Description:
This routine registers a client unknown for aggregation.
Arguments:
Object -
Contains a pointer to an object.
ClientUnknown -
Contains a pointer to the client's undelegated IUnknown
interface.
Return Value:
The outer unknown for the KS object.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsRegisterAggregatedClientUnknown]"));
PAGED_CODE();
ASSERT(Object);
ASSERT(ClientUnknown);
PKSPX_EXT ext = CONTAINING_RECORD(Object,KSPX_EXT,Public);
if (ext->AggregatedClientUnknown) {
ext->AggregatedClientUnknown->Release();
}
ext->AggregatedClientUnknown = ClientUnknown;
ext->AggregatedClientUnknown->AddRef();
return ext->Interface;
}
KSDDKAPI
PUNKNOWN
NTAPI
KsGetOuterUnknown(
IN PVOID Object
)
/*++
Routine Description:
This routine gets the outer unknown for aggregation.
Arguments:
Object -
Contains a pointer to an object.
Return Value:
The outer unknown for the KS object.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsGetOuterUnknown]"));
PAGED_CODE();
ASSERT(Object);
PKSPX_EXT ext = CONTAINING_RECORD(Object,KSPX_EXT,Public);
return ext->Interface;
}
#if DBG
void
DbgPrintCircuit(
IN PIKSTRANSPORT Transport,
IN CCHAR Depth,
IN CCHAR Direction
)
/*++
Routine Description:
This routine spews a transport circuit.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[DbgPrintCircuit]"));
PAGED_CODE();
ASSERT(Transport);
KSPTRANSPORTCONFIG config;
config.TransportType = 0;
config.IrpDisposition = KSPIRPDISPOSITION_ROLLCALL;
config.StackDepth = Depth;
PIKSTRANSPORT transport = Transport;
while (transport) {
PIKSTRANSPORT next;
PIKSTRANSPORT prev;
transport->SetTransportConfig(&config,&next,&prev);
if (Direction < 0) {
transport = prev;
} else {
transport = next;
}
if (transport == Transport) {
break;
}
}
}
#endif
NTSTATUS
KspInitializeDeviceBag(
IN PKSIDEVICEBAG DeviceBag
)
/*++
Routine Description:
This routine initializes a device bag.
Arguments:
DeviceBag -
Contains a pointer to the bag to be initialized
Return Value:
STATUS_SUCCESS or STATUS_INSUFFICIENT_RESOURCES.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspInitializeDeviceBag]"));
PAGED_CODE();
ASSERT(DeviceBag);
//
// Create and initialize the hash table.
//
KeInitializeMutex(&DeviceBag->Mutex, 0);
DeviceBag->HashTableEntryCount = DEVICEBAGHASHTABLE_INITIALSIZE;
DeviceBag->HashMask = DEVICEBAGHASHTABLE_INITIALMASK;
DeviceBag->HashTable =
new(PagedPool,POOLTAG_DEVICEBAGHASHTABLE)
LIST_ENTRY[DEVICEBAGHASHTABLE_INITIALSIZE];
if (DeviceBag->HashTable) {
PLIST_ENTRY entry = DeviceBag->HashTable;
for (ULONG count = DEVICEBAGHASHTABLE_INITIALSIZE; count--; entry++) {
InitializeListHead(entry);
}
return STATUS_SUCCESS;
} else {
return STATUS_INSUFFICIENT_RESOURCES;
}
}
void
KspTerminateDeviceBag(
IN PKSIDEVICEBAG DeviceBag
)
/*++
Routine Description:
This routine terminates a device bag.
Arguments:
DeviceBag -
Contains a pointer to the bag to be terminated.
Return Value:
None.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspTerminateDeviceBag]"));
PAGED_CODE();
ASSERT(DeviceBag);
if (DeviceBag->HashTable) {
#if DBG
PLIST_ENTRY entry = DeviceBag->HashTable;
for (ULONG count = DEVICEBAGHASHTABLE_INITIALSIZE; count--; entry++) {
ASSERT(IsListEmpty(entry));
}
#endif
delete [] DeviceBag->HashTable;
DeviceBag->HashTable = NULL;
}
}
ULONG
KspRemoveObjectBagEntry(
IN PKSIOBJECTBAG ObjectBag,
IN PKSIOBJECTBAG_ENTRY Entry,
IN BOOLEAN Free
)
/*++
Routine Description:
This routine removes an entry from an object bag, optionally freeing the
item.
Arguments:
ObjectBag -
Contains a pointer to the bag.
Entry -
Contains a pointer to the entry to be removed.
Free -
Contains an indication of whether the item is to be freed if its
reference count reaches zero as a result of the function call.
Return Value:
The number of references to the item prior to the call to this function.
If the return value is 1, there are no more references to the item when
the function call completes.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspRemoveObjectBagEntry]"));
PAGED_CODE();
ASSERT(ObjectBag);
ASSERT(Entry);
PKSIDEVICEBAG_ENTRY deviceBagEntry = Entry->DeviceBagEntry;
RemoveEntryList (&Entry -> ListEntry);
delete Entry;
return KspReleaseDeviceBagEntry(ObjectBag->DeviceBag,deviceBagEntry,Free);
}
void
KspTerminateObjectBag(
IN PKSIOBJECTBAG ObjectBag
)
/*++
Routine Description:
This routine terminates an object bag.
Arguments:
ObjectBag -
Contains a pointer to the bag.
Return Value:
None.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspTerminateObjectBag]"));
PAGED_CODE();
ASSERT(ObjectBag);
if (ObjectBag->HashTable) {
PLIST_ENTRY HashChain = ObjectBag->HashTable;
for (ULONG count = ObjectBag->HashTableEntryCount; count--;
HashChain++) {
while (!IsListEmpty (HashChain)) {
PKSIOBJECTBAG_ENTRY BagEntry = (PKSIOBJECTBAG_ENTRY)
CONTAINING_RECORD (
HashChain->Flink,
KSIOBJECTBAG_ENTRY,
ListEntry
);
KspRemoveObjectBagEntry(ObjectBag,BagEntry,TRUE);
}
}
delete [] ObjectBag->HashTable;
}
}
PKSIDEVICEBAG_ENTRY
KspAcquireDeviceBagEntryForItem(
IN PKSIDEVICEBAG DeviceBag,
IN PVOID Item,
IN PFNKSFREE Free OPTIONAL
)
/*++
Routine Description:
This routine acquires an entry from a device bag.
Arguments:
DeviceBag -
Contains a pointer to the bag from which the entry is to be acquired.
Item -
Contains a pointer to the item.
Free -
Contains an optional pointer to a function to be used to free
the item. If this argument is NULL, the item is freed by
passing it to ExFreePool.
Return Value:
The device entry or NULL if memory could not be allocated for the item.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspAcquireDeviceBagEntryForItem]"));
PAGED_CODE();
ASSERT(DeviceBag);
ASSERT(Item);
KeWaitForMutexObject (
&DeviceBag->Mutex,
Executive,
KernelMode,
FALSE,
NULL
);
//
// Look for the entry in the hash table.
//
PLIST_ENTRY listHead =
&DeviceBag->HashTable[KspDeviceBagHash(DeviceBag,Item)];
PKSIDEVICEBAG_ENTRY deviceEntry = NULL;
for(PLIST_ENTRY listEntry = listHead->Flink;
listEntry != listHead;
listEntry = listEntry->Flink) {
PKSIDEVICEBAG_ENTRY entry =
CONTAINING_RECORD(listEntry,KSIDEVICEBAG_ENTRY,ListEntry);
if (entry->Item == Item) {
_DbgPrintF(DEBUGLVL_VERBOSE,("[KspAcquireDeviceBagEntryForItem] new reference to old item %p",Item));
entry->ReferenceCount++;
deviceEntry = entry;
break;
}
}
if (! deviceEntry) {
//
// Allocate a new entry and add it to the list.
//
deviceEntry =
new(PagedPool,POOLTAG_DEVICEBAGENTRY) KSIDEVICEBAG_ENTRY;
if (deviceEntry) {
_DbgPrintF(DEBUGLVL_VERBOSE,("[KspAcquireDeviceBagEntryForItem] new item %p",Item));
InsertHeadList(listHead,&deviceEntry->ListEntry);
deviceEntry->Item = Item;
deviceEntry->Free = Free;
deviceEntry->ReferenceCount = 1;
}
}
KeReleaseMutex (
&DeviceBag->Mutex,
FALSE
);
return deviceEntry;
}
ULONG
KspReleaseDeviceBagEntry(
IN PKSIDEVICEBAG DeviceBag,
IN PKSIDEVICEBAG_ENTRY DeviceBagEntry,
IN BOOLEAN Free
)
/*++
Routine Description:
This routine acquires an entry from a device bag.
Arguments:
DeviceBag -
Contains a pointer to the bag from which the entry is to be released.
DeviceBagEntry -
Contains a pointer to the entry to be released.
Free -
Contains an indication of whether the item should be freed if it has
no other references.
Return Value:
The number of references to the entry prior to release. A reference count
of 1 indicates that the call to this function released the last reference
to the entry.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspReleaseDeviceBagEntry]"));
PAGED_CODE();
ASSERT(DeviceBag);
ASSERT(DeviceBagEntry);
KeWaitForMutexObject (
&DeviceBag->Mutex,
Executive,
KernelMode,
FALSE,
NULL
);
ULONG referenceCount = DeviceBagEntry->ReferenceCount--;
if (referenceCount == 1) {
if (Free) {
_DbgPrintF(DEBUGLVL_VERBOSE,("[KspReleaseDeviceBagEntry] freeing %p",DeviceBagEntry->Item));
if (DeviceBagEntry->Free) {
DeviceBagEntry->Free(DeviceBagEntry->Item);
} else {
ExFreePool(DeviceBagEntry->Item);
}
RemoveEntryList(&DeviceBagEntry->ListEntry);
delete DeviceBagEntry;
}
}
KeReleaseMutex (
&DeviceBag->Mutex,
FALSE
);
return referenceCount;
}
PKSIOBJECTBAG_ENTRY
KspAddDeviceBagEntryToObjectBag(
IN PKSIOBJECTBAG ObjectBag,
IN PKSIDEVICEBAG_ENTRY DeviceBagEntry
)
/*++
Routine Description:
This routine adds a device bag entry to an object bag.
Arguments:
ObjectBag -
Contains a pointer to the bag.
DeviceBagEntry -
Contains a pointer to the device bag entry to be added.
Return Value:
The new object bag entry or NULL if memory could not be allocated to
complete the operation.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspAddDeviceBagEntryToObjectBag]"));
PAGED_CODE();
ASSERT(ObjectBag);
ASSERT(DeviceBagEntry);
//
// Allocate a new entry and add it to the list.
//
PKSIOBJECTBAG_ENTRY objectEntry =
new(PagedPool,POOLTAG_OBJECTBAGENTRY) KSIOBJECTBAG_ENTRY;
if (! objectEntry) {
return NULL;
}
if (! ObjectBag->HashTable) {
ObjectBag->HashTable =
new(PagedPool,POOLTAG_OBJECTBAGHASHTABLE)
LIST_ENTRY[OBJECTBAGHASHTABLE_INITIALSIZE];
if (! ObjectBag->HashTable) {
delete objectEntry;
return NULL;
} else {
PLIST_ENTRY HashChain = ObjectBag->HashTable;
for (ULONG i = OBJECTBAGHASHTABLE_INITIALSIZE; i;
i--, HashChain++) {
InitializeListHead (HashChain);
}
}
}
//
// Find the hash table entry.
//
PLIST_ENTRY HashChain =
&(ObjectBag->
HashTable[KspObjectBagHash(ObjectBag,DeviceBagEntry->Item)]);
objectEntry->DeviceBagEntry = DeviceBagEntry;
InsertHeadList (HashChain, &(objectEntry->ListEntry));
return objectEntry;
}
KSDDKAPI
NTSTATUS
NTAPI
KsAddItemToObjectBag(
IN KSOBJECT_BAG ObjectBag,
IN PVOID Item,
IN PFNKSFREE Free OPTIONAL
)
/*++
Routine Description:
This routine adds an item to an object bag.
Arguments:
ObjectBag -
Contains a pointer to the bag to which the item is to be added.
Item -
Contains a pointer to the item to be added.
Free -
Contains an optional pointer to a function to be used to free
the item. If this argument is NULL, the item is freed by
passing it to ExFreePool.
Return Value:
STATUS_SUCCESS or STATUS_INSUFFICIENT_RESOURCES.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsAddItemToObjectBag]"));
PAGED_CODE();
ASSERT(ObjectBag);
ASSERT(Item);
_DbgPrintF(DEBUGLVL_VERBOSE,("KsAddItemToObjectBag %p item=%p",ObjectBag,Item));
PKSIOBJECTBAG bag = reinterpret_cast<PKSIOBJECTBAG>(ObjectBag);
NTSTATUS Status = STATUS_SUCCESS;
KeWaitForSingleObject (
bag->Mutex,
Executive,
KernelMode,
FALSE,
NULL
);
PKSIDEVICEBAG_ENTRY deviceBagEntry =
KspAcquireDeviceBagEntryForItem(bag->DeviceBag,Item,Free);
if (! deviceBagEntry) {
Status = STATUS_INSUFFICIENT_RESOURCES;
}
else if (! KspAddDeviceBagEntryToObjectBag(bag,deviceBagEntry)) {
KspReleaseDeviceBagEntry(bag->DeviceBag,deviceBagEntry,FALSE);
Status = STATUS_INSUFFICIENT_RESOURCES;
}
KeReleaseMutex (
bag->Mutex,
FALSE
);
return Status;
}
PKSIOBJECTBAG_ENTRY
KspFindObjectBagEntry(
IN PKSIOBJECTBAG ObjectBag,
IN PVOID Item
)
/*++
Routine Description:
This routine finds an entry in an object bag.
Arguments:
ObjectBag -
Contains a pointer to the bag.
Item -
Contains a pointer to the item to be found.
Return Value:
A pointer to the entry, or NULL if the item was not found in
the bag. This value, when not NULL, is suitable for submission to
KspRemoveObjectBagEntry.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspFindObjectBagEntry]"));
PAGED_CODE();
ASSERT(ObjectBag);
ASSERT(Item);
if (ObjectBag->HashTable) {
//
// Start at the hash table entry.
//
PLIST_ENTRY HashChain =
&(ObjectBag->HashTable[KspObjectBagHash(ObjectBag,Item)]);
//
// Find the end of the list, bailing out if the item is found.
//
for (PLIST_ENTRY Entry = HashChain -> Flink;
Entry != HashChain;
Entry = Entry -> Flink) {
PKSIOBJECTBAG_ENTRY BagEntry = (PKSIOBJECTBAG_ENTRY)
CONTAINING_RECORD (
Entry,
KSIOBJECTBAG_ENTRY,
ListEntry
);
if (BagEntry -> DeviceBagEntry -> Item == Item) {
return BagEntry;
}
}
}
return NULL;
}
KSDDKAPI
ULONG
NTAPI
KsRemoveItemFromObjectBag(
IN KSOBJECT_BAG ObjectBag,
IN PVOID Item,
IN BOOLEAN Free
)
/*++
Routine Description:
This routine removes an item from an object bag.
Arguments:
ObjectBag -
Contains a pointer to the bag from which the item is to be removed.
Item -
Contains a pointer to the item to be removed.
Free -
Contains an indication of whether the item should be freed if it has
no other references.
Return Value:
The number of references to the item prior to removal. A reference count
of 0 indicates that the item was not in the bag. A reference count of 1
indicates that the call to this function removed the last reference to
item, and there is no longer any object bag associated with the device
bag which contains an entry for the item.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsRemoveItemFromObjectBag]"));
PAGED_CODE();
_DbgPrintF(DEBUGLVL_VERBOSE,("KsRemoveItemFromObjectBag %p item=%p",ObjectBag,Item));
ASSERT(ObjectBag);
ASSERT(Item);
PKSIOBJECTBAG bag = reinterpret_cast<PKSIOBJECTBAG>(ObjectBag);
ULONG RefCount = 0;
KeWaitForSingleObject (
bag->Mutex,
Executive,
KernelMode,
FALSE,
NULL
);
PKSIOBJECTBAG_ENTRY Entry = KspFindObjectBagEntry(bag,Item);
if (Entry) {
RefCount = KspRemoveObjectBagEntry(bag,Entry,Free);
}
KeReleaseMutex (
bag->Mutex,
FALSE
);
return RefCount;
}
KSDDKAPI
NTSTATUS
NTAPI
KsCopyObjectBagItems(
IN KSOBJECT_BAG ObjectBagDestination,
IN KSOBJECT_BAG ObjectBagSource
)
/*++
Routine Description:
This routine copies all the items in a bag into another bag.
Arguments:
ObjectBagDestination -
Contains the bag into which items will be copied.
ObjectBagSource -
Contains the bag from which items will be copied.
Return Value:
Status.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsCopyObjectBagItems]"));
_DbgPrintF(DEBUGLVL_VERBOSE,("KsCopyObjectBagItems to %p from %p",ObjectBagDestination,ObjectBagSource));
PAGED_CODE();
ASSERT(ObjectBagDestination);
ASSERT(ObjectBagSource);
PKSIOBJECTBAG bagSource = reinterpret_cast<PKSIOBJECTBAG>(ObjectBagSource);
PKSIOBJECTBAG bagDestination =
reinterpret_cast<PKSIOBJECTBAG>(ObjectBagDestination);
NTSTATUS status = STATUS_SUCCESS;
PKMUTEX FirstMutex, SecondMutex;
//
// FULLMUTEX:
//
// Guarantee that the order we grab mutexes is such that any bag with
// MutexOrder marked as TRUE has its mutex taken before any bag with
// MutexOrder marked as FALSE.
//
if (bagSource->MutexOrder) {
FirstMutex = bagSource->Mutex;
SecondMutex = bagDestination->Mutex;
}
else {
FirstMutex = bagDestination->Mutex;
SecondMutex = bagSource->Mutex;
}
KeWaitForSingleObject (
FirstMutex,
Executive,
KernelMode,
FALSE,
NULL
);
if (FirstMutex != SecondMutex) {
KeWaitForSingleObject (
SecondMutex,
Executive,
KernelMode,
FALSE,
NULL
);
}
if (bagSource->HashTable) {
PLIST_ENTRY HashChain = bagSource->HashTable;
for (ULONG count = bagSource->HashTableEntryCount; count--;
HashChain++) {
for (PLIST_ENTRY Entry = HashChain -> Flink;
Entry != HashChain;
Entry = Entry -> Flink) {
PKSIOBJECTBAG_ENTRY BagEntry = (PKSIOBJECTBAG_ENTRY)
CONTAINING_RECORD (
Entry,
KSIOBJECTBAG_ENTRY,
ListEntry
);
status =
KsAddItemToObjectBag(
ObjectBagDestination,
BagEntry->DeviceBagEntry->Item,
BagEntry->DeviceBagEntry->Free
);
if (! NT_SUCCESS(status)) {
break;
}
}
}
}
if (FirstMutex != SecondMutex) {
KeReleaseMutex (
SecondMutex,
FALSE
);
}
KeReleaseMutex (
FirstMutex,
FALSE
);
return STATUS_SUCCESS;
}
KSDDKAPI
NTSTATUS
NTAPI
_KsEdit(
IN KSOBJECT_BAG ObjectBag,
IN OUT PVOID* PointerToPointerToItem,
IN ULONG NewSize,
IN ULONG OldSize,
IN ULONG Tag
)
/*++
Routine Description:
This routine insures that an item to be edited is in a specified
object bag.
Arguments:
ObjectBag -
Contains a pointer to the bag in which the item to be edited must be
included.
PointerToPointerToItem -
Contains a pointer to a pointer to the item to be edited. If the item
is not in the bag, OldSize is less than NewSize, or the item is NULL,
*PointerToPointer is modified to point to a new item which is in the
bag and is NewSize bytes long.
NewSize -
Contains the minimum size of the item to be edited. The item will be
replaced with a new copy if OldSize this size.
OldSize -
Contains the size of the old item. This is used to determine how much
data to copy from an old item not in the bag to a new replacement item.
Tag -
Contains the tag to use for new allocations.
Return Value:
STATUS_SUCCESS or STATUS_INSUFFICIENT_RESOURCES.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[_KsEdit]"));
PAGED_CODE();
ASSERT(ObjectBag);
ASSERT(PointerToPointerToItem);
ASSERT(NewSize);
PKSIOBJECTBAG bag = reinterpret_cast<PKSIOBJECTBAG>(ObjectBag);
NTSTATUS Status = STATUS_SUCCESS;
KeWaitForSingleObject (
bag->Mutex,
Executive,
KernelMode,
FALSE,
NULL
);
//
// Find the item in the object bag.
//
PKSIOBJECTBAG_ENTRY entry;
if (*PointerToPointerToItem) {
entry = KspFindObjectBagEntry(bag,*PointerToPointerToItem);
} else {
entry = NULL;
}
if ((! entry) || (NewSize > OldSize)) {
//
// Either the item is not in the bag or it is too small.
//
PVOID newItem = ExAllocatePoolWithTag(PagedPool,NewSize,Tag);
if (! newItem) {
//
// Failed to allocate.
//
Status = STATUS_INSUFFICIENT_RESOURCES;
} else if (! NT_SUCCESS(KsAddItemToObjectBag(ObjectBag,newItem,NULL))) {
//
// Failed to attach.
//
ExFreePool(newItem);
Status = STATUS_INSUFFICIENT_RESOURCES;
} else {
if (*PointerToPointerToItem) {
//
// Copy the old item and zero any growth.
//
if (NewSize > OldSize) {
RtlCopyMemory(newItem,*PointerToPointerToItem,OldSize);
RtlZeroMemory(PUCHAR(newItem) + OldSize,NewSize - OldSize);
} else {
RtlCopyMemory(newItem,*PointerToPointerToItem,NewSize);
}
//
// Detach the old item from the bag.
//
if (entry) {
KspRemoveObjectBagEntry(bag,entry,TRUE);
}
} else {
//
// There is no old item. Zero the new item.
//
RtlZeroMemory(newItem,NewSize);
}
//
// Install the new item.
//
*PointerToPointerToItem = newItem;
}
}
KeReleaseMutex (
bag->Mutex,
FALSE
);
return Status;
}
KSDDKAPI
PVOID
NTAPI
KsGetParent(
IN PVOID Object
)
/*++
Routine Description:
This routine obtains an object's parent object.
Arguments:
Object -
Points to the object structure.
Return Value:
A pointer to the parent object structure.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsGetParent]"));
PAGED_CODE();
ASSERT(Object);
PKSPX_EXT ext = CONTAINING_RECORD(Object,KSPX_EXT,Public);
if (ext->Parent) {
return &ext->Parent->Public;
} else {
return NULL;
}
}
KSDDKAPI
PKSFILTER
NTAPI
KsPinGetParentFilter(
IN PKSPIN Pin
)
/*++
Routine Description:
This routine obtains a filter given a pin.
Arguments:
Pin -
Points to the pin structure.
Return Value:
A pointer to the parent filter structure.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsGetParentFilter]"));
PAGED_CODE();
ASSERT(Pin);
return (PKSFILTER) KsGetParent((PVOID) Pin);
}
KSDDKAPI
PVOID
NTAPI
KsGetFirstChild(
IN PVOID Object
)
/*++
Routine Description:
This routine obtains an object's first child object.
Arguments:
Object -
Points to the object structure.
Return Value:
A pointer to the first child object. NULL is returned if there are no
child objects.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsGetFirstChild]"));
PAGED_CODE();
ASSERT(Object);
PKSPX_EXT ext = CONTAINING_RECORD(Object,KSPX_EXT,Public);
//
// In debug, ensure that the caller has the proper synchronization objects
// held.
//
// NOTE: we shouldn't be called for pins anyway.
//
#if DBG
if (ext -> ObjectType == KsObjectTypeDevice ||
ext -> ObjectType == KsObjectTypeFilterFactory) {
if (!KspIsDeviceMutexAcquired (ext->Device)) {
_DbgPrintF(DEBUGLVL_ERROR,("CLIENT BUG: unsychronized access to object hierarchy - need to acquire device mutex"));
}
}
#endif // DBG
if (IsListEmpty(&ext->ChildList)) {
return NULL;
} else {
return
&CONTAINING_RECORD(ext->ChildList.Flink,KSPX_EXT,SiblingListEntry)->
Public;
}
}
KSDDKAPI
PVOID
NTAPI
KsGetNextSibling(
IN PVOID Object
)
/*++
Routine Description:
This routine obtains an object's next sibling object.
Arguments:
Object -
Points to the object structure.
Return Value:
A pointer to the next sibling object. NULL is returned if there is
no next sibling object.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsGetNextSibling]"));
PAGED_CODE();
ASSERT(Object);
PKSPX_EXT ext = CONTAINING_RECORD(Object,KSPX_EXT,Public);
//
// In debug, ensure that the caller has the proper synchronization objects
// held.
//
#if DBG
if (ext -> ObjectType == KsObjectTypePin) {
if (!KspMutexIsAcquired (ext->FilterControlMutex)) {
_DbgPrintF(DEBUGLVL_ERROR,("CLIENT BUG: unsychronized access to object hierarchy - need to acquire control mutex"));
}
} else {
if (!KspIsDeviceMutexAcquired (ext->Device)) {
_DbgPrintF(DEBUGLVL_ERROR,("CLIENT BUG: unsychronized access to object hierarchy - need to acquire device mutex"));
}
}
#endif // DBG
if (ext->SiblingListEntry.Flink == ext->SiblingListHead) {
return NULL;
} else {
return
&CONTAINING_RECORD(ext->SiblingListEntry.Flink,KSPX_EXT,SiblingListEntry)->
Public;
}
}
KSDDKAPI
PKSPIN
NTAPI
KsPinGetNextSiblingPin(
IN PKSPIN Pin
)
/*++
Routine Description:
This routine obtains a pins's next sibling object.
Arguments:
Pin -
Points to the Pin structure.
Return Value:
A pointer to the next sibling object. NULL is returned if there is
no next sibling object.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KsPinGetNextSiblingPin]"));
PAGED_CODE();
ASSERT(Pin);
return (PKSPIN) KsGetNextSibling((PVOID) Pin);
}
//
// CKsFileObjectThunk is the implementation of the thunk object which
// exposes interfaces for PFILE_OBJECTs..
//
class CKsFileObjectThunk:
public IKsControl,
public CBaseUnknown
{
private:
PFILE_OBJECT m_FileObject;
public:
DEFINE_STD_UNKNOWN();
IMP_IKsControl;
CKsFileObjectThunk(PUNKNOWN OuterUnknown):
CBaseUnknown(OuterUnknown)
{
}
~CKsFileObjectThunk();
NTSTATUS
Init(
IN PFILE_OBJECT FileObject
);
};
IMPLEMENT_STD_UNKNOWN(CKsFileObjectThunk)
NTSTATUS
KspCreateFileObjectThunk(
OUT PUNKNOWN* Unknown,
IN PFILE_OBJECT FileObject
)
/*++
Routine Description:
This routine creates a new control file object object.
Arguments:
Unknown -
Contains a pointer to the location at which the IUnknown interface
for the object will be deposited.
FileObject -
Contains a pointer to the file object to be thunked.
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[KspCreateFileObjectThunk]"));
PAGED_CODE();
ASSERT(Unknown);
ASSERT(FileObject);
CKsFileObjectThunk *object =
new(PagedPool,POOLTAG_FILEOBJECTTHUNK) CKsFileObjectThunk(NULL);
NTSTATUS status;
if (object) {
object->AddRef();
status = object->Init(FileObject);
if (NT_SUCCESS(status)) {
*Unknown = static_cast<PUNKNOWN>(object);
} else {
object->Release();
}
} else {
status = STATUS_INSUFFICIENT_RESOURCES;
}
return status;
}
CKsFileObjectThunk::
~CKsFileObjectThunk(
void
)
/*++
Routine Description:
This routine destructs a control file object object.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[CKsFileObjectThunk::~CKsFileObjectThunk]"));
PAGED_CODE();
if (m_FileObject) {
ObDereferenceObject(m_FileObject);
}
}
STDMETHODIMP_(NTSTATUS)
CKsFileObjectThunk::
NonDelegatedQueryInterface(
IN REFIID InterfaceId,
OUT PVOID* InterfacePointer
)
/*++
Routine Description:
This routine obtains an interface to a control file object object.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[CKsFileObjectThunk::NonDelegatedQueryInterface]"));
PAGED_CODE();
ASSERT(InterfacePointer);
NTSTATUS status = STATUS_SUCCESS;
if (IsEqualGUIDAligned(InterfaceId,__uuidof(IKsControl))) {
*InterfacePointer = reinterpret_cast<PVOID>(static_cast<PIKSCONTROL>(this));
AddRef();
} else {
status = CBaseUnknown::NonDelegatedQueryInterface(InterfaceId,InterfacePointer);
}
return status;
}
NTSTATUS
CKsFileObjectThunk::
Init(
IN PFILE_OBJECT FileObject
)
/*++
Routine Description:
This routine initializes a control file object object.
Arguments:
Return Value:
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[CKsFileObjectThunk::Init]"));
PAGED_CODE();
ASSERT(FileObject);
ASSERT(! m_FileObject);
m_FileObject = FileObject;
ObReferenceObject(m_FileObject);
return STATUS_SUCCESS;
}
STDMETHODIMP_(NTSTATUS)
CKsFileObjectThunk::
KsProperty(
IN PKSPROPERTY Property,
IN ULONG PropertyLength,
IN OUT LPVOID PropertyData,
IN ULONG DataLength,
OUT ULONG* BytesReturned
)
/*++
Routine Description:
This routine sends a property request to the file object.
Arguments:
Return Value:
Status.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[CKsFileObjectThunk::KsProperty]"));
PAGED_CODE();
ASSERT(Property);
ASSERT(PropertyLength >= sizeof(*Property));
ASSERT(PropertyData || (DataLength == 0));
ASSERT(BytesReturned);
ASSERT(m_FileObject);
return
KsSynchronousIoControlDevice(
m_FileObject,
KernelMode,
IOCTL_KS_PROPERTY,
Property,
PropertyLength,
PropertyData,
DataLength,
BytesReturned);
}
STDMETHODIMP_(NTSTATUS)
CKsFileObjectThunk::
KsMethod(
IN PKSMETHOD Method,
IN ULONG MethodLength,
IN OUT LPVOID MethodData,
IN ULONG DataLength,
OUT ULONG* BytesReturned
)
/*++
Routine Description:
This routine sends a method request to the file object.
Arguments:
Return Value:
Status.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[CKsFileObjectThunk::KsMethod]"));
PAGED_CODE();
ASSERT(Method);
ASSERT(MethodLength >= sizeof(*Method));
ASSERT(MethodData || (DataLength == 0));
ASSERT(BytesReturned);
ASSERT(m_FileObject);
return
KsSynchronousIoControlDevice(
m_FileObject,
KernelMode,
IOCTL_KS_METHOD,
Method,
MethodLength,
MethodData,
DataLength,
BytesReturned);
}
STDMETHODIMP_(NTSTATUS)
CKsFileObjectThunk::
KsEvent(
IN PKSEVENT Event OPTIONAL,
IN ULONG EventLength,
IN OUT LPVOID EventData,
IN ULONG DataLength,
OUT ULONG* BytesReturned
)
/*++
Routine Description:
This routine sends an event request to the file object.
Arguments:
Return Value:
Status.
--*/
{
_DbgPrintF(DEBUGLVL_BLAB,("[CKsFileObjectThunk::KsEvent]"));
PAGED_CODE();
ASSERT(Event);
ASSERT(EventLength >= sizeof(*Event));
ASSERT(EventData || (DataLength == 0));
ASSERT(BytesReturned);
ASSERT(m_FileObject);
//
// If an event structure is present, this must either be an Enable or
// or a Support query. Otherwise this must be a Disable.
//
if (EventLength) {
return
KsSynchronousIoControlDevice(
m_FileObject,
KernelMode,
IOCTL_KS_ENABLE_EVENT,
Event,
EventLength,
EventData,
DataLength,
BytesReturned);
} else {
return
KsSynchronousIoControlDevice(
m_FileObject,
KernelMode,
IOCTL_KS_DISABLE_EVENT,
EventData,
DataLength,
NULL,
0,
BytesReturned);
}
}
#define FCC(ch4) ((((DWORD)(ch4) & 0xFF) << 24) | \
(((DWORD)(ch4) & 0xFF00) << 8) | \
(((DWORD)(ch4) & 0xFF0000) >> 8) | \
(((DWORD)(ch4) & 0xFF000000) >> 24))
// OK to have zero instances of pin In this case you will have to
// Create a pin to have even one instance
#define REG_PIN_B_ZERO 0x1
// The filter renders this input
#define REG_PIN_B_RENDERER 0x2
// OK to create many instance of pin
#define REG_PIN_B_MANY 0x4
// This is an Output pin
#define REG_PIN_B_OUTPUT 0x8
typedef struct {
ULONG Version;
ULONG Merit;
ULONG Pins;
ULONG Reserved;
} REGFILTER_REG;
typedef struct {
ULONG Signature;
ULONG Flags;
ULONG PossibleInstances;
ULONG MediaTypes;
ULONG MediumTypes;
ULONG CategoryOffset;
ULONG MediumOffset; // By definition, we always have a Medium
} REGFILTERPINS_REG2;
KSDDKAPI
NTSTATUS
NTAPI
KsRegisterFilterWithNoKSPins(
IN PDEVICE_OBJECT DeviceObject,
IN const GUID * InterfaceClassGUID,
IN ULONG PinCount,
IN BOOL * PinDirection,
IN KSPIN_MEDIUM * MediumList,
IN OPTIONAL GUID * CategoryList
)
/*++
Routine Description:
This routine is used to register filters with DShow which have no
KS pins and therefore do not stream in kernel mode. This is typically
used for TvTuners, Crossbars, and the like. On exit, a new binary
registry key, "FilterData" is created which contains the Mediums and
optionally the Categories for each pin on the filter.
Arguments:
DeviceObject -
Device object
InterfaceClassGUID
GUID representing the class to register
PinCount -
Count of the number of pins on this filter
PinDirection -
Array of BOOLS indicating pin direction for each pin (length PinCount)
If TRUE, this pin is an output pin
MediumList -
Array of PKSMEDIUM_DATA (length PinCount)
CategoryList -
Array of GUIDs indicating pin categories (length PinCount) OPTIONAL
Return Value:
NTSTATUS SUCCESS if the Blob was created
--*/
{
NTSTATUS Status;
ULONG CurrentPin;
ULONG TotalCategories;
REGFILTER_REG *RegFilter;
REGFILTERPINS_REG2 *RegPin;
GUID *CategoryCache;
PKSPIN_MEDIUM MediumCache;
ULONG FilterDataLength;
PUCHAR FilterData;
PWSTR SymbolicLinkList;
ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
if ((PinCount == 0) || (!InterfaceClassGUID) || (!PinDirection) || (!MediumList)) {
return STATUS_INVALID_DEVICE_REQUEST;
}
//
// Calculate the maximum amount of space which could be taken up by
// this cache data.
//
TotalCategories = (CategoryList ? PinCount : 0);
FilterDataLength = sizeof(REGFILTER_REG) +
PinCount * sizeof(REGFILTERPINS_REG2) +
PinCount * sizeof(KSPIN_MEDIUM) +
TotalCategories * sizeof(GUID);
//
// Allocate space to create the BLOB
//
FilterData = (PUCHAR)ExAllocatePool(PagedPool, FilterDataLength);
if (!FilterData) {
return STATUS_INSUFFICIENT_RESOURCES;
}
//
// Place the header in the data, defaulting the Merit to "unused".
//
RegFilter = (REGFILTER_REG *) FilterData;
RegFilter->Version = 2;
RegFilter->Merit = 0x200000;
RegFilter->Pins = PinCount;
RegFilter->Reserved = 0;
//
// Calculate the offset to the list of pins, and to the
// MediumList and CategoryList
//
RegPin = (REGFILTERPINS_REG2 *) (RegFilter + 1);
MediumCache = (PKSPIN_MEDIUM) ((PUCHAR) (RegPin + PinCount));
CategoryCache = (GUID *) (MediumCache + PinCount);
//
// Create each pin header, followed by the list of Mediums
// followed by the list of optional categories.
//
for (CurrentPin = 0; CurrentPin < PinCount; CurrentPin++, RegPin++) {
//
// Initialize the pin header.
//
RegPin->Signature = FCC('0pi3');
(*(PUCHAR) & RegPin->Signature) += (BYTE) CurrentPin;
RegPin->Flags = (PinDirection[CurrentPin] ? REG_PIN_B_OUTPUT : 0);
RegPin->PossibleInstances = 1;
RegPin->MediaTypes = 0;
RegPin->MediumTypes = 1;
RegPin->MediumOffset = (ULONG) ((PUCHAR) MediumCache - (PUCHAR) FilterData);
*MediumCache++ = MediumList[CurrentPin];
if (CategoryList) {
RegPin->CategoryOffset = (ULONG) ((PUCHAR) CategoryCache - (PUCHAR) FilterData);
*CategoryCache++ = CategoryList[CurrentPin];
} else {
RegPin->CategoryOffset = 0;
}
}
//
// Now create the BLOB in the registry
//
//
// Note for using the flag DEVICE_INTERFACE_INCLUDE_NONACTIVE following:
// PnP change circa 3/30/99 made the funtion IoSetDeviceInterfaceState() become
// asynchronous. It returns SUCCESS even when the enabling is deferred. Now when
// we arrive here, the DeviceInterface is still not enabled, we receive empty
// Symbolic link if the flag is not set. Here we only try to write relevent
// FilterData to the registry. I argue this should be fine for
// 1. Currently, if a device is removed, the registry key for the DeviceClass
// remains and with FilterData.Whatever components use the FilterData should
// be able to handle if the device is removed by either check Control\Linked
// or handling the failure in attempt to make connection to the non-exiting device.
// 2. I have found that if a device is moved between slots ( PCI, USB ports ) the
// DeviceInterface at DeviceClass is reused or at lease become the first entry in
// the registry. Therefore, we will be updating the right entry with the proposed flag.
//
if (NT_SUCCESS(Status = IoGetDeviceInterfaces(
InterfaceClassGUID, // ie.&KSCATEGORY_TVTUNER,etc.
DeviceObject, // IN PDEVICE_OBJECT PhysicalDeviceObject,OPTIONAL,
DEVICE_INTERFACE_INCLUDE_NONACTIVE, // IN ULONG Flags,
&SymbolicLinkList // OUT PWSTR *SymbolicLinkList
))) {
UNICODE_STRING SymbolicLinkListU;
HANDLE DeviceInterfaceKey;
RtlInitUnicodeString(&SymbolicLinkListU, SymbolicLinkList);
#if 0
DebugPrint((DebugLevelVerbose,
"NoKSPin for SymbolicLink %S\n",
SymbolicLinkList ));
#endif // 0
if (NT_SUCCESS(Status = IoOpenDeviceInterfaceRegistryKey(
&SymbolicLinkListU, // IN PUNICODE_STRING SymbolicLinkName,
STANDARD_RIGHTS_ALL, // IN ACCESS_MASK DesiredAccess,
&DeviceInterfaceKey // OUT PHANDLE DeviceInterfaceKey
))) {
UNICODE_STRING FilterDataString;
RtlInitUnicodeString(&FilterDataString, L"FilterData");
Status = ZwSetValueKey(DeviceInterfaceKey,
&FilterDataString,
0,
REG_BINARY,
FilterData,
FilterDataLength);
ZwClose(DeviceInterfaceKey);
}
// START NEW MEDIUM CACHING CODE
for (CurrentPin = 0; CurrentPin < PinCount; CurrentPin++) {
NTSTATUS LocalStatus;
LocalStatus = KsCacheMedium(&SymbolicLinkListU,
&MediumList[CurrentPin],
(DWORD) ((PinDirection[CurrentPin] ? 1 : 0)) // 1 == output
);
#if 0 //DBG
if (LocalStatus != STATUS_SUCCESS) {
DebugPrint((DebugLevelError,
"KsCacheMedium: SymbolicLink = %S, Status = %x\n",
SymbolicLinkListU.Buffer, LocalStatus));
}
#endif
}
// END NEW MEDIUM CACHING CODE
ExFreePool(SymbolicLinkList);
}
ExFreePool(RegFilter);
return Status;
}
ULONG
KspInsertCacheItem (
IN PUCHAR ItemToCache,
IN PUCHAR CacheBase,
IN ULONG CacheItemSize,
IN PULONG CacheItems
)
/*++
Routine Description:
Insert a GUID into the GUID cache for creating FilterData registry
blobs.
Arguments:
ItemToCache -
The GUID to cache
CacheBase -
The base address of the GUID cache
CacheItemSize -
The size of cache items for this cache, including ItemToCache
CacheItems -
Points to a ULONG containing the number of items currently in the
cache.
Return Value:
The offset into the cache where the item exists.
--*/
{
//
// Check to see whether the item to cache is already contained in
// the cache.
//
for (ULONG i = 0; i < *CacheItems; i++) {
if (RtlCompareMemory (
ItemToCache,
CacheBase + i * CacheItemSize,
CacheItemSize
) == CacheItemSize) {
//
// If the item is already contained in the cache, don't recache
// it; save registry space.
//
break;
}
}
if (i >= *CacheItems) {
RtlCopyMemory (
CacheBase + (*CacheItems * CacheItemSize),
ItemToCache,
CacheItemSize
);
i = *CacheItems;
(*CacheItems)++;
}
//
// Return the offset into the cache that the item fits.
//
return (i * CacheItemSize);
}
typedef struct {
ULONG Signature;
ULONG Flags;
ULONG PossibleInstances;
ULONG MediaTypes;
ULONG MediumTypes;
ULONG Category;
} REGFILTERPINS_REG3;
typedef struct {
ULONG Signature;
ULONG Reserved;
ULONG MajorType;
ULONG MinorType;
} REGPINTYPES_REG2;
NTSTATUS
KspBuildFilterDataBlob (
IN const KSFILTER_DESCRIPTOR *FilterDescriptor,
OUT PUCHAR *FilterData,
OUT PULONG FilterDataLength
)
/*++
Routine Description:
For a given filter descriptor, build the registry FilterData blob that
is used by the graph builder.
Arguments:
FilterDescriptor -
The filter descriptor to build the filter data blob for.
FilterData -
The filter data blob will be placed here. Note that the caller
is responsible for freeing the memory.
FilterDataLength -
The size of the filter data blob will be placed here.
Return Value:
Success / Failure
--*/
{
PAGED_CODE();
ASSERT (FilterDescriptor);
ASSERT (FilterData);
ASSERT (FilterDataLength);
NTSTATUS Status = STATUS_SUCCESS;
//
// Count the number of pins, the number of mediums on each pin,
// and the number of data ranges on each pin to determine
// how much memory will be required for the filterdata key.
//
ULONG MediumsCount = 0;
ULONG DataRangesCount = 0;
const KSPIN_DESCRIPTOR_EX *PinDescriptor = FilterDescriptor->PinDescriptors;
for (ULONG PinDescriptorsCount = FilterDescriptor->PinDescriptorsCount;
PinDescriptorsCount;
PinDescriptorsCount--
) {
//
// Update the count of the number of mediums and data ranges
//
MediumsCount += PinDescriptor->PinDescriptor.MediumsCount;
DataRangesCount += PinDescriptor->PinDescriptor.DataRangesCount;
//
// Walk to the next pin descriptor by size offset specified in
// the filter descriptor.
//
PinDescriptor = (const KSPIN_DESCRIPTOR_EX *)(
(PUCHAR)PinDescriptor + FilterDescriptor->PinDescriptorSize
);
}
ULONG TotalGUIDCachePotential =
FilterDescriptor->PinDescriptorsCount +
DataRangesCount * 2;
//
// Allocate enough memory for the FilterData blob in the registry.
//
*FilterDataLength =
// Initial filter description
sizeof (REGFILTER_REG) +
// each pin description
FilterDescriptor->PinDescriptorsCount * sizeof (REGFILTERPINS_REG3) +
// each media type description
DataRangesCount * sizeof (REGPINTYPES_REG2) +
// each medium description
MediumsCount * sizeof (ULONG) +
// mediums cached
MediumsCount * sizeof (KSPIN_MEDIUM) +
// category GUIDs cached
TotalGUIDCachePotential * sizeof (GUID);
*FilterData = (PUCHAR)
ExAllocatePool (PagedPool, *FilterDataLength);
if (!*FilterData) {
*FilterDataLength = 0;
Status = STATUS_INSUFFICIENT_RESOURCES;
} else {
//
// The GUID cache follows all the filter/pin/media type structures in
// the filter data blob.
//
ULONG GuidCacheOffset =
sizeof (REGFILTER_REG) +
FilterDescriptor->PinDescriptorsCount * sizeof(REGFILTERPINS_REG3) +
DataRangesCount * sizeof(REGPINTYPES_REG2) +
MediumsCount * sizeof (ULONG);
GUID *GuidCacheBase = (GUID *)((PUCHAR)*FilterData + GuidCacheOffset);
ULONG GuidCacheItems = 0;
//
// The medium cache (not the registry medium cache), but the cached
// list of mediums in the FilterData blob follows the GUID cache. It
// may need to shift down later if there were items referenced out
// of the existing cache entries.
//
ULONG MediumCacheOffset =
GuidCacheOffset + (TotalGUIDCachePotential * sizeof (GUID));
KSPIN_MEDIUM *MediumCacheBase = (KSPIN_MEDIUM *)
((PUCHAR)*FilterData + MediumCacheOffset);
ULONG MediumCacheItems = 0;
RtlZeroMemory (*FilterData, *FilterDataLength);
REGFILTER_REG *RegFilter;
REGFILTERPINS_REG3 *RegPin;
REGPINTYPES_REG2 *RegPinType;
ULONG *RegPinMedium;
RegFilter = (REGFILTER_REG *)*FilterData;
RegFilter->Version = 2;
RegFilter->Merit = 0x200000;
RegFilter->Pins = FilterDescriptor->PinDescriptorsCount;
RegFilter->Reserved = 0;
//
// Walk through each pin in the filter descriptor yet again and
// actually build the registry blob.
//
PinDescriptor = FilterDescriptor->PinDescriptors;
RegPin = (REGFILTERPINS_REG3 *)(RegFilter + 1);
for (ULONG CurrentPin = 0;
CurrentPin < FilterDescriptor->PinDescriptorsCount;
CurrentPin++
) {
RegPin->Signature = FCC('0pi3');
(*(PUCHAR)&RegPin->Signature) += (BYTE)CurrentPin;
//
// Set the requisite flags if the pin is multi-instance.
//
if (PinDescriptor->InstancesPossible > 1) {
RegPin->Flags |= REG_PIN_B_MANY;
}
//
// Set all the counts on mediums, media types, etc...
//
RegPin->MediaTypes = PinDescriptor->PinDescriptor.DataRangesCount;
RegPin->MediumTypes = PinDescriptor->PinDescriptor.MediumsCount;
RegPin->PossibleInstances = PinDescriptor->InstancesPossible;
if (PinDescriptor->PinDescriptor.Category) {
RegPin->Category = GuidCacheOffset +
KspInsertCacheItem (
(PUCHAR)PinDescriptor->PinDescriptor.Category,
(PUCHAR)GuidCacheBase,
sizeof (GUID),
&GuidCacheItems
);
} else {
RegPin->Category = 0;
}
//
// Append all media types supported on the pin
//
RegPinType = (REGPINTYPES_REG2 *)(RegPin + 1);
for (ULONG CurrentType = 0;
CurrentType < PinDescriptor->PinDescriptor.DataRangesCount;
CurrentType++
) {
const KSDATARANGE *DataRange =
PinDescriptor->PinDescriptor.DataRanges [CurrentType];
RegPinType->Signature = FCC('0ty3');
(*(PUCHAR)&RegPinType->Signature) += (BYTE)CurrentType;
RegPinType->Reserved = 0;
RegPinType->MajorType = GuidCacheOffset +
KspInsertCacheItem (
(PUCHAR)&(DataRange->MajorFormat),
(PUCHAR)GuidCacheBase,
sizeof (GUID),
&GuidCacheItems
);
RegPinType->MinorType = GuidCacheOffset +
KspInsertCacheItem (
(PUCHAR)&(DataRange->SubFormat),
(PUCHAR)GuidCacheBase,
sizeof (GUID),
&GuidCacheItems
);
//
// Walk forward one media type.
//
RegPinType++;
}
//
// Append the list of mediums.
//
const KSPIN_MEDIUM *Medium = PinDescriptor->PinDescriptor.Mediums;
RegPinMedium = (PULONG)RegPinType;
for (ULONG CurrentMedium = 0;
CurrentMedium < PinDescriptor->PinDescriptor.MediumsCount;
CurrentMedium++
) {
*RegPinMedium++ = MediumCacheOffset +
KspInsertCacheItem (
(PUCHAR)Medium,
(PUCHAR)MediumCacheBase,
sizeof (KSPIN_MEDIUM),
&MediumCacheItems
);
}
RegPin = (REGFILTERPINS_REG3 *)RegPinMedium;
}
ASSERT (GuidCacheItems < TotalGUIDCachePotential);
//
// Find out how much empty space sits between the GUID cache
// and the medium cache in the constructed blob and remove it.
//
ULONG OffsetAdjustment =
(TotalGUIDCachePotential - GuidCacheItems) * sizeof (GUID);
if (OffsetAdjustment) {
//
// Walk through all medium offsets and change the offsets to
// pack the GUID and Medium cache together in the blob.
//
RegPin = (REGFILTERPINS_REG3 *)(RegFilter + 1);
for (CurrentPin = 0;
CurrentPin < FilterDescriptor->PinDescriptorsCount;
CurrentPin++
) {
RegPinMedium = (PULONG)(
(REGPINTYPES_REG2 *)(RegPin + 1) +
RegPin -> MediaTypes
);
for (ULONG CurrentMedium = 0;
CurrentMedium < RegPin -> MediumTypes;
CurrentMedium++
) {
*RegPinMedium -= OffsetAdjustment;
RegPinMedium++;
}
//
// Increment to the next pin header position.
//
RegPin = (REGFILTERPINS_REG3 *)RegPinMedium;
}
//
// Move the medium entries down, and adjust the overall size.
//
RtlMoveMemory (
(PUCHAR)MediumCacheBase - OffsetAdjustment,
MediumCacheBase,
MediumCacheItems * sizeof (KSPIN_MEDIUM)
);
//
// Adjust the total length by the size of the empty space between
// the GUID cache and the Medium cache.
//
*FilterDataLength -= OffsetAdjustment;
}
//
// Adjust the total length by the size of the empty space following
// the medium cache.
//
*FilterDataLength -= (MediumsCount - MediumCacheItems) *
sizeof (KSPIN_MEDIUM);
}
return Status;
}
NTSTATUS
KspCacheAllFilterPinMediums (
PUNICODE_STRING InterfaceString,
const KSFILTER_DESCRIPTOR *FilterDescriptor
)
/*++
Routine Description:
Update the medium cache for all mediums on all pins on the filter
described by FilterDescriptor. The filter interface to be used is
specified by InterfaceString.
Arguments:
InterfaceString -
The device interface to register under the cache for the mediums
on all pins on the specified filter
FilterDescriptor -
Describes the filter to update the medium cache for.
Return Value:
Success / Failure
--*/
{
PAGED_CODE();
NTSTATUS Status = STATUS_SUCCESS;
//
// Walk through all pins on the filter and cache their mediums.
//
const KSPIN_DESCRIPTOR_EX *PinDescriptor = FilterDescriptor->PinDescriptors;
for (ULONG CurrentPin = 0;
NT_SUCCESS (Status) &&
CurrentPin < FilterDescriptor->PinDescriptorsCount;
CurrentPin++
) {
//
// Walk through all mediums on the given pin and cache each of them
// under the specified device interface.
//
const KSPIN_MEDIUM *Medium = PinDescriptor->PinDescriptor.Mediums;
for (ULONG CurrentMedium = 0;
NT_SUCCESS (Status) &&
CurrentMedium < PinDescriptor->PinDescriptor.MediumsCount;
CurrentMedium++
) {
//
// Cache the given medium on the given pin under the device
// interface passed in.
//
Status = KsCacheMedium (
InterfaceString,
(PKSPIN_MEDIUM)Medium,
PinDescriptor->PinDescriptor.DataFlow == KSPIN_DATAFLOW_OUT ?
1 : 0
);
Medium++;
}
PinDescriptor = (const KSPIN_DESCRIPTOR_EX *)(
(PUCHAR)PinDescriptor + FilterDescriptor->PinDescriptorSize
);
}
return Status;
}
| 23.264161 | 130 | 0.574579 | [
"object"
] |
3d324818b2f052a7f78779088b1d9d4511c8ac7c | 16,746 | cpp | C++ | apps/pose_proposal/pose_proposal.cpp | mhalber/Rescan | f45283be31119e9bd955d40bc159b1774dfed092 | [
"MIT"
] | 15 | 2019-09-18T19:29:50.000Z | 2022-03-03T11:11:35.000Z | apps/pose_proposal/pose_proposal.cpp | mhalber/Rescan | f45283be31119e9bd955d40bc159b1774dfed092 | [
"MIT"
] | 1 | 2020-03-10T12:41:02.000Z | 2020-03-17T10:38:58.000Z | apps/pose_proposal/pose_proposal.cpp | mhalber/Rescan | f45283be31119e9bd955d40bc159b1774dfed092 | [
"MIT"
] | 4 | 2019-10-08T18:18:41.000Z | 2020-10-24T04:43:17.000Z |
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cassert>
#include "msh/msh_std.h"
#include "msh/msh_vec_math.h"
#include "msh/msh_geometry.h"
#include "msh/msh_hash_grid.h"
#include "mg/hashtable.h"
#include "msh/msh_ply.h"
#include "rs_pointcloud.h"
#include "rs_distance_function.h"
#include "rs_database.h"
#define INTERSECTION_IMPLEMENTATION
#include "intersect.h"
#include "pose_proposal.h"
void
mgs_init_opts( mgs_opts_t* opts )
{
opts->search_grid_spacing = 0.10f;
opts->search_grid_angle_delta = MSH_TWO_PI / 10.0f;
opts->max_neigh_search_radius = 0.25f;
opts->naive = false;
opts->use_geometry = 1;
opts->use_mask_rcnn = 0;
}
inline double
mgs__exp_score_sq( double dist_sq, double sigma )
{
return exp( -dist_sq / (2.0*sigma*sigma) );
}
inline float
mgs_weighted_pt2pt_score( msh_vec3_t p, msh_vec3_t q,
msh_vec3_t n, msh_vec3_t m, float factor )
{
msh_vec3_t diff = msh_vec3_sub( p, q );
float dist_sq = msh_vec3_norm_sq(diff);
float dot = msh_vec3_dot(n,m);
float w = msh_clamp01( dot );
return w * mgs__exp_score_sq( dist_sq, factor );
}
inline float
mgs_pt2pl_score( msh_vec3_t p, msh_vec3_t q,
msh_vec3_t n, msh_vec3_t m, float factor )
{
msh_vec3_t diff = msh_vec3_sub( q, p );
float dist = msh_vec3_dot(n, diff);
return mgs__exp_score_sq( dist*dist, factor );
}
tmp_score_calc_storage_t
allocate_tmp_calc_storage( const int32_t obj_n_pts, const int32_t scn_n_pts, const int32_t max_n_neigh )
{
tmp_score_calc_storage_t storage = { 0 };
storage.max_n_neigh = max_n_neigh;
storage.obj_pos = (msh_vec3_t*)malloc( obj_n_pts * sizeof(msh_vec3_t) );
storage.obj_nor = (msh_vec3_t*)malloc( obj_n_pts * sizeof(msh_vec3_t) );
storage.obj_n_pts = obj_n_pts;
storage.obj2scn_indices = (int32_t*)malloc( max_n_neigh * obj_n_pts * sizeof(int32_t) );
storage.obj2scn_dists_sq = (float*)malloc( max_n_neigh * obj_n_pts * sizeof(float) );
storage.obj2scn_n_neighbors = (size_t*)malloc( obj_n_pts * sizeof(size_t) );
return storage;
}
void
free_tmp_calc_storage( tmp_score_calc_storage_t* storage )
{
free( storage->obj2scn_indices );
free( storage->obj2scn_n_neighbors );
free( storage->obj2scn_dists_sq );
free( storage->obj_pos );
free( storage->obj_nor );
storage->max_n_neigh = 0;
storage->obj_n_pts = 0;
}
float
mgs_compute_object_alignment_score( rs_pointcloud_t* object, rs_pointcloud_t* scene,
int32_t search_lvl, int32_t query_lvl,
msh_mat4_t xform, tmp_score_calc_storage_t* storage )
{
static float search_radii[5] = { 0.05f, 0.1f, 0.15f, 0.2f, 0.25f };
double max_angle = msh_deg2rad( 35.0 );
double score_sigma = search_radii[search_lvl];
msh_hash_grid_t* scn_search_index = scene->search_grids[search_lvl];
double alpha = 0.05;
double beta = 1.0 - alpha;
// Transform object's points
for( int32_t i = 0; i < storage->obj_n_pts; ++i )
{
msh_vec3_t p = object->positions[query_lvl][i];
msh_vec3_t n = object->normals[query_lvl][i];
storage->obj_pos[i] = msh_mat4_vec3_mul( xform, p, 1 );
storage->obj_nor[i] = msh_mat4_vec3_mul( xform, n, 0 );
}
// Perform nearest neighbor search
msh_hash_grid_search_desc_t search_opts = {0};
search_opts.query_pts = &storage->obj_pos[0].x;
search_opts.n_query_pts = storage->obj_n_pts;
search_opts.distances_sq = storage->obj2scn_dists_sq;
search_opts.indices = storage->obj2scn_indices;
search_opts.n_neighbors = storage->obj2scn_n_neighbors;
search_opts.radius = search_radii[search_lvl];
search_opts.max_n_neigh = storage->max_n_neigh;
search_opts.sort = 1;
msh_hash_grid_radius_search( scn_search_index, &search_opts );
double overall_score = 0.0;
for( int32_t i = 0; i < storage->obj_n_pts; ++i )
{
size_t cur_nn = storage->obj2scn_n_neighbors[i];
double best_dist_sq = -1.0;
double dot = 0.0;
double best_angle = 0.0;
for( size_t j = 0 ; j < cur_nn; ++j )
{
int32_t k = storage->obj2scn_indices[ i * storage->max_n_neigh + j ];
msh_vec3_t n = storage->obj_nor[i];
msh_vec3_t m = scene->normals[search_lvl][k];
dot = msh_vec3_dot( m, n );
dot = msh_max( dot, 0.0f );
double angle = acos( dot );
if( angle - max_angle < 0.000001 )
{
best_dist_sq = storage->obj2scn_dists_sq[ i * storage->max_n_neigh + j ];
best_angle = angle;
break;
}
}
if( best_dist_sq < -0.0001 ) { continue; }
double normals_compat = exp( -(best_angle*best_angle) / (2.0 * 0.5 * 0.5 ) );
double dist_compat = mgs__exp_score_sq( best_dist_sq, score_sigma );
double score = alpha * normals_compat + beta * dist_compat;
overall_score += score;
}
overall_score /= (double)( storage->obj_n_pts );
return (float)overall_score;
}
float
mgs__score_threshold( int32_t lvl )
{
if( lvl == RSPC_N_LEVELS - 1 ) { return 0.25f; }
if( lvl == RSPC_N_LEVELS - 2 ) { return 0.35f; }
if( lvl == RSPC_N_LEVELS - 3 ) { return 0.40f; }
if( lvl == RSPC_N_LEVELS - 4 ) { return 0.50f; }
else { return 0.50f; }
}
void
mgs__initial_pose_proposals( rsdb_t* rsdb, rs_pointcloud_t* input_scan,
rs_df_t* df_input_scan, int32_t lvl,
msh_array(msh_array(pose_proposal_t)) *proposed_poses,
const mgs_opts_t* opts )
{
uint64_t st, et;
int32_t n_objects = msh_array_len( rsdb->objects );
int32_t search_lvl = 1;
int32_t max_n_neigh = 64;
for( int32_t i = 0 ; i < n_objects ; ++i )
{
msh_array_push( *proposed_poses, NULL );
}
printf( "POSE_PROPOSAL: Starting initial pose proposal search...\n");
st = msh_time_now();
for( int32_t i = 0 ; i < n_objects; ++i )
{
uint64_t t1, t2;
t1 = msh_time_now();
msh_vec3_t origin = input_scan->bbox.min_p;
rs_object_t* object = &rsdb->objects[i];
tmp_score_calc_storage_t storage = allocate_tmp_calc_storage( object->shape->n_pts[lvl], input_scan->n_pts[lvl], max_n_neigh );
// Skip static
if( rsdb_is_object_static(rsdb, i) )
{
continue;
}
float spacing = opts->search_grid_spacing;
float y_angle_inc = opts->search_grid_angle_delta;
float length_x = input_scan->bbox.max_p.x - input_scan->bbox.min_p.x;
float length_z = input_scan->bbox.max_p.z - input_scan->bbox.min_p.z;
float height = 0.0f;
char* class_name = rsdb_get_class_name( rsdb, object->class_idx );
printf( "POSE_PROPOSAL: Searching for transformation for model %s.%03d (%d)...\n",
class_name, object->uidx, i );
float max_score = -1e9;
float score_threshold = mgs__score_threshold(lvl);
for(float ox = -spacing; ox < length_x + spacing; ox += spacing )
{
for(float oz = -spacing; oz < length_z + spacing; oz += spacing)
{
float best_rot_score = 0;
msh_mat4_t best_rot_xform = {0};
for( float y_angle = 0.0f; y_angle < MSH_TWO_PI; y_angle += y_angle_inc )
{
msh_mat4_t xform = msh_rotate(msh_mat4_identity(), y_angle, msh_vec3(0.0f, 1.0f, 0.0f));
xform.col[3] = msh_vec4(origin.x + ox, height, origin.z + oz, 1.0f);
if( df_input_scan )
{
float nearest = rs_df_closest_surface(df_input_scan, (float*)&xform.col[3]);
if( nearest > 0.6 ) { continue; }
}
float score = mgs_compute_object_alignment_score( object->shape, input_scan,
search_lvl, lvl, xform, &storage );
if( score > best_rot_score )
{
best_rot_score = score;
best_rot_xform = xform;
if( best_rot_score > max_score ) { max_score = best_rot_score; }
}
}
if( best_rot_score > score_threshold )
{
pose_proposal_t proposal = {.xform = best_rot_xform, .score = best_rot_score };
msh_array_push( (*proposed_poses)[i], proposal );
}
}
}
free_tmp_calc_storage( &storage );
t2 = msh_time_now();
double elapsed = msh_time_diff_sec( t2, t1 );
printf( "POSE_PROPOSAL: --> Found %zu potential poses in %fs. (Max score: %f)\n",
msh_array_len((*proposed_poses)[i]), elapsed, max_score );
}
et = msh_time_now();
printf( "POSE_PROPOSAL: Initial pose proposals made in %fs.\n", msh_time_diff_sec( et, st) );
}
void
mgs__pose_verification( rsdb_t* rsdb, rs_pointcloud_t* input_scan, int32_t lvl,
msh_array(msh_array(pose_proposal_t)) *proposed_poses,
const mgs_opts_t* opts )
{
float score_threshold = mgs__score_threshold(lvl);
int32_t n_objects = msh_array_len(rsdb->objects);
int32_t search_lvl = 1;
int32_t max_n_neigh = 64;
for( int32_t i = 0; i < n_objects; ++i )
{
if( rsdb_is_object_static( rsdb, i ) ) { continue; }
int32_t n_poses = msh_array_len((*proposed_poses)[i]);
int32_t n_valid_poses = n_poses;
int32_t class_idx = rsdb->objects[i].class_idx;
int32_t instance_idx = rsdb->objects[i].uidx;
tmp_score_calc_storage_t storage = allocate_tmp_calc_storage( rsdb->objects[i].shape->n_pts[lvl],
input_scan->n_pts[lvl],
max_n_neigh );
if( n_poses )
{
char* class_name = rsdb_get_class_name( rsdb, class_idx );
printf( "POSE_PROPOSAL: Verifying transformations for model %s.%03d(%d) using...\n",
class_name, instance_idx, i);
float max_score = -1e9;
for( int32_t j = 0; j < n_poses; j++ )
{
if( (*proposed_poses)[i][j].score > 0.0f )
{
msh_mat4_t xform = (*proposed_poses)[i][j].xform;
float score = mgs_compute_object_alignment_score( rsdb->objects[i].shape, input_scan,
search_lvl, lvl, xform, &storage );
if(score > max_score ) { max_score = score; }
if(score > score_threshold ) { (*proposed_poses)[i][j].score = score; }
else { (*proposed_poses)[i][j].score = -1.0f; n_valid_poses--; }
}
else
{
n_valid_poses--;
}
}
printf( "POSE_PROPOSAL: --> Found %d poses( Max. score: %f)\n", n_valid_poses, max_score);
}
free_tmp_calc_storage(&storage);
}
}
void
mgs__propose_poses_at_level(rsdb_t* rsdb, rs_pointcloud_t* input_scan,
rs_df_t* df_input_scan, int32_t lvl,
msh_array(msh_array(pose_proposal_t)) *proposed_poses,
const mgs_opts_t* opts )
{
if( !(*proposed_poses) )
{
mgs__initial_pose_proposals( rsdb, input_scan, df_input_scan, lvl,
proposed_poses, opts );
}
else
{
mgs__pose_verification( rsdb, input_scan, lvl,
proposed_poses, opts );
}
}
void
mgs_propose_poses( rsdb_t* rsdb, rs_pointcloud_t* input_scan,
msh_array(msh_array(pose_proposal_t)) *proposed_poses,
const mgs_opts_t* opts, int32_t verbose )
{
double st, et;
double gst, get;
gst = msh_time_now();
msh_array(msh_array(pose_proposal_t)) proposal_storage = NULL;
// Pose proposals
for( int32_t lvl = RSPC_N_LEVELS-1; lvl > RSPC_N_LEVELS-4; lvl--)
{
st = msh_time_now();
msh_cprintf( verbose, "POSE PROPOSAL: Working on level: %d | Threshold: %6.4f\n", lvl, mgs__score_threshold( lvl ) );
mgs__propose_poses_at_level( rsdb, input_scan, NULL, lvl,
&proposal_storage, opts );
et = msh_time_now();
msh_cprintf( verbose, "POSE PROPOSAL: Level %d processing time: %fs\n", lvl, msh_time_diff_sec( et, st) );
}
// Copy valid poses
for( size_t i = 0; i < msh_array_len( proposal_storage ); ++i )
{
msh_array(pose_proposal_t) cur_proposals = NULL;
for( size_t j = 0; j < msh_array_len( proposal_storage[i] ); ++j)
{
if( fabsf(proposal_storage[i][j].score) > 0.000001f )
{
msh_array_push( cur_proposals, proposal_storage[i][j] );
}
}
msh_array_push( *proposed_poses, cur_proposals );
}
// Cleanup
for( size_t i = 0; i < msh_array_len( proposal_storage ); ++i )
{
if( proposal_storage[i] ) { msh_array_free(proposal_storage[i]); }
}
if( proposal_storage ) { msh_array_free( proposal_storage ); }
get = msh_time_now();
msh_cprintf( verbose, "POSE PROPOSAL: Done in %fs\n", msh_time_diff_sec( get, gst ) );
}
void
mgs_non_maxima_suppresion( rsdb_t* rsdb,
msh_array(msh_array(pose_proposal_t))* proposed_poses,
int32_t verbose, float dist_threshold )
{
int32_t n_objects = msh_array_len(*proposed_poses);
for( int32_t i = 0; i < n_objects; ++i )
{
// Initialize useful vars
rs_object_t* object = &rsdb->objects[i];
rs_pointcloud_t* shape = object->shape;
msh_vec3_t c = rs_pointcloud_centroid( shape, 0 );
msh_array(pose_proposal_t) cur_proposals = (*proposed_poses)[i];
int32_t n_detections = msh_array_len(cur_proposals);
if( n_detections == 0 ) { continue; }
msh_array( mark_t ) indices_marks = {0};
int32_t marked_detections = 0;
char* class_name = rsdb_get_class_name( rsdb, object->class_idx );
msh_cprintf( verbose, "POSE_PROPOSAL: Non-max suppress. : Working on object class %s.%03d (%d/%d) \n",
class_name, object->uidx, i, n_objects );
for( int32_t i = 0; i < n_detections; ++i ) { msh_array_push( indices_marks, PP_UNMARKED ); }
while( marked_detections != n_detections )
{
// find max unmarked detection
int32_t max_idx = -1; float max_score = -1e9;
for( int32_t i = 0 ; i < n_detections ; ++i )
{
if( indices_marks[i] == PP_UNMARKED &&
cur_proposals[i].score > max_score )
{
max_score = cur_proposals[i].score;
max_idx = i;
}
}
// mark detection as a keep
indices_marks[max_idx] = PP_KEEP;
marked_detections++;
// discard all detections that are overlapping this one.
for( int32_t i = 0 ; i < n_detections; ++i )
{
if( indices_marks[i] == PP_UNMARKED )
{
msh_vec3_t p1 = msh_mat4_vec3_mul( cur_proposals[max_idx].xform, c, 1 );
msh_vec3_t p2 = msh_mat4_vec3_mul( cur_proposals[i].xform, c, 1 );
float dist = msh_vec3_norm( msh_vec3_sub( p1, p2 ) );
float overlap = isect_get_overlap_factor(shape, cur_proposals[max_idx].xform,
shape, cur_proposals[i].xform,
0.1f, 1, 0 );
if( overlap > 0.5f || dist < dist_threshold || cur_proposals[i].score < 0.01f )
{
indices_marks[i] = PP_DISCARD;
marked_detections++;
}
}
}
}
// report stats
int32_t counts[3] = {0, 0, 0};
for( int32_t i = 0 ; i < n_detections; ++i )
{
counts[indices_marks[i]]++;
}
msh_cprintf( verbose, "POSE_PROPOSAL: Non-max suppress. --> Keep: %5d Discard: %5d Unmarked: %5d\n",
counts[1], counts[2], counts[0]);
// copy the data
msh_array(pose_proposal_t) new_proposals = {0};
for( int32_t i = 0 ; i < n_detections; ++i )
{
if( indices_marks[i] == PP_KEEP )
{
msh_array_push( new_proposals, cur_proposals[i] );
}
}
(*proposed_poses)[i] = new_proposals;
msh_array_free( cur_proposals );
msh_array_free( indices_marks );
}
}
int32_t
pose_proposal_cmp(const void *a, const void *b)
{
float score_a = ((pose_proposal_t*)a)->score;
float score_b = ((pose_proposal_t*)b)->score;
return (score_a > score_b) ? -1 : (score_a < score_b);
}
void
mgs_sort_poses( msh_array(msh_array(pose_proposal_t))* poses, int32_t verbose )
{
uint64_t t1, t2;
t1 = msh_time_now();
for(size_t i = 0; i < msh_array_len((*poses)); ++i)
{
size_t cur_size = msh_array_len((*poses)[i]);
qsort( (*poses)[i], cur_size, sizeof(pose_proposal), pose_proposal_cmp );
}
t2 = msh_time_now();
msh_cprintf( verbose, "POSE_PROPOSAL: Sorting poses done in %fms.\n", msh_time_diff_ms(t2,t1));
} | 35.254737 | 131 | 0.612445 | [
"object",
"shape",
"model",
"transform"
] |
3d424f66019488844ed588b4507a0573aad936c3 | 30,223 | cxx | C++ | panda/src/distort/projectionScreen.cxx | kestred/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | panda/src/distort/projectionScreen.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | panda/src/distort/projectionScreen.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | // Filename: projectionScreen.cxx
// Created by: drose (11Dec01)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "projectionScreen.h"
#include "geomNode.h"
#include "transformState.h"
#include "workingNodePath.h"
#include "switchNode.h"
#include "geom.h"
#include "geomTristrips.h"
#include "geomVertexWriter.h"
#include "geomVertexReader.h"
#include "geomVertexRewriter.h"
#include "config_distort.h"
#include "cullTraverserData.h"
TypeHandle ProjectionScreen::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::Constructor
// Access: Published
// Description:
////////////////////////////////////////////////////////////////////
ProjectionScreen::
ProjectionScreen(const string &name) : PandaNode(name)
{
set_cull_callback();
_texcoord_name = InternalName::get_texcoord();
_has_undist_lut = false;
_invert_uvs = project_invert_uvs;
_texcoord_3d = false;
_vignette_on = false;
_vignette_color.set(0.0f, 0.0f, 0.0f, 1.0f);
_frame_color.set(1.0f, 1.0f, 1.0f, 1.0f);
_computed_rel_top_mat = false;
_stale = true;
_auto_recompute = true;
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
ProjectionScreen::
~ProjectionScreen() {
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::Copy Constructor
// Access: Protected
// Description:
////////////////////////////////////////////////////////////////////
ProjectionScreen::
ProjectionScreen(const ProjectionScreen ©) :
PandaNode(copy),
_projector(copy._projector),
_projector_node(copy._projector_node),
_texcoord_name(copy._texcoord_name),
_vignette_on(copy._vignette_on),
_vignette_color(copy._vignette_color),
_frame_color(copy._frame_color),
_auto_recompute(copy._auto_recompute)
{
_computed_rel_top_mat = false;
_stale = true;
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::make_copy
// Access: Public, Virtual
// Description: Returns a newly-allocated Node that is a shallow copy
// of this one. It will be a different Node pointer,
// but its internal data may or may not be shared with
// that of the original Node.
////////////////////////////////////////////////////////////////////
PandaNode *ProjectionScreen::
make_copy() const {
return new ProjectionScreen(*this);
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::cull_callback
// Access: Public, Virtual
// Description: This function will be called during the cull
// traversal to perform any additional operations that
// should be performed at cull time. This may include
// additional manipulation of render state or additional
// visible/invisible decisions, or any other arbitrary
// operation.
//
// Note that this function will *not* be called unless
// set_cull_callback() is called in the constructor of
// the derived class. It is necessary to call
// set_cull_callback() to indicated that we require
// cull_callback() to be called.
//
// By the time this function is called, the node has
// already passed the bounding-volume test for the
// viewing frustum, and the node's transform and state
// have already been applied to the indicated
// CullTraverserData object.
//
// The return value is true if this node should be
// visible, or false if it should be culled.
////////////////////////////////////////////////////////////////////
bool ProjectionScreen::
cull_callback(CullTraverser *, CullTraverserData &data) {
if (_auto_recompute) {
recompute_if_stale(data._node_path.get_node_path());
}
return true;
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::set_projector
// Access: Published
// Description: Specifies the LensNode that is to serve as the
// projector for this screen. The relative position of
// the LensNode to the ProjectionScreen, as well as the
// properties of the lens associated with the LensNode,
// determines the UV's that will be assigned to the
// geometry within the ProjectionScreen.
//
// The NodePath must refer to a LensNode (or a Camera).
////////////////////////////////////////////////////////////////////
void ProjectionScreen::
set_projector(const NodePath &projector) {
_projector_node = (LensNode *)NULL;
_projector = projector;
if (!projector.is_empty()) {
nassertv(projector.node()->is_of_type(LensNode::get_class_type()));
_projector_node = DCAST(LensNode, projector.node());
_stale = true;
}
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::generate_screen
// Access: Published
// Description: Synthesizes a polygon mesh based on the projection
// area of the indicated projector. This generates and
// returns a new GeomNode but does not automatically
// parent it to the ProjectionScreen node; see
// regenerate_screen().
//
// The specified projector need not be the same as the
// projector given to the ProjectionScreen with
// set_projector() (although this is often what you
// want).
//
// num_x_verts and num_y_verts specify the number of
// vertices to make in the grid across the horizontal
// and vertical dimension of the projector,
// respectively; distance represents the approximate
// distance of the screen from the lens center.
//
// The fill_ratio parameter specifies the fraction of
// the image to cover. If it is 1.0, the entire image
// is shown full-size; if it is 0.9, 10% of the image
// around the edges is not part of the grid (and the
// grid is drawn smaller by the same 10%). This is
// intended to work around graphics drivers that tend to
// show dark edges or other unsatisfactory artifacts
// around the edges of textures: render the texture
// larger than necessary by a certain fraction, and make
// the screen smaller by the inverse fraction.
////////////////////////////////////////////////////////////////////
PT(GeomNode) ProjectionScreen::
generate_screen(const NodePath &projector, const string &screen_name,
int num_x_verts, int num_y_verts, PN_stdfloat distance,
PN_stdfloat fill_ratio) {
nassertr(!projector.is_empty() &&
projector.node()->is_of_type(LensNode::get_class_type()),
NULL);
LensNode *projector_node = DCAST(LensNode, projector.node());
nassertr(projector_node->get_lens() != NULL, NULL);
// First, get the relative coordinate space of the projector.
LMatrix4 rel_mat;
NodePath this_np(this);
rel_mat = projector.get_transform(this_np)->get_mat();
// Create a GeomNode to hold this mesh.
PT(GeomNode) geom_node = new GeomNode(screen_name);
// Now compute all the vertices for the screen. These are arranged
// in order from left to right and bottom to top.
int num_verts = num_x_verts * num_y_verts;
Lens *lens = projector_node->get_lens();
PN_stdfloat t = (distance - lens->get_near()) / (lens->get_far() - lens->get_near());
PN_stdfloat x_scale = 2.0f / (num_x_verts - 1);
PN_stdfloat y_scale = 2.0f / (num_y_verts - 1);
PT(GeomVertexData) vdata = new GeomVertexData
("projectionScreen", GeomVertexFormat::get_v3n3(),
Geom::UH_dynamic);
GeomVertexWriter vertex(vdata, InternalName::get_vertex());
GeomVertexWriter normal(vdata, InternalName::get_normal());
for (int yi = 0; yi < num_y_verts; yi++) {
for (int xi = 0; xi < num_x_verts; xi++) {
LPoint2 film = LPoint2((PN_stdfloat)xi * x_scale - 1.0f,
(PN_stdfloat)yi * y_scale - 1.0f);
// Reduce the image by the fill ratio.
film *= fill_ratio;
LPoint3 near_point, far_point;
lens->extrude(film, near_point, far_point);
LPoint3 point = near_point + t * (far_point - near_point);
// Normals aren't often needed on projection screens, but you
// never know.
LVector3 norm;
lens->extrude_vec(film, norm);
vertex.add_data3(point * rel_mat);
normal.add_data3(-normalize(norm * rel_mat));
}
}
nassertr(vdata->get_num_rows() == num_verts, NULL);
// Now synthesize a triangle mesh. We run triangle strips
// horizontally across the grid.
PT(GeomTristrips) strip = new GeomTristrips(Geom::UH_static);
// Fill up the index array into the vertices. This lays out the
// order of the vertices in each tristrip.
int ti, si;
for (ti = 1; ti < num_y_verts; ti++) {
strip->add_vertex(ti * num_x_verts);
for (si = 1; si < num_x_verts; si++) {
strip->add_vertex((ti - 1) * num_x_verts + (si-1));
strip->add_vertex(ti * num_x_verts + si);
}
strip->add_vertex((ti - 1) * num_x_verts + (num_x_verts-1));
strip->close_primitive();
}
PT(Geom) geom = new Geom(vdata);
geom->add_primitive(strip);
geom_node->add_geom(geom);
_stale = true;
++_last_screen;
return geom_node;
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::regenerate_screen
// Access: Published
// Description: Removes all the children from the ProjectionScreen
// node, and adds the newly generated child returned by
// generate_screen().
////////////////////////////////////////////////////////////////////
void ProjectionScreen::
regenerate_screen(const NodePath &projector, const string &screen_name,
int num_x_verts, int num_y_verts, PN_stdfloat distance,
PN_stdfloat fill_ratio) {
// First, remove all existing children.
remove_all_children();
// And attach a new child.
PT(GeomNode) geom_node =
generate_screen(projector, screen_name, num_x_verts, num_y_verts,
distance, fill_ratio);
add_child(geom_node);
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::make_flat_mesh
// Access: Published
// Description: Generates a deep copy of the hierarchy at the
// ProjectionScreen node and below, with vertices
// flattened into two dimensions as if they were seen by
// the indicated camera node.
//
// This is useful for rendering an image as seen through
// a non-linear lens. The resulting mesh will have
// vertices in the range [-1, 1] in both x and y, and
// may be then rendered with an ordinary orthographic
// lens, to generate the effect of seeing the image
// through the specified non-linear lens.
//
// The returned node has no parent; it is up to the
// caller to parent it somewhere or store it so that it
// does not get dereferenced and deleted.
////////////////////////////////////////////////////////////////////
PT(PandaNode) ProjectionScreen::
make_flat_mesh(const NodePath &this_np, const NodePath &camera) {
nassertr(!this_np.is_empty() && this_np.node() == this, NULL);
nassertr(!camera.is_empty() &&
camera.node()->is_of_type(LensNode::get_class_type()),
NULL);
LensNode *camera_node = DCAST(LensNode, camera.node());
nassertr(camera_node->get_lens() != (Lens *)NULL, NULL);
// First, ensure the UV's are up-to-date.
recompute_if_stale(this_np);
PT(PandaNode) top = new PandaNode(get_name());
LMatrix4 rel_mat;
bool computed_rel_mat = false;
make_mesh_children(top, this_np, camera, rel_mat, computed_rel_mat);
return top;
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::recompute
// Access: Published
// Description: Recomputes all the UV's for geometry below the
// ProjectionScreen node, as if the texture were
// projected from the associated projector.
//
// This function is normally called automatically
// whenever the relevant properties change, so it should
// not normally need to be called directly by the user.
// However, it does no harm to call this if there is any
// doubt.
////////////////////////////////////////////////////////////////////
void ProjectionScreen::
recompute() {
NodePath this_np(NodePath::any_path(this));
do_recompute(this_np);
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::recompute_if_stale
// Access: Published
// Description: Calls recompute() only if the relative transform
// between the ProjectionScreen and the projector has
// changed, or if any other relevant property has
// changed. Returns true if recomputed, false
// otherwise.
////////////////////////////////////////////////////////////////////
bool ProjectionScreen::
recompute_if_stale() {
NodePath this_np(NodePath::any_path(this));
return recompute_if_stale(this_np);
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::recompute_if_stale
// Access: Published
// Description: Calls recompute() only if the relative transform
// between the ProjectionScreen and the projector has
// changed, or if any other relevant property has
// changed. Returns true if recomputed, false
// otherwise.
////////////////////////////////////////////////////////////////////
bool ProjectionScreen::
recompute_if_stale(const NodePath &this_np) {
nassertr(!this_np.is_empty() && this_np.node() == this, false);
if (_projector_node != (LensNode *)NULL &&
_projector_node->get_lens() != (Lens *)NULL) {
UpdateSeq lens_change = _projector_node->get_lens()->get_last_change();
if (_stale || lens_change != _projector_lens_change) {
recompute();
return true;
} else {
// Get the relative transform to ensure it hasn't changed.
CPT(TransformState) transform = this_np.get_transform(_projector);
const LMatrix4 &top_mat = transform->get_mat();
if (!_rel_top_mat.almost_equal(top_mat)) {
_rel_top_mat = top_mat;
_computed_rel_top_mat = true;
do_recompute(this_np);
return true;
}
}
}
return false;
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::do_recompute
// Access: Private
// Description: Starts the recomputation process.
////////////////////////////////////////////////////////////////////
void ProjectionScreen::
do_recompute(const NodePath &this_np) {
if (_projector_node != (LensNode *)NULL &&
_projector_node->get_lens() != (Lens *)NULL) {
recompute_node(this_np, _rel_top_mat, _computed_rel_top_mat);
// Make sure this flag is set to false for next time.
_computed_rel_top_mat = false;
_projector_lens_change = _projector_node->get_lens()->get_last_change();
_stale = false;
}
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::recompute_node
// Access: Private
// Description: Recurses over all geometry at the indicated node and
// below, looking for GeomNodes that want to have new
// UV's computed. When a new transform space is
// encountered, a new relative matrix is computed.
////////////////////////////////////////////////////////////////////
void ProjectionScreen::
recompute_node(const WorkingNodePath &np, LMatrix4 &rel_mat,
bool &computed_rel_mat) {
PandaNode *node = np.node();
if (node->is_geom_node()) {
recompute_geom_node(np, rel_mat, computed_rel_mat);
}
if (node->is_exact_type(SwitchNode::get_class_type())) {
// We make a special case for switch nodes only. Other kinds of
// selective child nodes, like LOD's and sequence nodes, will get
// all of their children traversed; switch nodes will only
// traverse the currently active child.
int i = DCAST(SwitchNode, node)->get_visible_child();
if (i >= 0 && i < node->get_num_children()) {
PandaNode *child = node->get_child(i);
recompute_child(WorkingNodePath(np, child), rel_mat, computed_rel_mat);
}
} else {
// A non-switch node. Recurse on all children.
int num_children = node->get_num_children();
for (int i = 0; i < num_children; i++) {
PandaNode *child = node->get_child(i);
recompute_child(WorkingNodePath(np, child), rel_mat, computed_rel_mat);
}
}
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::recompute_child
// Access: Private
// Description: Works in conjunction with recompute_node() to recurse
// over the whole graph. This is called on each child
// of a given node.
////////////////////////////////////////////////////////////////////
void ProjectionScreen::
recompute_child(const WorkingNodePath &np, LMatrix4 &rel_mat,
bool &computed_rel_mat) {
PandaNode *child = np.node();
const TransformState *transform = child->get_transform();
if (!transform->is_identity()) {
// This child node has a transform; therefore, we must recompute
// the relative matrix from this point.
LMatrix4 new_rel_mat;
bool computed_new_rel_mat = false;
if (distort_cat.is_spam()) {
distort_cat.spam()
<< "Saving rel_mat " << (void *)&new_rel_mat << " at " << np << "\n";
}
recompute_node(np, new_rel_mat, computed_new_rel_mat);
} else {
// This child has no transform, so we can use the same transform
// space from before.
recompute_node(np, rel_mat, computed_rel_mat);
}
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::recompute_geom_node
// Access: Private
// Description: Recomputes the UV's just for the indicated GeomNode.
////////////////////////////////////////////////////////////////////
void ProjectionScreen::
recompute_geom_node(const WorkingNodePath &np, LMatrix4 &rel_mat,
bool &computed_rel_mat) {
GeomNode *node = DCAST(GeomNode, np.node());
if (!computed_rel_mat) {
// All right, time to compute the matrix.
NodePath true_np = np.get_node_path();
rel_mat = true_np.get_transform(_projector)->get_mat();
computed_rel_mat = true;
if (distort_cat.is_spam()) {
distort_cat.spam()
<< "Computing rel_mat " << (void *)&rel_mat << " at " << np << "\n";
distort_cat.spam()
<< " " << rel_mat << "\n";
}
} else {
if (distort_cat.is_spam()) {
distort_cat.spam()
<< "Applying rel_mat " << (void *)&rel_mat << " to " << np << "\n";
}
}
int num_geoms = node->get_num_geoms();
for (int i = 0; i < num_geoms; i++) {
PT(Geom) geom = node->modify_geom(i);
distort_cat.debug()
<< " " << *node << " got geom " << geom
<< ", cache_ref = " << geom->get_cache_ref_count() << "\n";
geom->test_ref_count_integrity();
recompute_geom(geom, rel_mat);
}
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::recompute_geom
// Access: Private
// Description: Recomputes the UV's just for the indicated Geom.
////////////////////////////////////////////////////////////////////
void ProjectionScreen::
recompute_geom(Geom *geom, const LMatrix4 &rel_mat) {
static const LMatrix4 lens_to_uv
(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);
static const LMatrix4 lens_to_uv_inverted
(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);
Thread *current_thread = Thread::get_current_thread();
Lens *lens = _projector_node->get_lens();
nassertv(lens != (Lens *)NULL);
const LMatrix4 &to_uv = _invert_uvs ? lens_to_uv_inverted : lens_to_uv;
// Iterate through all the vertices in the Geom.
CPT(GeomVertexData) vdata = geom->get_vertex_data(current_thread);
vdata = vdata->animate_vertices(true, current_thread);
CPT(GeomVertexFormat) vformat = vdata->get_format();
if (!vformat->has_column(_texcoord_name) || (_texcoord_3d && vformat->get_column(_texcoord_name)->get_num_components() < 3)) {
// We need to add a new column for the new texcoords.
vdata = vdata->replace_column
(_texcoord_name, 3, Geom::NT_stdfloat, Geom::C_texcoord);
geom->set_vertex_data(vdata);
}
if (_vignette_on && !vdata->has_column(InternalName::get_color())) {
// We need to add a column for color.
vdata = vdata->replace_column
(InternalName::get_color(), 1, Geom::NT_packed_dabc, Geom::C_color);
geom->set_vertex_data(vdata);
}
// Clear the vdata pointer so we don't force a copy in the below.
vdata.clear();
PT(GeomVertexData) modify_vdata = geom->modify_vertex_data();
// Maybe the vdata has animation that we should consider.
CPT(GeomVertexData) animated_vdata = geom->get_vertex_data(current_thread)->animate_vertices(true, current_thread);
GeomVertexWriter texcoord(modify_vdata, _texcoord_name, current_thread);
GeomVertexWriter color(modify_vdata, current_thread);
GeomVertexReader vertex(animated_vdata, InternalName::get_vertex(), current_thread);
if (_vignette_on) {
color.set_column(InternalName::get_color());
}
while (!vertex.is_at_end()) {
LVertex vert = vertex.get_data3();
// For each vertex, project to the film plane.
LPoint3 vert3d = vert * rel_mat;
LPoint3 film(0.0f, 0.0f, 0.0f);
bool good = lens->project(vert3d, film);
// Now the lens gives us coordinates in the range [-1, 1].
// Rescale these to [0, 1].
LPoint3 uvw = film * to_uv;
if (good && _has_undist_lut) {
LPoint3f p;
if (!_undist_lut.calc_bilinear_point(p, uvw[0], 1.0 - uvw[1])) {
// Point is missing.
// We're better off keeping the point where it is,
// undistorted--it's probably close to where it should
// be--than we are changing it arbitrarily to (0, 0), which
// might be far away from where it should be.
//uvw.set(0, 0, 0);
good = false;
} else {
uvw = LCAST(PN_stdfloat, p);
uvw[1] = 1.0 - uvw[1];
}
}
texcoord.set_data3(uvw);
// If we have vignette color in effect, color the vertex according
// to whether it fell in front of the lens or not.
if (_vignette_on) {
if (good) {
color.set_data4(_frame_color);
} else {
color.set_data4(_vignette_color);
}
}
}
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::make_mesh_node
// Access: Private
// Description: Recurses over all geometry at the indicated node and
// below, and generates a corresponding node hierarchy
// with all the geometry copied, but flattened into 2-d,
// as seen from the indicated camera. Returns the newly
// created node, or NULL if no node was created.
////////////////////////////////////////////////////////////////////
PandaNode *ProjectionScreen::
make_mesh_node(PandaNode *result_parent, const WorkingNodePath &np,
const NodePath &camera,
LMatrix4 &rel_mat, bool &computed_rel_mat) {
PandaNode *node = np.node();
PT(PandaNode) new_node;
if (node->is_geom_node()) {
new_node = make_mesh_geom_node(np, camera, rel_mat, computed_rel_mat);
} else if (node->safe_to_flatten()) {
new_node = node->make_copy();
new_node->clear_transform();
} else {
// If we can't safely flatten the node, just make a plain node in
// its place.
new_node = new PandaNode(node->get_name());
new_node->set_state(node->get_state());
}
// Now attach the new node to the result.
result_parent->add_child(new_node);
make_mesh_children(new_node, np, camera, rel_mat, computed_rel_mat);
return new_node;
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::make_mesh_children
// Access: Private
// Description: Walks over the list of children for the indicated
// node, calling make_mesh_node() on each one.
////////////////////////////////////////////////////////////////////
void ProjectionScreen::
make_mesh_children(PandaNode *new_node, const WorkingNodePath &np,
const NodePath &camera,
LMatrix4 &rel_mat, bool &computed_rel_mat) {
PandaNode *node = np.node();
int num_children = node->get_num_children();
for (int i = 0; i < num_children; i++) {
PandaNode *child = node->get_child(i);
PandaNode *new_child;
const TransformState *transform = child->get_transform();
if (!transform->is_identity()) {
// This child node has a transform; therefore, we must recompute
// the relative matrix from this point.
LMatrix4 new_rel_mat;
bool computed_new_rel_mat = false;
new_child = make_mesh_node(new_node, WorkingNodePath(np, child), camera,
new_rel_mat, computed_new_rel_mat);
} else {
// This child has no transform, so we can use the same transform
// space from before.
new_child = make_mesh_node(new_node, WorkingNodePath(np, child), camera,
rel_mat, computed_rel_mat);
}
if (new_child != NULL) {
// Copy all of the render state (except TransformState) to the
// new arc.
new_child->set_state(child->get_state());
}
}
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::make_mesh_geom_node
// Access: Private
// Description: Makes a new GeomNode, just like the given one, except
// flattened into two dimensions as seen by the
// indicated camera.
////////////////////////////////////////////////////////////////////
PT(GeomNode) ProjectionScreen::
make_mesh_geom_node(const WorkingNodePath &np, const NodePath &camera,
LMatrix4 &rel_mat, bool &computed_rel_mat) {
GeomNode *node = DCAST(GeomNode, np.node());
PT(GeomNode) new_node = new GeomNode(node->get_name());
LensNode *lens_node = DCAST(LensNode, camera.node());
if (!computed_rel_mat) {
// All right, time to compute the matrix.
NodePath true_np = np.get_node_path();
rel_mat = true_np.get_transform(camera)->get_mat();
computed_rel_mat = true;
}
int num_geoms = node->get_num_geoms();
for (int i = 0; i < num_geoms; i++) {
const Geom *geom = node->get_geom(i);
PT(Geom) new_geom =
make_mesh_geom(geom, lens_node->get_lens(), rel_mat);
if (new_geom != (Geom *)NULL) {
new_node->add_geom(new_geom, node->get_geom_state(i));
}
}
return new_node;
}
////////////////////////////////////////////////////////////////////
// Function: ProjectionScreen::make_mesh_geom
// Access: Private
// Description: Makes a new Geom, just like the given one, except
// flattened into two dimensions as seen by the
// indicated lens. Any triangle in the original mesh
// that involves an unprojectable vertex is eliminated.
////////////////////////////////////////////////////////////////////
PT(Geom) ProjectionScreen::
make_mesh_geom(const Geom *geom, Lens *lens, LMatrix4 &rel_mat) {
static const LMatrix4 lens_to_uv
(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);
static const LMatrix4 uv_to_lens = invert(lens_to_uv);
Thread *current_thread = Thread::get_current_thread();
PT(Geom) new_geom = geom->make_copy();
PT(GeomVertexData) vdata = new_geom->modify_vertex_data();
new_geom->set_vertex_data(vdata->animate_vertices(false, current_thread));
vdata = new_geom->modify_vertex_data();
GeomVertexRewriter vertex(vdata, InternalName::get_vertex());
while (!vertex.is_at_end()) {
LVertex vert = vertex.get_data3();
// Project each vertex into the film plane, but use three
// dimensions so the Z coordinate remains meaningful.
LPoint3 vert3d = vert * rel_mat;
LPoint3 film(0.0f, 0.0f, 0.0f);
bool good = lens->project(vert3d, film);
if (good && _has_undist_lut) {
// Now the lens gives us coordinates in the range [-1, 1].
// Rescale these to [0, 1].
LPoint3 uvw = film * lens_to_uv;
LPoint3f p;
if (!_undist_lut.calc_bilinear_point(p, uvw[0], 1.0 - uvw[1])) {
// Point is missing.
uvw.set(0, 0, 0);
good = false;
} else {
uvw = LCAST(PN_stdfloat, p);
uvw[1] = 1.0 - uvw[1];
}
film = uvw * uv_to_lens;
}
vertex.set_data3(film);
}
return new_geom;
}
| 38.256962 | 128 | 0.585944 | [
"mesh",
"geometry",
"render",
"object",
"transform",
"3d"
] |
3d462b187953fb9945166356bf33db4ff0edf1c1 | 2,234 | hpp | C++ | include/global_kernel_functions.hpp | rgcv/libcgal-julia | 8d5bc5f13d3c9c6160cfff795d2a0bbe1e473d94 | [
"MIT"
] | 5 | 2020-01-22T14:06:29.000Z | 2021-09-23T11:29:18.000Z | include/global_kernel_functions.hpp | rgcv/libcgal-julia | 8d5bc5f13d3c9c6160cfff795d2a0bbe1e473d94 | [
"MIT"
] | null | null | null | include/global_kernel_functions.hpp | rgcv/libcgal-julia | 8d5bc5f13d3c9c6160cfff795d2a0bbe1e473d94 | [
"MIT"
] | 2 | 2021-02-16T13:56:02.000Z | 2022-03-14T17:17:30.000Z | #ifndef CGAL_JL_GLOBAL_KERNEL_FUNCTIONS_HPP
#define CGAL_JL_GLOBAL_KERNEL_FUNCTIONS_HPP
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/variant.hpp>
#include <jlcxx/type_conversion.hpp>
#include <julia.h>
#include "kernel.hpp"
#include "kernel_conversion.hpp"
namespace jlcgal {
struct Intersection_visitor {
typedef jl_value_t* result_type;
template<typename T>
inline
result_type
operator()(const T& t) const {
return jlcxx::box<T>(t);
}
template<typename... TS>
inline
result_type
operator()(const boost::variant<TS...>& v) const {
return boost::apply_visitor(*this, v);
}
template<typename T>
result_type
operator()(const std::vector<T>& ts) const {
if (ts.empty()) {
return jl_nothing;
}
const std::size_t sz = ts.size();
result_type first = (*this)(ts[0]);
if (sz == 1) {
return first;
}
jl_value_t* atype = jl_apply_array_type(jl_typeof(first), 1);
jl_array_t* ja = jl_alloc_array_1d(atype, sz);
JL_GC_PUSH1(&ja);
for (std::size_t i = 0; i < sz; ++i) {
jl_arrayset(ja, (*this)(ts[i]), i);
}
JL_GC_POP();
return (result_type)ja;
}
// Circular types
inline
result_type
operator()(const std::pair<CK::Circular_arc_point_2, unsigned>& p) const {
return jlcxx::box<Point_2>(To_linear<CK::Circular_arc_point_2>()(p.first));
}
inline
result_type
operator()(const CK::Circle_2& c) const {
return jlcxx::box<Circle_2>(To_linear<CK::Circle_2>()(c));
}
// Spherical types
inline
result_type
operator()(const std::pair<SK::Circular_arc_point_3, unsigned>& p) const {
return jlcxx::box<Point_3>(To_linear<SK::Circular_arc_point_3>()(p.first));
}
#define SPHERICAL_VISITOR(T, ST) \
inline \
result_type \
operator()(const SK::T& t) const { \
return jlcxx::box<T>(To_linear<SK::ST>()(t)); \
}
#define SSPHERICAL_VISITOR(T) SPHERICAL_VISITOR(T, T)
SSPHERICAL_VISITOR(Sphere_3)
SSPHERICAL_VISITOR(Plane_3)
SSPHERICAL_VISITOR(Line_3)
SSPHERICAL_VISITOR(Circle_3)
SPHERICAL_VISITOR(Segment_3, Line_arc_3)
#undef SPHERICAL_VISITOR
#undef SSPHERICAL_VISITOR
};
} // jlcgal
#endif // CGAL_JL_GLOBAL_KERNEL_FUNCTIONS_HPP
| 22.34 | 79 | 0.680394 | [
"vector"
] |
3d4801a5973f40bb75fc6a8ed6b21dc013be5c95 | 612 | cpp | C++ | test/math/enumerate_k-th_power.test.cpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | 1 | 2021-12-26T14:17:29.000Z | 2021-12-26T14:17:29.000Z | test/math/enumerate_k-th_power.test.cpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | 3 | 2020-07-13T06:23:02.000Z | 2022-02-16T08:54:26.000Z | test/math/enumerate_k-th_power.test.cpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | null | null | null | /*
* @brief 数学/$i^k \bmod m \ (0 \leq i \leq n)$
*/
#define PROBLEM "https://yukicoder.me/problems/no/1409"
#include <iostream>
#include <vector>
#include "../../math/enumerate_k-th_power.hpp"
int main() {
int t;
std::cin >> t;
while (t--) {
int v, x;
std::cin >> v >> x;
int p = x * v + 1;
std::vector<int> pw = enumerate_kth_power(p - 1, x, p);
std::vector<int> a;
a.reserve(x);
for (int i = 1; i < p; ++i) {
if (pw[i] == 1) a.emplace_back(i);
}
for (int i = 0; i < x; ++i) std::cout << a[i] << " \n"[i + 1 == x];
}
return 0;
}
| 22.666667 | 72 | 0.477124 | [
"vector"
] |
3d48986c18abf006a3701f7db1505741dc0c51cd | 1,691 | hpp | C++ | vm/builtin/data.hpp | bruce/rubinius | 44d3bdd0d988a17de1fe446bd29d2e9dede65f45 | [
"BSD-3-Clause"
] | 1 | 2017-09-09T21:28:06.000Z | 2017-09-09T21:28:06.000Z | vm/builtin/data.hpp | bruce/rubinius | 44d3bdd0d988a17de1fe446bd29d2e9dede65f45 | [
"BSD-3-Clause"
] | null | null | null | vm/builtin/data.hpp | bruce/rubinius | 44d3bdd0d988a17de1fe446bd29d2e9dede65f45 | [
"BSD-3-Clause"
] | null | null | null | #ifndef RBX_BUILTIN_DATA_HPP
#define RBX_BUILTIN_DATA_HPP
#include "builtin/object.hpp"
#include "type_info.hpp"
namespace rubinius {
// HACK manually copied here from ruby.h
struct RDataExposed {
void (*dmark)(void*);
void (*dfree)(void*);
void *data;
};
class Data : public Object {
public:
const static object_type type = DataType;
public: /* Types */
/** The signature for the mark function. */
typedef void (*MarkFunctor)(void*);
/** The signature for the free function. */
typedef void (*FreeFunctor)(void*);
private:
RDataExposed exposed_;
public: /* Interface */
/** Register class with the VM. */
static void init(STATE);
/** New Data instance. */
static Data* create(STATE, void* data, MarkFunctor mark, FreeFunctor free);
static void finalize(STATE, Data* data);
RDataExposed* exposed() {
return &exposed_;
}
void* data() {
return exposed_.data;
}
FreeFunctor free() {
return exposed_.dfree;
}
MarkFunctor mark() {
return exposed_.dmark;
}
void** data_address() {
return &exposed_.data;
}
void data(STATE, void* data) {
exposed_.data = data;
}
void free(STATE, FreeFunctor free) {
exposed_.dfree = free;
}
void mark(STATE, MarkFunctor mark) {
exposed_.dmark = mark;
}
public: /* TypeInfo */
class Info : public TypeInfo {
public:
Info(object_type type, bool cleanup = false) : TypeInfo(type, cleanup) { }
virtual void mark(Object* t, ObjectMark& mark);
virtual void auto_mark(Object* obj, ObjectMark& mark) {}
};
};
}
#endif
| 19.894118 | 80 | 0.612064 | [
"object"
] |
3d48c762de42d61ef0206ebfef037861c837557f | 26,627 | cpp | C++ | src/database/impl/BufferedSequenceDatabase.cpp | nileshpatra/plast-library | 7c962282fdb68ac1f48a587e03fbb1a1b70a7a32 | [
"Intel",
"DOC"
] | 9 | 2016-09-30T05:44:35.000Z | 2020-09-03T19:40:06.000Z | src/database/impl/BufferedSequenceDatabase.cpp | nileshpatra/plast-library | 7c962282fdb68ac1f48a587e03fbb1a1b70a7a32 | [
"Intel",
"DOC"
] | 10 | 2017-05-05T14:55:16.000Z | 2022-01-24T18:21:51.000Z | src/database/impl/BufferedSequenceDatabase.cpp | nileshpatra/plast-library | 7c962282fdb68ac1f48a587e03fbb1a1b70a7a32 | [
"Intel",
"DOC"
] | 1 | 2020-12-05T21:33:27.000Z | 2020-12-05T21:33:27.000Z | /*****************************************************************************
* *
* PLAST : Parallel Local Alignment Search Tool *
* Version 2.3, released November 2015 *
* Copyright (c) 2009-2015 Inria-Cnrs-Ens *
* *
* PLAST is free software; you can redistribute it and/or modify it under *
* the Affero GPL ver 3 License, that is compatible with the GNU General *
* Public License *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* Affero GPL ver 3 License for more details. *
*****************************************************************************/
#include <database/impl/BufferedSequenceDatabase.hpp>
#include <designpattern/impl/Property.hpp>
#include <misc/api/macros.hpp>
#include <misc/api/PlastStrings.hpp>
#include <designpattern/api/ICommand.hpp>
#include <designpattern/impl/CommandDispatcher.hpp>
#include <stdlib.h>
#include <stdio.h>
#define DEBUG(a) //printf a
using namespace std;
using namespace dp;
using namespace dp::impl;
using namespace os;
using namespace os::impl;
extern "C" void seg_filterSequence (char* sequence, int length);
extern "C" void dust_filterSequence (char* sequence, int length);
extern "C" void DustMasker_filterSequence (char* s, int len);
/********************************************************************************/
namespace database { namespace impl {
/********************************************************************************/
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
BufferedSequenceDatabase::BufferedSequenceDatabase (ISequenceIterator* refIterator, int filterLowComplexity)
: _nbSequences(0),
_refIterator(0),
_cache(0),
_firstIdx(0), _lastIdx(0),
_filterLowComplexity (filterLowComplexity),
_direction(ISequenceDatabase::PLUS)
{
DEBUG (("BufferedSequenceDatabase::BufferedSequenceDatabase this=%p '%s'\n", this, refIterator->getId().c_str()));
/** We just keep a reference on the provided sequence iterator. The cache should be built on the first call
* to some public API method. */
setRefSequenceIterator (refIterator);
/** We get the same id of the iterator used for building the database. */
setId (_refIterator->getId());
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
BufferedSequenceDatabase::BufferedSequenceDatabase (
const string& id,
ISequenceCache* cache,
size_t firstIdx,
size_t lastIdx
)
: _id(id), _nbSequences(0), _refIterator(0), _cache(0), _firstIdx(firstIdx), _lastIdx(lastIdx), _direction(ISequenceDatabase::PLUS)
{
DEBUG (("BufferedSequenceDatabase::BufferedSequenceDatabase this=%p [%ld,%ld] \n", this, _firstIdx, _lastIdx));
/** We set the current cache. */
setCache (cache);
/** We use a shortcut for time optimization. */
_nbSequences = _lastIdx - _firstIdx + 1;
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
BufferedSequenceDatabase::~BufferedSequenceDatabase ()
{
DEBUG (("BufferedSequenceDatabase::~BufferedSequenceDatabase this=%p '%s' \n", this, this->getId().c_str()));
/** We release instances. */
setCache (0);
setRefSequenceIterator (0);
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
ISequenceCache* BufferedSequenceDatabase::getCache()
{
if (_cache == 0)
{
/** We build the cache. */
setCache (buildCache(_refIterator));
/** We can now release the referenced iterator. */
//setRefSequenceIterator (0);
}
return _cache;
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
ISequenceCache* BufferedSequenceDatabase::buildCache (ISequenceIterator* refIterator)
{
ISequenceCache* result = 0;
DEBUG (("BufferedSequenceDatabase::buildCache BEGIN\n"));
/** We create a new cache. */
result = new ISequenceCache (10*1024);
/** We change the sequence builder. We initialize it with the vectors of the cache to be filled during iteration. */
ISequenceBuilder* builder = 0;
if (_filterLowComplexity == 0) { builder = new BufferedSequenceBuilder (result); }
else { builder = new BufferedSegmentSequenceBuilder (result, _filterLowComplexity); }
refIterator->setBuilder (builder);
/** We just loop through the ref iterator => the builder will fill the cache vectors. */
for (refIterator->first(); !refIterator->isDone(); refIterator->next()) {}
DEBUG (("BufferedSequenceDatabase::buildCache iteration done: dataSize=%d nbSequences=%ld \n",
result->dataSize, result->nbSequences
));
/** We may have no result; just return. */
if (result->dataSize == 0) { return result; }
/** We can resize the containers with true sizes. */
result->database.resize (result->dataSize + result->shift);
result->comments.resize (result->nbSequences);
result->offsets.resize (result->nbSequences + 1);
/** We add some extra letters in order to be sure that the BLAST algorithm won't read too far in unauthorized memory. */
for (Offset i=result->dataSize; i<result->dataSize + result->shift; i++)
{
result->database.data [i] = EncodingManager::singleton().getAlphabet(SUBSEED)->any;
}
/** Note that we add an extra offset that matches the total size of the data.
* => useful for computing the last sequence size by difference of two offsets. */
(result->offsets.data) [result->nbSequences] = result->dataSize;
/** We may have to do some post treatment. */
if (builder != 0) { builder->postTreamtment(); }
/** We compute the sequence average size. */
size_t sizeAverage = (result->nbSequences > 0 ? result->database.size / result->nbSequences : 1);
/** We increase this average by a factor (avoids too many interpolation failures in the getSequenceByOffset method). */
sizeAverage = (sizeAverage*115) / 100;
/** We compute coeffs [a,b] giving an estimate of this average as the number 2^b/a.
* The computation tries to achieve some relative error. */
size_t a=0, b=0;
/** We loop over powers of 2. */
for (b=1; b<32; b++)
{
/** We look for a b such as 2^b >= N. */
if ( (1<<b) >= sizeAverage)
{
/** 'a' should be > 0. */
a = (1<<b) / sizeAverage;
/** We look for a small relative error. */
float err = 1.0 - (float)(1<<b) / (float)a / (float)sizeAverage ;
if (ABS(err) < 0.03) { break; }
}
}
result->sequenceAverageA = a;
result->sequenceAverageB = b;
/** We memorize the number of sequences found during iteration. */
_nbSequences = result->nbSequences;
/** We can set the [first,last] indexes for iterators. */
if (_nbSequences > 0)
{
_firstIdx = 0;
_lastIdx = _nbSequences - 1;
}
else
{
_firstIdx = 1;
_lastIdx = 0;
}
DEBUG (("BufferedSequenceDatabase::buildCache dataSize=%lld nbSeq=%ld average=[%d,%d] first=%ld last=%ld \n",
result->dataSize, result->nbSequences,
result->sequenceAverageA, result->sequenceAverageB,
_firstIdx, _lastIdx
));
/** We return the result. */
return result;
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
void BufferedSequenceDatabase::updateSequence (size_t idx, ISequence& sequence)
{
DEBUG (("BufferedSequenceDatabase::updateSequence idx=%ld\n", idx));
/** Shortcut. */
ISequenceCache* cache = getCache ();
/** We set the index of the sequence in the database. */
sequence.index = idx;
/** A little shortcut (avoid two memory accesses). */
Offset currentOffset = cache->offsets.data [idx];
/** We set 'database' attribute. */
sequence.database = this;
/** We set the offset in database attribute. */
sequence.offsetInDb = currentOffset - cache->shift;
/** We get a pointer to the comment of the current sequence. */
sequence.comment = cache->comments[idx].c_str();
/** We get a pointer to the data of the current sequence. */
sequence.data.setReference (
cache->offsets.data[idx+1] - currentOffset,
(LETTER*) (cache->database.data + currentOffset)
);
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
bool BufferedSequenceDatabase::getSequenceByIndex (size_t index, ISequence& sequence)
{
DEBUG (("BufferedSequenceDatabase::getSequenceByIndex index=%ld\n", index));
bool result = false;
if (isIndexValid(index) == true)
{
updateSequence (_firstIdx + index, sequence);
result = true;
}
return result;
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
bool BufferedSequenceDatabase::getSequenceByOffset (
u_int64_t offset,
ISequence& sequence,
u_int32_t& offsetInSequence,
u_int64_t& actualOffsetInDatabase
)
{
/** Shortcut. */
ISequenceCache* cache = getCache ();
/** We reset the argument to be filled. */
offsetInSequence = 0;
/** Note that we have to take into account the potential shift in the cache data buffer */
offset += cache->shift;
/** Shortcut. */
Offset* offsets = cache->offsets.data;
size_t nb = cache->offsets.size;
u_int8_t A = cache->sequenceAverageA;
u_int8_t B = cache->sequenceAverageB;
/** We first look for the sequence index from the provided offset (use dichotomy search) */
size_t smin = 0;
size_t smax = nb - 1;
/** We initialize the first index for beginning the dichotomy process.
* A classical choice may be idx = (smax+smin)/2 but we can try better initial guess. */
size_t idx = (offset *A) >> B;
if (idx >= smax) { idx = (smax+smin) >> 1; }
/** We use a temporary variable in order not to do a comparison twice. */
bool b = false;
/** We compute the delta between the provided offset and the highest position in the current range.
* If this delta is >= 0, it means that we have still not found the idx.
* In this case, we now that the min index will be updated and that the delta can be used for computing
* the idx interpolation.
*/
int32_t delta = 0;
while ( (b = offsets[idx] > offset) || ((delta = offset-offsets[idx+1]) >= 0) )
{
if (b) { smax = idx - 1; }
else { smin = idx + 1; }
/** We interpolate the index. Ideally, we should compute: idx = smin + delta / averageSize
* Because of the division time cost, we try instead to perform a bits shift; this will be
* less accurate in terms of interpolation but much quicker in terms of speed.
*/
idx = smin + ((delta * A) >> B);
/** If interpolation fails, we use classical dichotomy approach. */
if (idx >= smax) { idx = (smin+smax) >> 1; }
}
if (false)
{
if (offset < offsets[idx] || offset >= offsets[idx+1]) { throw MSG_DATABASE_MSG1; }
}
/** Optimization that avoids several memory acces. */
size_t off0 = offsets[idx];
/** Now, 'idx' should contain the index of the wanted sequence. */
offsetInSequence = offset - off0;
/** We set the actual offset in db. */
actualOffsetInDatabase = offset - cache->shift;
/** We set the database field. */
sequence.database = this;
/** We set the offset in database attribute. */
sequence.offsetInDb = off0 - cache->shift;
/** We get a pointer to the comment of the current sequence. */
sequence.comment = cache->comments[idx].c_str();
/** We get a pointer to the data of the current sequence. */
sequence.data.setReference (
offsets[idx+1] - off0,
(LETTER*) (cache->database.data + off0)
);
sequence.index = idx;
/** Always true because the dichotomy is not supposed to fail. */
return true;
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
bool BufferedSequenceDatabase::getSequenceByName (
const std::string& id,
ISequence& sequence
)
{
bool result = false;
/** Shortcut. */
vector<string>& comments = _cache->comments;
size_t i=0;
for (i=0; i<comments.size(); i++)
{
result = comments[i].find (id) != string::npos;
if (result) { break; }
}
if (result) { result = getSequenceByIndex (i, sequence); }
/** We return the result. */
return result;
}
/*********************************************************************
** METHOD : CacheIterator::changeSequence
** PURPOSE : fill the attributes of the sequence returned by 'currentItem'
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS : uses cached information for setting the sequence attributes
*********************************************************************/
void BufferedSequenceDatabase::retrieveSequencesIdentifiers (std::set<std::string>& ids)
{
ISequenceCache* cache = getCache ();
for (size_t i=0; i<cache->nbSequences; i++)
{
string& comment = cache->comments[i];
/** We look for the first space. */
char* locate = ISequence::searchIdSeparator (comment.c_str());
if (locate != 0)
{
ids.insert (comment.substr (0, locate - comment.c_str()));
}
else
{
ids.insert (comment);
}
}
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
void BufferedSequenceDatabase::reverse ()
{
getCache()->reverse();
_direction = (_direction == ISequenceDatabase::PLUS ? ISequenceDatabase::MINUS : ISequenceDatabase::PLUS);
}
/*********************************************************************
** METHOD : CacheIterator::changeSequence
** PURPOSE : fill the attributes of the sequence returned by 'currentItem'
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS : uses cached information for setting the sequence attributes
*********************************************************************/
void BufferedSequenceDatabase::BufferedSequenceIterator::updateItem()
{
/** A little shortcut (avoid two memory accesses). */
Offset currentOffset = _cache->offsets.data[_currentIdx];
/** We set the database field. */
_item.database = _db;
/** We get a pointer to the comment of the current sequence. */
_item.comment = _cache->comments[_currentIdx].c_str();
/** We set the offset in database attribute. */
_item.offsetInDb = currentOffset - _cache->shift;
/** We set the index. */
_item.index = _currentIdx;
/** We get a pointer to the data of the current sequence. */
_item.data.setReference (
_cache->offsets.data[_currentIdx+1] - currentOffset,
(LETTER*) (_cache->database.data + currentOffset)
);
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
vector<ISequenceDatabase*> BufferedSequenceDatabase::split (size_t nbSplit)
{
vector<ISequenceDatabase*> result;
if (nbSplit > 0)
{
/** Shortcut. */
ISequenceCache* cache = getCache ();
/** We compute the average sequences number for each iterator. */
size_t averageNbSequences = cache->nbSequences / nbSplit;
/** We may have to add one if the remainder is not null. */
if (cache->nbSequences % nbSplit != 0) { averageNbSequences++; }
DEBUG (("BufferedIterator::split nbSplit=%ld => average=%ld (nbSeq=%ld) \n",
nbSplit, averageNbSequences, cache->nbSequences
));
size_t first = 0;
size_t last = 0;
for (size_t i=0; first<cache->nbSequences && i<nbSplit; i++)
{
last = min (first + averageNbSequences - 1, cache->nbSequences-1);
/** We create a new iterator. */
ISequenceDatabase* it = new BufferedSequenceDatabase (_id, cache, first, last);
/** We add it into the list of split iterators. */
result.push_back (it);
/** We increase the first index of the next iterator. */
first += averageNbSequences;
}
}
/** We return the result. */
return result;
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
IProperties* BufferedSequenceDatabase::getProperties (const std::string& root)
{
IProperties* props = new Properties();
props->add (0, root, "%lld bytes, %ld sequences", getSize(), getSequencesNumber());
props->add (1, "size", "%lld", getSize());
props->add (1, "nb_sequences", "%ld", getSequencesNumber());
/** We look for the shortest and longest sequences. */
size_t minSeq = ~0;
size_t maxSeq = 0;
ISequenceIterator* it = createSequenceIterator();
LOCAL(it);
for (it->first(); !it->isDone(); it->next() )
{
const ISequence* seq = it->currentItem();
if (seq != 0)
{
size_t size = seq->data.letters.size;
if (size > maxSeq) { maxSeq = size; }
if (size < minSeq) { minSeq = size; }
}
}
props->add (1, "shortest", "%ld", minSeq);
props->add (1, "largest", "%ld", maxSeq);
return props;
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
BufferedSequenceBuilder::BufferedSequenceBuilder (ISequenceCache* cache)
: _cache(0), _sourceEncoding(UNKNOWN), _destEncoding(SUBSEED), _convertTable(0)
{
setCache (cache);
_currentDataCapacity = _cache->database.size;
_currentSequencesCapacity = _cache->offsets.size;
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
void BufferedSequenceBuilder::setCommentUri (const char* filename, u_int32_t offsetHeader, u_int32_t size)
{
char bufferNumber[30];
if (_currentSequencesCapacity <= _cache->nbSequences)
{
_currentSequencesCapacity += _currentSequencesCapacity/2;
_cache->offsets.resize (_currentSequencesCapacity);
_cache->comments.resize (_currentSequencesCapacity);
}
//DEBUG (("BufferedSequenceDatabase::BufferedSequenceBuilder::setComment: len=%ld\n", length));
_cache->comments [_cache->nbSequences].assign (filename, strlen(filename));
sprintf(bufferNumber,",%d,%d",offsetHeader,size);
_cache->comments [_cache->nbSequences].append (bufferNumber, strlen(bufferNumber));
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
void BufferedSequenceBuilder::setComment (const char* buffer, size_t length)
{
if (_currentSequencesCapacity <= _cache->nbSequences)
{
_currentSequencesCapacity += _currentSequencesCapacity/2;
_cache->offsets.resize (_currentSequencesCapacity);
_cache->comments.resize (_currentSequencesCapacity);
}
//DEBUG (("BufferedSequenceDatabase::BufferedSequenceBuilder::setComment: len=%ld\n", length));
_cache->comments [_cache->nbSequences].assign (buffer, length);
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
void BufferedSequenceBuilder::resetData (void)
{
_cache->offsets.data [_cache->nbSequences++] = _cache->dataSize;
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
BufferedSegmentSequenceBuilder::BufferedSegmentSequenceBuilder (ISequenceCache* cache, int segMinSize)
: BufferedSequenceBuilder (cache),
_filterSequenceCallback (seg_filterSequence),
_segMinSize(segMinSize)
{
/** We have a specific sequence filter algorithm (dust) for nucleotide database.
* Note that, by default, we use an amino acid algorithm (seg).
*/
if (EncodingManager::singleton().getKind () == EncodingManager::ALPHABET_NUCLEOTID)
{
_filterSequenceCallback = DustMasker_filterSequence;
}
_destEncoding = ASCII;
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
struct FilterParams
{
FilterParams (char* seq, int len) : seq(seq), len(len) {}
char* seq; int len;
};
class FilterSequenceCmd : public dp::ICommand
{
public:
FilterSequenceCmd (void (*cbk) (char* seq, int len), list<FilterParams>& params) : cbk(cbk), params(params) {}
void execute ()
{
for (list<FilterParams>::iterator it = params.begin(); it != params.end(); ++it) { cbk (it->seq, it->len); }
}
private:
void (*cbk) (char* seq, int len);
list<FilterParams>& params;
};
/**********************************************************************/
void BufferedSegmentSequenceBuilder::postTreamtment (void)
{
/** Shortcut. */
LETTER* data = _cache->database.data;
//printf ("BufferedSegmentSequenceBuilder::postTreamtment 1. : size=%ld\n", _cache->dataSize);
//for (size_t i=0; i<_cache->dataSize; i++) { printf ("%c", data[i]); } printf("\n");
#if 1
size_t nbCores = 1;
/** Right now, 'seg' is not parallelizable, so do it just for 'dust'. */
if (_filterSequenceCallback == DustMasker_filterSequence) { nbCores = DefaultFactory::thread().getNbCores(); }
vector<list<FilterParams> > paramsVector (nbCores);
/** We launch low complexity removal for each sequence.
* Note that this post treatment could be parallelized in several threads. */
for (size_t i=0; i<_cache->nbSequences; i++)
{
/** We get the size of the sequence. */
size_t len = _cache->offsets.data[i+1] - _cache->offsets.data[i];
/** We memorize the parameters for the filter algorithm. */
if (len >= _segMinSize && _filterSequenceCallback != 0) { paramsVector[i%nbCores].push_back (FilterParams(data + _cache->offsets.data[i], len)); }
}
/** We build as many commands as wanted and execute them through a dispatcher. */
list<ICommand*> commands;
for (size_t i=0; i<nbCores; i++) { commands.push_back (new FilterSequenceCmd (_filterSequenceCallback, paramsVector[i])); }
ParallelCommandDispatcher(nbCores).dispatchCommands (commands);
#else
/** We launch low complexity removal for each sequence.
* Note that this post treatment could be parallelized in several threads. */
for (size_t i=0; i<_cache->nbSequences; i++)
{
/** We get the size of the sequence. */
size_t len = _cache->offsets.data[i+1] - _cache->offsets.data[i];
/** We launch the algorithm only for big enough sequences. */
if (len >= _segMinSize && _filterSequenceCallback != 0) { _filterSequenceCallback (data + _cache->offsets.data[i], len); }
}
#endif
const LETTER* convert = EncodingManager::singleton().getEncodingConversion (ASCII, SUBSEED);
/** We convert the cache from ASCII to SUBSEED. */
for (size_t i=0; i<_cache->dataSize; i++)
{
LETTER l = (convert ? convert [(int)data[i]] : data[i]);
/** We may have some strange database; we change bad letter into "any" letter. */
if (l == CODE_BAD) { l = EncodingManager::singleton().getAlphabet(SUBSEED)->any; }
data[i] = l;
}
//printf ("BufferedSegmentSequenceBuilder::postTreamtment 3. : size=%ld\n", _cache->dataSize);
//for (size_t i=0; i<_cache->dataSize; i++) { printf ("%d ", data[i]); } printf("\n");
}
/********************************************************************************/
} } /* end of namespaces. */
/********************************************************************************/
| 33.493082 | 158 | 0.54272 | [
"vector"
] |
3d594e417a5e62ce743e17a7fa9953c2d429e5ba | 733 | cpp | C++ | moitre.cpp | darksidergod/CompetitiveProgramming | ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a | [
"MIT"
] | null | null | null | moitre.cpp | darksidergod/CompetitiveProgramming | ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a | [
"MIT"
] | null | null | null | moitre.cpp | darksidergod/CompetitiveProgramming | ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a | [
"MIT"
] | 1 | 2020-10-03T19:48:05.000Z | 2020-10-03T19:48:05.000Z | #include <bits/stdc++.h>
#define ll long long int
#define vi vector<int>
#define ii pair<int, int>
using namespace std;
bool visited[1000000];
int main(void)
{
int t;
cin>>t;
while(t--)
{
int x, y, e, citiesbought=0;
cin>>e;
memset(visited, 0, sizeof(visited));
for(int i=0; i<e; i++)
{
cin>>x>>y;
if( (!visited[x]) || (!visited[y]) )
{
if((!visited[x]) && (!visited[y]))
{
if(x!=y)
citiesbought+=2;
else
citiesbought+=1;
visited[x]=true;
visited[y]=true;
}
else if(!visited[x])
{
visited[x]=true;
citiesbought+=1;
}
else
{
visited[y]=true;
citiesbought+=1;
}
}
}
cout<<citiesbought<<"\n";
}
return 0;
} | 14.096154 | 39 | 0.521146 | [
"vector"
] |
3d5a17c6a6eee6c2350c951f86296e599040f318 | 3,826 | cc | C++ | cdrs/src/model/AddCdrsMonitorRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | cdrs/src/model/AddCdrsMonitorRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | cdrs/src/model/AddCdrsMonitorRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/cdrs/model/AddCdrsMonitorRequest.h>
using AlibabaCloud::CDRS::Model::AddCdrsMonitorRequest;
AddCdrsMonitorRequest::AddCdrsMonitorRequest() :
RpcServiceRequest("cdrs", "2020-11-01", "AddCdrsMonitor")
{
setMethod(HttpRequest::Method::Post);
}
AddCdrsMonitorRequest::~AddCdrsMonitorRequest()
{}
std::string AddCdrsMonitorRequest::getMonitorType()const
{
return monitorType_;
}
void AddCdrsMonitorRequest::setMonitorType(const std::string& monitorType)
{
monitorType_ = monitorType;
setBodyParameter("MonitorType", monitorType);
}
std::string AddCdrsMonitorRequest::getCorpId()const
{
return corpId_;
}
void AddCdrsMonitorRequest::setCorpId(const std::string& corpId)
{
corpId_ = corpId;
setBodyParameter("CorpId", corpId);
}
std::string AddCdrsMonitorRequest::getDescription()const
{
return description_;
}
void AddCdrsMonitorRequest::setDescription(const std::string& description)
{
description_ = description;
setBodyParameter("Description", description);
}
std::string AddCdrsMonitorRequest::getNotifierAppSecret()const
{
return notifierAppSecret_;
}
void AddCdrsMonitorRequest::setNotifierAppSecret(const std::string& notifierAppSecret)
{
notifierAppSecret_ = notifierAppSecret;
setBodyParameter("NotifierAppSecret", notifierAppSecret);
}
std::string AddCdrsMonitorRequest::getNotifierExtendValues()const
{
return notifierExtendValues_;
}
void AddCdrsMonitorRequest::setNotifierExtendValues(const std::string& notifierExtendValues)
{
notifierExtendValues_ = notifierExtendValues;
setBodyParameter("NotifierExtendValues", notifierExtendValues);
}
std::string AddCdrsMonitorRequest::getNotifierUrl()const
{
return notifierUrl_;
}
void AddCdrsMonitorRequest::setNotifierUrl(const std::string& notifierUrl)
{
notifierUrl_ = notifierUrl;
setBodyParameter("NotifierUrl", notifierUrl);
}
std::string AddCdrsMonitorRequest::getNotifierType()const
{
return notifierType_;
}
void AddCdrsMonitorRequest::setNotifierType(const std::string& notifierType)
{
notifierType_ = notifierType;
setBodyParameter("NotifierType", notifierType);
}
int AddCdrsMonitorRequest::getBatchIndicator()const
{
return batchIndicator_;
}
void AddCdrsMonitorRequest::setBatchIndicator(int batchIndicator)
{
batchIndicator_ = batchIndicator;
setBodyParameter("BatchIndicator", std::to_string(batchIndicator));
}
std::string AddCdrsMonitorRequest::getBizId()const
{
return bizId_;
}
void AddCdrsMonitorRequest::setBizId(const std::string& bizId)
{
bizId_ = bizId;
setBodyParameter("BizId", bizId);
}
int AddCdrsMonitorRequest::getNotifierTimeOut()const
{
return notifierTimeOut_;
}
void AddCdrsMonitorRequest::setNotifierTimeOut(int notifierTimeOut)
{
notifierTimeOut_ = notifierTimeOut;
setBodyParameter("NotifierTimeOut", std::to_string(notifierTimeOut));
}
std::string AddCdrsMonitorRequest::getAlgorithmVendor()const
{
return algorithmVendor_;
}
void AddCdrsMonitorRequest::setAlgorithmVendor(const std::string& algorithmVendor)
{
algorithmVendor_ = algorithmVendor;
setBodyParameter("AlgorithmVendor", algorithmVendor);
}
| 25.337748 | 93 | 0.769995 | [
"model"
] |
87e702f00e6e990041eb93b79acaf2e44ebf6d0c | 11,560 | cc | C++ | src/float-counts-to-pre-arpa.cc | RoseSAK/pocolm | 2da2b6e5a709fb40021f7bbcdd18d84f174dfe30 | [
"Apache-2.0"
] | 88 | 2016-04-16T03:42:04.000Z | 2022-02-10T17:45:39.000Z | src/float-counts-to-pre-arpa.cc | RoseSAK/pocolm | 2da2b6e5a709fb40021f7bbcdd18d84f174dfe30 | [
"Apache-2.0"
] | 81 | 2016-05-09T00:07:18.000Z | 2022-02-02T05:59:04.000Z | src/float-counts-to-pre-arpa.cc | RoseSAK/pocolm | 2da2b6e5a709fb40021f7bbcdd18d84f174dfe30 | [
"Apache-2.0"
] | 43 | 2016-05-17T04:51:10.000Z | 2022-01-25T12:14:15.000Z | // float-counts-to-pre-arpa.cc
// Copyright 2016 Johns Hopkins University (Author: Daniel Povey)
// See ../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <math.h>
#include <sstream>
#include <fstream>
#include <vector>
#include <stdlib.h>
#include <string.h>
#include "pocolm-types.h"
#include "lm-state.h"
namespace pocolm {
class PreArpaGenerator {
public:
PreArpaGenerator(int argc, const char **argv) {
// note: we checked the following condition already in main(), this
// documents it locally.
assert(argc == 4 || (argc == 5 && !strcmp(argv[1], "--no-unigram")));
if (argc == 5) {
print_unigrams_ = false;
argc--;
argv++;
} else {
print_unigrams_ = true;
}
order_ = ConvertToInt(argv[1]);
num_words_ = ConvertToInt(argv[2]);
assert(order_ >= 2 && num_words_ >= 4);
lm_states_.resize(order_);
num_ngrams_.resize(order_, 0);
// we add one to the number of n-grams for order 1 (history-length 0),
// because the BOS (<s>) will have its backoff printed although it has no
// n-gram probability, which adds one line to the file that wouldn't
// otherwise be counted.
num_ngrams_[0] += 1;
word_to_position_map_.resize((num_words_ + 1) * (order_ - 1));
// set fill character to space and precision to 6.
std::cout << std::setfill(' ') << std::setprecision(6);
ProcessInput(argv[3]);
OutputNumNgrams();
}
int32 ConvertToInt(const char *arg) {
char *end;
int32 ans = strtol(arg, &end, 10);
if (end == arg || *end != '\0') {
std::cerr << "float-counts-to-pre-arpa: command line: expected int, got '"
<< arg << "'\n";
exit(1);
}
return ans;
}
private:
void ProcessInput(const char *float_counts) {
std::ifstream input;
input.open(float_counts, std::ios_base::in|std::ios_base::binary);
if (input.fail()) {
std::cerr << "float-counts-to-pre-arpa: error opening float-counts file "
<< float_counts << "\n";
exit(1);
}
while (input.peek(), !input.eof()) {
FloatLmState lm_state;
lm_state.Read(input);
size_t hist_length = lm_state.history.size();
assert(hist_length < lm_states_.size());
lm_states_[hist_length].Swap(&lm_state);
if (static_cast<int32>(hist_length) < order_ - 1)
PopulateMap(hist_length);
if (hist_length == 0)
assert(lm_states_[0].total > 0 &&
"Zero count for 1-gram history state (something went wrong?)");
if (hist_length > 0 || print_unigrams_)
OutputLmState(hist_length);
}
}
void PopulateMap(int32 hist_length) {
int32 pos = 0, num_words = num_words_;
assert(word_to_position_map_.size() ==
static_cast<size_t>((num_words + 1) * (order_ - 1)));
int32 *map_data = &(word_to_position_map_[0]),
orderm1 = order_ - 1;
std::vector<std::pair<int32, float> >::const_iterator
iter = lm_states_[hist_length].counts.begin(),
end = lm_states_[hist_length].counts.end();
for (pos = 0; iter != end; ++iter, pos++) {
int32 word = iter->first,
index = word * orderm1 + hist_length;
assert(word > 0 && word <= num_words);
map_data[index] = pos;
}
}
// This function writes out the LM-state in lm_states_[hist_length].
void OutputLmState(int32 hist_length) {
CheckBackoffStatesExist(hist_length);
int32 order = hist_length + 1;
assert(order < 100 && "N-gram order cannot exceed 99.");
const FloatLmState &lm_state = lm_states_[hist_length];
const std::vector<int32> &history = lm_state.history;
// 'prefix' will be something like:
// ' 3 1842 46 ', consisting of the n-gram order and then
// the history.
std::ostringstream prefix;
prefix << std::setfill(' ') << std::setw(2) << order << std::setw(0) << ' ';
for (int32 j = hist_length - 1; j >= 0; j--) {
// we need to go in reverse to get the history-state words into their
// natural order.
prefix << history[j] << ' ';
}
std::string prefix_str = prefix.str();
std::vector<int32> reversed_history(lm_state.history);
std::reverse(reversed_history.begin(), reversed_history.end());
std::vector<std::pair<int32, float> >::const_iterator
iter = lm_state.counts.begin(),
end = lm_state.counts.end();
float total_count = lm_state.total,
discount_prob = lm_state.discount / total_count;
for (; iter != end; ++iter) {
int32 word = iter->first;
float prob = iter->second / total_count;
if (hist_length > 0)
prob += discount_prob * GetProbability(hist_length - 1, word);
float log10_prob = log10f(prob);
assert(log10_prob - log10_prob == 0.0); // check for NaN/inf.
std::cout << prefix_str << word << ' ' << log10_prob << '\n';
}
num_ngrams_[hist_length] += static_cast<int64>(lm_state.counts.size());
if (hist_length > 0) {
// print the backoff prob for this history state.
std::cout << std::setw(2) << hist_length << std::setw(0);
for (int32 j = hist_length - 1; j >= 0; j--)
std::cout << ' ' << history[j];
float log10_backoff_prob = log10f(discount_prob);
// we use tab instead of space just before the backoff prob...
// this ensures that the backoff prob precedes the same-named
// n-gram prob
std::cout << '\t' << log10_backoff_prob << "\n";
}
}
// this function returns the count of word 'word' in the currently cached
// LM-state whose history has length 'hist_length'.
inline float GetCountForWord(int32 hist_length, int32 word) const {
assert(word > 0 && word <= num_words_);
size_t pos = word_to_position_map_[word * (order_ - 1) + hist_length];
if (pos < lm_states_[hist_length].counts.size() &&
lm_states_[hist_length].counts[pos].first == word) {
return lm_states_[hist_length].counts[pos].second;
} else {
if (hist_length == 0) {
std::cerr << "word " << word
<< "has zero count in unigram counts.";
exit(1);
}
// we allow the count to be zero for orders >0, because
// it might be possible that we'd prune away a lower-order
// count while keeping a higher-order one.
return 0.0;
}
}
// This function gets the probability (not log-prob) of word indexed 'word'
// given the lm-state of history-length 'hist_length', including backoff.
// It will crash if the word is not in that history state.
// We only call this function when handling backoff. This function
// does not work for the highest-order history state (order_ - 1).
inline float GetProbability(int32 hist_length, int32 word) const {
assert(hist_length < order_ - 1);
float numerator = GetCountForWord(hist_length, word);
if (hist_length > 0)
numerator += lm_states_[hist_length].discount *
GetProbability(hist_length - 1, word);
return numerator / lm_states_[hist_length].total;
}
// this function checks that the states in lm_states_[i] for
// i < hist_length are for histories that are the backoff histories
// of the state in lm_states_[hist_length].
void CheckBackoffStatesExist(int32 hist_length) const {
for (int32 i = 1; i < hist_length; i++) {
assert(static_cast<int32>(lm_states_[i].history.size()) == i);
assert(std::equal(lm_states_[i].history.begin(),
lm_states_[i].history.end(),
lm_states_[hist_length].history.begin()));
}
}
void OutputNumNgrams() const {
assert(static_cast<int32>(num_ngrams_.size()) == order_);
std::cerr << "float-counts-to-pre-arpa: output [ ";
for (int32 order = (print_unigrams_ ? 1 : 2); order <= order_; order++) {
// output will be something like: " 0 3 43142".
// the "0" will be interpreted by pre-arpa-to-arpa- it tells it
// that the rest of the line says the number of n-grams for some order.
// The padding with space is there to ensure that string order and
// numeric order coincide, up to n-gram order = 99
std::cout << std::setw(2) << 0 << ' ' << std::setw(2) << order << ' '
<< num_ngrams_[order-1] << '\n';
std::cerr << num_ngrams_[order-1] << ' ';
}
std::cerr << "] n-grams\n";
}
// the n-gram order of the LM we're writing.
int32 order_;
// the size of the vocabulary, excluding epsilon (equals highest-numbered word).
int32 num_words_;
// this vector is indexed by n-gram order - 1 (i.e. by history length).
std::vector<int64> num_ngrams_;
// lm-states, indexed by history length.
std::vector<FloatLmState> lm_states_;
// This maps from word-index to the position in the 'counts' vectors of the LM
// states. It exists to help us do rapid lookup of counts in lower-order
// states when we are doing the backoff computation. For history-length 0 <=
// hist_len < order - 1 and word 0 < word <= num_words_,
// word_to_position_map_[(order - 1) * word + hist_len] contains the position
// in lm_states_[hist_len].counts that this word exists. Note: for words that
// are not in that counts vector, the value is undefined.
std::vector<int32> word_to_position_map_;
// will be false if --no-unigram option was used.
bool print_unigrams_;
};
} // namespace pocolm
int main (int argc, const char **argv) {
if (!(argc == 4 || (argc == 5 && !strcmp(argv[1], "--no-unigram")))) {
std::cerr << "Usage: float-counts-to-pre-arpa [--no-unigram] <ngram-order> <num-words> <float-counts> > <pre-arpa-out>\n"
<< "E.g. float-counts-to-pre-arpa 3 40000 float.all | LC_ALL=C sort | pre-arpa-to-pre-arpa words.txt > arpa"
<< "The output is in text form, with lines of the following types:\n"
<< "N-gram probability lines: <n-gram-order> <word1> ... <wordN> <log10-prob>, e.g.:\n"
<< " 3 162 82 978 -1.72432\n"
<< "Backoff probability lines: <n-gram-order> <word1> ... <wordN> b<log10-prob>, e.g:\n"
<< " 3 162 82 978 b-1.72432\n"
<< "Lines (beginning with 0) that announce the counts of n-grams for a\n"
<< " particular n-gram order, e.g.:\n"
<< " 0 3 894121\n"
<< "announces that there are 894121 3-grams. (we print leading spaces\n"
<< "so that string order will coincide with numeric order). These will be processed\n"
<< "into the arpa header.\n"
<< "The output of this program will be sorted and then piped into\n"
<< "pre-arpa-to-arpa.\n";
exit(1);
}
// everything gets called from the constructor.
pocolm::PreArpaGenerator generator(argc, argv);
return 0;
}
// see discount-counts.cc for a command-line example that was used to test this.
| 39.725086 | 126 | 0.630969 | [
"vector"
] |
87e9d6195ca146034f08f71f288a85d002023a85 | 3,301 | cpp | C++ | src/test-case/grammar.cpp | andrei-datcu/cxxhttp | dce2eb99fd9c61baa75d92cd328f355882daf698 | [
"MIT"
] | 29 | 2017-06-06T13:42:13.000Z | 2021-03-19T11:12:23.000Z | src/test-case/grammar.cpp | andrei-datcu/cxxhttp | dce2eb99fd9c61baa75d92cd328f355882daf698 | [
"MIT"
] | 1 | 2017-04-24T21:37:05.000Z | 2017-05-14T20:45:53.000Z | src/test-case/grammar.cpp | andrei-datcu/cxxhttp | dce2eb99fd9c61baa75d92cd328f355882daf698 | [
"MIT"
] | 5 | 2017-12-28T20:04:48.000Z | 2020-06-03T19:38:18.000Z | /* Test cases for some of the grammar rules.
*
* HTTP is described in a modified ABNF, which for this library was translated
* to regular expressions. Since the two aren't the same, this tests some of the
* grammar rules to ensure they allow things that ought to be allowed and reject
* things that aren't allowed.
*
* See also:
* * Project Documentation: https://ef.gy/documentation/cxxhttp
* * Project Source Code: https://github.com/ef-gy/cxxhttp
* * Licence Terms: https://github.com/ef-gy/cxxhttp/blob/master/COPYING
*
* @copyright
* This file is part of the cxxhttp project, which is released as open source
* under the terms of an MIT/X11-style licence, described in the COPYING file.
*/
#include <cxxhttp/http-grammar.h>
#include <ef.gy/test-case.h>
#include <regex>
using namespace cxxhttp;
/* Test grammar matches.
* @log Test output stream.
*
* Tests some of the more complicated grammar rules, to make sure there's no odd
* surprises further down the road.
*
* @return 'true' on success, 'false' otherwise.
*/
bool testGrammar(std::ostream &log) {
struct sampleData {
std::string in, reference;
bool result;
};
std::vector<sampleData> tests{
{"", "", true},
{"a", "", false},
{http::grammar::vchar, "a", true},
{http::grammar::vchar, "\n", false},
{http::grammar::vchar, "\t", false},
{http::grammar::quotedPair, "\\t", true},
{http::grammar::quotedPair, "\\\"", true},
{http::grammar::quotedPair, "a", false},
{http::grammar::quotedPair, "\"", false},
{http::grammar::qdtext, "a", true},
{http::grammar::qdtext, ",", true},
{http::grammar::qdtext, "[", true},
{http::grammar::qdtext, "\\", false},
{http::grammar::qdtext, "]", true},
{http::grammar::qdtext, "\\", false},
{http::grammar::qdtext, "\"", false},
{http::grammar::quotedString, "\"\"", true},
{http::grammar::quotedString, "\"foo\"\"", false},
{http::grammar::quotedString, "\"foo\"bar\"", false},
{http::grammar::quotedString, "\"foo=\"bar\"\"", false},
{http::grammar::quotedString, "\"foo=\\\"bar\\\"\"", true},
{http::grammar::comment, "(foo)", true},
{http::grammar::comment, "(foo!)", true},
{http::grammar::comment, "(foo (bar))", true},
{http::grammar::token, "foo", true},
{http::grammar::token, "foo-B4r", true},
{http::grammar::token, "foo-B4r ", false},
{http::grammar::token, " ", false},
{http::grammar::token, "", false},
{http::grammar::fieldContent, "fo of", true},
{http::grammar::fieldContent, "fo", true},
{http::grammar::fieldContent, " foof ", false},
};
for (const auto &tt : tests) {
try {
const std::regex rx(tt.in);
const auto v = std::regex_match(tt.reference, rx);
if (v != tt.result) {
log << "regex_match('" << tt.reference << "', '" << tt.in << "')='" << v
<< "', expected '" << tt.result << "'\n";
return false;
}
} catch (std::exception &e) {
log << "Exception: " << e.what() << "\nWhile trying to test: " << tt.in
<< "\n";
return false;
}
}
return true;
}
namespace test {
using efgy::test::function;
static function grammar(testGrammar);
} // namespace test
| 33.683673 | 80 | 0.588004 | [
"vector"
] |
e2013fd87d901e844261c53680b2fd6387131395 | 382 | cpp | C++ | Data Structures/Array/C++/Arrays - DS.cpp | abdzitter/Daily-Coding-DS-ALGO-Practice | 26ddbf7a3673608039a07d26d812fce31b69871a | [
"MIT"
] | 289 | 2021-05-15T22:56:03.000Z | 2022-03-28T23:13:25.000Z | Data Structures/Array/C++/Arrays - DS.cpp | abdzitter/Daily-Coding-DS-ALGO-Practice | 26ddbf7a3673608039a07d26d812fce31b69871a | [
"MIT"
] | 1,812 | 2021-05-09T13:49:58.000Z | 2022-01-15T19:27:17.000Z | Data Structures/Array/C++/Arrays - DS.cpp | abdzitter/Daily-Coding-DS-ALGO-Practice | 26ddbf7a3673608039a07d26d812fce31b69871a | [
"MIT"
] | 663 | 2021-05-09T16:57:58.000Z | 2022-03-27T14:15:07.000Z | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/*
*
* Prosen Ghosh
* American International University - Bangladesh (AIUB)
*
*/
int main() {
int T,ar[1000];
cin >> T;
for(int i = 0;i < T; i++)cin >> ar[i];
for(int i = T-1; i >=0; i--)cout << ar[i] << " ";
return 0;
}
| 17.363636 | 59 | 0.539267 | [
"vector"
] |
e203efb7b5b7d33ac9cc3cb28a3149f2a1cef2d9 | 3,286 | hpp | C++ | softlight/include/softlight/SL_WindowBufferXlib.hpp | Kim-Du-Yeon/SoftLight | 26c1c04be5a99167f2cda0c7a992cecdc8259968 | [
"MIT"
] | 27 | 2019-04-22T01:51:51.000Z | 2022-02-11T06:12:17.000Z | softlight/include/softlight/SL_WindowBufferXlib.hpp | Kim-Du-Yeon/SoftLight | 26c1c04be5a99167f2cda0c7a992cecdc8259968 | [
"MIT"
] | 1 | 2021-11-12T05:19:52.000Z | 2021-11-12T05:19:52.000Z | softlight/include/softlight/SL_WindowBufferXlib.hpp | Kim-Du-Yeon/SoftLight | 26c1c04be5a99167f2cda0c7a992cecdc8259968 | [
"MIT"
] | 2 | 2020-09-07T03:04:39.000Z | 2021-11-09T06:08:37.000Z |
#ifndef SL_WINDOW_BUFFER_XLIB_HPP
#define SL_WINDOW_BUFFER_XLIB_HPP
#include "softlight/SL_WindowBuffer.hpp"
// Should be defined by the build system
// OSX with XQuartz runs out of memory when attaching textures to shared
// memory segments.
#ifndef SL_ENABLE_XSHM
#define SL_ENABLE_XSHM 0
#endif /* SL_ENABLE_XSHM */
/*-----------------------------------------------------------------------------
* Forward Declarations
-----------------------------------------------------------------------------*/
namespace ls
{
namespace math
{
template <typename color_type>
union vec4_t;
}
}
/*-----------------------------------------------------------------------------
* Xlib Render Window
-----------------------------------------------------------------------------*/
class SL_WindowBufferXlib : public SL_WindowBuffer
{
private:
SL_RenderWindow* mWindow;
void* mBuffer;
#if SL_ENABLE_XSHM != 0
void* mShmInfo;
#endif
public:
virtual ~SL_WindowBufferXlib() noexcept override;
SL_WindowBufferXlib() noexcept;
SL_WindowBufferXlib(const SL_WindowBufferXlib&) = delete;
SL_WindowBufferXlib(SL_WindowBufferXlib&&) noexcept;
SL_WindowBufferXlib& operator=(const SL_WindowBufferXlib&) = delete;
SL_WindowBufferXlib& operator=(SL_WindowBufferXlib&&) noexcept;
virtual int init(SL_RenderWindow& win, unsigned width, unsigned height) noexcept override;
virtual int terminate() noexcept override;
virtual unsigned width() const noexcept override;
virtual unsigned height() const noexcept override;
virtual const void* native_handle() const noexcept override;
virtual void* native_handle() noexcept override;
virtual const ls::math::vec4_t<uint8_t>* buffer() const noexcept override;
virtual ls::math::vec4_t<uint8_t>* buffer() noexcept override;
};
/*-------------------------------------
* Get the backbuffer width
-------------------------------------*/
inline unsigned SL_WindowBufferXlib::width() const noexcept
{
return mTexture.width();
}
/*-------------------------------------
* Get the backbuffer height
-------------------------------------*/
inline unsigned SL_WindowBufferXlib::height() const noexcept
{
return mTexture.height();
}
/*-------------------------------------
* Native Handle
-------------------------------------*/
inline const void* SL_WindowBufferXlib::native_handle() const noexcept
{
return mBuffer;
}
/*-------------------------------------
* Native Handle
-------------------------------------*/
inline void* SL_WindowBufferXlib::native_handle() noexcept
{
return mBuffer;
}
/*-------------------------------------
* Retrieve the raw data within the backbuffer
-------------------------------------*/
inline const ls::math::vec4_t<uint8_t>* SL_WindowBufferXlib::buffer() const noexcept
{
return reinterpret_cast<const ls::math::vec4_t<uint8_t>*>(mTexture.data());
}
/*-------------------------------------
* Retrieve the raw data within the backbuffer
-------------------------------------*/
inline ls::math::vec4_t<uint8_t>* SL_WindowBufferXlib::buffer() noexcept
{
return reinterpret_cast<ls::math::vec4_t<uint8_t>*>(mTexture.data());
}
#endif /* SL_WINDOW_BUFFER_XLIB_HPP */
| 23.640288 | 94 | 0.556908 | [
"render"
] |
e20dbd5cfd712eada49358d7c027f9dc59cc5e41 | 6,777 | hpp | C++ | include/idocp/cost/cost_function_component_base.hpp | z8674558/idocp | 946524db7ae4591b578be2409ca619961572e7be | [
"BSD-3-Clause"
] | 43 | 2020-10-13T03:43:45.000Z | 2021-09-23T05:29:48.000Z | include/idocp/cost/cost_function_component_base.hpp | z8674558/idocp | 946524db7ae4591b578be2409ca619961572e7be | [
"BSD-3-Clause"
] | 32 | 2020-10-21T09:40:16.000Z | 2021-10-24T00:00:04.000Z | include/idocp/cost/cost_function_component_base.hpp | z8674558/idocp | 946524db7ae4591b578be2409ca619961572e7be | [
"BSD-3-Clause"
] | 4 | 2020-10-08T05:47:16.000Z | 2021-10-15T12:15:26.000Z | #ifndef IDOCP_COST_FUNCTION_COMPONENT_BASE_HPP_
#define IDOCP_COST_FUNCTION_COMPONENT_BASE_HPP_
#include "Eigen/Core"
#include "idocp/robot/robot.hpp"
#include "idocp/cost/cost_function_data.hpp"
#include "idocp/ocp/split_solution.hpp"
#include "idocp/ocp/split_kkt_residual.hpp"
#include "idocp/ocp/split_kkt_matrix.hpp"
#include "idocp/impulse/impulse_split_solution.hpp"
#include "idocp/impulse/impulse_split_kkt_residual.hpp"
#include "idocp/impulse/impulse_split_kkt_matrix.hpp"
namespace idocp {
///
/// @class CostFunctionComponentBase
/// @brief Base class of components of cost function.
///
class CostFunctionComponentBase {
public:
///
/// @brief Default constructor.
///
CostFunctionComponentBase() {}
///
/// @brief Destructor.
///
virtual ~CostFunctionComponentBase() {}
///
/// @brief Default copy constructor.
///
CostFunctionComponentBase(const CostFunctionComponentBase&) = default;
///
/// @brief Default copy operator.
///
CostFunctionComponentBase& operator=(const CostFunctionComponentBase&)
= default;
///
/// @brief Default move constructor.
///
CostFunctionComponentBase(CostFunctionComponentBase&&) noexcept = default;
///
/// @brief Default move assign operator.
///
CostFunctionComponentBase& operator=(CostFunctionComponentBase&&) noexcept
= default;
///
/// @brief Check if the cost function component requres kinematics
/// (forward kinematics and its Jacobians) of robot model.
/// @return true if the cost function component requres kinematics of
/// Robot model. false if not.
///
virtual bool useKinematics() const = 0;
///
/// @brief Computes the stage cost.
/// @param[in] robot Robot model.
/// @param[in] data Cost function data.
/// @param[in] t Time.
/// @param[in] dt Time step.
/// @param[in] s Split solution.
/// @return Stage cost.
///
virtual double computeStageCost(Robot& robot, CostFunctionData& data,
const double t, const double dt,
const SplitSolution& s) const = 0;
///
/// @brief Computes the first-order partial derivatives of the stage cost.
/// This function is always called just after computeStageCost().
/// @param[in] robot Robot model.
/// @param[in] data Cost function data.
/// @param[in] t Time.
/// @param[in] dt Time step.
/// @param[in] s Split solution.
/// @param[in, out] kkt_residual Split KKT residual. The partial derivatives
/// are added to this object.
///
virtual void computeStageCostDerivatives(
Robot& robot, CostFunctionData& data, const double t, const double dt,
const SplitSolution& s, SplitKKTResidual& kkt_residual) const = 0;
///
/// @brief Computes the Hessian, i.e., the second-order partial derivatives of
/// the stage cost. This function is always called just after
/// computeStageCostDerivatives().
/// @param[in] robot Robot model.
/// @param[in] data Cost function data.
/// @param[in] t Time.
/// @param[in] dt Time step.
/// @param[in] s Split solution.
/// @param[in, out] kkt_matrix Split KKT matrix. The Hessians are added to
/// this object.
///
virtual void computeStageCostHessian(
Robot& robot, CostFunctionData& data, const double t, const double dt,
const SplitSolution& s, SplitKKTMatrix& kkt_matrix) const = 0;
///
/// @brief Computes the terminal cost.
/// @param[in] robot Robot model.
/// @param[in] data Cost function data.
/// @param[in] t Time.
/// @param[in] s Split solution.
/// @return Terminal cost.
///
virtual double computeTerminalCost(Robot& robot, CostFunctionData& data,
const double t,
const SplitSolution& s) const = 0;
///
/// @brief Computes the first-order partial derivatives of the terminal cost.
/// This function is always called just after computeTerminalCost().
/// @param[in] robot Robot model.
/// @param[in] data Cost function data.
/// @param[in] t Time.
/// @param[in] s Split solution.
/// @param[in, out] kkt_residual Split KKT residual. The partial derivatives
/// are added to this object.
///
virtual void computeTerminalCostDerivatives(
Robot& robot, CostFunctionData& data, const double t,
const SplitSolution& s, SplitKKTResidual& kkt_residual) const = 0;
///
/// @brief Computes the Hessian, i.e., the second-order partial derivatives of
/// the teminal cost. This function is always called just after
/// computeTerminalCostDerivatives().
/// @param[in] robot Robot model.
/// @param[in] data Cost function data.
/// @param[in] t Time.
/// @param[in] s Split solution.
/// @param[in, out] kkt_matrix Split KKT matrix. The Hessians are added to
/// this object.
///
virtual void computeTerminalCostHessian(
Robot& robot, CostFunctionData& data, const double t,
const SplitSolution& s, SplitKKTMatrix& kkt_matrix) const = 0;
///
/// @brief Computes the impulse cost.
/// @param[in] robot Robot model.
/// @param[in] data Cost function data.
/// @param[in] t Time.
/// @param[in] s Split solution.
/// @return Impulse cost.
///
virtual double computeImpulseCost(Robot& robot, CostFunctionData& data,
const double t,
const ImpulseSplitSolution& s) const = 0;
///
/// @brief Computes the first-order partial derivatives of the impulse cost.
/// This function is always called just after computeImpulseCost().
/// @param[in] robot Robot model.
/// @param[in] data Cost function data.
/// @param[in] t Time.
/// @param[in] s Split solution.
/// @param[in, out] kkt_residual Split KKT residual. The partial derivatives
/// are added to this object.
///
virtual void computeImpulseCostDerivatives(
Robot& robot, CostFunctionData& data, const double t,
const ImpulseSplitSolution& s,
ImpulseSplitKKTResidual& kkt_residual) const = 0;
///
/// @brief Computes the Hessian, i.e., the second-order partial derivatives of
/// the impulse cost. This function is always called just after
/// computeImpulseCostDerivatives().
/// @param[in] robot Robot model.
/// @param[in] data Cost function data.
/// @param[in] t Time.
/// @param[in] s Split solution.
/// @param[in, out] kkt_matrix Impulse split KKT matrix. The Hessians are
/// added to this object.
///
virtual void computeImpulseCostHessian(
Robot& robot, CostFunctionData& data, const double t,
const ImpulseSplitSolution& s,
ImpulseSplitKKTMatrix& kkt_matrix) const = 0;
};
} // namespace idocp
#endif // IDOCP_COST_FUNCTION_COMPONENT_BASE_HPP_ | 34.576531 | 81 | 0.666224 | [
"object",
"model"
] |
e217492aa787b09539dda9650239fd3f383c0c07 | 18,838 | cpp | C++ | quakelib/src/QuakeLibMetadata.cpp | kwschultz/VirtualCalifornia | 1e6b0a70f00f953018e8bd5336f8f94c5dad04b9 | [
"MIT"
] | null | null | null | quakelib/src/QuakeLibMetadata.cpp | kwschultz/VirtualCalifornia | 1e6b0a70f00f953018e8bd5336f8f94c5dad04b9 | [
"MIT"
] | null | null | null | quakelib/src/QuakeLibMetadata.cpp | kwschultz/VirtualCalifornia | 1e6b0a70f00f953018e8bd5336f8f94c5dad04b9 | [
"MIT"
] | null | null | null | // Copyright (c) 2012 Eric Heien <emheien@ucdavis.edu>
//
// 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 "QuakeLib.h"
bool quakelib::EQSimMetadataReader::parse_metadata_line(const int &rec_num, const int &line_num, std::istringstream &line_stream) {
// If we haven't parsed the signature yet, we must do that first
if (!parsed_sig) {
if (rec_num == 101) {
parse_signature(line_num, line_stream);
return true;
} else {
return false;
}
}
// If we're past the signature but not yet past the metadata, parse the appropriate lines
if (!parse_metadata_finished) {
switch (rec_num) {
case 100: parse_comment(line_num, line_stream); return true;
case 102: parse_end_metadata(line_num, line_stream); return true;
case 110: parse_info_record(line_num, line_stream); return true;
case 111: parse_title_record(line_num, line_stream); return true;
case 112: parse_author_record(line_num, line_stream); return true;
case 113: parse_date_record(line_num, line_stream); return true;
case 999: parse_eof(line_num, line_stream); return true;
default: return false;
}
}
// Otherwise, assuming we're not done parsing descriptors, we read them in
if (!parsed_descriptors) {
switch (rec_num) {
case 100: parse_comment(line_num, line_stream); return true;
case 103: parse_end_descriptor(line_num, line_stream); return true;
case 120: parse_record_desc_record(line_num, line_stream); return true;
case 121: parse_field_desc_record(line_num, line_stream); return true;
case 999: parse_eof(line_num, line_stream); return true;
default: return false;
}
}
// Once we're past the descriptors, we can only accept EOF and comments
switch (rec_num) {
case 100: parse_comment(line_num, line_stream); return true;
case 999: parse_eof(line_num, line_stream); return true;
default: return false;
}
}
bool quakelib::EQSimMetadataReader::parse_file(const std::string &file_name, const int &start_line_num) {
std::string next_line;
std::istringstream line_stream;
int record_num, line_num;
std::ifstream input_file;
bool found_match;
input_file.open(file_name.c_str());
if (!input_file.good()) return false;
line_num = start_line_num;
finish_parsing = false;
while (input_file.good() && !finish_parsing) {
// Increment the line count
++line_num;
// Get the next line in the file
getline(input_file, next_line);
// Find the record number for the line
line_stream.str(next_line);
line_stream >> record_num;
// Call the corresponding line processor with the remainder of the line
try {
found_match = parse_metadata_line(record_num, line_num, line_stream);
if (!found_match) found_match = parse_line(record_num, line_num, line_stream);
if (!found_match) {
std::stringstream error_msg;
error_msg << "Unexpected record number: " << record_num;
parse_errors.report(error_msg.str(), line_num);
}
} catch (std::exception e) {
std::stringstream error_msg;
error_msg << "Unexpected error: " << e.what();
parse_errors.report(error_msg.str(), line_num);
}
line_stream.clear();
record_num = 0;
}
input_file.close();
return true;
}
bool quakelib::internal::EQSimMetadata::has_bad_chars(const std::string &test_str) {
if (test_str.find_first_of("\n\r") != std::string::npos) return true;
return false;
}
unsigned int quakelib::internal::EQSimMetadata::meta_num_records(const RECORD_TYPE &rec_type) const throw(std::invalid_argument) {
switch (rec_type) {
case META_COMMENT:
case META_INFO:
case META_AUTHOR:
case META_TITLE:
case META_SIGNATURE:
case META_DATE:
return metadata_recs.find(rec_type)->second.size();
default:
throw std::invalid_argument("quakelib::EQSimMetadata::meta_num_records");
}
}
void quakelib::internal::EQSimMetadata::meta_clear_record(const RECORD_TYPE &rec_type) throw(std::invalid_argument) {
switch (rec_type) {
case META_COMMENT:
case META_INFO:
case META_AUTHOR:
case META_TITLE:
case META_SIGNATURE:
case META_DATE:
metadata_recs[rec_type].clear();
metadata_line_nums[rec_type].clear();
break;
default:
throw std::invalid_argument("quakelib::EQSimMetadata::meta_clear_record");
}
}
std::string quakelib::internal::EQSimMetadata::meta_get_record(const RECORD_TYPE &rec_type, const unsigned int &rec_num) const throw(std::invalid_argument, std::out_of_range) {
switch (rec_type) {
case META_COMMENT:
case META_INFO:
case META_AUTHOR:
case META_TITLE:
case META_SIGNATURE:
case META_DATE:
if (rec_num >= metadata_recs.find(rec_type)->second.size()) throw std::out_of_range("quakelib::EQSimMetadata::meta_get_record");
return metadata_recs.find(rec_type)->second.at(rec_num);
default:
throw std::invalid_argument("quakelib::EQSimMetadata::meta_get_record");
}
}
void quakelib::internal::EQSimMetadata::meta_add_record(const RECORD_TYPE &rec_type, const std::string &new_rec) throw(std::invalid_argument) {
if (has_bad_chars(new_rec)) throw std::invalid_argument("quakelib::EQSimMetadata::meta_add_record");
switch (rec_type) {
case META_COMMENT:
case META_INFO:
case META_AUTHOR:
metadata_recs.find(rec_type)->second.push_back(new_rec);
metadata_line_nums.find(rec_type)->second.push_back(-1);
break;
case META_TITLE:
case META_SIGNATURE:
case META_DATE:
metadata_recs.find(rec_type)->second.clear();
metadata_line_nums.find(rec_type)->second.clear();
metadata_recs.find(rec_type)->second.push_back(new_rec);
metadata_line_nums.find(rec_type)->second.push_back(-1);
break;
default:
throw std::invalid_argument("quakelib::EQSimMetadata::meta_add_record");
}
}
void quakelib::internal::EQSimMetadata::meta_set_record(const RECORD_TYPE &rec_type, const unsigned int &rec_num, const std::string &new_rec) throw(std::invalid_argument, std::out_of_range) {
switch (rec_type) {
case META_COMMENT:
case META_INFO:
case META_AUTHOR:
if (rec_num >= metadata_recs.find(rec_type)->second.size()) throw std::out_of_range("quakelib::EQSimMetadata::meta_set_record");
metadata_recs.find(rec_type)->second.at(rec_num) = new_rec;
metadata_line_nums.find(rec_type)->second.at(rec_num) = -1;
break;
case META_TITLE:
case META_SIGNATURE:
case META_DATE:
if (rec_num >= metadata_recs.find(rec_type)->second.size()) throw std::out_of_range("quakelib::EQSimMetadata::meta_set_record");
metadata_recs.find(rec_type)->second.clear();
metadata_line_nums.find(rec_type)->second.clear();
metadata_recs.find(rec_type)->second.push_back(new_rec);
metadata_line_nums.find(rec_type)->second.push_back(-1);
break;
default:
throw std::invalid_argument("quakelib::EQSimMetadata::meta_set_record");
}
}
void quakelib::internal::EQSimMetadata::meta_erase_record(const RECORD_TYPE &rec_type, const unsigned int &rec_num) throw(std::invalid_argument, std::out_of_range) {
switch (rec_type) {
case META_COMMENT:
case META_INFO:
case META_AUTHOR:
case META_TITLE:
case META_SIGNATURE:
case META_DATE:
if (rec_num >= metadata_recs.find(rec_type)->second.size()) throw std::out_of_range("quakelib::EQSimMetadata::meta_erase_record");
metadata_recs.find(rec_type)->second.erase(metadata_recs.find(rec_type)->second.begin()+rec_num);
metadata_line_nums.find(rec_type)->second.erase(metadata_line_nums.find(rec_type)->second.begin()+rec_num);
break;
default:
throw std::invalid_argument("quakelib::EQSimMetadata::meta_erase_record");
}
}
void quakelib::internal::EQSimMetadata::add_record_desc_record(const unsigned int &rec_key, internal::RecordDesc &rec_desc) throw(std::invalid_argument) {
if(rec_key<200 || rec_key>=400) throw std::invalid_argument("quakelib::EQSimMetadata::add_record_desc_record");
record_descs.insert(std::make_pair(rec_key, rec_desc));
}
void quakelib::EQSimMetadataReader::parse_comment(const int &line_num, std::istringstream &line_stream) {
std::string comment;
getline(line_stream, comment);
comment.erase(0,1); // erase the extra space getline adds to the beginning
metadata_recs.find(META_COMMENT)->second.push_back(comment);
metadata_line_nums.find(META_COMMENT)->second.push_back(line_num);
}
void quakelib::EQSimMetadataReader::parse_signature(const int &line_num, std::istringstream &line_stream) {
std::string sig_rec;
line_stream >> sig_rec
>> spec_level;
metadata_recs.find(META_SIGNATURE)->second.clear();
metadata_line_nums.find(META_SIGNATURE)->second.clear();
metadata_recs.find(META_SIGNATURE)->second.push_back(sig_rec);
metadata_line_nums.find(META_SIGNATURE)->second.push_back(line_num);
parsed_sig = true;
}
void quakelib::EQSimMetadataReader::parse_end_metadata(const int &line_num, std::istringstream &line_stream) {
std::string str;
line_stream >> str;
if (str.compare("End_Metadata")) parse_errors.report("Metadata end record has incorrect format.", line_num);
if (parse_metadata_finished) parse_errors.report("Metadata end record previously found.", line_num);
parse_metadata_finished = true;
}
void quakelib::EQSimMetadataReader::parse_end_descriptor(const int &line_num, std::istringstream &line_stream) {
std::string str;
line_stream >> str;
if (str.compare("End_Descriptor")) parse_errors.report("Descriptor end record has incorrect format.", line_num);
parsed_descriptors = true;
}
void quakelib::EQSimMetadataReader::parse_info_record(const int &line_num, std::istringstream &line_stream) {
std::string new_info;
getline(line_stream, new_info);
new_info.erase(0,1); // erase the extra space getline adds to the beginning
metadata_recs.find(META_INFO)->second.push_back(new_info);
metadata_line_nums.find(META_INFO)->second.push_back(line_num);
}
void quakelib::EQSimMetadataReader::parse_title_record(const int &line_num, std::istringstream &line_stream) {
std::string title_rec;
getline(line_stream, title_rec);
title_rec.erase(0,1); // erase the extra space getline adds to the beginning
metadata_recs.find(META_TITLE)->second.clear();
metadata_line_nums.find(META_TITLE)->second.clear();
metadata_recs.find(META_TITLE)->second.push_back(title_rec);
metadata_line_nums.find(META_TITLE)->second.push_back(line_num);
if (parsed_title) parse_errors.report("Title record previously found.", line_num);
parsed_title = true;
}
void quakelib::EQSimMetadataReader::parse_author_record(const int &line_num, std::istringstream &line_stream) {
std::string new_author;
getline(line_stream, new_author);
new_author.erase(0,1); // erase the extra space getline adds to the beginning
metadata_recs.find(META_AUTHOR)->second.push_back(new_author);
metadata_line_nums.find(META_AUTHOR)->second.push_back(line_num);
}
void quakelib::EQSimMetadataReader::parse_date_record(const int &line_num, std::istringstream &line_stream) {
std::string date_rec;
getline(line_stream, date_rec);
date_rec.erase(0,1); // erase the extra space getline adds to the beginning
metadata_recs.find(META_DATE)->second.clear();
metadata_line_nums.find(META_DATE)->second.clear();
metadata_recs.find(META_DATE)->second.push_back(date_rec);
metadata_line_nums.find(META_DATE)->second.push_back(line_num);
if (parsed_date) parse_errors.report("Date record previously found.", line_num);
parsed_date = true;
}
void quakelib::EQSimMetadataReader::parse_record_desc_record(const int &line_num, std::istringstream &line_stream) {
int rec_kind;
std::string rec_name;
int rec_n_field;
line_stream >> rec_kind
>> rec_name
>> rec_n_field;
if (record_descs.count(rec_kind)) {
parse_errors.report("Record descriptor with this ID already exists.", line_num);
} else if (rec_kind < 200 || rec_kind > 399) {
parse_errors.report("Record kind must be between 200 and 399.", line_num);
} else if (rec_n_field < 1 || rec_n_field > 100) {
parse_errors.report("Record descriptor must have between 1 and 100 fields.", line_num);
} else {
record_descs.insert(std::make_pair(rec_kind, internal::RecordDesc(line_num, rec_name, rec_n_field)));
cur_record_index = rec_kind;
}
}
void quakelib::EQSimMetadataReader::parse_field_desc_record(const int &line_num, std::istringstream &line_stream) {
int field_index;
std::string field_name;
int field_type;
line_stream >> field_index
>> field_name
>> field_type;
if (!record_descs.count(cur_record_index)) {
parse_errors.report("Field descriptor may not be declared without corresponding record descriptor.", line_num);
} else if (field_index < 1 || field_index > 100) {
parse_errors.report("Field index must be between 1 and 100.", line_num);
} else if (field_index > record_descs[cur_record_index].get_num_fields()) {
parse_errors.report("Field index must be less than record maximum index.", line_num);
} else if (field_type < 1 || field_type > 3) {
parse_errors.report("Field type must be between 1 and 3.", line_num);
} else {
bool added_field;
added_field = record_descs[cur_record_index].add_field(field_index, internal::FieldDesc(field_name, field_type));
if (!added_field) {
parse_errors.report("Field index must be unique within record.", line_num);
}
}
}
void quakelib::EQSimMetadataReader::parse_eof(const int &line_num, std::istringstream &line_stream) {
std::string str;
line_stream >> str;
if (str.compare("End")) parse_errors.report("End record has incorrect format.", line_num);
finish_parsing = true;
}
void quakelib::EQSimMetadataReader::validate(EQSimErrors &errors) const {
internal::MultiRecordDesc::const_iterator it;
std::stringstream error_msg;
internal::EQSimMetadata::validate(errors);
for (it=record_descs.begin();it!=record_descs.end();++it) {
if (it->second.get_num_fields() != it->second.get_num_fields()) {
error_msg << "Number of field records (" << it->second.get_num_fields()
<< ") does not match specified number for record (" << it->second.get_num_fields() << ").";
errors.report(error_msg.str(), it->second.get_max_index());
}
}
}
void quakelib::EQSimMetadataWriter::validate(EQSimErrors &errors) const {
internal::EQSimMetadata::validate(errors);
}
void quakelib::internal::EQSimMetadata::validate(EQSimErrors &errors) const {
unsigned int i;
std::stringstream error_msg;
std::vector<RECORD_TYPE> rec_types;
std::vector<RECORD_TYPE>::const_iterator it;
rec_types.push_back(META_COMMENT);
rec_types.push_back(META_SIGNATURE);
rec_types.push_back(META_INFO);
rec_types.push_back(META_TITLE);
rec_types.push_back(META_AUTHOR);
rec_types.push_back(META_DATE);
for (it=rec_types.begin();it!=rec_types.end();++it) {
for (i=0;i<metadata_recs.find(*it)->second.size();++i) {
if (metadata_recs.find(*it)->second.at(i).empty()) {
error_msg << "Metadata records may not be blank (record "
<< metadata_rec_nums.find(*it)->second << " number "
<< i << ").";
errors.report(error_msg.str(), metadata_line_nums.find(*it)->second.at(i));
}
}
}
}
void quakelib::EQSimMetadataWriter::write(void) {
internal::MultiRecordDesc::const_iterator it;
internal::MultiRecord::const_iterator rit;
if (wrote_header) return;
for (rit=metadata_recs.find(META_SIGNATURE)->second.begin();rit!=metadata_recs.find(META_SIGNATURE)->second.end();++rit)
out_stream << metadata_rec_nums.find(META_SIGNATURE)->second << " " << *rit << " " << spec_level << "\n";
for (rit=metadata_recs.find(META_COMMENT)->second.begin();rit!=metadata_recs.find(META_COMMENT)->second.end();++rit)
out_stream << metadata_rec_nums.find(META_COMMENT)->second << " " << *rit << "\n";
for (rit=metadata_recs.find(META_INFO)->second.begin();rit!=metadata_recs.find(META_INFO)->second.end();++rit)
out_stream << metadata_rec_nums.find(META_INFO)->second << " " << *rit << "\n";
for (rit=metadata_recs.find(META_TITLE)->second.begin();rit!=metadata_recs.find(META_TITLE)->second.end();++rit)
out_stream << metadata_rec_nums.find(META_TITLE)->second << " " << *rit << "\n";
for (rit=metadata_recs.find(META_AUTHOR)->second.begin();rit!=metadata_recs.find(META_AUTHOR)->second.end();++rit)
out_stream << metadata_rec_nums.find(META_AUTHOR)->second << " " << *rit << "\n";
for (rit=metadata_recs.find(META_DATE)->second.begin();rit!=metadata_recs.find(META_DATE)->second.end();++rit)
out_stream << metadata_rec_nums.find(META_DATE)->second << " " << *rit << "\n";
out_stream << "102 End_Metadata\n";
for (it=record_descs.begin();it!=record_descs.end();++it) it->second.write(it->first, out_stream);
out_stream << "103 End_Descriptor\n";
out_stream.flush();
wrote_header = true;
}
void quakelib::EQSimMetadataWriter::close(void) {
out_stream << "999 End\n";
out_stream.flush();
}
void quakelib::internal::FieldDesc::write(const unsigned int &key, std::ostream &out_stream) const {
out_stream << "121 " << key << " " << _name << " " << _type << " " << "Field " << _field_num << ": " << _desc << "\n";
}
void quakelib::internal::RecordDesc::write(const unsigned int &key, std::ostream &out_stream) const {
MultiFieldDesc::const_iterator it;
out_stream << "120 " << key << " " << name << " " << field_descs.size() << " " << desc << "\n";
for (it=field_descs.begin();it!=field_descs.end();++it) it->second.write(it->first, out_stream);
}
bool quakelib::internal::RecordDesc::add_field(const int &_index, const FieldDesc &_new_desc) {
if (field_descs.count(_index)) return false;
else field_descs[_index] = _new_desc;
return true;
}
void quakelib::EQSimErrors::report(const std::string &error_msg, const int &line_num=-1) {
error_list.insert(std::make_pair(line_num, error_msg));
}
void quakelib::EQSimErrors::write(std::ostream &os) const {
std::multimap<int, std::string>::const_iterator it;
for (it=error_list.begin();it!=error_list.end();++it) {
if (it->first >= 0) os << "LINE " << it->first << ": ";
os << it->second << std::endl;
}
}
| 39.995754 | 191 | 0.740153 | [
"vector"
] |
e222da21bc5ea85adcb827017223983f9c9dd7e7 | 688 | hpp | C++ | Uebungsaufgaben/Beispielklausuren/labor2_loesung/graph.hpp | TEL21D/Informatik2 | d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075 | [
"MIT"
] | null | null | null | Uebungsaufgaben/Beispielklausuren/labor2_loesung/graph.hpp | TEL21D/Informatik2 | d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075 | [
"MIT"
] | null | null | null | Uebungsaufgaben/Beispielklausuren/labor2_loesung/graph.hpp | TEL21D/Informatik2 | d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075 | [
"MIT"
] | null | null | null | #ifndef GRAPH_H
#define GRAPH_H
#include <iostream>
#include <string>
#include <vector>
struct User {
std::string _username; // Name des Benutzers
std::string _town; // Wohnort des Benutzers
std::string _unicourse; // Studiengang des Benutzers
std::vector<User *> _friends;
User(std::string name, std::string town, std::string course) : _username{name}, _town{town}, _unicourse{course} {}
void addFriend(User * user) {
_friends.push_back(user);
}
// Aufgabe 3
std::vector<std::string> getFriendsStudy();
};
template<typename T>
void print_vector(std::vector<T> const & v) {
for (auto el : v) { std::cout << el << " "; }
std::cout << std::endl;
}
#endif | 22.933333 | 116 | 0.668605 | [
"vector"
] |
e223380e588f043eddc7d8bc0c556973ff79155b | 5,971 | cpp | C++ | tests/tests-iter/test-move-assign.cpp | eepp/yactfr | 5cec5680d025d82a4f175ffc19c0704b32ef529f | [
"MIT"
] | 7 | 2016-08-26T14:20:06.000Z | 2022-02-03T21:17:25.000Z | tests/tests-iter/test-move-assign.cpp | eepp/yactfr | 5cec5680d025d82a4f175ffc19c0704b32ef529f | [
"MIT"
] | 2 | 2018-05-29T17:43:37.000Z | 2018-05-30T18:38:39.000Z | tests/tests-iter/test-move-assign.cpp | eepp/yactfr | 5cec5680d025d82a4f175ffc19c0704b32ef529f | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2018-2022 Philippe Proulx <eepp.ca>
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include <limits>
#include <cstring>
#include <sstream>
#include <iostream>
#include <vector>
#include <yactfr/yactfr.hpp>
#include <mem-data-src-factory.hpp>
#include <elem-printer.hpp>
#include <common-trace.hpp>
static const auto expected =
"P {\n"
"PC {\n"
"SC:0 {\n"
"ST {\n"
"FLUI:magic:3254525889\n"
"PMN:3254525889\n"
"SLA:uuid {\n"
"FLUI:100\n"
"FLUI:223\n"
"FLUI:96\n"
"FLUI:142\n"
"FLUI:141\n"
"FLUI:185\n"
"FLUI:79\n"
"FLUI:237\n"
"FLUI:156\n"
"FLUI:80\n"
"FLUI:14\n"
"FLUI:185\n"
"FLUI:114\n"
"FLUI:57\n"
"FLUI:44\n"
"FLUI:247\n"
"TTU:64df608e-8db9-4fed-9c50-0eb972392cf7\n"
"}\n"
"FLUI:stream_id:221\n"
"}\n"
"}\n"
"DSI:T221\n"
"SC:1 {\n"
"ST {\n"
"FLUI:packet_size:584\n"
"FLUI:content_size:552\n"
"FLUI:custom:4562\n"
"}\n"
"}\n"
"PI:T584:C552\n"
"ER {\n"
"SC:2 {\n"
"ST {\n"
"FLUI:id:17\n"
"}\n"
"}\n"
"ERI:T17\n"
"SC:5 {\n"
"ST {\n"
"ST:s {\n"
"FLUI:a:2864434397\n"
"FLUI:b:57005\n"
"FLUI:c:255\n"
"}\n"
"}\n"
"}\n"
"}\n"
"ER {\n"
"SC:2 {\n"
"ST {\n"
"FLUI:id:17\n"
"}\n"
"}\n"
"ERI:T17\n"
"SC:5 {\n"
"ST {\n"
"ST:s {\n"
"FLUI:a:303178531\n"
"FLUI:b:17493\n"
"FLUI:c:102\n"
"}\n"
"}\n"
"}\n"
"}\n"
"ER {\n"
"SC:2 {\n"
"ST {\n"
"FLUI:id:34\n"
"}\n"
"}\n"
"ERI:T34\n"
"SC:4 {\n"
"ST {\n"
"FLUI:len:3\n"
"}\n"
"}\n"
"SC:5 {\n"
"ST {\n"
"DLA:strings {\n"
"NTS {\n"
"SS:6:alert\n"
"}\n"
"NTS {\n"
"SS:5:look\n"
"}\n"
"NTS {\n"
"SS:5:sour\n"
"}\n"
"}\n"
"}\n"
"}\n"
"}\n"
"ER {\n"
"SC:2 {\n"
"ST {\n"
"FLUI:id:17\n"
"}\n"
"}\n"
"ERI:T17\n"
"SC:5 {\n"
"ST {\n"
"ST:s {\n"
"FLUI:a:404295950\n"
"FLUI:b:62019\n"
"FLUI:c:81\n"
"}\n"
"}\n"
"}\n"
"}\n"
"}\n"
"}\n"
"P {\n"
"PC {\n"
"SC:0 {\n"
"ST {\n"
"FLUI:magic:3254525889\n"
"PMN:3254525889\n"
"SLA:uuid {\n"
"FLUI:100\n"
"FLUI:223\n"
"FLUI:96\n"
"FLUI:142\n"
"FLUI:141\n"
"FLUI:185\n"
"FLUI:79\n"
"FLUI:237\n"
"FLUI:156\n"
"FLUI:80\n"
"FLUI:14\n"
"FLUI:185\n"
"FLUI:114\n"
"FLUI:57\n"
"FLUI:44\n"
"FLUI:247\n"
"TTU:64df608e-8db9-4fed-9c50-0eb972392cf7\n"
"}\n"
"FLUI:stream_id:35\n"
"}\n"
"}\n"
"DSI:T35\n"
"SC:1 {\n"
"ST {\n"
"FLUI:packet_size:352\n"
"FLUI:content_size:352\n"
"}\n"
"}\n"
"PI:T352:C352\n"
"ER {\n"
"ERI:T0\n"
"SC:5 {\n"
"ST {\n"
"NTS:a {\n"
"SS:6:salut\n"
"}\n"
"FLUI:b:1146447479\n"
"}\n"
"}\n"
"}\n"
"ER {\n"
"ERI:T0\n"
"SC:5 {\n"
"ST {\n"
"NTS:a {\n"
"SS:5:Cola\n"
"}\n"
"FLUI:b:1146447479\n"
"}\n"
"}\n"
"}\n"
"}\n"
"}\n"
"P {\n"
"PC {\n"
"SC:0 {\n"
"ST {\n"
"FLUI:magic:3254525889\n"
"PMN:3254525889\n"
"SLA:uuid {\n"
"FLUI:100\n"
"FLUI:223\n"
"FLUI:96\n"
"FLUI:142\n"
"FLUI:141\n"
"FLUI:185\n"
"FLUI:79\n"
"FLUI:237\n"
"FLUI:156\n"
"FLUI:80\n"
"FLUI:14\n"
"FLUI:185\n"
"FLUI:114\n"
"FLUI:57\n"
"FLUI:44\n"
"FLUI:247\n"
"TTU:64df608e-8db9-4fed-9c50-0eb972392cf7\n"
"}\n"
"FLUI:stream_id:221\n"
"}\n"
"}\n"
"DSI:T221\n"
"SC:1 {\n"
"ST {\n"
"FLUI:packet_size:384\n"
"FLUI:content_size:368\n"
"FLUI:custom:65244\n"
"}\n"
"}\n"
"PI:T384:C368\n"
"ER {\n"
"SC:2 {\n"
"ST {\n"
"FLUI:id:34\n"
"}\n"
"}\n"
"ERI:T34\n"
"SC:4 {\n"
"ST {\n"
"FLUI:len:2\n"
"}\n"
"}\n"
"SC:5 {\n"
"ST {\n"
"DLA:strings {\n"
"NTS {\n"
"SS:4:dry\n"
"}\n"
"NTS {\n"
"SS:5:thaw\n"
"}\n"
"}\n"
"}\n"
"}\n"
"}\n"
"ER {\n"
"SC:2 {\n"
"ST {\n"
"FLUI:id:17\n"
"}\n"
"}\n"
"ERI:T17\n"
"SC:5 {\n"
"ST {\n"
"ST:s {\n"
"FLUI:a:16909060\n"
"FLUI:b:1286\n"
"FLUI:c:7\n"
"}\n"
"}\n"
"}\n"
"}\n"
"}\n"
"}\n";
int main()
{
const auto traceTypeEnvPair = yactfr::fromMetadataText(metadata,
metadata + std::strlen(metadata));
MemDataSrcFactory factory {stream, sizeof stream};
yactfr::ElementSequence seq {*traceTypeEnvPair.first, factory};
std::ostringstream ss;
ElemPrinter printer {ss, 0};
auto it = seq.begin();
while (it != seq.end()) {
it->accept(printer);
auto newIt = seq.begin();
newIt = std::move(it);
if (it != seq.end()) {
std::cerr << "Source element sequence iterator isn't set to end of element sequence.\n";
return 1;
}
it = std::move(newIt);
++it;
if (newIt != seq.end()) {
std::cerr << "Source element sequence iterator isn't set to end of element sequence.\n";
return 1;
}
}
if (ss.str() != expected) {
std::cerr << "Expected:\n\n" << expected << "\n" <<
"Got:\n\n" << ss.str();
return 1;
}
// move-assign end iterator
auto endIt = seq.end();
auto it2 = seq.begin();
it2 = std::move(endIt);
if (it2 != seq.end()) {
std::cerr << "Destination element sequence iterator isn't set to end of element sequence\n";
return 1;
}
if (endIt != seq.end()) {
std::cerr << "Source element sequence iterator isn't set to end of element sequence\n";
return 1;
}
return 0;
}
| 17.770833 | 100 | 0.44197 | [
"vector"
] |
e22417b9080cb62a75ab82f3848bad2846d432ca | 13,383 | cpp | C++ | src/app/imgui_nvrhi.cpp | Kuranes/KickstartRT_demo | 6de7453ca42e46db180f8bead7ba23f9e8936b69 | [
"MIT"
] | 83 | 2021-07-19T13:55:33.000Z | 2022-03-29T16:00:57.000Z | src/app/imgui_nvrhi.cpp | CompileException/donut | bc400a8c2c9db9c3c5ed16190dc108e75722b503 | [
"MIT"
] | 2 | 2021-11-04T06:41:28.000Z | 2021-11-30T08:25:28.000Z | src/app/imgui_nvrhi.cpp | CompileException/donut | bc400a8c2c9db9c3c5ed16190dc108e75722b503 | [
"MIT"
] | 10 | 2021-07-19T15:03:58.000Z | 2022-01-10T07:15:35.000Z | /*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved.
*
* 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 for Dear ImGui
Copyright (c) 2014-2019 Omar Cornut
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 <stddef.h>
#include <imgui.h>
#include <nvrhi/nvrhi.h>
#include <donut/engine/ShaderFactory.h>
#include <donut/app/imgui_nvrhi.h>
using namespace donut::engine;
using namespace donut::app;
struct VERTEX_CONSTANT_BUFFER
{
float mvp[4][4];
};
bool ImGui_NVRHI::createFontTexture(nvrhi::ICommandList* commandList)
{
ImGuiIO& io = ImGui::GetIO();
unsigned char *pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
{
nvrhi::TextureDesc desc;
desc.width = width;
desc.height = height;
desc.format = nvrhi::Format::RGBA8_UNORM;
desc.debugName = "ImGui font texture";
fontTexture = renderer->createTexture(desc);
commandList->beginTrackingTextureState(fontTexture, nvrhi::AllSubresources, nvrhi::ResourceStates::Common);
if (fontTexture == nullptr)
return false;
commandList->writeTexture(fontTexture, 0, 0, pixels, width * 4);
commandList->setPermanentTextureState(fontTexture, nvrhi::ResourceStates::ShaderResource);
commandList->commitBarriers();
io.Fonts->TexID = fontTexture;
}
{
const auto desc = nvrhi::SamplerDesc()
.setAllAddressModes(nvrhi::SamplerAddressMode::Wrap)
.setAllFilters(true);
fontSampler = renderer->createSampler(desc);
if (fontSampler == nullptr)
return false;
}
return true;
}
bool ImGui_NVRHI::init(nvrhi::DeviceHandle renderer, std::shared_ptr<ShaderFactory> shaderFactory)
{
this->renderer = renderer;
m_commandList = renderer->createCommandList();
m_commandList->open();
vertexShader = shaderFactory->CreateShader("donut/imgui_vertex", "main", nullptr, nvrhi::ShaderType::Vertex);
if (vertexShader == nullptr)
{
printf("error creating NVRHI vertex shader object\n");
assert(0);
return false;
}
pixelShader = shaderFactory->CreateShader("donut/imgui_pixel", "main", nullptr, nvrhi::ShaderType::Pixel);
if (pixelShader == nullptr)
{
printf("error creating NVRHI pixel shader object\n");
assert(0);
return false;
}
// create attribute layout object
nvrhi::VertexAttributeDesc vertexAttribLayout[] = {
{ "POSITION", nvrhi::Format::RG32_FLOAT, 1, 0, offsetof(ImDrawVert,pos), sizeof(ImDrawVert), false },
{ "TEXCOORD", nvrhi::Format::RG32_FLOAT, 1, 0, offsetof(ImDrawVert,uv), sizeof(ImDrawVert), false },
{ "COLOR", nvrhi::Format::RGBA8_UNORM, 1, 0, offsetof(ImDrawVert,col), sizeof(ImDrawVert), false },
};
shaderAttribLayout = renderer->createInputLayout(vertexAttribLayout, sizeof(vertexAttribLayout) / sizeof(vertexAttribLayout[0]), vertexShader);
// create font texture
if (!createFontTexture(m_commandList))
{
return false;
}
// create PSO
{
nvrhi::BlendState blendState;
blendState.targets[0].setBlendEnable(true)
.setSrcBlend(nvrhi::BlendFactor::SrcAlpha)
.setDestBlend(nvrhi::BlendFactor::InvSrcAlpha)
.setSrcBlendAlpha(nvrhi::BlendFactor::InvSrcAlpha)
.setDestBlendAlpha(nvrhi::BlendFactor::Zero);
auto rasterState = nvrhi::RasterState()
.setFillSolid()
.setCullNone()
.setScissorEnable(true)
.setDepthClipEnable(true);
auto depthStencilState = nvrhi::DepthStencilState()
.disableDepthTest()
.enableDepthWrite()
.disableStencil()
.setDepthFunc(nvrhi::ComparisonFunc::Always);
nvrhi::RenderState renderState;
renderState.blendState = blendState;
renderState.depthStencilState = depthStencilState;
renderState.rasterState = rasterState;
nvrhi::BindingLayoutDesc layoutDesc;
layoutDesc.visibility = nvrhi::ShaderType::All;
layoutDesc.bindings = {
nvrhi::BindingLayoutItem::PushConstants(0, sizeof(float) * 2),
nvrhi::BindingLayoutItem::Texture_SRV(0),
nvrhi::BindingLayoutItem::Sampler(0)
};
bindingLayout = renderer->createBindingLayout(layoutDesc);
basePSODesc.primType = nvrhi::PrimitiveType::TriangleList;
basePSODesc.inputLayout = shaderAttribLayout;
basePSODesc.VS = vertexShader;
basePSODesc.PS = pixelShader;
basePSODesc.renderState = renderState;
basePSODesc.bindingLayouts = { bindingLayout };
}
auto& io = ImGui::GetIO();
io.Fonts->AddFontDefault();
m_commandList->close();
renderer->executeCommandList(m_commandList);
return true;
}
bool ImGui_NVRHI::reallocateBuffer(nvrhi::BufferHandle& buffer, size_t requiredSize, size_t reallocateSize, const bool indexBuffer)
{
if (buffer == nullptr || size_t(buffer->getDesc().byteSize) < requiredSize)
{
nvrhi::BufferDesc desc;
desc.byteSize = uint32_t(reallocateSize);
desc.structStride = 0;
desc.debugName = indexBuffer ? "ImGui index buffer" : "ImGui vertex buffer";
desc.canHaveUAVs = false;
desc.isVertexBuffer = !indexBuffer;
desc.isIndexBuffer = indexBuffer;
desc.isDrawIndirectArgs = false;
desc.isVolatile = false;
desc.initialState = indexBuffer ? nvrhi::ResourceStates::IndexBuffer : nvrhi::ResourceStates::VertexBuffer;
desc.keepInitialState = true;
buffer = renderer->createBuffer(desc);
if (!buffer)
{
return false;
}
}
return true;
}
bool ImGui_NVRHI::beginFrame(float elapsedTimeSeconds)
{
ImGuiIO& io = ImGui::GetIO();
io.DeltaTime = elapsedTimeSeconds;
io.MouseDrawCursor = false;
ImGui::NewFrame();
return true;
}
nvrhi::IGraphicsPipeline* ImGui_NVRHI::getPSO(nvrhi::IFramebuffer* fb)
{
if (pso)
return pso;
pso = renderer->createGraphicsPipeline(basePSODesc, fb);
assert(pso);
return pso;
}
nvrhi::IBindingSet* ImGui_NVRHI::getBindingSet(nvrhi::ITexture* texture)
{
auto iter = bindingsCache.find(texture);
if (iter != bindingsCache.end())
{
return iter->second;
}
nvrhi::BindingSetDesc desc;
desc.bindings = {
nvrhi::BindingSetItem::PushConstants(0, sizeof(float) * 2),
nvrhi::BindingSetItem::Texture_SRV(0, texture),
nvrhi::BindingSetItem::Sampler(0, fontSampler)
};
nvrhi::BindingSetHandle binding;
binding = renderer->createBindingSet(desc, bindingLayout);
assert(binding);
bindingsCache[texture] = binding;
return binding;
}
bool ImGui_NVRHI::updateGeometry(nvrhi::ICommandList* commandList)
{
ImDrawData *drawData = ImGui::GetDrawData();
// create/resize vertex and index buffers if needed
if (!reallocateBuffer(vertexBuffer,
drawData->TotalVtxCount * sizeof(ImDrawVert),
(drawData->TotalVtxCount + 5000) * sizeof(ImDrawVert),
false))
{
return false;
}
if (!reallocateBuffer(indexBuffer,
drawData->TotalIdxCount * sizeof(ImDrawIdx),
(drawData->TotalIdxCount + 5000) * sizeof(ImDrawIdx),
true))
{
return false;
}
vtxBuffer.resize(vertexBuffer->getDesc().byteSize / sizeof(ImDrawVert));
idxBuffer.resize(indexBuffer->getDesc().byteSize / sizeof(ImDrawIdx));
// copy and convert all vertices into a single contiguous buffer
ImDrawVert *vtxDst = &vtxBuffer[0];
ImDrawIdx *idxDst = &idxBuffer[0];
for(int n = 0; n < drawData->CmdListsCount; n++)
{
const ImDrawList *cmdList = drawData->CmdLists[n];
memcpy(vtxDst, cmdList->VtxBuffer.Data, cmdList->VtxBuffer.Size * sizeof(ImDrawVert));
memcpy(idxDst, cmdList->IdxBuffer.Data, cmdList->IdxBuffer.Size * sizeof(ImDrawIdx));
vtxDst += cmdList->VtxBuffer.Size;
idxDst += cmdList->IdxBuffer.Size;
}
commandList->writeBuffer(vertexBuffer, &vtxBuffer[0], vertexBuffer->getDesc().byteSize);
commandList->writeBuffer(indexBuffer, &idxBuffer[0], indexBuffer->getDesc().byteSize);
return true;
}
bool ImGui_NVRHI::render(nvrhi::IFramebuffer* framebuffer)
{
ImDrawData *drawData = ImGui::GetDrawData();
const auto& io = ImGui::GetIO();
m_commandList->open();
m_commandList->beginMarker("ImGUI");
if (!updateGeometry(m_commandList))
{
return false;
}
// handle DPI scaling
drawData->ScaleClipRects(io.DisplayFramebufferScale);
float invDisplaySize[2] = { 1.f / io.DisplaySize.x, 1.f / io.DisplaySize.y };
// set up graphics state
nvrhi::GraphicsState drawState;
drawState.framebuffer = framebuffer;
assert(drawState.framebuffer);
drawState.pipeline = getPSO(drawState.framebuffer);
drawState.viewport.viewports.push_back(nvrhi::Viewport(io.DisplaySize.x * io.DisplayFramebufferScale.x,
io.DisplaySize.y * io.DisplayFramebufferScale.y));
drawState.viewport.scissorRects.resize(1); // updated below
nvrhi::VertexBufferBinding vbufBinding;
vbufBinding.buffer = vertexBuffer;
vbufBinding.slot = 0;
vbufBinding.offset = 0;
drawState.vertexBuffers.push_back(vbufBinding);
drawState.indexBuffer.buffer = indexBuffer;
drawState.indexBuffer.format = (sizeof(ImDrawIdx) == 2 ? nvrhi::Format::R16_UINT : nvrhi::Format::R32_UINT);
drawState.indexBuffer.offset = 0;
// render command lists
int vtxOffset = 0;
int idxOffset = 0;
for(int n = 0; n < drawData->CmdListsCount; n++)
{
const ImDrawList *cmdList = drawData->CmdLists[n];
for(int i = 0; i < cmdList->CmdBuffer.Size; i++)
{
const ImDrawCmd *pCmd = &cmdList->CmdBuffer[i];
if (pCmd->UserCallback)
{
pCmd->UserCallback(cmdList, pCmd);
} else {
drawState.bindings = { getBindingSet((nvrhi::ITexture*)pCmd->TextureId) };
assert(drawState.bindings[0]);
drawState.viewport.scissorRects[0] = nvrhi::Rect(int(pCmd->ClipRect.x),
int(pCmd->ClipRect.z),
int(pCmd->ClipRect.y),
int(pCmd->ClipRect.w));
nvrhi::DrawArguments drawArguments;
drawArguments.vertexCount = pCmd->ElemCount;
drawArguments.startIndexLocation = idxOffset;
drawArguments.startVertexLocation = vtxOffset;
m_commandList->setGraphicsState(drawState);
m_commandList->setPushConstants(invDisplaySize, sizeof(invDisplaySize));
m_commandList->drawIndexed(drawArguments);
}
idxOffset += pCmd->ElemCount;
}
vtxOffset += cmdList->VtxBuffer.Size;
}
m_commandList->endMarker();
m_commandList->close();
renderer->executeCommandList(m_commandList);
return true;
}
void ImGui_NVRHI::backbufferResizing()
{
pso = nullptr;
}
| 32.963054 | 147 | 0.663304 | [
"render",
"object"
] |
e224c9381ab95d4aa0d987a22928df8ba4a14fb4 | 1,119 | cpp | C++ | ndcmd_img.cpp | nsdrozario/nd_cmd_paint | a35a222bd68f782b7cf0ee100afddc47d3212e28 | [
"MIT"
] | null | null | null | ndcmd_img.cpp | nsdrozario/nd_cmd_paint | a35a222bd68f782b7cf0ee100afddc47d3212e28 | [
"MIT"
] | null | null | null | ndcmd_img.cpp | nsdrozario/nd_cmd_paint | a35a222bd68f782b7cf0ee100afddc47d3212e28 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <fstream>
#include "headers/paint.h"
#include "headers/file.h"
nd_cmd_paint::image_data::image_data(int sx, int sy)
: size_x(sx), size_y(sy)
{
for (int y=0; y<sy; y++) {
this->data.push_back(std::vector<int>()); // default value
for (int x=0; x<sx; x++) {
this->data[y].push_back(0);
}
}
}
nd_cmd_paint::Pixel* nd_cmd_paint::image_data::get_pixel(int x, int y) {
nd_cmd_paint::Pixel *p = new nd_cmd_paint::Pixel(x,y,0);
p->color = this->data[y][x];
return p;
}
void nd_cmd_paint::image_data::place_pixel(int x, int y, int c) {
std::cout << "Placing pixel info" << std::endl;
int *pixel_to_write = &(this->data.at(y).at(x));
*pixel_to_write = c;
std::cout << "Placed" << std::endl;
}
void nd_cmd_paint::image_data::store_in_file(const char *file) {
std::ofstream f;
f.open(file, std::ios::out | std::ios::binary | std::ios::app);
if (f.is_open()) {
std::cout << "Successfully opened file" << std::endl;
f.write((char*)this, (int)sizeof(this));
}
f.close();
}
| 25.431818 | 72 | 0.598749 | [
"vector"
] |
e22a5f8b80717bb4c4f5fc70f17ddba29013a56f | 4,549 | cpp | C++ | src/compiler/ir_optimizer.cpp | LangUMS/langums | 99487610e7c8feb07c7250eea7cf09ec2bee8037 | [
"MIT"
] | 24 | 2017-05-27T13:46:44.000Z | 2021-07-04T11:42:10.000Z | src/compiler/ir_optimizer.cpp | LangUMS/langums | 99487610e7c8feb07c7250eea7cf09ec2bee8037 | [
"MIT"
] | 6 | 2017-10-05T01:41:28.000Z | 2021-01-25T21:23:24.000Z | src/compiler/ir_optimizer.cpp | LangUMS/langums | 99487610e7c8feb07c7250eea7cf09ec2bee8037 | [
"MIT"
] | 3 | 2017-05-07T05:44:30.000Z | 2021-07-04T11:43:46.000Z | #include "ir_optimizer.h"
namespace LangUMS
{
std::vector<std::unique_ptr<IIRInstruction>> IROptimizer::Process(std::vector<std::unique_ptr<IIRInstruction>> instructions)
{
m_Instructions = std::move(instructions);
return std::move(m_Instructions);
}
bool IROptimizer::EliminateRedundantPushPopPairs()
{
auto jmpTargets = CalculateJmpTargets(m_Instructions);
bool madeChanges = false;
for (auto i = 0u; i < m_Instructions.size() - 1u; i++)
{
auto& current = m_Instructions[i];
auto& next = m_Instructions[i + 1];
if (current->GetType() == IRInstructionType::Push &&
next->GetType() == IRInstructionType::Pop)
{
auto push = (IRPushInstruction*)current.get();
auto pop = (IRPopInstruction*)next.get();
if (push->GetRegisterId() == pop->GetRegisterId() ||
pop->GetRegisterId() == -1)
{
if (jmpTargets[i] || jmpTargets[i + 1])
{
continue; // we shouldn't optimize out jmp targets
}
m_Instructions[i] = std::make_unique<IRNopInstruction>();
m_Instructions[i + 1] = std::make_unique<IRNopInstruction>();
madeChanges = true;
}
}
}
return madeChanges;
}
std::vector<bool> IROptimizer::CalculateJmpTargets(const std::vector<std::unique_ptr<IIRInstruction>>& instructions)
{
std::vector<bool> jmpTargets;
jmpTargets.resize(instructions.size());
for (auto i = 0u; i < instructions.size(); i++)
{
auto& instruction = instructions[i];
if (instruction->GetType() == IRInstructionType::Jmp)
{
auto jmp = (IRJmpInstruction*)instruction.get();
auto offset = jmp->GetOffset();
if (!jmp->IsAbsolute())
{
offset += i;
}
if (offset >= (int)jmpTargets.size())
{
throw IRCompilerException("Out of bounds jump", 0);
}
jmpTargets[offset] = true;
}
else if (instruction->GetType() == IRInstructionType::JmpIfEq)
{
auto jmp = (IRJmpIfEqInstruction*)instruction.get();
auto offset = jmp->GetOffset();
if (!jmp->IsAbsolute())
{
offset += i;
}
if (offset >= (int)jmpTargets.size())
{
throw IRCompilerException("Out of bounds jump", 0);
}
jmpTargets[offset] = true;
}
else if (instruction->GetType() == IRInstructionType::JmpIfNotEq)
{
auto jmp = (IRJmpIfNotEqInstruction*)instruction.get();
auto offset = jmp->GetOffset();
if (!jmp->IsAbsolute())
{
offset += i;
}
if (offset >= (int)jmpTargets.size())
{
throw IRCompilerException("Out of bounds jump", 0);
}
jmpTargets[offset] = true;
}
else if (instruction->GetType() == IRInstructionType::JmpIfSwSet)
{
auto jmp = (IRJmpIfSwSetInstruction*)instruction.get();
auto offset = jmp->GetOffset();
if (!jmp->IsAbsolute())
{
offset += i;
}
if (offset >= (int)jmpTargets.size())
{
throw IRCompilerException("Out of bounds jump", 0);
}
jmpTargets[offset] = true;
}
else if (instruction->GetType() == IRInstructionType::JmpIfSwNotSet)
{
auto jmp = (IRJmpIfSwNotSetInstruction*)instruction.get();
auto offset = jmp->GetOffset();
if (!jmp->IsAbsolute())
{
offset += i;
}
if (offset >= (int)jmpTargets.size())
{
throw IRCompilerException("Out of bounds jump", 0);
}
jmpTargets[offset] = true;
}
}
return jmpTargets;
}
}
| 30.945578 | 128 | 0.459222 | [
"vector"
] |
e23766c80111a28d3f9720268314e45dcd942d4e | 2,154 | cpp | C++ | library/appl_library_std_mgr.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | library/appl_library_std_mgr.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | library/appl_library_std_mgr.cpp | fboucher9/appl | bb90398cf9985d4cc0a2a079c4d49d891108e6d1 | [
"MIT"
] | null | null | null | /* See LICENSE for license details */
/*
*/
#if defined APPL_OS_LINUX
#include <appl_status.h>
#include <appl_types.h>
#include <object/appl_object.h>
#include <library/appl_library_mgr.h>
#include <library/appl_library_std_mgr.h>
#include <library/appl_library_node.h>
#include <library/appl_library_std_node.h>
#include <context/appl_context_handle.h>
#include <allocator/appl_allocator_handle.h>
//
//
//
enum appl_status
appl_library_std_mgr::s_create(
struct appl_allocator * const
p_allocator,
class appl_library_mgr * * const
r_library_mgr)
{
enum appl_status
e_status;
class appl_library_std_mgr *
p_library_std_mgr;
e_status =
appl_new(
p_allocator,
&(
p_library_std_mgr));
if (
appl_status_ok
== e_status)
{
*(
r_library_mgr) =
p_library_std_mgr;
}
return
e_status;
} // s_create()
//
//
//
appl_library_std_mgr::appl_library_std_mgr(
struct appl_context * const
p_context) :
appl_library_mgr(
p_context)
{
}
//
//
//
appl_library_std_mgr::~appl_library_std_mgr()
{
}
//
//
//
appl_size_t
appl_library_std_mgr::v_cleanup(void)
{
return
sizeof(class appl_library_std_mgr);
} // v_cleanup()
//
//
//
enum appl_status
appl_library_std_mgr::v_create_node(
struct appl_library_descriptor const * const
p_library_descriptor,
struct appl_library * * const
r_library)
{
return
appl_library_std_node::s_create(
appl_context_get_allocator(
m_context),
p_library_descriptor,
r_library);
} // v_create_node()
//
//
//
enum appl_status
appl_library_std_mgr::v_destroy_node(
struct appl_library * const
p_library)
{
return
appl_library_std_node::s_destroy(
appl_context_get_allocator(
m_context),
p_library);
} // v_destroy_node()
#endif /* #if defined APPL_OS_LINUX */
/* end-of-file: appl_library_std_mgr.cpp */
| 16.569231 | 52 | 0.618384 | [
"object"
] |
e23cdbbdfba94f1326f346eb77ac48bf3f922824 | 1,342 | hpp | C++ | sdk/core/perf/inc/azure/perf/random_stream.hpp | RickWinter/azure-sdk-for-cpp | b4fe751310f53669a941e00aa93072f2d10a4eba | [
"MIT"
] | 96 | 2020-03-19T07:49:39.000Z | 2022-03-20T14:22:41.000Z | sdk/core/perf/inc/azure/perf/random_stream.hpp | RickWinter/azure-sdk-for-cpp | b4fe751310f53669a941e00aa93072f2d10a4eba | [
"MIT"
] | 2,572 | 2020-03-18T22:54:53.000Z | 2022-03-31T22:09:59.000Z | sdk/core/perf/inc/azure/perf/random_stream.hpp | RickWinter/azure-sdk-for-cpp | b4fe751310f53669a941e00aa93072f2d10a4eba | [
"MIT"
] | 81 | 2020-03-19T09:42:00.000Z | 2022-03-24T05:11:05.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
/**
* @file
* @brief A random stream of any specific size. Useful for test cases.
*
*/
#pragma once
#include <azure/core/io/body_stream.hpp>
#include <memory>
#include <random>
namespace Azure { namespace Perf {
/**
* @brief A random stream of any specific size. Useful for test cases.
*
*/
class RandomStream {
private:
/**
* @brief Wraps a stream and keep reading bytes from it by rewinding it until some length.
*
* @note Enables to create a stream with huge size by re-using a small buffer.
*
*/
class CircularStream : public Azure::Core::IO::BodyStream {
private:
std::unique_ptr<std::vector<uint8_t>> m_buffer;
size_t m_length;
size_t m_totalRead = 0;
Azure::Core::IO::MemoryBodyStream m_memoryStream;
size_t OnRead(uint8_t* buffer, size_t count, Azure::Core::Context const& context) override;
public:
CircularStream(size_t size);
int64_t Length() const override { return this->m_length; }
void Rewind() override { m_totalRead = 0; }
};
public:
static std::unique_ptr<Azure::Core::IO::BodyStream> Create(size_t size)
{
return std::make_unique<CircularStream>(size);
}
};
}} // namespace Azure::Perf
| 24.851852 | 97 | 0.660209 | [
"vector"
] |
e23e7b2a29f40648c5aa1edcb40b9785148c1e60 | 3,776 | cpp | C++ | src/asset/cubemap.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | src/asset/cubemap.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | src/asset/cubemap.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | #include "chokoengine.hpp"
#include "texture_internal.hpp"
#include "backend/chokoengine_backend.hpp"
#include "glsl/minVert.h"
#include "glsl/presum_ggx_cube.h"
CE_BEGIN_NAMESPACE
#define SAMPLES 1024
bool _CubeMap::initd;
Shader _CubeMap::ggxBlurShad;
TextureBuffer _CubeMap::noiseTex;
void _CubeMap::Init() {
(ggxBlurShad = Shader::New(glsl::minVert, glsl::presumGGXCube))
->AddUniforms({ "cubemap", "rough", "screenSize", "noise", "samples", "face", "dirx", "diry", "level" });
std::vector<Vec2> noise(65535);
for (auto& n : noise) {
n = Vec2(rand() * 1.f / RAND_MAX, rand() * 1.f / RAND_MAX);
}
const auto& noiseBuf = VertexBuffer_New(true, 2, 65535, noise.data());
noiseTex = TextureBuffer::New(noiseBuf, GL_RG32F);
initd = true;
}
_CubeMap::_CubeMap(uint res, GLenum type, const TextureOptions& opts, int div) : _Texture(nullptr), _layers(div) {
glGenTextures(1, &_pointer);
glBindTexture(GL_TEXTURE_CUBE_MAP, _pointer);
Color cs[] = {
Color::red(), Color::yellow(), Color::green(), Color(0.5f), Color::blue(), Color::cyan()
};
for (int a = 0; a < 6; a++) {
std::vector<Color> cols(res * res, cs[a]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + a, 0, type, (int)res, (int)res, 0, GL_RGBA, GL_FLOAT, cols.data());
}
SetTexParams<GL_TEXTURE_CUBE_MAP>(-1,
GL_CLAMP_TO_EDGE,
GL_CLAMP_TO_EDGE,
(opts.linear) ? (
(opts.mipmaps > 0) ?
GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR
) : GL_NEAREST,
(opts.linear) ?
GL_LINEAR : GL_NEAREST
);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
if (opts.mipmaps > 0) {
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
}
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
_width = _height = res;
}
void _CubeMap::ComputeGlossMipmaps() {
if (!initd)
Init();
const float vec[] = {
1, 0, 0, -1, 0, 0,
0, 1, 0, 0, -1, 0,
0, 0, 1, 0, 0, -1
};
const float dx[] = {
0, 0, -1, 0, 0, 1,
0, 0, -1, 0, 0, -1,
1, 0, 0, -1, 0, 0
};
const float dy[] = {
0, 1, 0, 0, 1, 0,
-1, 0, 0, 1, 0, 0,
0, 1, 0, 0, 1, 0
};
int res = _width / 2;
for (int a = 1; a < _layers; a++) {
glViewport(0, 0, res, res);
std::array<RenderTarget, 6> tars;
for (int f = 0; f < 6; f++) {
tars[f] = RenderTarget::New(res, res, true, false);
ggxBlurShad->Bind();
glUniform1i(ggxBlurShad->Loc(0), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, _pointer);
glUniform1f(ggxBlurShad->Loc(1), a * 1.f / _layers);
glUniform2f(ggxBlurShad->Loc(2), res, res);
glUniform1i(ggxBlurShad->Loc(3), 1);
glActiveTexture(GL_TEXTURE1);
noiseTex->Bind();
glUniform1i(ggxBlurShad->Loc(4), SAMPLES);
glUniform3f(ggxBlurShad->Loc(5), vec[a * 3], vec[a * 3 + 1], vec[a * 3 + 2]);
glUniform3f(ggxBlurShad->Loc(6), dx[a * 3], dx[a * 3 + 1], dx[a * 3 + 2]);
glUniform3f(ggxBlurShad->Loc(7), dy[a * 3], dy[a * 3 + 1], dy[a * 3 + 2]);
glUniform1f(ggxBlurShad->Loc(8), a - 1);
tars[f]->BindTarget();
Backend::Renderer::emptyVao()->Bind();
glDrawArrays(GL_TRIANGLES, 0, 6);
Backend::Renderer::emptyVao()->Unbind();
tars[f]->UnbindTarget();
ggxBlurShad->Unbind();
}
glBindTexture(GL_TEXTURE_CUBE_MAP, _pointer);
for (int f = 0; f < 6; f++) {
tars[f]->BindTarget(true);
glCopyTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, a, 0, 0, 0, 0, res, res);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
}
SetTexParams<GL_TEXTURE_CUBE_MAP>(-1, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
res /= 2;
}
}
void _CubeMap::Bind() {
glBindTexture(GL_TEXTURE_CUBE_MAP, _pointer);
}
void _CubeMap::Unbind() const {
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}
CE_END_NAMESPACE
| 30.451613 | 115 | 0.65572 | [
"vector"
] |
f46c4706843f58c62fda99f1dc02b83005df3d4b | 6,224 | cpp | C++ | src/GameLogic/Game/TankClientGame.cpp | gameraccoon/tank-game | ec2ca0550269b8051c8742abdfad6ae8adc2a83a | [
"MIT"
] | null | null | null | src/GameLogic/Game/TankClientGame.cpp | gameraccoon/tank-game | ec2ca0550269b8051c8742abdfad6ae8adc2a83a | [
"MIT"
] | null | null | null | src/GameLogic/Game/TankClientGame.cpp | gameraccoon/tank-game | ec2ca0550269b8051c8742abdfad6ae8adc2a83a | [
"MIT"
] | null | null | null | #include "Base/precomp.h"
#include "GameLogic/Game/TankClientGame.h"
#include "Base/Types/TemplateHelpers.h"
#include "GameData/ComponentRegistration/ComponentFactoryRegistration.h"
#include "GameData/ComponentRegistration/ComponentJsonSerializerRegistration.h"
#include "GameData/ComponentRegistration/ComponentFactoryRegistration.h"
#include "GameData/ComponentRegistration/ComponentJsonSerializerRegistration.h"
#include "GameData/Components/CharacterStateComponent.generated.h"
#include "GameData/Components/ClientGameDataComponent.generated.h"
#include "GameData/Components/ConnectionManagerComponent.generated.h"
#include "GameData/Components/InputHistoryComponent.generated.h"
#include "GameData/Components/MovementComponent.generated.h"
#include "GameData/Components/NetworkIdComponent.generated.h"
#include "GameData/Components/NetworkIdMappingComponent.generated.h"
#include "GameData/Components/RenderAccessorComponent.generated.h"
#include "GameData/Components/SpriteCreatorComponent.generated.h"
#include "GameData/Components/TransformComponent.generated.h"
#include "Utils/Application/ArgumentsParser.h"
#include "Utils/World/GameDataLoader.h"
#include "HAL/Base/Engine.h"
#include "GameLogic/Systems/AnimationSystem.h"
#include "GameLogic/Systems/CharacterStateSystem.h"
#include "GameLogic/Systems/ClientInpuntSendSystem.h"
#include "GameLogic/Systems/ClientNetworkSystem.h"
#include "GameLogic/Systems/ControlSystem.h"
#include "GameLogic/Systems/DeadEntitiesDestructionSystem.h"
#include "GameLogic/Systems/DebugDrawSystem.h"
#include "GameLogic/Systems/InputSystem.h"
#include "GameLogic/Systems/MovementSystem.h"
#include "GameLogic/Systems/RenderSystem.h"
#include "GameLogic/Systems/ResourceStreamingSystem.h"
#ifdef IMGUI_ENABLED
#include "GameLogic/Systems/ImguiSystem.h"
#endif // IMGUI_ENABLED
#ifdef ENABLE_SCOPED_PROFILER
#include "Utils/Profiling/ProfileDataWriter.h"
#endif // ENABLE_SCOPED_PROFILER
#include "GameLogic/Initialization/StateMachines.h"
void TankClientGame::preStart(ArgumentsParser& arguments, RenderAccessor& renderAccessor)
{
SCOPED_PROFILER("TankClientGame::preStart");
ComponentsRegistration::RegisterComponents(getComponentFactory());
ComponentsRegistration::RegisterJsonSerializers(getComponentSerializers());
initSystems();
GameDataLoader::LoadWorld(getWorldHolder().getWorld(), arguments.getArgumentValue("world", "test"), getComponentSerializers());
GameDataLoader::LoadGameData(getGameData(), arguments.getArgumentValue("gameData", "gameData"), getComponentSerializers());
RenderAccessorComponent* renderAccessorComponent = getGameData().getGameComponents().getOrAddComponent<RenderAccessorComponent>();
renderAccessorComponent->setAccessor(&renderAccessor);
EntityManager& worldEntityManager = getWorldHolder().getWorld().getEntityManager();
Entity controlledEntity = worldEntityManager.addEntity();
{
TransformComponent* transform = worldEntityManager.addComponent<TransformComponent>(controlledEntity);
transform->setLocation(Vector2D(50, 50));
MovementComponent* movement = worldEntityManager.addComponent<MovementComponent>(controlledEntity);
movement->setOriginalSpeed(20.0f);
worldEntityManager.addComponent<InputHistoryComponent>(controlledEntity);
SpriteCreatorComponent* spriteCreator = worldEntityManager.addComponent<SpriteCreatorComponent>(controlledEntity);
spriteCreator->getDescriptionsRef().emplace_back(SpriteParams{Vector2D(16,16), ZERO_VECTOR}, "resources/textures/tank-enemy-level1-1.png");
worldEntityManager.addComponent<CharacterStateComponent>(controlledEntity);
NetworkIdComponent* networkId = worldEntityManager.addComponent<NetworkIdComponent>(controlledEntity);
networkId->setId(0);
}
{
ClientGameDataComponent* clientGameData = getWorldHolder().getWorld().getWorldComponents().getOrAddComponent<ClientGameDataComponent>();
clientGameData->setControlledPlayer(controlledEntity);
NetworkIdMappingComponent* networkIdMapping = getWorldHolder().getWorld().getWorldComponents().getOrAddComponent<NetworkIdMappingComponent>();
networkIdMapping->getNetworkIdToEntityRef().emplace(0, controlledEntity);
}
{
ConnectionManagerComponent* connectionManager = getWorldHolder().getGameData().getGameComponents().getOrAddComponent<ConnectionManagerComponent>();
connectionManager->setManagerPtr(&mConnectionManager);
}
Game::preStart(arguments);
}
void TankClientGame::initSystems()
{
SCOPED_PROFILER("TankClientGame::initSystems");
AssertFatal(getEngine(), "TankClientGame created without Engine. We're going to crash");
getPreFrameSystemsManager().registerSystem<InputSystem>(getWorldHolder(), getInputData(), getTime());
getPreFrameSystemsManager().registerSystem<ClientInputSendSystem>(getWorldHolder(), getTime());
getPreFrameSystemsManager().registerSystem<ClientNetworkSystem>(getWorldHolder(), mShouldQuitGameNextTick);
getGameLogicSystemsManager().registerSystem<ControlSystem>(getWorldHolder());
getGameLogicSystemsManager().registerSystem<DeadEntitiesDestructionSystem>(getWorldHolder());
getGameLogicSystemsManager().registerSystem<MovementSystem>(getWorldHolder(), getTime());
getGameLogicSystemsManager().registerSystem<CharacterStateSystem>(getWorldHolder(), getTime());
getGameLogicSystemsManager().registerSystem<AnimationSystem>(getWorldHolder(), getTime());
getPostFrameSystemsManager().registerSystem<ResourceStreamingSystem>(getWorldHolder(), getResourceManager());
getPostFrameSystemsManager().registerSystem<RenderSystem>(getWorldHolder(), getTime(), getResourceManager(), getThreadPool());
getPostFrameSystemsManager().registerSystem<DebugDrawSystem>(getWorldHolder(), getTime(), getResourceManager());
#ifdef IMGUI_ENABLED
getPostFrameSystemsManager().registerSystem<ImguiSystem>(mImguiDebugData, *getEngine());
#endif // IMGUI_ENABLED
}
void TankClientGame::initResources()
{
SCOPED_PROFILER("TankGameClient::initResources");
getResourceManager().loadAtlasesData("resources/atlas/atlas-list.json");
Game::initResources();
}
void TankClientGame::dynamicTimePostFrameUpdate(float dt, int processedFixedUpdates)
{
Game::dynamicTimePostFrameUpdate(dt, processedFixedUpdates);
if (mShouldQuitGameNextTick)
{
mShouldQuitGame = true;
}
}
| 47.151515 | 149 | 0.830977 | [
"transform"
] |
f46da8297bc6742f658687cb6863f8654affacf9 | 6,516 | cpp | C++ | src/edge/edge.cpp | Victoooooor/ECE-395-SeniorProj | 60a5a111401c0086a9eb801e1088f5e2a9a7331d | [
"MIT"
] | 2 | 2021-11-07T18:59:25.000Z | 2021-11-29T01:31:29.000Z | src/edge/edge.cpp | Victoooooor/Vectorize-Arch | 60a5a111401c0086a9eb801e1088f5e2a9a7331d | [
"MIT"
] | 1 | 2022-02-10T14:21:52.000Z | 2022-02-10T14:21:52.000Z | src/edge/edge.cpp | Victoooooor/ECE-395-SeniorProj | 60a5a111401c0086a9eb801e1088f5e2a9a7331d | [
"MIT"
] | null | null | null | #include <png++/png.hpp>
#include <iostream>
#include <queue>
#define L 50
using namespace std;
typedef pair<int, int> cord;
int main(int argc, char **argv) {
if (argc < 2) {
printf("incorrect params, expected: ./.exe <input> <output>\n");
exit(EXIT_FAILURE);
}
// Load image
png::image <png::rgb_pixel> img(argv[1]);
vector <cord> edges;
queue <cord> buff;
bool checked[img.get_height()][img.get_width()] = {0};
cout << img.get_height() << "\t" << img.get_width() << endl;
// Get first black pixel
for (png::uint_32 y = 0; y < img.get_height(); ++y) {
for (png::uint_32 x = 0; x < img.get_width(); ++x) {
if (img[y][x].red < 127) {
buff.push({y, x});
checked[y][x] = 1;
break;
}
if (!buff.empty()) {
break;
}
}
}
// Start square method
cord temp;
int sum = 0;
int n = 2 * L + 1;
int x, y;
while (!buff.empty()) {
temp = buff.front();
buff.pop();
edges.push_back(temp);
x = temp.second;
y = temp.first;
//cout<<x<<"\t"<<y<<endl;
for (int i = -L; i <= L; i++) {
if (x - L >= 0) {
if (y + i >= 0 && y + i < img.get_height()) {
if (y + i - 1 == 0 || y + i + 1 == img.get_height()) {
if (img[y + i][x - L].red < 127) {
if (checked[y + i][x - L] == 0) {
buff.push({y + i, x - L});
checked[y + i][x - L] = 1;
}
}
} else if (y + i - 1 > 0 && y + i + 1 < img.get_height()) {
if ((img[y + i][x - L].red < 127) != (img[y + i - 1][x - L].red < 127)) {
if (checked[y + i][x - L] == 0) {
buff.push({y + i, x - L});
checked[y + i][x - L] = 1;
} else if ((img[y + i][x - L].red < 127) != (img[y + i + 1][x - L].red < 127)) {
if (checked[y + i][x - L] == 0) {
buff.push({y + i, x - L});
checked[y + i][x - L] = 1;
}
}
}
}
}
}
if (x + L < img.get_width()) {
if (y + i >= 0 && y + i < img.get_height()) {
if (y + i - 1 == 0 || y + i + 1 == img.get_height()) {
if (img[y + i][x + L].red < 127) {
if (checked[y + i][x + L] == 0) {
buff.push({y + i, x + L});
checked[y + i][x + L] = 1;
}
}
} else if (y + i - 1 > 0 && y + i + 1 < img.get_height()) {
if ((img[y + i][x + L].red < 127) != (img[y + i - 1][x + L].red < 127)) {
if (checked[y + i][x + L] == 0) {
buff.push({y + i, x + L});
checked[y + i][x + L] = 1;
} else if ((img[y + i][x + L].red < 127) != (img[y + i + 1][x + L].red < 127)) {
if (checked[y + i][x + L] == 0) {
buff.push({y + i, x + L});
checked[y + i][x + L] = 1;
}
}
}
}
}
}
if (y - L >= 0) {
if (x + i >= 0 && x + i < img.get_width()) {
if (x + i - 1 == 0 || x + i + 1 == img.get_width()) {
if (img[y - L][x + i].red < 127) {
if (checked[y - L][x + i] == 0) {
buff.push({y - L, x + i});
checked[y - L][x + i] = 1;
}
}
} else if (x + i - 1 > 0 && x + i + 1 < img.get_width()) {
if ((img[y - L][x + i].red < 127) != (img[y - L][x + i - 1].red < 127)) {
if (checked[y - L][x + i] == 0) {
buff.push({y - L, x + i});
checked[y - L][x + i] = 1;
} else if ((img[y - L][x + i].red < 127) != (img[y - L][x + i + 1].red < 127)) {
if (checked[y - L][x + i] == 0) {
buff.push({y - L, x + i});
checked[y - L][x + i] = 1;
}
}
}
}
}
}
if (y + L < img.get_height()) {
if (x + i >= 0 && x + i < img.get_width()) {
if (x + i - 1 == 0 || x + i + 1 == img.get_width()) {
if (img[y + L][x + i].red < 127) {
if (checked[y + L][x + i] == 0) {
buff.push({y + L, x + i});
checked[y + L][x + i] = 1;
}
}
} else if (x + i - 1 > 0 && x + i + 1 < img.get_width()) {
if ((img[y + L][x + i].red < 127) != (img[y + L][x + i - 1].red < 127)) {
if (checked[y + L][x + i] == 0) {
buff.push({y + L, x + i});
checked[y + L][x + i] = 1;
} else if ((img[y + L][x + i].red < 127) != (img[y + L][x + i + 1].red < 127)) {
if (checked[y + L][x + i] == 0) {
buff.push({y + L, x + i});
checked[y + L][x + i] = 1;
}
}
}
}
}
}
}
}
// Write to img
for (auto ite:edges) {
img[ite.first][ite.second] = png::rgb_pixel(254, 0, 0);
}
// Write to new png
img.write(argv[2]);
return 0;
}
| 40.981132 | 108 | 0.26903 | [
"vector"
] |
f477452dab8b4b5f812a70b9d9b0e0aea04aae89 | 5,100 | cpp | C++ | cpp/concurrency/matrix_mul_openmp.cpp | dasfex/Algorithms | 21d6d32816c997bf5d4c2a99f61a79f8e97a653e | [
"Unlicense"
] | 1 | 2020-03-31T08:05:57.000Z | 2020-03-31T08:05:57.000Z | cpp/concurrency/matrix_mul_openmp.cpp | dasfex/Algorithms | 21d6d32816c997bf5d4c2a99f61a79f8e97a653e | [
"Unlicense"
] | 2 | 2021-11-17T16:36:18.000Z | 2021-12-18T11:03:03.000Z | cpp/concurrency/matrix_mul_openmp.cpp | dasfex/practice | 21d6d32816c997bf5d4c2a99f61a79f8e97a653e | [
"Unlicense"
] | 1 | 2020-12-27T11:24:54.000Z | 2020-12-27T11:24:54.000Z | #include <cstring>
#include <chrono>
#include <stdexcept>
#include <string>
#include <iostream>
#include <vector>
#define VERIFY(condition, message) \
if (!(condition)) { \
throw std::runtime_error(std::string("File: ") + \
std::string(__FILE__) + \
std::string(", line ") + \
std::to_string(__LINE__) + \
std::string(": ") + message); \
}
class Matrix {
public:
explicit Matrix(size_t size = 1, int val = 0)
: data_(std::vector<int>(size * size, val))
, size_(size) {}
int& operator[](std::pair<size_t, size_t> p) {
return data_[p.first * size_ + p.second];
}
int operator[](std::pair<size_t, size_t> p) const {
return data_[p.first * size_ + p.second];
}
[[nodiscard]] size_t Size() const {
return size_;
}
bool operator==(const Matrix& rhs) const {
if (size_ != rhs.size_) {
return false;
}
for (size_t i = 0; i < size_; ++i) {
if (data_[i] != rhs.data_[i]) {
return false;
}
}
return true;
}
private:
std::vector<int> data_;
size_t size_;
};
std::istream& operator>>(std::istream& in, Matrix& m) {
for (size_t i = 0; i < m.Size(); ++i) {
for (size_t j = 0; j < m.Size(); ++j) {
in >> m[{i, j}];
}
}
return in;
}
std::ostream& operator<<(std::ostream& out, const Matrix& m) {
for (size_t i = 0; i < m.Size(); ++i) {
for (size_t j = 0; j < m.Size(); ++j) {
out << m[{i, j}] << ' ';
}
out << std::endl;
}
}
struct Helper {
size_t matrix_size = 1;
size_t block_size = 1;
bool outer_par = false;
bool inner_par = false;
};
Helper parseArgs(int argc, char* argv[]) {
Helper ret{};
std::vector<std::string> options{"-s", "-b", "-i", "-o"};
for (size_t i = 1; i < argc; ++i) {
for (auto& option : options) {
if (strcmp(option.c_str(), argv[i]) == 0) {
if (option == "-b") {
VERIFY(i + 1 < argc, "Where is block size after -b motherfucker?");
ret.block_size = std::stoi(argv[i + 1]);
} else if (option == "-i") {
ret.inner_par = true;
} else if (option == "-o") {
ret.outer_par = true;
}
}
}
}
return ret;
}
Matrix mul(const Matrix& a, const Matrix& b, const Helper& info) {
VERIFY(a.Size() == b.Size(), "Why sizes are not equal stupid?");
Matrix c(a.Size());
int i;
bool inner_par = info.inner_par;
bool outer_par = info.outer_par;
#pragma omp parallel for shared(a, b, c, inner_par) private(i) if (outer_par) default(none)
for (i = 0; i < c.Size(); ++i) {
int j;
#pragma omp parallel for shared(i, a, b, c) private(j) if (inner_par) default(none)
for (j = 0; j < c.Size(); ++j) {
for (size_t k = 0; k < c.Size(); ++k) {
c[{i, j}] += a[{i, k}] * b[{k, j}];
}
}
}
return c;
}
Matrix blockMul(const Matrix& a, const Matrix& b, const Helper& info) {
VERIFY(a.Size() == b.Size(), "Why sizes are not equal stupid?");
VERIFY(a.Size() % info.block_size == 0, "Matrix size % block size != 0 u know?");
Matrix c(a.Size());
size_t block_cnt = a.Size() / info.block_size;
size_t i, j;
size_t block_size = info.block_size;
bool inner_par = info.inner_par;
bool outer_par = info.outer_par;
#pragma omp parallel for shared(block_cnt, block_size, a, b, c, inner_par) private(i) if (outer_par) default(none)
for (i = 0; i < block_cnt; ++i) {
#pragma omp parallel for shared(i, block_cnt, block_size, a, b, c) private(j) if (inner_par) default(none)
for (j = 0; j < block_cnt; ++j) {
for (size_t k = 0; k < block_cnt; ++k) {
for (size_t ii = i * block_size; ii < (i + 1) * block_size; ++ii) {
for (size_t jj = j * block_size; jj < (j + 1) * block_size; ++jj) {
for (size_t kk = k * block_size; kk < (k + 1) * block_size; ++kk) {
c[{ii, jj}] += a[{ii, kk}] * b[{kk, jj}];
}
}
}
}
}
}
return c;
}
template <typename T,
typename = std::void_t<
decltype(
std::chrono::duration<double, std::milli>(std::declval<T>() - std::declval<T>())
)>>
auto getTime(T start, T end) {
auto time = std::chrono::duration<double, std::milli>(end - start);
return time.count();
}
int main(int argc, char* argv[]) {
auto info = parseArgs(argc, argv);
std::cin >> info.matrix_size;
Matrix a(info.matrix_size);
Matrix b(info.matrix_size);
std::cin >> a >> b;
auto first_timepoint = std::chrono::high_resolution_clock::now();
auto first_res = blockMul(a, b, info);
auto second_timepoint = std::chrono::high_resolution_clock::now();
auto second_res = mul(a, b, info);
auto third_timepoint = std::chrono::high_resolution_clock::now();
VERIFY(first_res == second_res, "Error!");
auto block_time = getTime(first_timepoint, second_timepoint);
std::cout << "Block: " << block_time << std::endl;
auto trivial_time = getTime(second_timepoint, third_timepoint);
std::cout << "Trivial: " << trivial_time << std::endl;
return 0;
}
| 28.651685 | 116 | 0.559412 | [
"vector"
] |
f47f32fed94ab5b6667a05504c236d53371e20c1 | 58,187 | cpp | C++ | source/memory/brmemoryhandle.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 115 | 2015-01-18T17:29:30.000Z | 2022-01-30T04:31:48.000Z | source/memory/brmemoryhandle.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-22T04:53:38.000Z | 2015-01-31T13:52:40.000Z | source/memory/brmemoryhandle.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-23T20:06:46.000Z | 2020-05-20T16:06:00.000Z | /***************************************
Handle based memory manager
Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com>
It is released under an MIT Open Source license. Please see LICENSE for
license details. Yes, you can use it in a commercial title without paying
anything, just give me a credit.
Please? It's not like I'm asking you for money!
***************************************/
#include "brmemoryhandle.h"
#include "brassert.h"
#include "brdebug.h"
#include "brglobalmemorymanager.h"
#include "brmemoryfunctions.h"
#include "brnumberto.h"
#include "brstringfunctions.h"
/*! ************************************
\class Burger::MemoryManagerHandle
\brief Handle based Memory Manager
This class allocates and releases memory using movable
memory blocks and can allocate from the top and bottom of memory
if needed. Fixed memory blocks are allocate from the
top of memory and movable memory blocks are allocated
from the bottom. Movable blocks can be marked as purgeable
so in low memory situations, the memory can be freed without
the main application's knowledge. To accomplish this, any
access to a handle must be first locked and then tested
if it's been purged. If it's purged, the memory must be reallocated
and reloaded with the data. It's mostly used by the resource, texture
and audio managers to cache in data chunks that can be
reloaded from disk if need be.
***************************************/
/*! ************************************
\struct Burger::MemoryManagerHandle::Handle_t
\brief Structure describing an allocated chunk of memory
This opaque structure contains all of the information that
describes an allocated chunk of memory. The contents of this
class is NEVER to be read or written to without the use
of a MemoryManagerHandle call. The only exception is
the first entry of m_pData which allows the structure
to be used as a void ** to the data for instant access
to the data.
\note The data pointer can be \ref NULL of the memory was
zero bytes in length or if the data was purged in an attempt
to free memory for an allocation in a low memory situation
***************************************/
#if !defined(DOXYGEN)
#if (UINTPTR_MAX == 0xFFFFFFFFU)
#define SANITYCHECK 0xDEADBEEF
#define KILLSANITYCHECK 0xBADBADBA
#else
#define SANITYCHECK 0xABCDDEADBEEFDCBAULL
#define KILLSANITYCHECK 0xBADBADBADBADBADBULL
#endif
struct PointerPrefix_t {
void** m_ppParentHandle; ///< Handle to the parent memory object
uintptr_t m_uSignature; ///< Signature for debugging
#if (UINTPTR_MAX == 0xFFFFFFFFU) && \
!(defined(BURGER_MSDOS) || defined(BURGER_DS) || defined(BURGER_68K))
uint_t m_uPadding1; ///< Pad to alignment
uint_t m_uPadding2;
#endif
};
#endif
/*! ************************************
\brief Allocate fixed memory
Static function to allocate a pointer to a block of memory in high (Fixed)
memory.
\param pThis Pointer to the MemoryManagerHandle instance
\param uSize Size of memory block request
\return Pointer to allocated memory block or \ref NULL on failure or zero
byte allocation.
\sa Burger::MemoryManagerHandle::FreeProc(MemoryManager *,const void *)
***************************************/
void* BURGER_API Burger::MemoryManagerHandle::AllocProc(
MemoryManager* pThis, uintptr_t uSize) BURGER_NOEXCEPT
{
BURGER_STATIC_ASSERT((static_cast<uint_t>(sizeof(PointerPrefix_t)) &
(MemoryManagerHandle::ALIGNMENT - 1)) == 0);
void* pResult = nullptr;
if (uSize) {
MemoryManagerHandle* pSelf = static_cast<MemoryManagerHandle*>(pThis);
// Allocate the memory with memory for a back pointer
void** ppData =
pSelf->AllocHandle(uSize + sizeof(PointerPrefix_t), FIXED);
// Got the memory?
if (ppData) {
// Dereference the memory!
PointerPrefix_t* pData = static_cast<PointerPrefix_t*>(
reinterpret_cast<Handle_t*>(ppData)->m_pData);
// Save the handle in memory
pData->m_ppParentHandle = ppData;
pData->m_uSignature = SANITYCHECK;
// Return the memory pointer at the next alignment value
pResult = pData + 1;
}
}
// Allocation failure
return pResult;
}
/*! ************************************
\brief Release fixed memory
When a pointer is allocated using Burger::MemoryManagerHandle::AllocProc()
It has a pointer to the handle that references this memory prefixed to it.
If the input is not \ref NULL it will use this prefixed pointer to
release the handle and therefore this memory.
\param pThis Pointer to the MemoryManagerHandle instance
\param pInput Pointer to memory to release, \ref NULL does nothing
\sa Burger::MemoryManagerHandle::AllocProc(MemoryManager *,uintptr_t)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::FreeProc(
MemoryManager* pThis, const void* pInput) BURGER_NOEXCEPT
{
// Do nothing with NULL pointers
if (pInput) {
MemoryManagerHandle* pSelf = static_cast<MemoryManagerHandle*>(pThis);
PointerPrefix_t* pData =
static_cast<PointerPrefix_t*>(const_cast<void*>(pInput)) - 1;
BURGER_ASSERT(pData->m_uSignature == SANITYCHECK);
pData->m_uSignature = KILLSANITYCHECK;
pSelf->FreeHandle(pData->m_ppParentHandle);
}
}
/*! ************************************
\brief Resize a preexisting allocated block of memory
Using a pointer to memory, reallocate the size and copy
the contents.
If a zero length buffer is requested, the input pointer is deallocated,
if the input pointer is \ref NULL, a fresh pointer is created.
\param pThis Pointer to the MemoryManagerHandle instance
\param pInput Pointer to memory to resize, \ref NULL forces a new block to
be created
\param uSize Size of memory block request
\return Pointer to the new memory block or \ref NULL on failure.
\sa Burger::MemoryManagerHandle::FreeProc(MemoryManager *,const void *)
***************************************/
void* BURGER_API Burger::MemoryManagerHandle::ReallocProc(
Burger::MemoryManager* pThis, const void* pInput,
uintptr_t uSize) BURGER_NOEXCEPT
{
MemoryManagerHandle* pSelf = static_cast<MemoryManagerHandle*>(pThis);
// Handle the two edge cases first
// No input pointer?
if (!pInput) {
// Do I want any memory?
if (uSize) {
// Just get fresh memory
pInput = AllocProc(pSelf, uSize);
}
// No memory requested?
} else if (!uSize) {
// Release the memory
FreeProc(pSelf, pInput);
// Return a null pointer
pInput = nullptr;
} else {
// Convert the pointer back into a handle and perform the resize
// operation
PointerPrefix_t* pData =
static_cast<PointerPrefix_t*>(const_cast<void*>(pInput)) - 1;
BURGER_ASSERT(pData->m_uSignature == SANITYCHECK);
pData->m_uSignature = KILLSANITYCHECK;
void** ppData = pSelf->ReallocHandle(
pData->m_ppParentHandle, uSize + sizeof(PointerPrefix_t));
// Successful?
if (!ppData) {
pInput = nullptr;
} else {
// Dereference the memory!
pData = static_cast<PointerPrefix_t*>(
reinterpret_cast<Handle_t*>(ppData)->m_pData);
// Save the handle in memory
pData->m_ppParentHandle = ppData;
pData->m_uSignature = SANITYCHECK;
// Return the memory pointer at the next alignment value
pInput = pData + 1;
}
}
// Couldn't get the memory
return const_cast<void*>(pInput);
}
/*! ************************************
\brief Shutdown the handle based Memory Manager
\param pThis Pointer to the MemoryManagerHandle instance
\sa Burger::MemoryManagerHandle::Shutdown(void)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::ShutdownProc(
MemoryManager* pThis) BURGER_NOEXCEPT
{
MemoryManagerHandle* pSelf = static_cast<MemoryManagerHandle*>(pThis);
pSelf->m_Lock.Lock();
// For debugging, test if all the memory is already released.
// If not, report it
// The final step is to release all of the memory
// allocated from the operating system
// Get the first buffer
SystemBlock_t* pBlock = pSelf->m_pSystemMemoryBlocks;
if (pBlock) {
SystemBlock_t* pNext;
do {
// Get the pointer to the next block
pNext = pBlock->m_pNext;
FreeSystemMemory(pBlock);
pBlock = pNext;
} while (pNext);
pSelf->m_pSystemMemoryBlocks = nullptr;
}
pSelf->m_pFreeHandle = nullptr;
pSelf->m_MemPurgeCallBack = nullptr;
pSelf->m_Lock.Unlock();
}
/*! ************************************
\brief Allocate a new handle record.
If out of handles in the pool, allocate memory from the operating system in
\ref DEFAULTHANDLECOUNT * sizeof(\ref Handle_t) chunks
\return Pointer to a new uninitialized Handle_t structure
\sa Burger::MemoryManagerHandle::FreeHandle(void **)
***************************************/
Burger::MemoryManagerHandle::Handle_t* BURGER_API
Burger::MemoryManagerHandle::AllocNewHandle(void) BURGER_NOEXCEPT
{
// Get a new handle
Handle_t* pHandle = m_pFreeHandle;
if (!pHandle) {
// Get memory from system to prevent fragmentation
uintptr_t uChunkSize =
((DEFAULTHANDLECOUNT * sizeof(Handle_t)) + sizeof(SystemBlock_t));
SystemBlock_t* pBlock =
static_cast<SystemBlock_t*>(AllocSystemMemory(uChunkSize));
if (pBlock) {
// Log the memory allocation
m_uTotalSystemMemory += uChunkSize;
m_uTotalHandleCount += DEFAULTHANDLECOUNT;
// Mark this block for release on shutdown
pBlock->m_pNext = m_pSystemMemoryBlocks;
// Store the new master pointer
m_pSystemMemoryBlocks = pBlock;
// Adjust past the pointer
pHandle = reinterpret_cast<Handle_t*>(pBlock + 1);
// Add the new handles to the free handle list
uint_t i = DEFAULTHANDLECOUNT - 1;
Handle_t* pNext = nullptr;
// Index to the last one
pHandle = pHandle + (DEFAULTHANDLECOUNT - 1);
do {
// Bad ID
pHandle->m_uFlags = 0;
pHandle->m_uID = MEMORYIDUNUSED;
pHandle->m_pNextHandle = pNext; // Link in the list
pNext = pHandle; // New parent
--pHandle; // Next handle
} while (--i); // All done?
m_pFreeHandle = pNext; // Save the new free handle list
// pHandle has the first entry and it's not linked in. It's ready
// for use
} else {
// Non recoverable error!!
Debug::Fatal("Out of system memory for handles!\n");
}
} else {
// Unlink and continue
m_pFreeHandle = pHandle->m_pNextHandle;
}
return pHandle;
}
/*! ************************************
\brief Remove a range of memory from the free memory pool
Assume that the memory range is either attached to the
end of a free memory segment or the end of a free memory
segment.
If not, bad things will happen!
\param pData Pointer to the start of the memory block to reserve
\param uLength Size in bytes of the memory block to reserve
\param pParent Pointer to the handle to the allocated handle BEFORE this
block
\param pHandle Handle of the currently free block of memory to allocate
from or \ref NULL if the function has to scan manually
\sa Burger::MemoryManagerHandle::ReleaseMemoryRange(void *,
uintptr_t,Handle_t *)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::GrabMemoryRange(void* pData,
uintptr_t uLength, Handle_t* pParent, Handle_t* pHandle) BURGER_NOEXCEPT
{
// Pad the request to alignment size to ensure all blocks are aligned
uLength = (uLength + (ALIGNMENT - 1)) & (~(ALIGNMENT - 1));
// Has the allocation block already been found?
if (!pHandle) {
// Manually begin the scan
pHandle = m_FreeMemoryChunks.m_pNextHandle;
// I will now scan free memory until I find the free memory
// handle that contains the memory to be reserved
for (;;) {
// After free memory?
uint8_t* pChunk = static_cast<uint8_t*>(pHandle->m_pData);
if (static_cast<uint8_t*>(pData) >= pChunk) {
if (static_cast<uint8_t*>(pData) <
(pChunk + pHandle->m_uLength)) {
// pHandle has the memory block!
break;
}
}
pHandle = pHandle->m_pNextHandle;
if (pHandle == &m_FreeMemoryChunks) {
// Only possible on data corruption
DumpHandles();
Debug::Fatal(
"Requested memory range to free is not in the free list\n");
return;
}
}
}
// pHandle points to the block to obtain memory from.
// Let's mark the parent entry
pHandle->m_pNextPurge = pParent;
// Allocated from the end of the data?
if (pHandle->m_pData == pData) {
// Full match?
if (pHandle->m_uLength == uLength) {
// Since I allocated the entire block, dispose of this
// Unlink the free memory chunk
Handle_t* pPrev = pHandle->m_pPrevHandle;
Handle_t* pNext = pHandle->m_pNextHandle;
pNext->m_pPrevHandle = pPrev;
pPrev->m_pNextHandle = pNext;
// Add to the free list
// Mark the ID
pHandle->m_uFlags = 0;
pHandle->m_uID = MEMORYIDUNUSED;
// Link in the list
pHandle->m_pNextHandle = m_pFreeHandle;
m_pFreeHandle = pHandle;
return;
}
// Calculate new length
pHandle->m_uLength = pHandle->m_uLength - uLength;
// Calculate new beginning
pHandle->m_pData = static_cast<uint8_t*>(pData) + uLength;
return;
}
// Memory is from end to the beginning
// New length
pHandle->m_uLength = static_cast<uintptr_t>(
static_cast<uint8_t*>(pData) - static_cast<uint8_t*>(pHandle->m_pData));
}
/*! ************************************
\brief Add a range of memory to the free memory list.
\note If this memory "Touches" another free memory entry, they will
be merged together.
\param pData Pointer to the memory block to return to the pool
\param uLength Size of the memory block to return to the pool
\param pParent Pointer to the Handle_t structure of the memory that was
released
\sa GrabMemoryRange(void *,uintptr_t,Handle_t *,Handle_t *)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::ReleaseMemoryRange(
void* pData, uintptr_t uLength, Handle_t* pParent) BURGER_NOEXCEPT
{
// Pad to nearest alignment
uLength = (uLength + (ALIGNMENT - 1)) & (~(ALIGNMENT - 1));
Handle_t* pFreeChunk = &m_FreeMemoryChunks;
Handle_t* pPrev = pFreeChunk->m_pPrevHandle;
// No handles in the list?
if (pPrev != pFreeChunk) {
// I will now scan free memory list until I find the free memory
// handle after the memory to be freed
do {
// After free memory?
if (static_cast<uint8_t*>(pData) >=
static_cast<uint8_t*>(pPrev->m_pData)) {
break; // pFreeChunk = handle
}
pPrev = pPrev->m_pPrevHandle;
} while (pPrev != pFreeChunk);
// pFreeChunk has the free memory handle AFTER the memory
pFreeChunk = pPrev->m_pNextHandle;
// See if this free memory is just an extension of the previous
// Pointer to the end of the free memory
uint8_t* pEnd =
static_cast<uint8_t*>(pPrev->m_pData) + pPrev->m_uLength;
// Does the end match this block?
if (pEnd == static_cast<uint8_t*>(pData)) {
// Set the new parent handle
pPrev->m_pNextPurge = pParent;
// Extend this block to add this memory
pPrev->m_uLength = pPrev->m_uLength + uLength;
// Last handle?
if (pFreeChunk != &m_FreeMemoryChunks) {
// Was this the case where a hole between two entries merge?
pEnd = pEnd + uLength;
// Filled in two free memories?
if (pEnd == static_cast<uint8_t*>(pFreeChunk->m_pData)) {
// Extend again!
pPrev->m_uLength = pPrev->m_uLength + pFreeChunk->m_uLength;
// Remove the second handle
pPrev->m_pNextHandle = pFreeChunk->m_pNextHandle;
pFreeChunk->m_pNextHandle->m_pPrevHandle = pPrev;
// Release this handle to the free pool
pFreeChunk->m_uFlags = 0; // Bad ID
pFreeChunk->m_uID = MEMORYIDUNUSED;
pFreeChunk->m_pNextHandle =
m_pFreeHandle; // Link in the list
m_pFreeHandle = pFreeChunk; // New parent
}
}
} else {
// Check If I should merge with the next fragment
// Get the current memory fragment
pEnd = static_cast<uint8_t*>(pData) + uLength;
// Does it touch next handle?
if (pEnd == static_cast<uint8_t*>(pFreeChunk->m_pData)) {
pFreeChunk->m_pNextPurge = pParent; // New parent
pFreeChunk->m_uLength =
pFreeChunk->m_uLength + uLength; // New length
pFreeChunk->m_pData = pData; // New start pointer
} else {
// It is not mergeable... I need to create a handle
Handle_t* pNew = AllocNewHandle(); // Get a new handle
pNew->m_pData = pData; // New pointer
pNew->m_uFlags = 0;
pNew->m_uID = MEMORYIDFREE;
pNew->m_uLength = uLength; // Free memory length
pNew->m_pNextHandle = pFreeChunk; // Forward handle
pNew->m_pPrevHandle = pPrev; // Previous handle
pNew->m_pNextPurge = pParent; // Set the new parent
pNew->m_pPrevPurge = nullptr;
// Link me in
pPrev->m_pNextHandle = pNew;
pFreeChunk->m_pPrevHandle = pNew;
}
}
} else {
// There is no free memory, create the singular entry
pPrev = AllocNewHandle();
// Create the free memory entry
pPrev->m_pData = pData;
pPrev->m_uLength = uLength;
// Mark the parent handle
pPrev->m_uFlags = 0;
pPrev->m_uID = MEMORYIDFREE;
pPrev->m_pNextHandle = pFreeChunk;
pPrev->m_pPrevHandle = pFreeChunk;
pPrev->m_pNextPurge = pParent;
pPrev->m_pPrevPurge = nullptr;
// Link the new entry to the free list
pFreeChunk->m_pNextHandle = pPrev;
pFreeChunk->m_pPrevHandle = pPrev;
}
}
/*! ************************************
\brief Print the state of the memory to Burger::Debug::String(const char *)
Walk the linked list of handles from pFirst to pLast and print
to the text output a report of the memory handles. All text is printed via
Debug::String(const char *)
\param pFirst Pointer to the first block to dump
\param pLast Pointer to the block that the dump will cease (Don't dump it)
\param bNoCheck If true, print pFirst at all times
\sa Debug::String(const char *)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::PrintHandles(
const Handle_t* pFirst, const Handle_t* pLast,
uint_t bNoCheck) BURGER_NOEXCEPT
{
char FooBar[256];
// Init handle count
uint_t uCount = 1;
#if UINTPTR_MAX == 0xFFFFFFFFU
Debug::PrintString(
"# Handle Addr Attr ID Size Prev Next\n");
// "0000 00000000 00000000 0000 0000 00000000 00000000
// 00000000"
if (bNoCheck || pFirst != pLast) {
do {
NumberToAsciiHex(&FooBar[0], static_cast<uint32_t>(uCount),
NOENDINGNULL | LEADINGZEROS | 4);
FooBar[4] = ' ';
NumberToAsciiHex(&FooBar[5],
static_cast<uint32_t>(reinterpret_cast<uintptr_t>(pFirst)),
NOENDINGNULL | LEADINGZEROS | 8);
FooBar[13] = ' ';
NumberToAsciiHex(&FooBar[14],
static_cast<uint32_t>(
reinterpret_cast<uintptr_t>(pFirst->m_pData)),
NOENDINGNULL | LEADINGZEROS | 8);
FooBar[22] = ' ';
NumberToAsciiHex(&FooBar[23],
static_cast<uint32_t>(pFirst->m_uFlags),
NOENDINGNULL | LEADINGZEROS | 4);
FooBar[27] = ' ';
NumberToAsciiHex(&FooBar[28], static_cast<uint32_t>(pFirst->m_uID),
NOENDINGNULL | LEADINGZEROS | 4);
FooBar[32] = ' ';
NumberToAsciiHex(&FooBar[33],
static_cast<uint32_t>(pFirst->m_uLength),
NOENDINGNULL | LEADINGZEROS | 8);
FooBar[41] = ' ';
NumberToAsciiHex(&FooBar[42],
static_cast<uint32_t>(
reinterpret_cast<uintptr_t>(pFirst->m_pPrevHandle)),
NOENDINGNULL | LEADINGZEROS | 8);
FooBar[50] = ' ';
NumberToAsciiHex(&FooBar[51],
static_cast<uint32_t>(
reinterpret_cast<uintptr_t>(pFirst->m_pNextHandle)),
NOENDINGNULL | LEADINGZEROS | 8);
FooBar[59] = '\n';
FooBar[60] = 0;
Debug::PrintString(FooBar);
// Next handle in chain
pFirst = pFirst->m_pNextHandle;
++uCount;
// All done?
} while (pFirst != pLast);
}
#else
Debug::PrintString(
"# Handle Addr Attr ID Size Prev Next\n");
// "0000 0000000000000000 0000000000000000 0000 0000
// 0000000000000000 0000000000000000 0000000000000000"
if (bNoCheck || pFirst != pLast) {
do {
NumberToAsciiHex(&FooBar[0], static_cast<uint32_t>(uCount),
NOENDINGNULL | LEADINGZEROS | 4);
FooBar[4] = ' ';
NumberToAsciiHex(&FooBar[5], reinterpret_cast<uint64_t>(pFirst),
NOENDINGNULL | LEADINGZEROS | 16);
FooBar[21] = ' ';
NumberToAsciiHex(&FooBar[22],
reinterpret_cast<uint64_t>(pFirst->m_pData),
NOENDINGNULL | LEADINGZEROS | 16);
FooBar[38] = ' ';
NumberToAsciiHex(&FooBar[39],
static_cast<uint32_t>(pFirst->m_uFlags),
NOENDINGNULL | LEADINGZEROS | 4);
FooBar[43] = ' ';
NumberToAsciiHex(&FooBar[44], static_cast<uint32_t>(pFirst->m_uID),
NOENDINGNULL | LEADINGZEROS | 4);
FooBar[48] = ' ';
NumberToAsciiHex(&FooBar[49],
static_cast<uint64_t>(pFirst->m_uLength),
NOENDINGNULL | LEADINGZEROS | 16);
FooBar[65] = ' ';
NumberToAsciiHex(&FooBar[66],
reinterpret_cast<uint64_t>(pFirst->m_pPrevHandle),
NOENDINGNULL | LEADINGZEROS | 16);
FooBar[82] = ' ';
NumberToAsciiHex(&FooBar[83],
reinterpret_cast<uint64_t>(pFirst->m_pNextHandle),
NOENDINGNULL | LEADINGZEROS | 16);
FooBar[99] = '\n';
FooBar[100] = 0;
Debug::PrintString(FooBar);
// Next handle in chain
pFirst = pFirst->m_pNextHandle;
++uCount;
// All done?
} while (pFirst != pLast);
}
#endif
}
/***************************************
Public functions
***************************************/
/*! ************************************
\brief Initialize the Handle based Memory Manager
\note If this class cannot start up due to memory starvation, it will fail
with a call to Debug::Fatal()
\sa Burger::MemoryManagerHandle::~MemoryManagerHandle()
***************************************/
Burger::MemoryManagerHandle::MemoryManagerHandle(uintptr_t uDefaultMemorySize,
uint_t uDefaultHandleCount, uintptr_t uMinReserveSize) BURGER_NOEXCEPT
: m_pSystemMemoryBlocks(nullptr),
m_MemPurgeCallBack(nullptr),
m_pMemPurge(nullptr),
m_uTotalAllocatedMemory(0),
m_uTotalSystemMemory(0),
m_pFreeHandle(nullptr),
m_uTotalHandleCount(0),
m_Lock()
{
// Init my global pointers
m_pAlloc = AllocProc;
m_pFree = FreeProc;
m_pRealloc = ReallocProc;
m_pShutdown = ShutdownProc;
// At this point, if there was an initialization failure,
// Shutdown() will clean up gracefully
// Obtain the base memory from the operating system
// Enough for the OS?
void* pReserved = AllocSystemMemory(uMinReserveSize);
if (!pReserved) {
// You're boned
Debug::Fatal("Can't allocate minimum OS memory chunk\n");
}
// Allocate the super chunk
uintptr_t uSwing = uDefaultMemorySize;
// Try for the entire block
SystemBlock_t* pBlock =
static_cast<SystemBlock_t*>(AllocSystemMemory(uSwing));
if (!pBlock) {
// Low on memory, do a binary search to see how much is present
// First bisection
uSwing = uSwing >> 1U;
uintptr_t uMinsize = 0; // No minimum available found yet
for (;;) {
uintptr_t uSize = uMinsize + uSwing; // Attempt this size
pBlock = static_cast<SystemBlock_t*>(
AllocSystemMemory(uSize)); // Try to allocate it
if (pBlock) {
FreeSystemMemory(pBlock);
uMinsize = uSize; // This is acceptable!
} else {
uDefaultMemorySize = uSize; // Can't get bigger than this!
}
uSwing = (uDefaultMemorySize - uMinsize) >>
1U; // Get half the difference
if (uSwing < 1024) { // Close enough?
pBlock =
static_cast<SystemBlock_t*>(AllocSystemMemory(uMinsize));
uSwing = uMinsize;
break;
}
}
}
// This is my super block
m_pSystemMemoryBlocks = pBlock;
m_uTotalSystemMemory = uSwing;
// Release OS memory
FreeSystemMemory(pReserved);
// No memory at all???
if (!pBlock) {
// Die!
Debug::Fatal("Can't allocate super chunk\n");
return;
}
// Mark the next link so Shutdown works if fatal
pBlock->m_pNext = NULL;
// Not enough memory for any good
if (uSwing < 0x10000) {
Debug::Fatal("Super chunk is less than 64K bytes\n");
}
// Initialize the free handle list
Handle_t* pHandle = reinterpret_cast<Handle_t*>(pBlock + 1);
// This is my remaining memory
uSwing -= sizeof(SystemBlock_t);
// Check for boneheads
if (uDefaultHandleCount < 8) {
uDefaultHandleCount = 8;
}
m_uTotalHandleCount = uDefaultHandleCount;
// Memory needed for handles
uintptr_t uHandleSize = uDefaultHandleCount * sizeof(Handle_t);
// You've got to be kidding me!!
if (uHandleSize >= uSwing) {
// Die!
Debug::Fatal("Can't allocate default handle array\n");
}
// Link all the handles in the free handle list
// Set the next pointer to NULL since it's the last link
Handle_t* pNextHandle = nullptr;
// Start at the last entry
pHandle = pHandle + (uDefaultHandleCount - 1);
do {
// Iterate backwards
pHandle->m_uFlags = 0;
pHandle->m_uID = MEMORYIDUNUSED; // Bad ID
pHandle->m_pNextHandle = pNextHandle; // Link in the list
pNextHandle = pHandle; // New parent
--pHandle;
} while (--uDefaultHandleCount); // All done?
// New free handle linked list head pointer
m_pFreeHandle = pNextHandle;
// "Use up" the memory for the handles
pHandle = pHandle + (m_uTotalHandleCount + 1);
uSwing = uSwing - uHandleSize;
// Align the pointer
uintptr_t uSuperChunkStart =
(reinterpret_cast<uintptr_t>(pHandle) + (ALIGNMENT - 1)) &
(~(ALIGNMENT - 1));
uSwing -= uSuperChunkStart - reinterpret_cast<uintptr_t>(pHandle);
// Initialize the Used handle list for free memory strips
// Used memory starts at zero and ends at the free pointer
m_LowestUsedMemory.m_pData = nullptr;
m_LowestUsedMemory.m_uLength = uSuperChunkStart;
m_LowestUsedMemory.m_uFlags = LOCKED | FIXED;
m_LowestUsedMemory.m_uID = MEMORYIDRESERVED;
m_LowestUsedMemory.m_pNextHandle = &m_HighestUsedMemory;
m_LowestUsedMemory.m_pPrevHandle = &m_HighestUsedMemory;
m_LowestUsedMemory.m_pNextPurge = nullptr;
m_LowestUsedMemory.m_pPrevPurge = nullptr;
// Used memory continues from the end of the free buffer to the end of
// memory
uint8_t* pEnd = reinterpret_cast<uint8_t*>(uSuperChunkStart) + uSwing;
m_HighestUsedMemory.m_pData = pEnd;
m_HighestUsedMemory.m_uLength =
static_cast<uintptr_t>(-1) - reinterpret_cast<uintptr_t>(pEnd);
m_HighestUsedMemory.m_uFlags = LOCKED | FIXED;
m_HighestUsedMemory.m_uID = MEMORYIDRESERVED;
m_HighestUsedMemory.m_pNextHandle = &m_LowestUsedMemory;
m_HighestUsedMemory.m_pPrevHandle = &m_LowestUsedMemory;
m_HighestUsedMemory.m_pNextPurge = nullptr;
m_HighestUsedMemory.m_pPrevPurge = nullptr;
// Initialize the list of handles that have free memory blocks
m_FreeMemoryChunks.m_pData = nullptr;
m_FreeMemoryChunks.m_uLength = 0;
m_FreeMemoryChunks.m_uFlags = 0;
m_FreeMemoryChunks.m_uID = MEMORYIDRESERVED;
m_FreeMemoryChunks.m_pNextHandle = &m_FreeMemoryChunks;
m_FreeMemoryChunks.m_pPrevHandle = &m_FreeMemoryChunks;
m_FreeMemoryChunks.m_pNextPurge = nullptr;
m_FreeMemoryChunks.m_pPrevPurge = nullptr;
m_PurgeHands.m_pData = nullptr;
m_PurgeHands.m_uLength = 0;
m_PurgeHands.m_uFlags = 0;
m_PurgeHands.m_uID = MEMORYIDRESERVED;
m_PurgeHands.m_pNextHandle = &m_PurgeHands;
m_PurgeHands.m_pPrevHandle = &m_PurgeHands;
m_PurgeHands.m_pNextPurge = nullptr;
m_PurgeHands.m_pPrevPurge = nullptr;
m_PurgeHandleFiFo.m_pData = nullptr;
m_PurgeHandleFiFo.m_uLength = 0;
m_PurgeHandleFiFo.m_uFlags = 0;
m_PurgeHandleFiFo.m_uID = MEMORYIDRESERVED;
m_PurgeHandleFiFo.m_pNextHandle = &m_PurgeHandleFiFo;
m_PurgeHandleFiFo.m_pPrevHandle = &m_PurgeHandleFiFo;
m_PurgeHandleFiFo.m_pNextPurge = &m_PurgeHandleFiFo;
m_PurgeHandleFiFo.m_pPrevPurge = &m_PurgeHandleFiFo;
// Create the default free list
ReleaseMemoryRange(
reinterpret_cast<void*>(uSuperChunkStart), uSwing, &m_LowestUsedMemory);
}
/*! ************************************
\brief The destructor for the Handle based Memory Manager
This calls Burger::MemoryManagerHandle::Shutdown(MemoryManager *) to do the
actual work
\sa Shutdown(MemoryManager *)
***************************************/
Burger::MemoryManagerHandle::~MemoryManagerHandle()
{
ShutdownProc(this);
}
/*! ************************************
\fn Burger::MemoryManagerHandle::GetTotalAllocatedMemory(void) const
\brief Returns the total allocated memory used by pointers and handles in
bytes.
This is the total number of bytes allocated with all padding necessary for
data alignment
\sa Burger::MemoryManagerHandle::GetTotalFreeMemory(void)
***************************************/
/*! ************************************
\fn Burger::MemoryManagerHandle::Alloc(uintptr_t)
\brief Allocate fixed memory.
Allocates a pointer to a block of memory in high (Fixed) memory.
\param uSize Number of bytes requested
\return \ref NULL on allocation failure, valid handle to memory if
successful
\sa Burger::MemoryManagerHandle::AllocProc(MemoryManager *,uintptr_t)
***************************************/
/*! ************************************
\fn Burger::MemoryManagerHandle::Free(const void *)
\brief Release fixed memory.
When a pointer is allocated using
Burger::MemoryManagerHandle::Alloc(uintptr_t), it has a pointer to the
handle that references this memory prefixed to it. If the input is not
\ref NULL it will use this prefixed pointer to release the handle and
therefore this memory.
\param pInput Pointer to memory to release, \ref NULL does nothing
\sa Burger::MemoryManagerHandle::FreeProc(MemoryManager *,const void *)
***************************************/
/*! ************************************
\fn Burger::MemoryManagerHandle::Realloc(const void *,uintptr_t)
\brief Resize a preexisting allocated block of memory.
Using a pointer to memory, reallocate the size and copy the contents.
If a zero length buffer is requested, the input pointer is deallocated,
if the input pointer is \ref NULL, a fresh pointer is created.
\param pInput Pointer to memory to resize, \ref NULL forces a new block to
be created
\param uSize Size of memory block request \return Pointer to the new
memory block or \ref NULL on failure.
\sa Burger::MemoryManagerHandle::ReallocProc(MemoryManager *,
const void *,uintptr_t)
***************************************/
/*! ************************************
\fn Burger::MemoryManagerHandle::Shutdown(void)
\brief Shutdown the handle based Memory Manager.
\sa Burger::MemoryManagerHandle::ShutdownProc(MemoryManager *)
***************************************/
/*! ************************************
\brief Allocates a block of memory
Allocates from the top down if fixed and bottom up if movable
This routine handles all the magic for memory purging and
allocation.
\param uSize Number of bytes requested
\param uFlags Flags to modify how the memory is allocated, \ref FIXED for
fixed memory, 0 for movable memory
\return \ref NULL on allocation failure, valid handle to memory if
successful
\sa Burger::MemoryManagerHandle::FreeHandle(void **)
***************************************/
void** BURGER_API Burger::MemoryManagerHandle::AllocHandle(
uintptr_t uSize, uint_t uFlags) BURGER_NOEXCEPT
{
Handle_t* ppResult = nullptr;
// Don't allocate an empty handle!
if (uSize) {
m_Lock.Lock();
// Initialized?
if (m_pSystemMemoryBlocks) {
// Get a new handle
Handle_t* pNew = AllocNewHandle();
if (pNew) {
pNew->m_pNextPurge = nullptr;
pNew->m_pPrevPurge = nullptr;
// Save the handle size WITHOUT padding
pNew->m_uLength = uSize;
// Save the default attributes
pNew->m_uFlags = uFlags & (~MALLOC);
// Init data memory search stage
eMemoryStage eStage = StageCompact;
// Round up
uSize = (uSize + (ALIGNMENT - 1)) & (~(ALIGNMENT - 1));
if (uFlags & FIXED) {
// Scan from the top down for fixed handles
// Increases odds for compaction success
for (;;) {
Handle_t* pEntry = m_FreeMemoryChunks.m_pPrevHandle;
// Find the memory, pNew has the handle the memory
// will occupy BEFORE, pEntry is the prev handle before
// the new one
// No free memory?
if (pEntry != &m_FreeMemoryChunks) {
do {
if (pEntry->m_uLength >= uSize) {
Handle_t* pPrev =
pEntry->m_pNextPurge; // Get the parent
// handle
Handle_t* pNext =
pPrev->m_pNextHandle; // Next handle
pNew->m_pPrevHandle = pPrev;
pNew->m_pNextHandle = pNext;
pPrev->m_pNextHandle = pNew;
pNext->m_pPrevHandle = pNew;
void* pData = (static_cast<uint8_t*>(
pEntry->m_pData) +
(pEntry->m_uLength - uSize));
pNew->m_pData = pData;
GrabMemoryRange(
pData, uSize, pPrev, pEntry);
// Update the global allocated memory count.
m_uTotalAllocatedMemory += pNew->m_uLength;
// Good allocation!
m_Lock.Unlock();
return reinterpret_cast<void**>(pNew);
}
// Look at next handle
pEntry = pEntry->m_pPrevHandle;
// End of the list?
} while (pEntry != &m_FreeMemoryChunks);
}
if (eStage == StageCompact) {
// Pack memory together
CompactHandles();
eStage = StagePurge;
} else if (eStage == StagePurge) {
// Purge the handles
if (PurgeHandles(uSize)) {
// Try again with compaction
eStage = StageCompact;
} else {
// This is where giving up is the right thing
eStage = StageHailMary;
}
} else if (eStage == StageHailMary) {
break;
}
}
} else {
// Scan from the bottom up for movable handles
// Increases odds for compaction success
for (;;) {
// Get next index
Handle_t* pEntry = m_FreeMemoryChunks.m_pNextHandle;
// Find the memory, pNew has the handle the memory
// will occupy AFTER, pEntry is the next handle after
// the new one
// Already stop?
if (pEntry != &m_FreeMemoryChunks) {
do {
if (pEntry->m_uLength >= uSize) {
// Get the parent handle
Handle_t* pPrev = pEntry->m_pNextPurge;
Handle_t* pNext = pPrev->m_pNextHandle;
pNew->m_pPrevHandle = pPrev;
pNew->m_pNextHandle = pNext;
pPrev->m_pNextHandle = pNew;
pNext->m_pPrevHandle = pNew;
pNew->m_pData = pEntry->m_pData;
GrabMemoryRange(
pEntry->m_pData, uSize, pNew, pEntry);
// Update the global allocated memory count.
m_uTotalAllocatedMemory += pNew->m_uLength;
// Good allocation!
m_Lock.Unlock();
return reinterpret_cast<void**>(pNew);
}
// Look at next handle
pEntry = pEntry->m_pNextHandle;
// End of the list?
} while (pEntry != &m_FreeMemoryChunks);
}
if (eStage == StageCompact) {
// Pack memory together
CompactHandles();
eStage = StagePurge;
} else if (eStage == StagePurge) {
// Purge the handles
if (PurgeHandles(uSize)) {
// Try again with compaction
eStage = StageCompact;
} else {
// This is where giving up is the right thing
eStage = StageHailMary;
}
} else if (eStage == StageHailMary) {
break;
}
}
}
// Failed in the quest for memory, exit as a miserable loser
// Restore the actual byte request (Not padded)
uSize = pNew->m_uLength;
// Bad ID
pNew->m_uFlags = 0;
pNew->m_uID = MEMORYIDUNUSED;
// Link in the list
pNew->m_pNextHandle = m_pFreeHandle;
// New parent
m_pFreeHandle = pNew;
}
// Try to get memory from somewhere else.
// This is a last resort!
ppResult = static_cast<Handle_t*>(
AllocSystemMemory(uSize + sizeof(Handle_t) + ALIGNMENT));
if (ppResult) {
// Update the global allocated memory count.
m_uTotalAllocatedMemory += uSize;
ppResult->m_uLength = uSize;
ppResult->m_uFlags = uFlags | MALLOC; // It was Malloc'd
ppResult->m_pPrevHandle = nullptr; // Force crash
ppResult->m_pNextHandle = nullptr;
ppResult->m_pNextPurge = nullptr;
ppResult->m_pPrevPurge = nullptr;
// Ensure data alignment
ppResult->m_pData = reinterpret_cast<void*>(
(reinterpret_cast<uintptr_t>(ppResult) + sizeof(Handle_t) +
(ALIGNMENT - 1)) &
(~(ALIGNMENT - 1)));
// Return the fake handle
}
}
m_Lock.Lock();
}
return reinterpret_cast<void**>(ppResult);
}
/*! ************************************
\brief Dispose of a memory handle into the free handle pool
\note \ref NULL is acceptable input.
\param ppInput Handle to memory allocated by AllocHandle(uintptr_t,uint_t)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::FreeHandle(void** ppInput) BURGER_NOEXCEPT
{
// Valid handle?
if (ppInput) {
m_Lock.Lock();
// Subtract from global size.
Handle_t* pHandle = reinterpret_cast<Handle_t*>(ppInput);
m_uTotalAllocatedMemory -= pHandle->m_uLength;
if (!(pHandle->m_uFlags & MALLOC)) {
// Only perform an action if the class
// is initialized. Otherwise assume an out of order
// class shutdown and do nothing
if (m_pSystemMemoryBlocks) {
Handle_t* pPrev;
// If this handle is on the purge list,
// unlink it
Handle_t* pNext = pHandle->m_pNextPurge;
if (pNext) {
// Remove from the linked purge list
pPrev = pHandle->m_pPrevPurge;
pPrev->m_pNextPurge = pNext;
pNext->m_pPrevPurge = pPrev;
}
// Unlink from the main list
pNext = pHandle->m_pNextHandle;
pPrev = pHandle->m_pPrevHandle;
pPrev->m_pNextHandle = pNext;
pNext->m_pPrevHandle = pPrev;
// Release the memory range back into the pool
// if there was any memory attached to this handle
void* pData = pHandle->m_pData;
if (pData) {
ReleaseMemoryRange(pData, pHandle->m_uLength, pPrev);
}
// Add in this handle to the free list
// Mark with INVALID entry ID
pHandle->m_uFlags = 0;
pHandle->m_uID = MEMORYIDUNUSED;
pHandle->m_pNextHandle = m_pFreeHandle;
m_pFreeHandle = pHandle;
}
} else {
// Just release the memory
FreeSystemMemory(pHandle);
}
m_Lock.Unlock();
}
}
/*! ************************************
\brief Resize a handle
Using a handle to memory, reallocate the size and copy
the contents. If the input handle is \ref NULL, then just allocate a
new handle, if the size requested is zero then discard the input
handle.
\param ppInput Handle to resize
\param uSize Size in bytes of the new handle
\return Handle of the newly resized memory chunk
\sa Burger::MemoryManagerHandle::FreeHandle(void **) and
Burger::MemoryManagerHandle::AllocHandle(uintptr_t,uint_t)
***************************************/
void** BURGER_API Burger::MemoryManagerHandle::ReallocHandle(
void** ppInput, uintptr_t uSize) BURGER_NOEXCEPT
{
// No previous handle?
if (!ppInput) {
// New memory requested?
if (uSize) {
// Allocate the new memory
return AllocHandle(uSize, 0);
}
return nullptr;
}
// No memory requested?
if (!uSize) {
// Release the original
FreeHandle(ppInput);
// Normal exit
return nullptr;
}
// Try the easy way, just shrink the handle...
Handle_t* pHandle = reinterpret_cast<Handle_t*>(ppInput);
// Get length
uintptr_t uOldSize = pHandle->m_uLength;
if (uSize == uOldSize) {
// Return the handle without any changes
return ppInput;
}
// Handle will shrink??
if (uSize < uOldSize &&
// Not manually allocated?
(!(pHandle->m_uFlags & MALLOC))) {
m_Lock.Lock();
pHandle->m_uLength = uSize; // Set the new size
uSize =
(uSize + (ALIGNMENT - 1)) & (~(ALIGNMENT - 1)); // Long word align
uOldSize = (uOldSize + (ALIGNMENT - 1)) & (~(ALIGNMENT - 1));
uOldSize = uOldSize - uSize; // How many bytes to release?
if (uOldSize) { // Will I release any memory?
uint8_t* pStart = static_cast<uint8_t*>(pHandle->m_pData) +
uSize; // Get start pointer
ReleaseMemoryRange(pStart, uOldSize, pHandle);
}
m_Lock.Unlock();
} else {
// Handle is growing...
// I have to do it the hard way!!
// Allocate the new memory
Handle_t* pNew =
reinterpret_cast<Handle_t*>(AllocHandle(uSize, pHandle->m_uFlags));
if (pNew) { // Success!
if (uSize <
uOldSize) { // Make sure I only copy the SMALLER of the two
uOldSize = uSize; // New size
}
// Copy the contents
MemoryCopy(pNew->m_pData, pHandle->m_pData, uOldSize);
}
// Release the previous memory
FreeHandle(ppInput);
ppInput = reinterpret_cast<void**>(pNew);
}
// Return the new pointer
return ppInput;
}
/*! ************************************
\brief If the handle was purged, reallocate memory to it.
\note The returned handle will REPLACE the handle that was passed in.
This code effectively disposes of the previous handle and allocates
a new one of the old one's size. If the data is still intact then
nothing happens
\param ppInput Handle to be restored
\return New handle for data
\sa Burger::MemoryManagerHandle::SetPurgeFlag(void **,uint_t)
***************************************/
void** BURGER_API Burger::MemoryManagerHandle::RefreshHandle(void** ppInput) BURGER_NOEXCEPT
{
if (ppInput) {
if (*ppInput) { // Handle already valid?
SetPurgeFlag(ppInput, FALSE); // Don't purge now
} else {
// How much memory to allocate
uintptr_t uSize =
reinterpret_cast<const Handle_t*>(ppInput)->m_uLength;
uint_t uFlags =
reinterpret_cast<const Handle_t*>(ppInput)->m_uFlags;
FreeHandle(ppInput); // Dispose of the old handle
ppInput = AllocHandle(
uSize, uFlags); // Create a new one with the old size
}
}
return ppInput;
}
/*! ************************************
\brief Search the handle tree for a pointer
\note The pointer does NOT have to be the head pointer, just in the domain
of the handle Return \ref NULL if the handle is not here.
\param pInput Pointer to memory to locate
\return MemoryManagerHandle::Handle_t to handle that contains the pointer.
\sa Burger::MemoryManagerHandle::GetSize(void **)
***************************************/
void** BURGER_API Burger::MemoryManagerHandle::FindHandle(
const void* pInput) BURGER_NOEXCEPT
{
// Get the first handle
m_Lock.Lock();
Handle_t* pHandle = m_LowestUsedMemory.m_pNextHandle;
void** ppResult = nullptr;
// Are there handles?
if (pHandle != &m_HighestUsedMemory) {
do {
// Get the handle's memory pointer
uint8_t* pData = static_cast<uint8_t*>(pHandle->m_pData);
// Is it too far?
if (pData > static_cast<const uint8_t*>(pInput)) {
// Abort now...
break;
}
// Get the final byte address
pData += pHandle->m_uLength;
// In range?
if (pData > static_cast<const uint8_t*>(pInput)) {
// This is the handle!
ppResult = reinterpret_cast<void**>(pHandle);
break;
}
pHandle = pHandle->m_pNextHandle;
// List still valid?
} while (pHandle != &m_HighestUsedMemory);
}
m_Lock.Unlock();
// Didn't find it...
return ppResult;
}
/*! ************************************
\brief Returns the size of a memory handle
\param ppInput Valid handle of allocated memory, or \ref NULL
\return Number of bytes handle controls or zero if empty or \ref NULL input
\sa Burger::MemoryManagerHandle::GetSize(const void *)
***************************************/
uintptr_t BURGER_API Burger::MemoryManagerHandle::GetSize(
void** ppInput) BURGER_NOEXCEPT
{
if (ppInput) {
return reinterpret_cast<Handle_t*>(ppInput)->m_uLength;
}
return 0;
}
/*! ************************************
\brief Returns the size of a memory pointer
\param pInput Valid pointer to allocated memory or \ref NULL
\return Number of bytes pointer controls or zero if \ref NULL
\sa Burger::MemoryManagerHandle::GetSize(void **)
***************************************/
uintptr_t BURGER_API Burger::MemoryManagerHandle::GetSize(
const void* pInput) BURGER_NOEXCEPT
{
if (pInput) { // Null pointer?!?
PointerPrefix_t* pData =
static_cast<PointerPrefix_t*>(const_cast<void*>(pInput)) - 1;
BURGER_ASSERT(pData->m_uSignature == SANITYCHECK);
const Handle_t* pHandle =
reinterpret_cast<Handle_t*>(pData->m_ppParentHandle);
return pHandle->m_uLength;
}
return 0;
}
/*! ************************************
\brief Returns the total free space with purging
This is accomplished by adding all the memory found in
the free memory linked list and then adding all the memory
in the used list that can be purged.
\return Number of bytes available for allocation including all purgeable
memory
***************************************/
uintptr_t BURGER_API Burger::MemoryManagerHandle::GetTotalFreeMemory(
void) BURGER_NOEXCEPT
{
uintptr_t uFree = 0; // Running total
// Add all the free memory handles
m_Lock.Lock();
Handle_t* pHandle =
m_FreeMemoryChunks.m_pNextHandle; // Follow the entire list
if (pHandle != &m_FreeMemoryChunks) { // List valid?
do {
uFree += pHandle->m_uLength; // Just add it in
pHandle = pHandle->m_pNextHandle; // Next one in chain
} while (pHandle != &m_FreeMemoryChunks); // All done?
}
// Now traverse the used list for all purgeable memory
pHandle = m_LowestUsedMemory.m_pNextHandle; // Find all purgeable memory
if (pHandle != &m_HighestUsedMemory) { // Valid chain?
do {
if (!(pHandle->m_uFlags & LOCKED) && // Unlocked and purgeable
(pHandle->m_pNextPurge)) {
// Round up the length
const uintptr_t uTemp =
(pHandle->m_uLength + (ALIGNMENT - 1)) & (~(ALIGNMENT - 1));
uFree += uTemp; /* Add into the total */
}
// Next link
pHandle = pHandle->m_pNextHandle;
// All done?
} while (pHandle != &m_HighestUsedMemory);
}
m_Lock.Unlock();
// Return the free size
return uFree;
}
/*! ************************************
\brief Set the lock flag to a given handle and return the data pointer
\note This is a boolean flag, not reference counted
\param ppInput Pointer to handle to lock or \ref NULL
\return Pointer to dereferenced memory or \ref NULL on failure or \ref NULL
input
\sa Burger::MemoryManagerHandle::Unlock(void **ppInput)
***************************************/
void* BURGER_API Burger::MemoryManagerHandle::Lock(
void** ppInput) BURGER_NOEXCEPT
{
if (ppInput) {
// Lock the handle down
reinterpret_cast<Handle_t*>(ppInput)->m_uFlags |= LOCKED;
return reinterpret_cast<Handle_t*>(ppInput)->m_pData;
}
return NULL;
}
/*! ************************************
\brief Clear the lock flag to a given handle
\note This is a boolean flag, not reference counted
\param ppInput Pointer to handle to unlock or \ref NULL
\sa Burger::MemoryManagerHandle::Lock(void **ppInput)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::Unlock(
void** ppInput) BURGER_NOEXCEPT
{
if (ppInput) {
// Clear the lock flag
reinterpret_cast<Handle_t*>(ppInput)->m_uFlags &= (~LOCKED);
}
}
/*! ************************************
\brief Set a user supplied ID value for a handle
\param ppInput Pointer to handle to set the ID
\param uID Handle ID
***************************************/
void BURGER_API Burger::MemoryManagerHandle::SetID(
void** ppInput, uint_t uID) BURGER_NOEXCEPT
{
if (ppInput) {
// Clear the lock flag
reinterpret_cast<Handle_t*>(ppInput)->m_uID = uID;
}
}
/*! ************************************
\brief Set the purge flag to a given handle
\param ppInput Handle to allocated memory or \ref NULL
\param uFlag \ref TRUE to enable purging, \ref FALSE to disable purging
***************************************/
void BURGER_API Burger::MemoryManagerHandle::SetPurgeFlag(
void** ppInput, uint_t uFlag) BURGER_NOEXCEPT
{
if (ppInput) {
Handle_t* pHandle = reinterpret_cast<Handle_t*>(ppInput);
if (!(pHandle->m_uFlags & MALLOC)) {
// Was it purgeable?
if (pHandle->m_pNextPurge) {
// Unlink from the purge fifo
pHandle->m_pPrevPurge->m_pNextPurge = pHandle->m_pNextPurge;
pHandle->m_pNextPurge->m_pPrevPurge = pHandle->m_pPrevPurge;
}
// Now is it purgeable?
if (uFlag) {
pHandle->m_pPrevPurge = &m_PurgeHandleFiFo;
pHandle->m_pNextPurge = m_PurgeHandleFiFo.m_pNextPurge;
m_PurgeHandleFiFo.m_pNextPurge->m_pPrevPurge = pHandle;
m_PurgeHandleFiFo.m_pNextPurge = pHandle;
} else {
pHandle->m_pNextPurge = nullptr;
pHandle->m_pPrevPurge = nullptr;
}
}
}
}
/*! ************************************
\brief Get the current purge and lock flags of the handle
\param ppInput Pointer to valid handle. \ref NULL is invalid
\return All the flags from the memory handle. Mask with \ref LOCKED to
check only for memory being locked
\sa Burger::MemoryManagerHandle::SetLockedState(void **,uint_t)
***************************************/
uint_t BURGER_API Burger::MemoryManagerHandle::GetLockedState(
void** ppInput) BURGER_NOEXCEPT
{
return reinterpret_cast<const Handle_t*>(ppInput)->m_uFlags;
}
/*! ************************************
\brief Set the current purge and lock flags of the handle
\param ppInput Handle to valid memory.
\param uFlag \ref PURGABLE and \ref LOCKED are the only valid input flags
\sa Burger::MemoryManagerHandle::GetLockedState(void **)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::SetLockedState(
void** ppInput, uint_t uFlag) BURGER_NOEXCEPT
{
uFlag &= (~(PURGABLE | LOCKED));
Handle_t* pHandle = reinterpret_cast<Handle_t*>(ppInput);
pHandle->m_uFlags = (pHandle->m_uFlags & (~(PURGABLE | LOCKED))) | uFlag;
if (!(pHandle->m_uFlags & MALLOC)) {
if (pHandle->m_pNextPurge) { // Was it purgeable?
// Unlink from the purge fifo
pHandle->m_pPrevPurge->m_pNextPurge = pHandle->m_pNextPurge;
pHandle->m_pNextPurge->m_pPrevPurge = pHandle->m_pPrevPurge;
}
// Now is it purgeable?
if (uFlag & PURGABLE) {
pHandle->m_pPrevPurge = &m_PurgeHandleFiFo;
pHandle->m_pNextPurge = m_PurgeHandleFiFo.m_pNextPurge;
m_PurgeHandleFiFo.m_pNextPurge->m_pPrevPurge = pHandle;
m_PurgeHandleFiFo.m_pNextPurge = pHandle;
} else {
pHandle->m_pNextPurge = nullptr;
pHandle->m_pPrevPurge = nullptr;
}
}
}
/*! ************************************
\brief Move a handle into the purged list
This routine will move a handle from the used list
into the purged handle list. The handle is not discarded.
This is the only way a handle can be placed into the purged list.
It will call Burger::MemoryManagerHandle::ReleaseMemoryRange() to alert the
free memory list that there is new free memory.
\param ppInput Handle to allocated memory or \ref NULL to perform no action
\sa Burger::MemoryManagerHandle::PurgeHandles(uintptr_t)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::Purge(void** ppInput) BURGER_NOEXCEPT
{
Handle_t* pHandle = reinterpret_cast<Handle_t*>(ppInput);
if (pHandle && // Valid pointer?
pHandle->m_pData && !(pHandle->m_uFlags & MALLOC)) { // Not purged?
if (m_MemPurgeCallBack) {
m_MemPurgeCallBack(m_pMemPurge, StagePurge); // I will purge now!
}
m_Lock.Lock();
pHandle->m_uFlags &= (~LOCKED); // Force unlocked
// Unlink from the purge list
Handle_t* pPrev; // Previous link
Handle_t* pNext = pHandle->m_pNextPurge; // Forward link
if (pNext) {
pPrev = pHandle->m_pPrevPurge; // Backward link
pNext->m_pPrevPurge = pPrev; // Unlink me from the list
pPrev->m_pNextPurge = pNext;
pHandle->m_pNextPurge = nullptr;
pHandle->m_pPrevPurge = nullptr;
}
// Unlink from the used list
pNext = pHandle->m_pNextHandle; // Forward link
pPrev = pHandle->m_pPrevHandle; // Backward link
pNext->m_pPrevHandle = pPrev; // Unlink me from the list
pPrev->m_pNextHandle = pNext;
// Move to the purged handle list
// Don't harm the flags or the length!!
ReleaseMemoryRange(
pHandle->m_pData, pHandle->m_uLength, pPrev); // Release the memory
pPrev = m_PurgeHands.m_pNextHandle; // Get the first link
pHandle->m_pData = nullptr; // Zap the pointer (Purge list)
pHandle->m_pPrevHandle = &m_PurgeHands; // I am the parent
pHandle->m_pNextHandle = pPrev; // Link it to the purge list
pPrev->m_pPrevHandle = pHandle;
m_PurgeHands.m_pNextHandle = pHandle; // Make as the new head
m_Lock.Unlock();
}
}
/*! ************************************
\brief Purges handles until the amount of memory requested is freed
Purges all handles that are purgeable and are
greater or equal to the amount of memory
It will call Purge(void **) to alert the free memory
list that there is free memory.
\param uSize The number of bytes to recover before aborting
\return \ref TRUE if ANY memory was purged, \ref FALSE is there was no
memory to recover
\sa Burger::MemoryManagerHandle::Purge(void **)
***************************************/
uint_t BURGER_API Burger::MemoryManagerHandle::PurgeHandles(uintptr_t uSize) BURGER_NOEXCEPT
{
uint_t uResult = FALSE;
m_Lock.Lock();
// Index to the purgeable handle list
Handle_t* pHandle = m_PurgeHandleFiFo.m_pPrevPurge;
// No purgeable memory?
if (pHandle != &m_PurgeHandleFiFo) {
// Follow the handle list
do {
// Preload next link
Handle_t* pNext = pHandle->m_pPrevPurge;
// Round up
uintptr_t uTempLen =
(pHandle->m_uLength + (ALIGNMENT - 1)) & (~(ALIGNMENT - 1));
// Force a purge
Purge(reinterpret_cast<void**>(pHandle));
uResult = TRUE;
if (uTempLen >= uSize) {
break;
}
uSize -= uTempLen; // Remove this...
pHandle = pNext; // Get the next link
} while (pHandle != &m_PurgeHandleFiFo); // At the end?
}
m_Lock.Unlock();
return uResult;
}
/*! ************************************
\brief Compact all of the movable blocks together
Packs all memory together to reduce or eliminate fragmentation
This doesn't alter the handle list in any way but it can move
memory around to get rid of empty holes in the memory map.
\sa Burger::MemoryManagerHandle::PurgeHandles(uintptr_t) or
Burger::MemoryManagerHandle::Purge(void **)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::CompactHandles(void) BURGER_NOEXCEPT
{
m_Lock.Lock();
// Index to the active handle list
Handle_t* pHandle = m_LowestUsedMemory.m_pNextHandle;
// Failsafe
if (pHandle != &m_HighestUsedMemory) {
// Assume bogus
uint_t bCalledCallBack = TRUE;
if (m_MemPurgeCallBack) {
// Valid pointer?
bCalledCallBack = FALSE;
}
// Skip all locked or fixed handles
do {
if (!(pHandle->m_uFlags & (LOCKED | FIXED))) {
// Get the previous handle
Handle_t* pPrev = pHandle->m_pPrevHandle;
// Pad to long word
uintptr_t uSize =
(pPrev->m_uLength + (ALIGNMENT - 1)) & (~(ALIGNMENT - 1));
uint8_t* pStartMem =
static_cast<uint8_t*>(pPrev->m_pData) + uSize;
// Any space here?
uSize = static_cast<uintptr_t>(
static_cast<uint8_t*>(pHandle->m_pData) - pStartMem);
// If there is free space, then pack them
if (uSize) {
// Hadn't called it yet?
if (!bCalledCallBack) {
bCalledCallBack = TRUE;
// Alert the app
m_MemPurgeCallBack(m_pMemPurge, StageCompact);
}
// Save old address
void* pTemp = pHandle->m_pData;
// Set new address
pHandle->m_pData = pStartMem;
// Release the memory
ReleaseMemoryRange(pTemp, pHandle->m_uLength, pPrev);
// Grab the memory again
GrabMemoryRange(
pStartMem, pHandle->m_uLength, pHandle, nullptr);
// Move the unpadded length
MemoryMove(pStartMem, pTemp, pHandle->m_uLength);
}
}
// Next handle in chain
pHandle = pHandle->m_pNextHandle;
} while (pHandle != &m_HighestUsedMemory);
}
m_Lock.Unlock();
}
/*! ************************************
\brief Display all the memory
\sa Burger::Debug::String(const char *)
***************************************/
void BURGER_API Burger::MemoryManagerHandle::DumpHandles(void) BURGER_NOEXCEPT
{
m_Lock.Lock();
const uintptr_t uSize = GetTotalFreeMemory();
Debug::PrintString("Total free memory with purging ");
Debug::PrintString(uSize);
Debug::PrintString("\nUsed handle list\n");
// Set the flag here, Debug::String COULD allocate memory on some
// file systems for directory caches.
// As a result, the recurse flag being set could case a handle that needs
// to be tracked to be removed from the tracking list and therefore
// flag an error that doesn't exist
PrintHandles(&m_LowestUsedMemory, &m_LowestUsedMemory, TRUE);
Debug::PrintString("Purged handle list\n");
PrintHandles(m_PurgeHands.m_pNextHandle, &m_PurgeHands, FALSE);
Debug::PrintString("Free memory list\n");
PrintHandles(m_FreeMemoryChunks.m_pNextHandle, &m_FreeMemoryChunks, FALSE);
m_Lock.Unlock();
}
/*! ************************************
\class Burger::MemoryManagerGlobalHandle
\brief Global Handle Memory Manager helper class
This class is a helper that attaches a \ref Burger::MemoryManagerHandle
class to the global memory manager. When this instance shuts down,
it will remove itself from the global memory manager.
\sa Burger::GlobalMemoryManager and Burger::MemoryManagerHandle
***************************************/
/*! ************************************
\brief Attaches a \ref Burger::MemoryManagerHandle class to the global
memory manager.
When this class is created, it will automatically attach itself
to the global memory manager.
***************************************/
Burger::MemoryManagerGlobalHandle::MemoryManagerGlobalHandle(
uintptr_t uDefaultMemorySize, uint_t uDefaultHandleCount,
uintptr_t uMinReserveSize) BURGER_NOEXCEPT
: MemoryManagerHandle(
uDefaultMemorySize, uDefaultHandleCount, uMinReserveSize)
{
m_pPrevious = GlobalMemoryManager::Init(this);
}
/*! ************************************
\brief Releases a Burger::MemoryManagerGlobalHandle class from the global
memory manager.
When this class is released, it will automatically remove itself
to the global memory manager.
***************************************/
Burger::MemoryManagerGlobalHandle::~MemoryManagerGlobalHandle()
{
GlobalMemoryManager::Shutdown(m_pPrevious);
}
| 30.80307 | 101 | 0.66453 | [
"object"
] |
f4937ad473335b8988e5d3536201899134fbff4e | 25,512 | hxx | C++ | main/sfx2/inc/sfx2/itemconnect.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sfx2/inc/sfx2/itemconnect.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sfx2/inc/sfx2/itemconnect.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef SFX_ITEMCONNECT_HXX
#define SFX_ITEMCONNECT_HXX
#include "sal/config.h"
#include "sfx2/dllapi.h"
#include <memory>
#include <sfx2/itemwrapper.hxx>
#include <sfx2/controlwrapper.hxx>
// ============================================================================
namespace sfx {
// ============================================================================
typedef int ItemConnFlags;
/** No special state for the connection. */
const ItemConnFlags ITEMCONN_NONE = 0x0000;
/** Connection is inactive - virtual functions will not be called. */
const ItemConnFlags ITEMCONN_INACTIVE = 0x0001;
/** Clone item in FillItemSet() from old item set. */
//const ItemConnFlags ITEMCONN_CLONE_ITEM = 0x0002;
/** Enable control(s), if the item is known. */
const ItemConnFlags ITEMCONN_ENABLE_KNOWN = 0x0010;
/** Disable control(s), if the item is unknown. */
const ItemConnFlags ITEMCONN_DISABLE_UNKNOWN = 0x0020;
/** Show control(s), if the item is known. */
const ItemConnFlags ITEMCONN_SHOW_KNOWN = 0x0040;
/** Hide control(s), if the item is unknown. */
const ItemConnFlags ITEMCONN_HIDE_UNKNOWN = 0x0080;
/** Default value for constructors. */
const ItemConnFlags ITEMCONN_DEFAULT = ITEMCONN_NONE;
// ============================================================================
// Base connection classes
// ============================================================================
/** A helper for SfxTabPages to connect controls to items.
This is the base class of all control connection classes. Their purpose is
to connect one or more controls from an SfxTabPage with an item from an
item set. The goal is to omit any additional code in the virtual functions
Reset() and FillItemSet() in classes derived from SfxTabPage.
Examples of connections:
- A check box with an SfxBoolItem,
- A metric (spin) field with an SfxInt32Item.
- A group of radio buttons with an SfxEnumItem.
Each SfxTabPage will contain a list of connection objects (derived from
this class). The connection objects remember the item and control(s) they
have to work on. The SfxTabPage will call the DoApplyFlags(), DoReset(),
and DoFillItemSet() functions of all connection objects it knows. The code
to initialize control(s) from the item value and fill the item from
control(s) has to be written only once for each control type.
Additional flags passed in the constructor allow to control the behaviour
of the control(s) if the item is supported/unsupported in the currently
used item set. For example, it is possible to specify that a control will
be disabled or hidden if the item is not supported. This is done before
each call of Reset().
The special flag ITEMCONN_CLONE_ITEM controls how to create new items in
the DoFillItemSet() function. The standard (and faster) method is to create
a temporary item on the stack and put it into the item set. But this does
not work if the item set expects a special item type derived from a common
item class, i.e. a Boolean item derived from SfxBoolItem providing special
item representation text. As this code does not know the item type, the
item cannot be created on the stack. For this case the flag specifies to
use the virtual Clone() method of the pool default item. This will create
an item of the correct type but can still be used in conjunction with i.e.
the standard BoolItemWrapper.
How to use the item connection feature:
A) Single item <-> single control connection
Example: An SfxBoolItem and a check box.
A1) Create a new item wrapper class derived from the SingleItemWrapper
template, or use the template directly, or use one of the
predefined item wrappers. See documentation of the
SingleItemWrapper template for details (itemwrapper.hxx).
A2) Create a new control wrapper class derived from the
SingleControlWrapper template and implement the abstract functions,
or use one of the predefined control wrappers. See documentation of
the SingleControlWrapper template for details (controlwrapper.hxx).
A3) Create a new connection class derived from one of the following
base classes, and implement the abstract functions, or use the
ItemControlConnection template directly, or use one of the
predefined connections.
A4) Create connection objects in the constructor of the tab page, and
insert them into the tab page with SfxTabPage::AddItemConnection().
A5) Remove old code from the tab page's Reset() and FillItemSet()
functions, if necessary.
B) Single item <-> multiple controls connections
B1) See step A1. If the item contains multiple values (and not a
structure that contains all the values for the different controls),
the best way is to use the IdentItemWrapper template, that works
with the item itself. This way it is possible to provide a 'data
type' that contains the values for all controls.
B2) Create a new control wrapper class derived from the
MultiControlWrapper template. Add single control wrapper members
for all controls to this class and register them in the
constructor, using the RegisterControlWrapper() function. Implement
the abstract functions GetControlValue() and SetControlValue().
These functions should call the respective functions of the own
single control wrappers and either fill a new data object (the item
itself in most cases, see step B1) with all the values from the
controls, or fill all the controls from the data object.
B3) Create a new connection class derived from ItemControlConnection,
or use the ItemControlConnection template directly. The multiple
control wrapper from step B2 acts like a single control, therefore
it is possible to use the ItemControlConnection.
B4) See steps A4 and A5.
C) Multiple items <-> single control connections
todo
D) Multiple items <-> multiple controls connections
todo
The current tree of base classes/templates and standard connections:
ItemConnectionBase
|
+- DummyItemConnection [1]
|
+- ItemControlConnection< ItemWrpT, ControlWrpT >
| |
| +- CheckBoxConnection [1]
| +- EditConnection [1]
| |
| +- NumericConnection< ItemWrpT > [1]
| | |
| | +- [ValueType]NumericConnection [1] [2]
| |
| +- MetricConnection< ItemWrpT > [1]
| | |
| | +- [ValueType]MetricConnection [1] [2]
| |
| +- ListBoxConnection< ItemWrpT > [1]
| | |
| | +- [ValueType]ListBoxConnection [1] [2]
| |
| +- ValueSetConnection< ItemWrpT > [1]
| |
| +- [ValueType]ValueSetConnection [1] [2]
|
+- ItemConnectionArray [1]
Notes:
[1] Standard connections ready to use.
[2] [ValueType] is one of Int16, UInt16, Int32, UInt32.
*/
class SFX2_DLLPUBLIC ItemConnectionBase
{
public:
virtual ~ItemConnectionBase();
/** Returns the flags passed in the constructor. */
inline ItemConnFlags GetFlags() const { return mnFlags; }
/** Activates or deactivates this connection.
@descr Deactivated connections do not execute the virtual functions
ApplyFlags(), Reset(), and FillItemSet(). */
void Activate( bool bActive = true );
/** Returns true if this connection is active. */
bool IsActive() const;
/** Calls the virtual ApplyFlags() function, if connection is active. */
void DoApplyFlags( const SfxItemSet& rItemSet );
/** Calls the virtual Reset() function, if connection is active. */
void DoReset( const SfxItemSet& rItemSet );
/** Calls the virtual FillItemSet() function, if connection is active. */
bool DoFillItemSet( SfxItemSet& rDestSet, const SfxItemSet& rOldSet );
protected:
explicit ItemConnectionBase( ItemConnFlags nFlags = ITEMCONN_DEFAULT );
/** Derived classes implement actions according to current flags here. */
virtual void ApplyFlags( const SfxItemSet& rItemSet ) = 0;
/** Derived classes implement initializing controls from item sets here. */
virtual void Reset( const SfxItemSet& rItemSet ) = 0;
/** Derived classes implement filling item sets from controls here. */
virtual bool FillItemSet( SfxItemSet& rDestSet, const SfxItemSet& rOldSet ) = 0;
/** Returns whether to enable a control, according to current flags. */
TriState GetEnableState( bool bKnown ) const;
/** Returns whether to show a control, according to current flags. */
TriState GetShowState( bool bKnown ) const;
private:
/* Disable copy c'tor and assignment. */
ItemConnectionBase( const ItemConnectionBase& );
ItemConnectionBase& operator=( const ItemConnectionBase& );
ItemConnFlags mnFlags; /// Flags for additional options.
};
// ----------------------------------------------------------------------------
/** Base class template for single item <-> single control connection objects.
This template uses functions provided by the SingleItemWrapper and the
SingleControlWrapper template classes. The virtual functions ApplyFlags(),
Reset(), and FillItemSet() are implemented here in a generic way using the
virtual functions of the wrapper classes. Derived classes only have to
create or otherwise provide appropriate wrappers.
*/
template< typename ItemWrpT, typename ControlWrpT >
class ItemControlConnection : public ItemConnectionBase
{
public:
typedef ItemWrpT ItemWrapperType;
typedef ControlWrpT ControlWrapperType;
typedef ItemControlConnection< ItemWrpT, ControlWrpT > ItemControlConnectionType;
typedef typename ItemWrpT::ItemType ItemType;
typedef typename ItemWrpT::ItemValueType ItemValueType;
typedef typename ControlWrpT::ControlType ControlType;
typedef typename ControlWrpT::ControlValueType ControlValueType;
typedef std::auto_ptr< ItemWrpT > ItemWrapperRef;
typedef std::auto_ptr< ControlWrpT > ControlWrapperRef;
/** Receives pointer to a newly created control wrapper.
@descr Takes ownership of the control wrapper. */
explicit ItemControlConnection( sal_uInt16 nSlot, ControlWrpT* pNewCtrlWrp,
ItemConnFlags nFlags = ITEMCONN_DEFAULT );
/** Convenience constructor. Receives reference to a control directly.
@descr May only be used, if ControlWrpT::ControlWrpT( ControlType& )
constructor exists. */
explicit ItemControlConnection( sal_uInt16 nSlot, ControlType& rControl,
ItemConnFlags nFlags = ITEMCONN_DEFAULT );
virtual ~ItemControlConnection();
protected:
/** Actions according to current flags for the control. */
virtual void ApplyFlags( const SfxItemSet& rItemSet );
/** Resets the control according to the item contents. */
virtual void Reset( const SfxItemSet& rItemSet );
/** Fills the item set according to the control's state. */
virtual bool FillItemSet( SfxItemSet& rDestSet, const SfxItemSet& rOldSet );
ItemWrapperType maItemWrp;
ControlWrapperRef mxCtrlWrp;
};
// ============================================================================
// Standard connections
// ============================================================================
/** This is a helper class to enable/disable/show/hide a control only.
This class does nothing special in the Reset() and FillItemSet() functions.
It can be used to control the visibility of i.e. fixed lines or fixed texts
related to the availability of an item by passing the appropriate flags to
the constructor of this connection.
*/
class SFX2_DLLPUBLIC DummyItemConnection:
public ItemConnectionBase, public DummyWindowWrapper
{
public:
explicit DummyItemConnection( sal_uInt16 nSlot, Window& rWindow,
ItemConnFlags nFlags = ITEMCONN_DEFAULT );
protected:
virtual void ApplyFlags( const SfxItemSet& rItemSet );
virtual void Reset( const SfxItemSet& rItemSet );
virtual bool FillItemSet( SfxItemSet& rDestSet, const SfxItemSet& rOldSet );
private:
sal_uInt16 mnSlot;
};
// ----------------------------------------------------------------------------
/** Connection between an SfxBoolItem and a VCL CheckBox. */
typedef ItemControlConnection< BoolItemWrapper, CheckBoxWrapper > CheckBoxConnection;
/** Connection between an SfxStringItem and a VCL Edit. */
typedef ItemControlConnection< StringItemWrapper, EditWrapper > EditConnection;
// ============================================================================
/** Connection between an item and the VCL NumericField. */
template< typename ItemWrpT >
class NumericConnection : public ItemControlConnection< ItemWrpT,
NumericFieldWrapper< typename ItemWrpT::ItemValueType > >
{
typedef ItemControlConnection< ItemWrpT,
NumericFieldWrapper< typename ItemWrpT::ItemValueType > >
ItemControlConnectionType;
public:
typedef typename ItemControlConnectionType::ControlWrapperType NumericFieldWrapperType;
explicit NumericConnection( sal_uInt16 nSlot, NumericField& rField,
ItemConnFlags nFlags = ITEMCONN_DEFAULT );
};
// ----------------------------------------------------------------------------
typedef NumericConnection< Int16ItemWrapper > Int16NumericConnection;
typedef NumericConnection< UInt16ItemWrapper > UInt16NumericConnection;
typedef NumericConnection< Int32ItemWrapper > Int32NumericConnection;
typedef NumericConnection< UInt32ItemWrapper > UInt32NumericConnection;
// ============================================================================
/** Connection between an item and the VCL MetricField.
Adds support of different field units during control value <-> item value
conversion. The field unit passed to the constructor applies for the item
values, while the field unit used in the control has to be set at the
control itself.
*/
template< typename ItemWrpT >
class MetricConnection : public ItemControlConnection< ItemWrpT,
MetricFieldWrapper< typename ItemWrpT::ItemValueType > >
{
typedef ItemControlConnection< ItemWrpT,
MetricFieldWrapper< typename ItemWrpT::ItemValueType > >
ItemControlConnectionType;
public:
typedef typename ItemControlConnectionType::ControlWrapperType MetricFieldWrapperType;
explicit MetricConnection( sal_uInt16 nSlot, MetricField& rField,
FieldUnit eItemUnit = FUNIT_NONE, ItemConnFlags nFlags = ITEMCONN_DEFAULT );
};
// ----------------------------------------------------------------------------
typedef MetricConnection< Int16ItemWrapper > Int16MetricConnection;
typedef MetricConnection< UInt16ItemWrapper > UInt16MetricConnection;
typedef MetricConnection< Int32ItemWrapper > Int32MetricConnection;
typedef MetricConnection< UInt32ItemWrapper > UInt32MetricConnection;
// ============================================================================
/** Connection between an item and a VCL ListBox.
Optionally a map can be passed that maps list box positions to item values.
This map MUST be terminated with an entry containing LISTBOX_ENTRY_NOTFOUND
as list box position. The item value contained in this last entry is used
as default item value in case of an error.
*/
template< typename ItemWrpT >
class ListBoxConnection : public ItemControlConnection< ItemWrpT,
ListBoxWrapper< typename ItemWrpT::ItemValueType > >
{
typedef ItemControlConnection< ItemWrpT,
ListBoxWrapper< typename ItemWrpT::ItemValueType > >
ItemControlConnectionType;
public:
typedef typename ItemControlConnectionType::ControlWrapperType ListBoxWrapperType;
typedef typename ListBoxWrapperType::MapEntryType MapEntryType;
explicit ListBoxConnection( sal_uInt16 nSlot, ListBox& rListBox,
const MapEntryType* pMap = 0, ItemConnFlags nFlags = ITEMCONN_DEFAULT );
};
// ----------------------------------------------------------------------------
typedef ListBoxConnection< Int16ItemWrapper > Int16ListBoxConnection;
typedef ListBoxConnection< UInt16ItemWrapper > UInt16ListBoxConnection;
typedef ListBoxConnection< Int32ItemWrapper > Int32ListBoxConnection;
typedef ListBoxConnection< UInt32ItemWrapper > UInt32ListBoxConnection;
// ============================================================================
/** Connection between an item and an SVTOOLS ValueSet.
Optionally a map can be passed that maps value set identifiers to item
values. This map MUST be terminated with an entry containing
VALUESET_ITEM_NOTFOUND as value set identifier. The item value contained in
this last entry is used as default item value in case of an error.
*/
template< typename ItemWrpT >
class ValueSetConnection : public ItemControlConnection< ItemWrpT,
ValueSetWrapper< typename ItemWrpT::ItemValueType > >
{
typedef ItemControlConnection< ItemWrpT,
ValueSetWrapper< typename ItemWrpT::ItemValueType > >
ItemControlConnectionType;
public:
typedef typename ItemControlConnectionType::ControlWrapperType ValueSetWrapperType;
typedef typename ValueSetWrapperType::MapEntryType MapEntryType;
explicit ValueSetConnection( sal_uInt16 nSlot, ValueSet& rValueSet,
const MapEntryType* pMap = 0, ItemConnFlags nFlags = ITEMCONN_DEFAULT );
};
// ----------------------------------------------------------------------------
typedef ValueSetConnection< Int16ItemWrapper > Int16ValueSetConnection;
typedef ValueSetConnection< UInt16ItemWrapper > UInt16ValueSetConnection;
typedef ValueSetConnection< Int32ItemWrapper > Int32ValueSetConnection;
typedef ValueSetConnection< UInt32ItemWrapper > UInt32ValueSetConnection;
// ============================================================================
// Array of connections
// ============================================================================
class ItemConnectionArrayImpl;
/** A container of connection objects.
This is a connection with the only purpose to contain other connection
objects. This way it is possible to create a tree structure of connections
for a convenient connection management. This class is used by the class
SfxTabPage to store all connections.
*/
class ItemConnectionArray : public ItemConnectionBase
{
public:
explicit ItemConnectionArray();
virtual ~ItemConnectionArray();
/** Adds a new connection to the list.
@descr Takes ownership of the connection! */
void AddConnection( ItemConnectionBase* pConnection );
protected:
virtual void ApplyFlags( const SfxItemSet& rItemSet );
virtual void Reset( const SfxItemSet& rItemSet );
virtual bool FillItemSet( SfxItemSet& rDestSet, const SfxItemSet& rOldSet );
private:
std::auto_ptr< ItemConnectionArrayImpl > mxImpl;
};
// ============================================================================
// ============================================================================
// *** Implementation of template functions ***
// ============================================================================
// ============================================================================
// Base connection classes
// ============================================================================
template< typename ItemWrpT, typename ControlWrpT >
ItemControlConnection< ItemWrpT, ControlWrpT >::ItemControlConnection(
sal_uInt16 nSlot, ControlWrpT* pNewCtrlWrp, ItemConnFlags nFlags ) :
ItemConnectionBase( nFlags ),
maItemWrp( nSlot ),
mxCtrlWrp( pNewCtrlWrp )
{
}
template< typename ItemWrpT, typename ControlWrpT >
ItemControlConnection< ItemWrpT, ControlWrpT >::ItemControlConnection(
sal_uInt16 nSlot, ControlType& rControl, ItemConnFlags nFlags ) :
ItemConnectionBase( nFlags ),
maItemWrp( nSlot ),
mxCtrlWrp( new ControlWrpT( rControl ) )
{
}
template< typename ItemWrpT, typename ControlWrpT >
ItemControlConnection< ItemWrpT, ControlWrpT >::~ItemControlConnection()
{
}
template< typename ItemWrpT, typename ControlWrpT >
void ItemControlConnection< ItemWrpT, ControlWrpT >::ApplyFlags( const SfxItemSet& rItemSet )
{
bool bKnown = ItemWrapperHelper::IsKnownItem( rItemSet, maItemWrp.GetSlotId() );
mxCtrlWrp->ModifyControl( GetEnableState( bKnown ), GetShowState( bKnown ) );
}
template< typename ItemWrpT, typename ControlWrpT >
void ItemControlConnection< ItemWrpT, ControlWrpT >::Reset( const SfxItemSet& rItemSet )
{
const ItemType* pItem = maItemWrp.GetUniqueItem( rItemSet );
mxCtrlWrp->SetControlDontKnow( pItem == 0 );
if( pItem )
mxCtrlWrp->SetControlValue( maItemWrp.GetItemValue( *pItem ) );
}
template< typename ItemWrpT, typename ControlWrpT >
bool ItemControlConnection< ItemWrpT, ControlWrpT >::FillItemSet(
SfxItemSet& rDestSet, const SfxItemSet& rOldSet )
{
const ItemType* pOldItem = maItemWrp.GetUniqueItem( rOldSet );
bool bChanged = false;
if( !mxCtrlWrp->IsControlDontKnow() )
{
// first store the control value in a local variable
ControlValueType aCtrlValue( mxCtrlWrp->GetControlValue() );
// convert to item value type -> possible to convert i.e. from 'T' to 'const T&'
ItemValueType aNewValue( aCtrlValue );
// do not rely on existence of ItemValueType::operator!=
if( !pOldItem || !(maItemWrp.GetItemValue( *pOldItem ) == aNewValue) )
{
sal_uInt16 nWhich = ItemWrapperHelper::GetWhichId( rDestSet, maItemWrp.GetSlotId() );
std::auto_ptr< ItemType > xItem(
static_cast< ItemType* >( maItemWrp.GetDefaultItem( rDestSet ).Clone() ) );
xItem->SetWhich( nWhich );
maItemWrp.SetItemValue( *xItem, aNewValue );
rDestSet.Put( *xItem );
bChanged = true;
}
}
if( !bChanged )
ItemWrapperHelper::RemoveDefaultItem( rDestSet, rOldSet, maItemWrp.GetSlotId() );
return bChanged;
}
// ============================================================================
// Standard connections
// ============================================================================
template< typename ItemWrpT >
NumericConnection< ItemWrpT >::NumericConnection(
sal_uInt16 nSlot, NumericField& rField, ItemConnFlags nFlags ) :
ItemControlConnectionType( nSlot, rField, nFlags )
{
}
// ============================================================================
template< typename ItemWrpT >
MetricConnection< ItemWrpT >::MetricConnection(
sal_uInt16 nSlot, MetricField& rField, FieldUnit eItemUnit, ItemConnFlags nFlags ) :
ItemControlConnectionType( nSlot, new MetricFieldWrapperType( rField, eItemUnit ), nFlags )
{
}
// ============================================================================
template< typename ItemWrpT >
ListBoxConnection< ItemWrpT >::ListBoxConnection(
sal_uInt16 nSlot, ListBox& rListBox, const MapEntryType* pMap, ItemConnFlags nFlags ) :
ItemControlConnectionType( nSlot, new ListBoxWrapperType( rListBox, pMap ), nFlags )
{
}
// ============================================================================
template< typename ItemWrpT >
ValueSetConnection< ItemWrpT >::ValueSetConnection(
sal_uInt16 nSlot, ValueSet& rValueSet, const MapEntryType* pMap, ItemConnFlags nFlags ) :
ItemControlConnectionType( nSlot, new ValueSetWrapperType( rValueSet, pMap ), nFlags )
{
}
// ============================================================================
} // namespace sfx
#endif
| 43.094595 | 104 | 0.639817 | [
"object"
] |
f496c758453a176c1c9d245331345b8dd5bc34a8 | 4,467 | cpp | C++ | emulator/src/devices/machine/i8214.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/devices/machine/i8214.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/devices/machine/i8214.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Curt Coder
/**********************************************************************
Intel 8214/3214 Priority Interrupt Control Unit
**********************************************************************/
#include "emu.h"
#include "i8214.h"
//#define VERBOSE 1
#include "logmacro.h"
// device type definition
DEFINE_DEVICE_TYPE(I8214, i8214_device, "i8214", "Intel 8214 PICU")
//**************************************************************************
// HELPERS
//**************************************************************************
//-------------------------------------------------
// trigger_interrupt -
//-------------------------------------------------
void i8214_device::trigger_interrupt(int level)
{
LOG("I8214 Interrupt Level %u\n", level);
m_a = level;
// disable more interrupts from being latched
m_int_dis = 1;
// disable next level group
m_write_enlg(0);
// set interrupt line
m_write_int(ASSERT_LINE);
m_write_int(CLEAR_LINE);
}
//-------------------------------------------------
// check_interrupt -
//-------------------------------------------------
void i8214_device::check_interrupt()
{
if (m_int_dis || !m_etlg || !m_inte) return;
for (int level = 7; level >= 0; level--)
{
if (!BIT(m_r, 7 - level))
{
if (m_sgs)
{
if (level > m_current_status)
{
trigger_interrupt(level);
}
}
else
{
trigger_interrupt(level);
}
}
}
}
//**************************************************************************
// LIVE DEVICE
//**************************************************************************
//-------------------------------------------------
// i8214_device - constructor
//-------------------------------------------------
i8214_device::i8214_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, I8214, tag, owner, clock)
, m_write_int(*this)
, m_write_enlg(*this)
, m_inte(0)
, m_int_dis(0)
, m_a(0)
, m_current_status(0)
, m_r(0xff)
, m_sgs(0)
, m_etlg(1)
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void i8214_device::device_start()
{
// resolve callbacks
m_write_int.resolve_safe();
m_write_enlg.resolve_safe();
m_int_dis = 0;
m_etlg = 1;
// register for state saving
save_item(NAME(m_inte));
save_item(NAME(m_int_dis));
save_item(NAME(m_a));
save_item(NAME(m_current_status));
save_item(NAME(m_r));
save_item(NAME(m_sgs));
save_item(NAME(m_etlg));
}
//-------------------------------------------------
// a_r -
//-------------------------------------------------
uint8_t i8214_device::a_r()
{
uint8_t a = m_a & 0x07;
LOG("I8214 A: %01x\n", a);
return a;
}
//-------------------------------------------------
// vector_r - read A outputs to be latched as an
// 8080-compatible interrupt vector
//-------------------------------------------------
READ8_MEMBER(i8214_device::vector_r)
{
return 0xc7 | (m_a << 3);
}
//-------------------------------------------------
// b_w -
//-------------------------------------------------
void i8214_device::b_w(uint8_t data)
{
m_current_status = data & 0x07;
LOG("I8214 B: %01x\n", m_current_status);
// enable interrupts
m_int_dis = 0;
// enable next level group
m_write_enlg(1);
check_interrupt();
}
//-------------------------------------------------
// r_w - update the interrupt request
// state for a given line
//-------------------------------------------------
void i8214_device::r_w(int line, int state)
{
LOG("I8214 R%d: %d\n", line, state);
m_r &= ~(1 << line);
m_r |= (state << line);
check_interrupt();
}
//-------------------------------------------------
// sgs_w -
//-------------------------------------------------
WRITE_LINE_MEMBER( i8214_device::sgs_w )
{
LOG("I8214 SGS: %u\n", state);
m_sgs = state;
check_interrupt();
}
//-------------------------------------------------
// etlg_w -
//-------------------------------------------------
WRITE_LINE_MEMBER( i8214_device::etlg_w )
{
LOG("I8214 ETLG: %u\n", state);
m_etlg = state;
check_interrupt();
}
//-------------------------------------------------
// inte_w -
//-------------------------------------------------
WRITE_LINE_MEMBER( i8214_device::inte_w )
{
LOG("I8214 INTE: %u\n", state);
m_inte = state;
check_interrupt();
}
| 19.941964 | 107 | 0.427132 | [
"vector"
] |
f49903486a0ed6e23358915bd02a7554b5a8e630 | 3,627 | cpp | C++ | test/test_logging_console_output_handler.cpp | jdlangs/rcutils | 10dca5bdb9f822ebb86f65eb6ba5120a9c60da27 | [
"Apache-2.0"
] | 40 | 2017-06-16T18:28:32.000Z | 2022-02-28T22:10:32.000Z | test/test_logging_console_output_handler.cpp | jdlangs/rcutils | 10dca5bdb9f822ebb86f65eb6ba5120a9c60da27 | [
"Apache-2.0"
] | 263 | 2017-04-20T18:33:04.000Z | 2022-03-28T18:17:39.000Z | test/test_logging_console_output_handler.cpp | jdlangs/rcutils | 10dca5bdb9f822ebb86f65eb6ba5120a9c60da27 | [
"Apache-2.0"
] | 82 | 2017-04-21T16:38:55.000Z | 2022-03-28T05:31:45.000Z | // Copyright 2020 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <string>
#include <vector>
#include "osrf_testing_tools_cpp/scope_exit.hpp"
#include "rcutils/logging.h"
static void call_handler(
const rcutils_log_location_t * location,
int severity, const char * name, rcutils_time_point_value_t timestamp,
const char * format, ...)
{
va_list args;
va_start(args, format);
rcutils_logging_console_output_handler(location, severity, name, timestamp, format, &args);
va_end(args);
}
// There are no outputs of the handler function, and the only result are fprintf() calls.
// This is just a smoke test to check that the code can handle simple inputs cleanly.
TEST(TestLoggingConsoleOutputHandler, typical_inputs) {
ASSERT_EQ(RCUTILS_RET_OK, rcutils_logging_initialize());
OSRF_TESTING_TOOLS_CPP_SCOPE_EXIT(
{
EXPECT_EQ(RCUTILS_RET_OK, rcutils_logging_shutdown());
});
rcutils_log_location_t log_location = {
"test_function",
"test_file",
1,
};
const char * log_name = "test_name";
rcutils_time_point_value_t timestamp = 1;
const char * format = "%s - %s";
call_handler(
&log_location, RCUTILS_LOG_SEVERITY_DEBUG, log_name, timestamp, format, "part1", "part2");
call_handler(
&log_location, RCUTILS_LOG_SEVERITY_INFO, log_name, timestamp, format, "part1", "part2");
call_handler(
&log_location, RCUTILS_LOG_SEVERITY_WARN, log_name, timestamp, format, "part1", "part2");
call_handler(
&log_location, RCUTILS_LOG_SEVERITY_ERROR, log_name, timestamp, format, "part1", "part2");
call_handler(
&log_location, RCUTILS_LOG_SEVERITY_FATAL, log_name, timestamp, format, "part1", "part2");
}
// There are no outputs of the handler function, and the only result are fprintf() calls.
// This is just a smoke test to check that the code can handle bad inputs cleanly.
TEST(TestLoggingConsoleOutputHandler, bad_inputs) {
rcutils_log_location_t log_location = {
"test_function",
"test_file",
1,
};
const char * log_name = "test_name";
rcutils_time_point_value_t timestamp = 1;
const char * format = "%s - %s";
// Check !g_rcutils_logging_initialized
call_handler(
&log_location, RCUTILS_LOG_SEVERITY_DEBUG, log_name, timestamp, format, "part1", "part2");
ASSERT_EQ(RCUTILS_RET_OK, rcutils_logging_initialize());
OSRF_TESTING_TOOLS_CPP_SCOPE_EXIT(
{
EXPECT_EQ(RCUTILS_RET_OK, rcutils_logging_shutdown());
});
call_handler(
nullptr, RCUTILS_LOG_SEVERITY_INFO, log_name, timestamp, format, "part1", "part2");
call_handler(
&log_location, RCUTILS_LOG_SEVERITY_UNSET, log_name, timestamp, format, "part1", "part2");
call_handler(
&log_location, RCUTILS_LOG_SEVERITY_INFO, nullptr, timestamp, format, "part1", "part2");
call_handler(
&log_location, RCUTILS_LOG_SEVERITY_INFO, log_name, 0, format, "part1", "part2");
// If format is NULL, this call will segfault on some (but not all) systems
call_handler(
&log_location, RCUTILS_LOG_SEVERITY_INFO, log_name, timestamp, "bad format", "part1", "part2");
}
| 37.010204 | 99 | 0.74166 | [
"vector"
] |
f49ddb246784f69ff86fb4d40a3c847426dcccc6 | 4,671 | cpp | C++ | MonoNative/mscorlib/System/IO/mscorlib_System_IO_DriveInfo.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative/mscorlib/System/IO/mscorlib_System_IO_DriveInfo.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative/mscorlib/System/IO/mscorlib_System_IO_DriveInfo.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | #include <mscorlib/System/IO/mscorlib_System_IO_DriveInfo.h>
#include <mscorlib/System/IO/mscorlib_System_IO_DirectoryInfo.h>
#include <mscorlib/System/mscorlib_System_Type.h>
namespace mscorlib
{
namespace System
{
namespace IO
{
//Public Methods
std::vector<mscorlib::System::IO::DriveInfo*> DriveInfo::GetDrives()
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "GetDrives", NullMonoObject, 0, NULL, NULL, NULL);
MonoArray *__array_ptr__ = (MonoArray*)__result__;
uintptr_t __array_length__ = mono_array_length(__array_ptr__);
std::vector<mscorlib::System::IO::DriveInfo*> __array_result__(__array_length__);
for(uintptr_t __array_index__ = 0; __array_index__ < __array_length__; __array_index__++)
{
MonoObject *__array_item__ = mono_array_get(__array_ptr__,MonoObject*,__array_index__);
__array_result__.push_back(new mscorlib::System::IO::DriveInfo (__array_item__));
}
return __array_result__;
}
mscorlib::System::String DriveInfo::ToString()
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "ToString", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::String(__result__);
}
//Get Set Properties Methods
// Get:AvailableFreeSpace
mscorlib::System::Int64 DriveInfo::get_AvailableFreeSpace() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "get_AvailableFreeSpace", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
// Get:TotalFreeSpace
mscorlib::System::Int64 DriveInfo::get_TotalFreeSpace() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "get_TotalFreeSpace", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
// Get:TotalSize
mscorlib::System::Int64 DriveInfo::get_TotalSize() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "get_TotalSize", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Int64*)mono_object_unbox(__result__);
}
// Get/Set:VolumeLabel
mscorlib::System::String DriveInfo::get_VolumeLabel() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "get_VolumeLabel", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::String(__result__);
}
void DriveInfo::set_VolumeLabel(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "set_VolumeLabel", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
// Get:DriveFormat
mscorlib::System::String DriveInfo::get_DriveFormat() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "get_DriveFormat", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::String(__result__);
}
// Get:DriveType
mscorlib::System::IO::DriveType::__ENUM__ DriveInfo::get_DriveType() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "get_DriveType", __native_object__, 0, NULL, NULL, NULL);
return static_cast<mscorlib::System::IO::DriveType::__ENUM__>(*(mscorlib::System::Int32*)mono_object_unbox(__result__));
}
// Get:Name
mscorlib::System::String DriveInfo::get_Name() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "get_Name", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::String(__result__);
}
// Get:RootDirectory
mscorlib::System::IO::DirectoryInfo DriveInfo::get_RootDirectory() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "get_RootDirectory", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::IO::DirectoryInfo(__result__);
}
// Get:IsReady
mscorlib::System::Boolean DriveInfo::get_IsReady() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.IO", "DriveInfo", 0, NULL, "get_IsReady", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
}
}
}
| 38.603306 | 163 | 0.71034 | [
"vector"
] |
f4a1ceaf59bea2e6c8f627ec9959897ce561f59e | 11,215 | cpp | C++ | RBVREnhanced/Hooking.cpp | InvoxiPlayGames/RBVREnhanced | 2b65bcad0c15f5c00ce323a600f01f6741307da3 | [
"MIT"
] | 1 | 2022-03-09T16:59:39.000Z | 2022-03-09T16:59:39.000Z | RBVREnhanced/Hooking.cpp | InvoxiPlayGames/RBVREnhanced | 2b65bcad0c15f5c00ce323a600f01f6741307da3 | [
"MIT"
] | null | null | null | RBVREnhanced/Hooking.cpp | InvoxiPlayGames/RBVREnhanced | 2b65bcad0c15f5c00ce323a600f01f6741307da3 | [
"MIT"
] | null | null | null | /*
Original source: https://github.com/khalladay/hooking-by-example
MIT License
Copyright (c) 2020 Kyle Halladay
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "pch.h"
#include <cstdlib>
#include <x86.h>
#include <capstone.h>
#include <vector>
#include <Windows.h>
#include <Psapi.h>
void* AllocatePageNearAddress(void* targetAddr)
{
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
const uint64_t PAGE_SIZE = sysInfo.dwPageSize;
uint64_t startAddr = (uint64_t(targetAddr) & ~(PAGE_SIZE - 1)); //round down to nearest page boundary
uint64_t minAddr = min(startAddr - 0x7FFFFF00, (uint64_t)sysInfo.lpMinimumApplicationAddress);
uint64_t maxAddr = max(startAddr + 0x7FFFFF00, (uint64_t)sysInfo.lpMaximumApplicationAddress);
uint64_t startPage = (startAddr - (startAddr % PAGE_SIZE));
uint64_t pageOffset = 1;
while (1)
{
uint64_t byteOffset = pageOffset * PAGE_SIZE;
uint64_t highAddr = startPage + byteOffset;
uint64_t lowAddr = (startPage > byteOffset) ? startPage - byteOffset : 0;
bool needsExit = highAddr > maxAddr && lowAddr < minAddr;
if (highAddr < maxAddr)
{
void* outAddr = VirtualAlloc((void*)highAddr, PAGE_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (outAddr)
return outAddr;
}
if (lowAddr > minAddr)
{
void* outAddr = VirtualAlloc((void*)lowAddr, PAGE_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (outAddr != nullptr)
return outAddr;
}
pageOffset++;
if (needsExit)
{
break;
}
}
return nullptr;
}
void WriteAbsoluteJump64(void* absJumpMemory, void* addrToJumpTo)
{
uint8_t absJumpInstructions[] = { 0x49, 0xBA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x41, 0xFF, 0xE2 };
uint64_t addrToJumpTo64 = (uint64_t)addrToJumpTo;
memcpy(&absJumpInstructions[2], &addrToJumpTo64, sizeof(addrToJumpTo64));
memcpy(absJumpMemory, absJumpInstructions, sizeof(absJumpInstructions));
}
typedef struct _X64Instructions
{
cs_insn* instructions;
uint32_t numInstructions;
uint32_t numBytes;
} X64Instructions;
X64Instructions StealBytes(void* function)
{
// Disassemble stolen bytes
csh handle;
cs_open(CS_ARCH_X86, CS_MODE_64, &handle);
cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON); // we need details enabled for relocating RIP relative instrs
size_t count;
cs_insn* disassembledInstructions; //allocated by cs_disasm, needs to be manually freed later
count = cs_disasm(handle, (uint8_t*)function, 20, (uint64_t)function, 20, &disassembledInstructions);
//get the instructions covered by the first 5 bytes of the original function
uint32_t byteCount = 0;
uint32_t stolenInstrCount = 0;
for (int32_t i = 0; i < count; ++i)
{
cs_insn& inst = disassembledInstructions[i];
byteCount += inst.size;
stolenInstrCount++;
if (byteCount >= 5) break;
}
//replace instructions in target func with NOPs
memset(function, 0x90, byteCount);
cs_close(&handle);
return { disassembledInstructions, stolenInstrCount, byteCount };
}
bool IsRelativeJump(cs_insn& inst)
{
bool isAnyJumpInstruction = inst.id >= X86_INS_JAE && inst.id <= X86_INS_JS;
bool isJmp = inst.id == X86_INS_JMP;
bool startsWithEBorE9 = inst.bytes[0] == 0xEB || inst.bytes[0] == 0xE9;
return isJmp ? startsWithEBorE9 : isAnyJumpInstruction;
}
bool IsRelativeCall(cs_insn& inst)
{
bool isCall = inst.id == X86_INS_CALL;
bool startsWithE8 = inst.bytes[0] == 0xE8;
return isCall && startsWithE8;
}
void RewriteJumpInstruction(cs_insn* instr, uint8_t* instrPtr, uint8_t* absTableEntry)
{
uint8_t distToJumpTable = uint8_t(absTableEntry - (instrPtr + instr->size));
//jmp instructions can have a 1 or 2 byte opcode, and need a 1-4 byte operand
//rewrite the operand for the jump to go to the jump table
uint8_t instrByteSize = instr->bytes[0] == 0x0F ? 2 : 1;
uint8_t operandSize = instr->size - instrByteSize;
switch (operandSize)
{
case 1: instr->bytes[instrByteSize] = distToJumpTable; break;
case 2: {uint16_t dist16 = distToJumpTable; memcpy(&instr->bytes[instrByteSize], &dist16, 2); } break;
case 4: {uint32_t dist32 = distToJumpTable; memcpy(&instr->bytes[instrByteSize], &dist32, 4); } break;
}
}
void RewriteCallInstruction(cs_insn* instr, uint8_t* instrPtr, uint8_t* absTableEntry)
{
uint8_t distToJumpTable = uint8_t(absTableEntry - (instrPtr + instr->size));
//calls need to be rewritten as relative jumps to the abs table
//but we want to preserve the length of the instruction, so pad with NOPs
uint8_t jmpBytes[2] = { 0xEB, distToJumpTable };
memset(instr->bytes, 0x90, instr->size);
memcpy(instr->bytes, jmpBytes, sizeof(jmpBytes));
}
uint32_t AddJmpToAbsTable(cs_insn& jmp, uint8_t* absTableMem)
{
char* targetAddrStr = jmp.op_str; //where the instruction intended to go
uint64_t targetAddr = _strtoui64(targetAddrStr, NULL, 0);
WriteAbsoluteJump64(absTableMem, (void*)targetAddr);
return 13; //size of mov/jmp instrs for absolute jump
}
uint32_t AddCallToAbsTable(cs_insn& call, uint8_t* absTableMem, uint8_t* jumpBackToHookedFunc)
{
char* targetAddrStr = call.op_str; //where the instruction intended to go
uint64_t targetAddr = _strtoui64(targetAddrStr, NULL, 0);
uint8_t* dstMem = absTableMem;
uint8_t callAsmBytes[] =
{
0x49, 0xBA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, //movabs 64 bit value into r10
0x41, 0xFF, 0xD2, //call r10
};
memcpy(&callAsmBytes[2], &targetAddr, sizeof(void*));
memcpy(dstMem, &callAsmBytes, sizeof(callAsmBytes));
dstMem += sizeof(callAsmBytes);
//after the call, we need to add a second 2 byte jump, which will jump back to the
//final jump of the stolen bytes
uint8_t jmpBytes[2] = { 0xEB, uint8_t(jumpBackToHookedFunc - (absTableMem + sizeof(jmpBytes))) };
memcpy(dstMem, jmpBytes, sizeof(jmpBytes));
return sizeof(callAsmBytes) + sizeof(jmpBytes); //15
}
bool IsRIPRelativeInstr(cs_insn& inst)
{
cs_x86* x86 = &(inst.detail->x86);
for (uint32_t i = 0; i < inst.detail->x86.op_count; i++)
{
cs_x86_op* op = &(x86->operands[i]);
//mem type is rip relative, like lea rcx,[rip+0xbeef]
if (op->type == X86_OP_MEM)
{
//if we're relative to rip
return op->mem.base == X86_REG_RIP;
}
}
return false;
}
template<class T>
T GetDisplacement(cs_insn* inst, uint8_t offset)
{
T disp;
memcpy(&disp, &inst->bytes[offset], sizeof(T));
return disp;
}
//rewrite instruction bytes so that any RIP-relative displacement operands
//make sense with wherever we're relocating to
void RelocateInstruction(cs_insn* inst, void* dstLocation)
{
cs_x86* x86 = &(inst->detail->x86);
uint8_t offset = x86->encoding.disp_offset;
uint64_t displacement = inst->bytes[x86->encoding.disp_offset];
switch (x86->encoding.disp_size)
{
case 1:
{
int8_t disp = GetDisplacement<uint8_t>(inst, offset);
disp -= int8_t(uint64_t(dstLocation) - inst->address);
memcpy(&inst->bytes[offset], &disp, 1);
}break;
case 2:
{
int16_t disp = GetDisplacement<uint16_t>(inst, offset);
disp -= int16_t(uint64_t(dstLocation) - inst->address);
memcpy(&inst->bytes[offset], &disp, 2);
}break;
case 4:
{
int32_t disp = GetDisplacement<int32_t>(inst, offset);
disp -= int32_t(uint64_t(dstLocation) - inst->address);
memcpy(&inst->bytes[offset], &disp, 4);
}break;
}
}
uint32_t BuildTrampoline(void* func2hook, void* dstMemForTrampoline)
{
X64Instructions stolenInstrs = StealBytes(func2hook);
uint8_t* stolenByteMem = (uint8_t*)dstMemForTrampoline;
uint8_t* jumpBackMem = stolenByteMem + stolenInstrs.numBytes;
uint8_t* absTableMem = jumpBackMem + 13; //13 is the size of a 64 bit mov/jmp instruction pair
for (uint32_t i = 0; i < stolenInstrs.numInstructions; ++i)
{
cs_insn& inst = stolenInstrs.instructions[i];
if (inst.id >= X86_INS_LOOP && inst.id <= X86_INS_LOOPNE)
{
return 0; //bail out on loop instructions, I don't have a good way of handling them
}
if (IsRIPRelativeInstr(inst))
{
RelocateInstruction(&inst, stolenByteMem);
}
else if (IsRelativeJump(inst))
{
uint32_t aitSize = AddJmpToAbsTable(inst, absTableMem);
RewriteJumpInstruction(&inst, stolenByteMem, absTableMem);
absTableMem += aitSize;
}
else if (inst.id == X86_INS_CALL)
{
uint32_t aitSize = AddCallToAbsTable(inst, absTableMem, jumpBackMem);
RewriteCallInstruction(&inst, stolenByteMem, absTableMem);
absTableMem += aitSize;
}
memcpy(stolenByteMem, inst.bytes, inst.size);
stolenByteMem += inst.size;
}
WriteAbsoluteJump64(jumpBackMem, (uint8_t*)func2hook + 5);
free(stolenInstrs.instructions);
return uint32_t(absTableMem - (uint8_t*)dstMemForTrampoline);
}
void InstallHook(void* func2hook, void* payloadFunc, void** trampolinePtr)
{
DWORD oldProtect;
VirtualProtect(func2hook, 1024, PAGE_EXECUTE_READWRITE, &oldProtect);
void* hookMemory = AllocatePageNearAddress(func2hook);
uint32_t trampolineSize = BuildTrampoline(func2hook, hookMemory);
*trampolinePtr = hookMemory;
//create the relay function
void* relayFuncMemory = (char*)hookMemory + trampolineSize;
WriteAbsoluteJump64(relayFuncMemory, payloadFunc); //write relay func instructions
//install the hook
uint8_t jmpInstruction[5] = { 0xE9, 0x0, 0x0, 0x0, 0x0 };
const int32_t relAddr = (int32_t)relayFuncMemory - ((int32_t)func2hook + sizeof(jmpInstruction));
memcpy(jmpInstruction + 1, &relAddr, 4);
memcpy(func2hook, jmpInstruction, sizeof(jmpInstruction));
}
| 34.507692 | 119 | 0.68025 | [
"vector"
] |
f4aaaea12d514feedaab22c61f18f7d57d797394 | 3,819 | hpp | C++ | tools/Vitis-AI-Library/mnistclassification/include/vitis/ai/mnistclassification.hpp | bluetiger9/Vitis-AI | a7728733bbcfc292ff3afa46b9c8b03e94b740b3 | [
"Apache-2.0"
] | 848 | 2019-12-03T00:16:17.000Z | 2022-03-31T22:53:17.000Z | tools/Vitis-AI-Library/mnistclassification/include/vitis/ai/mnistclassification.hpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 656 | 2019-12-03T00:48:46.000Z | 2022-03-31T18:41:54.000Z | tools/Vitis-AI-Library/mnistclassification/include/vitis/ai/mnistclassification.hpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 506 | 2019-12-03T00:46:26.000Z | 2022-03-30T10:34:56.000Z | /*
* Copyright 2019 Xilinx Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Filename: mnistclassification.hpp
*
* Description:
* This network is used to classify the number from a input image.
*
* Please refer to document "xilinx_XILINX_AI_SDK_user_guide.pdf" for more
* details of these APIs.
*/
#pragma once
#include <memory>
#include <opencv2/core.hpp>
#include <vitis/ai/library/tensor.hpp>
namespace vitis {
namespace ai {
/**
* @brief Base class for classification for Mnist dataset .
*
* Input is an image (cv:Mat) which must be cv::IMREAD_GRAYSCALE style
*
* Output is a struct of detection results, named MnistClassificationResult.
*
* Sample code :
@code
Mat img = cv::imread("sample_mnistclassification.jpg", cv::IMREAD_GRAYSCALE);
auto mnistclassification =
vitis::ai::MnistClassification::create("MNIST-Classification-TensorFlow",true);
auto results = mnistclassification->run(img);
// please check test samples for detail usage.
@endcode
*
*/
struct MnistClassificationResult{
// Weight of input image.
int width;
// Height of input image.
int height;
// class idx. 0--9
int classIdx;
};
class MnistClassification {
public:
/**
* @brief Factory function to get an instance of derived classes of class
* MnistClassification.
*
* @param model_name Model name
* @param need_preprocess Normalize with mean/scale or not,
* default value is true.
* @return An instance of MnistClassification class.
*
*/
static std::unique_ptr<MnistClassification> create(
const std::string &model_name, bool need_preprocess = true);
/**
* @cond NOCOMMENTS
*/
protected:
explicit MnistClassification();
MnistClassification(const MnistClassification &) = delete;
public:
virtual ~MnistClassification();
/**
* @endcond
*/
public:
/**
* @brief Function of get result of the MnistClassification neuron network.
*
* @param img Input data of input image (cv::Mat).
*
* @return MnistClassificationResult.
*
*/
virtual vitis::ai::MnistClassificationResult run(const cv::Mat &img) = 0;
/**
* @brief Function to get running results of the MnistClassification neuron network in
* batch mode.
*
* @param images Input data of input images (vector<cv::Mat>).The size of
* input images equals batch size obtained by get_input_batch.
*
* @return The vector of MnistClassificationResult.
*
*/
virtual std::vector<vitis::ai::MnistClassificationResult> run(
const std::vector<cv::Mat> &img) = 0;
/**
* @brief Function to get InputWidth of the MnistClassification network (input image cols).
*
* @return InputWidth of the MnistClassification network.
*/
virtual int getInputWidth() const = 0;
/**
*@brief Function to get InputHeight of the MnistClassification network (input image rows).
*
*@return InputHeight of the MnistClassification network.
*/
virtual int getInputHeight() const = 0;
/**
* @brief Function to get the number of images processed by the DPU at one
*time.
* @note Different DPU core the batch size may be different. This depends on
*the IP used.
*
*@return Batch size.
*/
virtual size_t get_input_batch() const = 0;
};
} // namespace ai
} // namespace vitis
| 27.673913 | 93 | 0.700969 | [
"vector",
"model"
] |
f4b1c86746202615534fd78ece06ceef28221b02 | 5,342 | cpp | C++ | Sources/CEigenBridge/eigen_s_rat.cpp | taketo1024/swm-eigen | 952ecdb73a2739641e75909c8d9e724e32b2ed0f | [
"MIT"
] | 6 | 2021-09-19T07:55:41.000Z | 2021-11-10T00:43:47.000Z | Sources/CEigenBridge/eigen_s_rat.cpp | taketo1024/swm-eigen | 952ecdb73a2739641e75909c8d9e724e32b2ed0f | [
"MIT"
] | null | null | null | Sources/CEigenBridge/eigen_s_rat.cpp | taketo1024/swm-eigen | 952ecdb73a2739641e75909c8d9e724e32b2ed0f | [
"MIT"
] | null | null | null | //
// File.cpp
//
//
// Created by Taketo Sano on 2021/06/10.
//
#import "eigen_s_rat.h"
#import "types/Rational.hpp"
#import <iostream>
#import <Eigen/Eigen>
using namespace std;
using namespace Eigen;
using R = RationalNum;
using Mat = SparseMatrix<R>;
void *eigen_s_rat_init(int_t rows, int_t cols) {
Mat *A = new Mat(rows, cols);
A->setZero();
return static_cast<void *>(A);
}
void eigen_s_rat_free(void *ptr) {
Mat *A = static_cast<Mat *>(ptr);
delete A;
}
void eigen_s_rat_copy(void *from, void *to) {
Mat *A = static_cast<Mat *>(from);
Mat *B = static_cast<Mat *>(to);
*B = *A;
}
void eigen_s_rat_copy_from_dense(void *from, void *to) {
using DMat = Matrix<R, Dynamic, Dynamic>;
DMat *A = static_cast<DMat *>(from);
Mat *B = static_cast<Mat *>(to);
*B = A->sparseView();
}
void eigen_s_rat_copy_to_dense(void *from, void *to) {
using DMat = Matrix<R, Dynamic, Dynamic>;
Mat *A = static_cast<Mat *>(from);
DMat *B = static_cast<DMat *>(to);
*B = *A;
}
void eigen_s_rat_set_entries(void *a, int_t *r, int_t *c, rational_t *v, int_t count) {
Mat *A = static_cast<Mat *>(a);
vector<Triplet<R>> vec;
for (int_t i = 0; i < count; ++i, ++r, ++c, ++v) {
Triplet<R> t(*r, *c, *v);
vec.push_back(t);
}
A->setFromTriplets(vec.begin(), vec.end());
}
rational_t eigen_s_rat_get_entry(void *a, int_t i, int_t j) {
Mat *A = static_cast<Mat *>(a);
return to_rational_t(A->coeff(i, j));
}
void eigen_s_rat_set_entry(void *a, int_t i, int_t j, rational_t r) {
Mat *A = static_cast<Mat *>(a);
A->coeffRef(i, j) = RationalNum(r);
}
int_t eigen_s_rat_rows(void *a) {
Mat *A = static_cast<Mat *>(a);
return A->rows();
}
int_t eigen_s_rat_cols(void *a) {
Mat *A = static_cast<Mat *>(a);
return A->cols();
}
void eigen_s_rat_transpose(void *a, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
*B = A->transpose();
}
void eigen_s_rat_submatrix(void *a, int_t i, int_t j, int_t h, int_t w, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
*B = A->block(i, j, h, w);
}
void eigen_s_rat_concat(void *a, void *b, void *c) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Mat *C = static_cast<Mat *>(c);
C->leftCols(A->cols()) = *A;
C->rightCols(B->cols()) = *B;
}
void eigen_s_rat_perm_rows(void *a, perm_t p, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Eigen::VectorXi indices(p.length);
for(int_t i = 0; i < p.length; ++i) {
indices[i] = p.indices[i];
}
PermutationMatrix<Eigen::Dynamic> P(indices);
*B = P * (*A);
}
void eigen_s_rat_perm_cols(void *a, perm_t p, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Eigen::VectorXi indices(p.length);
for(int_t i = 0; i < p.length; ++i) {
indices[i] = p.indices[i];
}
PermutationMatrix<Eigen::Dynamic> P(indices);
*B = (*A) * P.transpose();
}
bool eigen_s_rat_eq(void *a, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
return A->isApprox(*B);
}
void eigen_s_rat_add(void *a, void *b, void *c) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Mat *C = static_cast<Mat *>(c);
*C = *A + *B;
}
void eigen_s_rat_neg(void *a, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
*B = -(*A);
}
void eigen_s_rat_minus(void *a, void *b, void *c) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Mat *C = static_cast<Mat *>(c);
*C = *A - *B;
}
void eigen_s_rat_mul(void *a, void *b, void *c) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Mat *C = static_cast<Mat *>(c);
*C = (*A) * (*B);
}
void eigen_s_rat_scal_mul(rational_t r, void *a, void *b) {
RationalNum r_ = RationalNum(r);
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
*B = r_ * (*A);
}
int_t eigen_s_rat_nnz(void *a) {
Mat *A = static_cast<Mat *>(a);
A->prune(RationalNum(0));
return A->nonZeros();
}
void eigen_s_rat_copy_nz(void *a, int_t *rows, int_t *cols, rational_t *vals) {
Mat *A = static_cast<Mat *>(a);
A->prune(RationalNum(0));
for (int k = 0; k < A->outerSize(); ++k) {
for (Mat::InnerIterator it(*A, k); it; ++it) {
*(rows++) = it.row();
*(cols++) = it.col();
*(vals++) = to_rational_t(it.value());
}
}
}
void eigen_s_rat_solve_lt(void *l, void *b, void *x) {
Mat *L = static_cast<Mat *>(l);
Mat *B = static_cast<Mat *>(b);
Mat *X = static_cast<Mat *>(x);
using DMat = Matrix<R, Dynamic, Dynamic>;
DMat b_ = *B;
DMat x_ = L->triangularView<Lower>().solve(b_);
*X = x_.sparseView();
}
void eigen_s_rat_solve_ut(void *u, void *b, void *x) {
Mat *U = static_cast<Mat *>(u);
Mat *B = static_cast<Mat *>(b);
Mat *X = static_cast<Mat *>(x);
using DMat = Matrix<R, Dynamic, Dynamic>;
DMat b_ = *B;
DMat x_ = U->triangularView<Upper>().solve(b_);
*X = x_.sparseView();
}
void eigen_s_rat_dump(void *ptr) {
Mat *m = static_cast<Mat *>(ptr);
cout << *m << endl;
}
| 25.079812 | 87 | 0.569637 | [
"vector"
] |
f4b379a13dc7a7f42b49f8bdc3d552f7a8285422 | 2,697 | cpp | C++ | C++/Algorithms/Arrays/RotateArray.cpp | joao-neves95/Exercises_Challenges_Courses | 02b6e25d9a270395bbf6dc8111c2419bba4f3edc | [
"MIT"
] | null | null | null | C++/Algorithms/Arrays/RotateArray.cpp | joao-neves95/Exercises_Challenges_Courses | 02b6e25d9a270395bbf6dc8111c2419bba4f3edc | [
"MIT"
] | 4 | 2018-11-10T01:05:14.000Z | 2021-06-25T15:16:28.000Z | C++/Algorithms/Arrays/RotateArray.cpp | joao-neves95/Exercises_Challenges_Courses | 02b6e25d9a270395bbf6dc8111c2419bba4f3edc | [
"MIT"
] | null | null | null | /**
* @file RotateArray.cpp
* @author João Neves (https://github.com/joao-neves95)
* @brief
Given an array, rotate the array to the right by k steps, where k is non-negative.
E.g:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
- rotate 1 steps to the right: [7,1,2,3,4,5,6]
- rotate 2 steps to the right: [6,7,1,2,3,4,5]
- rotate 3 steps to the right: [5,6,7,1,2,3,4]
(LeetCode: runtime beats 100.00 % of cpp submissions)
* @version 1.0.0
* @copyright Copyright (c) 2021
* (_SHIVAYL_)
*/
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
#include "../../Utils.hpp"
class RotateArray {
public:
void rotate(vector<int>& nums, int k) {
// this->rotateSlowAF(nums, k);
this->computeRotation(nums, k);
}
private:
void computeRotation(vector<int>& nums, int k) {
size_t vecSize = nums.size();
if (vecSize < 2 || k == 0) {
return;
}
vector<int> result(vecSize, 0);
for (int i = 0; i < vecSize; ++i) {
result[this->calcNewPositon(i, k, vecSize)] = nums[i];
}
nums = result;
}
int calcNewPositon(int currentPosition, const int k, const int length) {
int position = currentPosition + k;
// To be honest, I've found this pattern by trial and error on a calculator.
// This is for when k is bigger than the length.
// Keep subtracting with the length until we are within bounds.
while (position > length - 1) {
position = abs(position - length);
}
return position;
}
// // Brute force. Keep rotating for k times.
// void rotateSlowAF(vector<int>& nums, const int k) {
// int rotationCount = 0;
// int i;
// int cache;
// // The idea above is to find the final position, so we don't
// // do O(n^2) with a write on every iteration.
// while (rotationCount < k) {
// for (i = nums.size() - 1; i > 0; --i) {
// cache = nums[i];
// nums[i] = nums[i - 1];
// nums[i - 1] = cache;
// }
// ++rotationCount;
// }
// }
};
int main()
{
vector<int> vec = { 1,2,3,4,5,6,7 };
Utils::logg("Rotate array: ");
Utils::loggVector(vec);
Utils::loggNL();
Utils::loggNL("Expected: [5,6,7,1,2,3,4]");
Utils::logg("Output: ");
RotateArray rotateArray;
rotateArray.rotate(vec , 3);
Utils::loggVector(vec);
Utils::loggNL();
return 0;
}
| 26.441176 | 85 | 0.522803 | [
"vector"
] |
f4b3a14899e8427680e23c930e8aef69430f45c7 | 19,100 | cpp | C++ | lib/debug/host/HostDebugger.cpp | alexbatashev/pi_reproduce | 7129111ff80b9d76e4dfad26f1f2b67ef3826e52 | [
"Apache-2.0"
] | null | null | null | lib/debug/host/HostDebugger.cpp | alexbatashev/pi_reproduce | 7129111ff80b9d76e4dfad26f1f2b67ef3826e52 | [
"Apache-2.0"
] | 4 | 2021-07-05T12:14:37.000Z | 2021-07-29T18:39:42.000Z | lib/debug/host/HostDebugger.cpp | alexbatashev/pi_reproduce | 7129111ff80b9d76e4dfad26f1f2b67ef3826e52 | [
"Apache-2.0"
] | null | null | null | #include "HostDebugger.hpp"
#include <Acceptor.h>
#include <Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h>
#include <lldb/Core/Module.h>
#include <lldb/Core/PluginManager.h>
#include <lldb/Host/ConnectionFileDescriptor.h>
#include <lldb/Host/MainLoop.h>
#include <lldb/Host/common/NativeProcessProtocol.h>
#include <lldb/Host/common/TCPSocket.h>
#include <lldb/Initialization/SystemInitializerCommon.h>
#include <lldb/Target/ExecutionContext.h>
#include <lldb/Target/Process.h>
#include <lldb/Target/ProcessTrace.h>
#include <lldb/Target/RegisterContext.h>
#include <lldb/Target/StopInfo.h>
#include <lldb/Target/ThreadPlan.h>
#include <lldb/Utility/ProcessInfo.h>
#include <lldb/Utility/RegisterValue.h>
#include <llvm/Support/TargetSelect.h>
#if defined(__linux__)
#include <Plugins/Process/Linux/NativeProcessLinux.h>
#elif defined(_WIN32)
#include <Plugins/Process/Windows/Common/NativeProcessWindows.h>
#endif
#define LLDB_PLUGIN(p) LLDB_PLUGIN_DECLARE(p)
#include "LLDBPlugins.def"
#undef LLDB_PLUGIN
#include <cpuinfo.h>
#include <cstdint>
#include <exception>
#include <fcntl.h>
#include <filesystem>
#include <fmt/core.h>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::lldb_server;
namespace fs = std::filesystem;
#if defined(__linux__)
typedef process_linux::NativeProcessLinux::Factory NativeProcessFactory;
#elif defined(_WIN32)
typedef NativeProcessWindows::Factory NativeProcessFactory;
#endif
std::unique_ptr<SystemInitializerCommon> gSystemInitializer;
extern "C" void deinitialize(dpcpp_trace::AbstractDebugger *d) { delete d; }
extern "C" int initialize(DebuggerInfo *info) {
// TODO enable python?
gSystemInitializer = std::make_unique<SystemInitializerCommon>(nullptr);
auto err = gSystemInitializer->Initialize();
if (err) {
llvm::errs() << err << "\n";
exit(EXIT_FAILURE);
}
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetDisassembler();
#define LLDB_PLUGIN(x) LLDB_PLUGIN_INITIALIZE(x);
#include "LLDBPlugins.def"
ProcessTrace::Initialize();
PluginManager::Initialize();
Debugger::SettingsInitialize();
info->debugger = new HostDebugger();
info->deinitialize = deinitialize;
return 0;
}
HostDebugger::HostDebugger() {
mDebugger = Debugger::CreateInstance();
mDebugger->SetAsyncExecution(true);
}
HostDebugger::~HostDebugger() {
if (mTarget)
mTarget->Destroy();
if (mDebugger)
Debugger::Destroy(mDebugger);
}
void HostDebugger::launch(std::string_view executable,
std::span<std::string> args,
std::span<std::string> env) {
mExecutablePath = fs::canonical(executable).string();
auto error = mDebugger->GetTargetList().CreateTarget(
*mDebugger, "", "", eLoadDependentsNo, nullptr, mTarget);
if (error.Fail()) {
std::terminate();
}
ProcessLaunchInfo launchInfo = mTarget->GetProcessLaunchInfo();
FileSpec execFileSpec(executable.data());
launchInfo.SetExecutableFile(execFileSpec, false);
launchInfo.GetFlags().Set(eLaunchFlagDebug | eLaunchFlagStopAtEntry);
launchInfo.SetLaunchInSeparateProcessGroup(true);
const auto toCString = [](const std::string &str) { return str.c_str(); };
std::vector<const char *> cArgs;
cArgs.reserve(args.size());
std::transform(args.begin(), args.end(), std::back_inserter(cArgs),
toCString);
cArgs.push_back(nullptr);
std::vector<const char *> cEnv;
cEnv.reserve(env.size());
std::transform(env.begin(), env.end(), std::back_inserter(cEnv), toCString);
cEnv.push_back(nullptr);
launchInfo.SetArguments(cArgs.data(), true);
launchInfo.SetArg0(args.front());
::pid_t pid = ::fork();
if (pid == 0) {
MainLoop mainLoop;
NativeProcessFactory factory;
process_gdb_remote::GDBRemoteCommunicationServerLLGS server(mainLoop,
factory);
server.SetLaunchInfo(launchInfo);
error = server.LaunchProcess();
if (error.Fail()) {
std::cerr << "Failed to launch process: " << error.AsCString() << "\n";
std::terminate();
}
auto listenerOrError = Socket::TcpListen("localhost:11111", true, nullptr);
if (!listenerOrError)
std::terminate();
auto listener = std::move(*listenerOrError);
Socket *connSocket;
error = listener->Accept(connSocket);
if (error.Fail()) {
std::cerr << "Failed to accept connection: " << error.AsCString() << "\n";
std::terminate();
}
std::unique_ptr<Connection> connection(
new ConnectionFileDescriptor(connSocket));
error = server.InitializeConnection(std::move(connection));
if (error.Fail()) {
std::cerr << "Failed to initialize connection: " << error.AsCString()
<< "\n";
std::terminate();
}
if (!server.IsConnected()) {
std::cerr << "gdb-remote is not connected\n";
std::terminate();
}
error = mainLoop.Run();
if (error.Fail()) {
std::cerr << "Failed to start main loop: " << error.AsCString() << "\n";
std::terminate();
}
exit(0);
}
ModuleSpec moduleSpec(FileSpec(executable.data()));
mModule = mTarget->GetOrCreateModule(moduleSpec, true);
if (!mModule) {
std::cerr << "Failed to create module\n";
std::terminate();
}
auto proc = mTarget->CreateProcess(nullptr, "gdb-remote", nullptr, true);
if (!proc) {
std::cerr << "Failed to create gdb-remote process\n";
std::terminate();
}
error = proc->ConnectRemote("tcp-connect://localhost:11111");
if (error.Fail()) {
std::cerr << "Failed to connect to gdb-remote process: "
<< error.AsCString() << "\n";
std::terminate();
}
proc->WaitForProcessToStop(llvm::None);
}
std::vector<uint8_t> HostDebugger::getRegistersData(size_t threadId) {
auto thread =
mTarget->GetProcessSP()->GetThreadList().FindThreadByID(threadId);
if (threadId == 0)
thread = mTarget->GetProcessSP()->GetThreadList().GetThreadAtIndex(0);
auto regContext = thread->GetRegisterContext();
std::vector<uint8_t> buffer;
for (uint32_t regNum = 0; regNum < regContext->GetRegisterCount(); regNum++) {
const RegisterInfo *regInfo = regContext->GetRegisterInfoAtIndex(regNum);
if (regInfo == nullptr) {
return {};
}
if (regInfo->value_regs != nullptr)
continue; // skip registers that are contained in other registers
RegisterValue regValue;
bool success = regContext->ReadRegister(regInfo, regValue);
if (!success) {
return {};
}
if (regInfo->byte_offset + regInfo->byte_size >= buffer.size())
buffer.resize(regInfo->byte_offset + regInfo->byte_size);
memcpy(buffer.data() + regInfo->byte_offset, regValue.GetBytes(),
regInfo->byte_size);
}
return buffer;
}
std::vector<uint8_t> HostDebugger::readRegister(size_t threadId, size_t regNum) {
auto thread =
mTarget->GetProcessSP()->GetThreadList().FindThreadByID(threadId);
if (threadId == 0)
thread = mTarget->GetProcessSP()->GetThreadList().GetThreadAtIndex(0);
auto regContext = thread->GetRegisterContext();
if (regNum > regContext->GetRegisterCount())
return {};
std::vector<uint8_t> buffer;
const RegisterInfo *regInfo = regContext->GetRegisterInfoAtIndex(regNum);
RegisterValue regValue;
bool success = regContext->ReadRegister(regInfo, regValue);
if (!success) {
return {};
}
buffer.resize(regInfo->byte_size);
memcpy(buffer.data(), regValue.GetBytes(), regInfo->byte_size);
return buffer;
}
void HostDebugger::writeRegistersData(std::span<uint8_t> data, uint64_t tid) {
auto thread = mTarget->GetProcessSP()->GetThreadList().FindThreadByID(tid);
if (tid == 0)
thread = mTarget->GetProcessSP()->GetThreadList().GetThreadAtIndex(0);
auto regContext = thread->GetRegisterContext();
for (uint32_t regNum = 0; regNum < regContext->GetRegisterCount(); regNum++) {
const RegisterInfo *regInfo = regContext->GetRegisterInfoAtIndex(regNum);
if (regInfo == nullptr) {
std::cerr << "Failed to fetch register info\n";
std::terminate();
}
if (regInfo->value_regs != nullptr)
continue; // skip registers that are contained in other registers
llvm::ArrayRef<uint8_t> raw(data.data() + regInfo->byte_offset,
regInfo->byte_size);
RegisterValue regValue(raw, eByteOrderLittle);
regContext->WriteRegister(regInfo, regValue);
}
}
void HostDebugger::attach(uint64_t pid) {}
void HostDebugger::detach() {
// mProcess->Detach(false);
}
int HostDebugger::wait() {
StateType type = eStateInvalid;
do {
type = mTarget->GetProcessSP()->WaitForProcessToStop(llvm::None);
} while (type != eStateExited || type != eStateCrashed);
return 0;
}
void HostDebugger::start() {}
void HostDebugger::kill() {}
void HostDebugger::interrupt() {}
bool HostDebugger::isAttached() { return mTarget != nullptr; }
dpcpp_trace::StopReason HostDebugger::getStopReason(size_t threadId) {
auto thread =
mTarget->GetProcessSP()->GetThreadList().FindThreadByID(threadId);
if (threadId == 0)
thread = mTarget->GetProcessSP()->GetThreadList().GetThreadAtIndex(0);
auto stateType = mTarget->GetProcessSP()->GetState();
dpcpp_trace::StopReason returnReason;
switch (stateType) {
case eStateExited:
case eStateInvalid:
case eStateUnloaded:
returnReason.type = dpcpp_trace::StopReason::Type::exit;
return returnReason;
case eStateAttaching:
case eStateLaunching:
case eStateRunning:
case eStateStepping:
case eStateDetached:
returnReason.type = dpcpp_trace::StopReason::Type::none;
return returnReason;
default:
break;
}
auto realReason = thread->GetStopReason();
switch (realReason) {
case eStopReasonInvalid:
returnReason.type = dpcpp_trace::StopReason::Type::exit;
break;
case eStopReasonTrace:
returnReason.type = dpcpp_trace::StopReason::Type::trace;
break;
case eStopReasonNone: // Software breakpoints?
case eStopReasonBreakpoint:
case eStopReasonPlanComplete:
returnReason.type = dpcpp_trace::StopReason::Type::breakpoint;
break;
case eStopReasonWatchpoint:
returnReason.type = dpcpp_trace::StopReason::Type::watchpoint;
break;
case eStopReasonSignal: {
returnReason.type = dpcpp_trace::StopReason::Type::signal;
auto info = thread->GetStopInfo();
returnReason.code = static_cast<int>(info->GetValue());
break;
}
case eStopReasonException:
returnReason.type = dpcpp_trace::StopReason::Type::exception;
break;
case eStopReasonFork:
returnReason.type = dpcpp_trace::StopReason::Type::fork;
break;
case eStopReasonVFork:
returnReason.type = dpcpp_trace::StopReason::Type::vfork;
break;
case eStopReasonVForkDone:
returnReason.type = dpcpp_trace::StopReason::Type::vfork_done;
break;
default:
returnReason.type = dpcpp_trace::StopReason::Type::none;
}
return returnReason;
}
size_t HostDebugger::getNumThreads() {
return mTarget->GetProcessSP()->GetThreadList().GetSize();
}
uint64_t HostDebugger::getThreadIDAtIndex(size_t threadIdx) {
return mTarget->GetProcessSP()
->GetThreadList()
.GetThreadAtIndex(threadIdx)
->GetID();
}
std::vector<uint8_t> HostDebugger::readMemory(uint64_t addr, size_t len) {
auto process = mTarget->GetProcessSP();
Process::StopLocker stopLocker;
if (stopLocker.TryLock(&process->GetRunLock())) {
std::lock_guard<std::recursive_mutex> guard(
process->GetTarget().GetAPIMutex());
std::vector<uint8_t> buf;
buf.resize(len);
Status error;
size_t actualBytes = process->ReadMemory(addr, buf.data(), len, error);
if (error.Fail())
return {};
buf.resize(actualBytes);
return buf;
}
return {};
}
void HostDebugger::writeMemory(uint64_t addr, size_t len,
std::span<uint8_t> data) {
auto process = mTarget->GetProcessSP();
Process::StopLocker stopLocker;
if (stopLocker.TryLock(&process->GetRunLock())) {
std::lock_guard<std::recursive_mutex> guard(
process->GetTarget().GetAPIMutex());
Status error;
process->WriteMemory(addr, data.data(), len, error);
}
}
std::string HostDebugger::getExecutablePath() { return mExecutablePath; }
static llvm::StringRef getEncodingNameOrEmpty(const RegisterInfo ®Info) {
switch (regInfo.encoding) {
case eEncodingUint:
return "uint";
case eEncodingSint:
return "sint";
case eEncodingIEEE754:
return "ieee754";
case eEncodingVector:
return "vector";
default:
return "";
}
}
static llvm::StringRef getFormatNameOrEmpty(const RegisterInfo ®Info) {
switch (regInfo.format) {
case eFormatBinary:
return "binary";
case eFormatDecimal:
return "decimal";
case eFormatHex:
return "hex";
case eFormatFloat:
return "float";
case eFormatVectorOfSInt8:
return "vector-sint8";
case eFormatVectorOfUInt8:
return "vector-uint8";
case eFormatVectorOfSInt16:
return "vector-sint16";
case eFormatVectorOfUInt16:
return "vector-uint16";
case eFormatVectorOfSInt32:
return "vector-sint32";
case eFormatVectorOfUInt32:
return "vector-uint32";
case eFormatVectorOfFloat32:
return "vector-float32";
case eFormatVectorOfUInt64:
return "vector-uint64";
case eFormatVectorOfUInt128:
return "vector-uint128";
default:
return "";
};
}
// TODO find a portable way of doing the same for GDB.
std::string HostDebugger::getGDBTargetXML() {
std::string result = "<?xml version=\"1.0\"?>\n"
"<target version=\"1.0\">\n";
result +=
fmt::format("<architecture>{}</architecture>\n",
mTarget->GetArchitecture().GetTriple().getArchName().str());
result += "<feature>\n";
auto thread = mTarget->GetProcessSP()->GetThreadList().GetThreadAtIndex(0);
auto regContext = thread->GetRegisterContext();
for (size_t regIndex = 0; regIndex < regContext->GetRegisterCount();
regIndex++) {
const RegisterInfo *regInfo = regContext->GetRegisterInfoAtIndex(regIndex);
result += fmt::format("<reg name=\"{}\" bitsize=\"{}\" regnum=\"{}\" ",
regInfo->name, regInfo->byte_size * 8, regIndex);
result += fmt::format("offset=\"{}\" ", regInfo->byte_offset);
if (regInfo->alt_name && regInfo->alt_name[0])
result += fmt::format("altname=\"{}\" ", regInfo->alt_name);
llvm::StringRef encoding = getEncodingNameOrEmpty(*regInfo);
if (!encoding.empty())
result += fmt::format("encoding=\"{}\" ", encoding);
llvm::StringRef format = getFormatNameOrEmpty(*regInfo);
if (!format.empty())
result += fmt::format("format=\"{}\" ", format);
result += "/>\n";
}
result += "</feature>\n</target>";
return result;
}
dpcpp_trace::ProcessInfo HostDebugger::getProcessInfo() {
if (!mTarget) {
std::cerr << "Invalid target\n";
std::terminate();
}
ProcessInstanceInfo info;
if (!mTarget->GetProcessSP()->GetProcessInfo(info)) {
std::cerr << "Failed to get process info\n";
std::terminate();
}
const ArchSpec &procArch = info.GetArchitecture();
if (!procArch.IsValid()) {
std::cerr << "Failed to get process info\n";
std::terminate();
}
std::string endian;
switch (procArch.GetByteOrder()) {
case lldb::eByteOrderLittle:
endian = "little";
break;
case lldb::eByteOrderBig:
endian = "big";
break;
case lldb::eByteOrderPDP:
endian = "pdp";
break;
default:
// Nothing.
break;
}
const llvm::Triple &triple = procArch.GetTriple();
dpcpp_trace::ProcessInfo returnInfo{
info.GetProcessID(), info.GetParentProcessID(), info.GetUserID(), info.GetGroupID(), info.GetEffectiveUserID(),
info.GetEffectiveGroupID(),
triple.getTriple(),
triple.getOSName().str(),
endian,
procArch.GetTargetABI(),
procArch.GetAddressByteSize()
};
return returnInfo;
}
void HostDebugger::createSoftwareBreakpoint(uint64_t address) {
if (mTarget) {
std::lock_guard guard(mTarget->GetAPIMutex());
auto bp = mTarget->CreateBreakpoint(address, false, false);
if (bp) {
mBreakpoints[address] = bp;
}
}
}
void HostDebugger::removeSoftwareBreakpoint(uint64_t address) {
if (mTarget) {
std::lock_guard guard(mTarget->GetAPIMutex());
if (mBreakpoints.contains(address)) {
mTarget->RemoveBreakpointByID(mBreakpoints[address]->GetID());
mBreakpoints.erase(address);
}
}
}
void HostDebugger::resume(int signal, uint64_t tid) {
mTarget->GetProcessSP()->GetThreadList().SetSelectedThreadByID(tid);
Status error = mTarget->GetProcessSP()->ResumeSynchronous(nullptr);
if (error.Fail()) {
std::cerr << "Error resuming process: " << error.AsCString() << "\n";
std::terminate();
}
}
void HostDebugger::stepInstruction(uint64_t tid, int signal) {
auto thread = mTarget->GetProcessSP()->GetThreadList().FindThreadByID(tid);
if (tid == 0)
thread = mTarget->GetProcessSP()->GetThreadList().GetThreadAtIndex(0);
if (!thread) {
std::cerr << "Failed to find thread with id " << tid << "\n";
std::terminate();
}
if (signal != 0) {
thread->SetResumeSignal(signal);
}
ExecutionContext exe;
thread->CalculateExecutionContext(exe);
if (!exe.HasThreadScope()) {
std::cerr << "Thread object is invalid\n";
std::terminate();
}
Status error;
ThreadPlanSP newPlan(thread->QueueThreadPlanForStepSingleInstruction(
false, true, true, error));
if (error.Fail()) {
std::cerr << "Failed to create thread plan: " << error.AsCString() << "\n";
std::terminate();
}
resumeNewPlan(exe, newPlan.get());
}
void HostDebugger::resumeNewPlan(ExecutionContext &ctx, ThreadPlan *newPlan) {
Process *proc = ctx.GetProcessPtr();
Thread *thread = ctx.GetThreadPtr();
if (!proc || !thread) {
std::cerr << "Invalid execution context\n";
std::terminate();
}
if (newPlan != nullptr) {
newPlan->SetIsMasterPlan(true);
newPlan->SetOkayToDiscard(false);
}
// Why do we need to set the current thread by ID here???
proc->GetThreadList().SetSelectedThreadByID(thread->GetID());
proc->ResumeSynchronous(nullptr);
}
std::vector<uint8_t> HostDebugger::getAuxvData() {
auto proc = mTarget->GetProcessSP();
auto data = proc->GetAuxvData();
std::vector<uint8_t> ret;
ret.resize(data.GetByteSize());
data.CopyData(0, data.GetByteSize(), ret.data());
return ret;
}
void *HostDebugger::cast(size_t type) {
if (type == DebuggerRTTI::getID()) {
return static_cast<dpcpp_trace::AbstractDebugger *>(this);
} else if (type == TracerRTTI::getID()) {
return static_cast<dpcpp_trace::Tracer *>(this);
} else if (type == ThisRTTI::getID()) {
return this;
}
return nullptr;
}
| 28.678679 | 119 | 0.677644 | [
"object",
"vector",
"transform"
] |
f4b44663d38bacf9e423d6fbf2bd206e4769feac | 4,403 | cpp | C++ | source/plum/platform/glfw/tilemap.cpp | Bananattack/Plum | 60ae0b07c0ef25dfa4bda6e81fe646ace6042664 | [
"BSD-3-Clause"
] | 5 | 2015-02-10T03:50:28.000Z | 2017-08-23T08:49:49.000Z | source/plum/platform/glfw/tilemap.cpp | Bananattack/Plum | 60ae0b07c0ef25dfa4bda6e81fe646ace6042664 | [
"BSD-3-Clause"
] | null | null | null | source/plum/platform/glfw/tilemap.cpp | Bananattack/Plum | 60ae0b07c0ef25dfa4bda6e81fe646ace6042664 | [
"BSD-3-Clause"
] | 1 | 2019-10-05T08:54:56.000Z | 2019-10-05T08:54:56.000Z | #include "engine.h"
#include "../../core/image.h"
#include "../../core/sheet.h"
#include "../../core/screen.h"
#include "../../core/tilemap.h"
namespace plum
{
class Tilemap::Impl
{
public:
Impl(int width, int height)
: width(width), height(height), vertices(new GLfloat[6 * 4 * sizeof(float) * width * height]), vbo(0)
{
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, 6 * 4 * sizeof(GLfloat) * width * height, nullptr, GL_DYNAMIC_DRAW);
}
~Impl()
{
delete[] vertices;
glDeleteBuffers(1, &vbo);
}
int width, height;
Sheet sheet;
GLfloat* vertices;
GLuint vbo;
};
Tilemap::Tilemap(int width, int height)
: impl(new Impl(width, height)), width(width), height(height), data(new unsigned int[width * height])
{
clear(0);
}
Tilemap::~Tilemap()
{
delete data;
}
void Tilemap::draw(Image& img, const Sheet& sheet, int x, int y, const Transform& transform, Screen& dest)
{
auto& sht(impl->sheet);
if(sheet.getColumns() != sht.getColumns()
|| sheet.getRows() != sht.getRows()
|| sheet.getWidth() != sht.getWidth()
|| sheet.getHeight() != sht.getHeight()
|| sheet.getPadding() != sht.getPadding())
{
impl->sheet = sheet;
modified = true;
}
dest.bindImage(img);
dest.applyTransform(transform, -x, -y, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, impl->vbo);
if(modified)
{
auto& vertices(impl->vertices);
float vx = 0;
float vy = 0;
int k = 0;
for(int i = 0; i < height; ++i)
{
for(int j = 0; j < width; ++j)
{
int sx = 0;
int sy = 0;
sheet.getFrame(data[i * width + j], sx, sy);
float u = float(sx) / img.canvas().getTrueWidth();
float v = float(sy) / img.canvas().getTrueHeight();
float u2 = float(sx + sheet.getWidth()) / img.canvas().getTrueWidth();
float v2 = float(sy + sheet.getHeight()) / img.canvas().getTrueHeight();
vertices[k++] = vx; vertices[k++] = vy; vertices[k++] = u; vertices[k++] = v;
vertices[k++] = vx; vertices[k++] = vy + sheet.getHeight(); vertices[k++] = u; vertices[k++] = v2;
vertices[k++] = vx + sheet.getWidth(); vertices[k++] = vy + sheet.getHeight(); vertices[k++] = u2; vertices[k++] = v2;
vertices[k++] = vx + sheet.getWidth(); vertices[k++] = vy + sheet.getHeight(); vertices[k++] = u2; vertices[k++] = v2;
vertices[k++] = vx + sheet.getWidth(); vertices[k++] = vy; vertices[k++] = u2; vertices[k++] = v;
vertices[k++] = vx; vertices[k++] = vy; vertices[k++] = u; vertices[k++] = v;
vx += sheet.getWidth();
}
vx -= sheet.getWidth() * width;
vy += sheet.getHeight();
}
glBufferSubData(GL_ARRAY_BUFFER, 0, 6 * 4 * sizeof(GLfloat) * width * height, vertices);
modified = false;
}
auto& e(dest.engine().impl);
if(e->modernPipeline)
{
glEnableVertexAttribArray(e->xyAttribute);
glEnableVertexAttribArray(e->uvAttribute);
glVertexAttribPointer(e->xyAttribute, 2, GL_FLOAT, false, 4 * sizeof(GLfloat), (void*) 0);
glVertexAttribPointer(e->uvAttribute, 2, GL_FLOAT, false, 4 * sizeof(GLfloat), (void*)(2 * sizeof(float)));
}
else
{
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(2, GL_FLOAT, 4 * sizeof(GLfloat), (void*) 0);
glTexCoordPointer(2, GL_FLOAT, 4 * sizeof(GLfloat), (void*)(2 * sizeof(float)));
}
glDrawArrays(GL_TRIANGLES, 0, 6 * width * height);
dest.unbindImage();
}
} | 38.622807 | 139 | 0.482625 | [
"transform"
] |
f4b8c9d98f6d2e1b4d9e5945d016fcd83257444a | 2,770 | hpp | C++ | Ref/CLEMOps/CLEMOpsComponentImpl.hpp | brhs17/fprime | 647eb40bfa68df774401fe12cb6171c53c27f846 | [
"Apache-2.0"
] | null | null | null | Ref/CLEMOps/CLEMOpsComponentImpl.hpp | brhs17/fprime | 647eb40bfa68df774401fe12cb6171c53c27f846 | [
"Apache-2.0"
] | null | null | null | Ref/CLEMOps/CLEMOpsComponentImpl.hpp | brhs17/fprime | 647eb40bfa68df774401fe12cb6171c53c27f846 | [
"Apache-2.0"
] | null | null | null | // ======================================================================
// \title CLEMOpsImpl.hpp
// \author bhs
// \brief hpp file for CLEMOps component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
//
// This software may be subject to U.S. export control laws and
// regulations. By accepting this document, the user agrees to comply
// with all U.S. export laws and regulations. User has the
// responsibility to obtain export licenses, or other export authority
// as may be required before exporting such information to foreign
// countries or providing access to foreign persons.
// ======================================================================
#ifndef CLEMOps_HPP
#define CLEMOps_HPP
#include "Ref/CLEMOps/CLEMOpsComponentAc.hpp"
namespace Ref {
class CLEMOpsComponentImpl :
public CLEMOpsComponentBase
{
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object CLEMOps
//!
CLEMOpsComponentImpl(
#if FW_OBJECT_NAMES == 1
const char *const compName /*!< The component name*/
#else
void
#endif
);
//! Initialize object CLEMOps
//!
void init(
const NATIVE_INT_TYPE queueDepth, /*!< The queue depth*/
const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! Destroy object CLEMOps
//!
~CLEMOpsComponentImpl(void);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for dataResult
//!
void dataResult_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
F32 result
);
PRIVATE:
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
//! Implementation for Ops_Get_Data command handler
//!
void Ops_Get_Data_cmdHandler(
const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq, /*!< The command sequence number*/
DataRequest data
);
};
} // end namespace Ref
#endif
| 30.43956 | 79 | 0.517329 | [
"object"
] |
f4be94eb9e9c536beb6397be07e1f90a6f569464 | 5,488 | hpp | C++ | include/El/number_theory/factor/PollardRho.hpp | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 473 | 2015-01-11T03:22:11.000Z | 2022-03-31T05:28:39.000Z | include/El/number_theory/factor/PollardRho.hpp | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 205 | 2015-01-10T20:33:45.000Z | 2021-07-25T14:53:25.000Z | include/El/number_theory/factor/PollardRho.hpp | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 109 | 2015-02-16T14:06:42.000Z | 2022-03-23T21:34:26.000Z | /*
Copyright (c) 2009-2016, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#ifndef EL_NUMBER_THEORY_FACTOR_POLLARD_RHO_HPP
#define EL_NUMBER_THEORY_FACTOR_POLLARD_RHO_HPP
#ifdef EL_HAVE_MPC
namespace El {
namespace factor {
namespace pollard_rho {
// TODO: Add the ability to set a maximum number of iterations
inline BigInt FindFactor
( const BigInt& n,
Int a,
const PollardRhoCtrl& ctrl )
{
const BigInt& one = BigIntOne();
if( a == 0 || a == -2 )
Output("WARNING: Problematic choice of Pollard rho shift");
BigInt tmp, gcd;
auto xAdvance =
[&]( BigInt& x )
{
if( ctrl.numSteps == 1 )
{
x *= x;
x += a;
x %= n;
}
else
{
PowMod( x, 2*ctrl.numSteps, n, x );
x += a;
x %= n;
}
};
auto QAdvance =
[&]( const BigInt& x, const BigInt& x2, BigInt& Q )
{
tmp = x2;
tmp -= x;
Q *= tmp;
Q %= n;
};
Int gcdDelay = ctrl.gcdDelay;
BigInt xi=ctrl.x0;
BigInt x2i(xi);
BigInt xiSave=xi, x2iSave=x2i;
BigInt Qi(1);
Int delayCounter=1, i=1;
while( true )
{
// Advance xi once
xAdvance( xi );
// Advance x2i twice
xAdvance( x2i );
xAdvance( x2i );
// Advance Qi
QAdvance( xi, x2i, Qi );
if( delayCounter >= gcdDelay )
{
GCD( Qi, n, gcd );
if( gcd > one )
{
if( gcd == n )
{
if( gcdDelay == 1 )
{
RuntimeError("(x) converged before (x mod p) at i=",i);
}
else
{
if( ctrl.progress )
Output("Backtracking at i=",i);
i = Max( i-(gcdDelay+1), 0 );
gcdDelay = 1;
xi = xiSave;
x2i = x2iSave;
}
}
else
{
if( ctrl.progress )
Output("Found factor ",gcd," at i=",i);
return gcd;
}
}
delayCounter = 0;
xiSave = xi;
x2iSave = x2i;
Qi = 1;
}
++delayCounter;
++i;
}
}
} // namespace pollard_rho
inline vector<BigInt> PollardRho
( const BigInt& n,
const PollardRhoCtrl& ctrl )
{
vector<BigInt> factors;
BigInt nRem = n;
if( !ctrl.avoidTrialDiv )
{
// Start with trial division
auto tinyFactors = TrialDivision( n, ctrl.trialDivLimit );
for( auto tinyFactor : tinyFactors )
{
factors.push_back( tinyFactor );
nRem /= tinyFactor;
if( ctrl.progress )
Output("Removed tiny factor of ",tinyFactor);
}
}
if( nRem <= BigInt(1) )
return factors;
Timer timer;
PushIndent();
while( true )
{
// Try Miller-Rabin first
if( ctrl.time )
timer.Start();
Primality primality = PrimalityTest( nRem, ctrl.numReps );
if( primality == PRIME )
{
if( ctrl.time )
Output(nRem," is prime (",timer.Stop()," seconds)");
else if( ctrl.progress )
Output(nRem," is prime");
factors.push_back( nRem );
break;
}
else if( primality == PROBABLY_PRIME )
{
if( ctrl.time )
Output(nRem," is probably prime (",timer.Stop()," seconds)");
else if( ctrl.progress )
Output(nRem," is probably prime");
factors.push_back( nRem );
break;
}
else
{
if( ctrl.time )
Output(nRem," is composite (",timer.Stop()," seconds)");
else if( ctrl.progress )
Output(nRem," is composite");
}
if( ctrl.progress )
Output("Attempting to factor ",nRem," with a=",ctrl.a0);
if( ctrl.time )
timer.Start();
PushIndent();
BigInt factor;
try
{
factor = pollard_rho::FindFactor( nRem, ctrl.a0, ctrl );
}
catch( const exception& e ) // TODO: Introduce factor exception?
{
// Try again with a=ctrl.a1
if( ctrl.progress )
Output("Attempting to factor ",nRem," with a=",ctrl.a1);
factor = pollard_rho::FindFactor( nRem, ctrl.a1, ctrl );
}
if( ctrl.time )
Output("Pollard-rho: ",timer.Stop()," seconds");
PopIndent();
// The factor might be composite, so attempt to factor it
PushIndent();
auto subfactors = PollardRho( factor, ctrl );
PopIndent();
for( const auto& subfactor : subfactors )
factors.push_back( subfactor );
nRem /= factor;
}
PopIndent();
sort( factors.begin(), factors.end() );
return factors;
}
} // namespace factor
} // namespace El
#endif // ifdef EL_HAVE_MPC
#endif // ifndef EL_NUMBER_THEORY_FACTOR_POLLARD_RHO_HPP
| 25.64486 | 79 | 0.474672 | [
"vector"
] |
f4c0ce94af42d1cf97d5a622333a423ca479531f | 105,677 | cpp | C++ | Plugins/BLUI/Intermediate/Build/Win64/UE4Editor/Inc/Blu/Blu.generated.cpp | crimsonstrife/velorum-defunct | 1a6e1eab9057293da2aa045eff021d069df54c5e | [
"CC0-1.0"
] | null | null | null | Plugins/BLUI/Intermediate/Build/Win64/UE4Editor/Inc/Blu/Blu.generated.cpp | crimsonstrife/velorum-defunct | 1a6e1eab9057293da2aa045eff021d069df54c5e | [
"CC0-1.0"
] | null | null | null | Plugins/BLUI/Intermediate/Build/Win64/UE4Editor/Inc/Blu/Blu.generated.cpp | crimsonstrife/velorum-defunct | 1a6e1eab9057293da2aa045eff021d069df54c5e | [
"CC0-1.0"
] | null | null | null | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Boilerplate C++ definitions for a single module.
This is automatically generated by UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "Private/BluPrivatePCH.h"
#include "Blu.generated.dep.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeBlu() {}
void UBluBlueprintFunctionLibrary::StaticRegisterNativesUBluBlueprintFunctionLibrary()
{
FNativeFunctionRegistrar::RegisterFunction(UBluBlueprintFunctionLibrary::StaticClass(), "JSONToString",(Native)&UBluBlueprintFunctionLibrary::execJSONToString);
FNativeFunctionRegistrar::RegisterFunction(UBluBlueprintFunctionLibrary::StaticClass(), "NewBluEye",(Native)&UBluBlueprintFunctionLibrary::execNewBluEye);
FNativeFunctionRegistrar::RegisterFunction(UBluBlueprintFunctionLibrary::StaticClass(), "NewBluJSONObj",(Native)&UBluBlueprintFunctionLibrary::execNewBluJSONObj);
FNativeFunctionRegistrar::RegisterFunction(UBluBlueprintFunctionLibrary::StaticClass(), "ParseJSON",(Native)&UBluBlueprintFunctionLibrary::execParseJSON);
FNativeFunctionRegistrar::RegisterFunction(UBluBlueprintFunctionLibrary::StaticClass(), "RunBluEventLoop",(Native)&UBluBlueprintFunctionLibrary::execRunBluEventLoop);
}
IMPLEMENT_CLASS(UBluBlueprintFunctionLibrary, 3000382412);
static class UEnum* EBluSpecialKeys_StaticEnum()
{
extern BLU_API class UPackage* Z_Construct_UPackage__Script_Blu();
static class UEnum* Singleton = NULL;
if (!Singleton)
{
extern BLU_API class UEnum* Z_Construct_UEnum_Blu_EBluSpecialKeys();
Singleton = GetStaticEnum(Z_Construct_UEnum_Blu_EBluSpecialKeys, Z_Construct_UPackage__Script_Blu(), TEXT("EBluSpecialKeys"));
}
return Singleton;
}
static FCompiledInDeferEnum Z_CompiledInDeferEnum_UEnum_EBluSpecialKeys(EBluSpecialKeys_StaticEnum, TEXT("/Script/Blu"), TEXT("EBluSpecialKeys"), false, nullptr, nullptr);
void UBluEye::StaticRegisterNativesUBluEye()
{
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "CharKeyPress",(Native)&UBluEye::execCharKeyPress);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "CloseBrowser",(Native)&UBluEye::execCloseBrowser);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "ExecuteJS",(Native)&UBluEye::execExecuteJS);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "ExecuteJSMethodWithParams",(Native)&UBluEye::execExecuteJSMethodWithParams);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "GetMaterialInstance",(Native)&UBluEye::execGetMaterialInstance);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "GetTexture",(Native)&UBluEye::execGetTexture);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "init",(Native)&UBluEye::execinit);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "IsBrowserLoading",(Native)&UBluEye::execIsBrowserLoading);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "KeyDown",(Native)&UBluEye::execKeyDown);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "KeyPress",(Native)&UBluEye::execKeyPress);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "KeyUp",(Native)&UBluEye::execKeyUp);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "LoadURL",(Native)&UBluEye::execLoadURL);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "NavBack",(Native)&UBluEye::execNavBack);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "NavForward",(Native)&UBluEye::execNavForward);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "RawCharKeyPress",(Native)&UBluEye::execRawCharKeyPress);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "ReloadBrowser",(Native)&UBluEye::execReloadBrowser);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "ResizeBrowser",(Native)&UBluEye::execResizeBrowser);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "SpecialKeyPress",(Native)&UBluEye::execSpecialKeyPress);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "TriggerLeftClick",(Native)&UBluEye::execTriggerLeftClick);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "TriggerLeftMouseDown",(Native)&UBluEye::execTriggerLeftMouseDown);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "TriggerLeftMouseUp",(Native)&UBluEye::execTriggerLeftMouseUp);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "TriggerMouseMove",(Native)&UBluEye::execTriggerMouseMove);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "TriggerMouseWheel",(Native)&UBluEye::execTriggerMouseWheel);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "TriggerRightClick",(Native)&UBluEye::execTriggerRightClick);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "TriggerRightMouseDown",(Native)&UBluEye::execTriggerRightMouseDown);
FNativeFunctionRegistrar::RegisterFunction(UBluEye::StaticClass(), "TriggerRightMouseUp",(Native)&UBluEye::execTriggerRightMouseUp);
}
IMPLEMENT_CLASS(UBluEye, 3480205770);
void UBluJsonObj::StaticRegisterNativesUBluJsonObj()
{
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "getBooleanArray",(Native)&UBluJsonObj::execgetBooleanArray);
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "getBooleanValue",(Native)&UBluJsonObj::execgetBooleanValue);
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "getNestedObject",(Native)&UBluJsonObj::execgetNestedObject);
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "getNumArray",(Native)&UBluJsonObj::execgetNumArray);
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "getNumValue",(Native)&UBluJsonObj::execgetNumValue);
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "getStringArray",(Native)&UBluJsonObj::execgetStringArray);
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "getStringValue",(Native)&UBluJsonObj::execgetStringValue);
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "setBooleanValue",(Native)&UBluJsonObj::execsetBooleanValue);
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "setNestedObject",(Native)&UBluJsonObj::execsetNestedObject);
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "setNumValue",(Native)&UBluJsonObj::execsetNumValue);
FNativeFunctionRegistrar::RegisterFunction(UBluJsonObj::StaticClass(), "setStringValue",(Native)&UBluJsonObj::execsetStringValue);
}
IMPLEMENT_CLASS(UBluJsonObj, 1329277757);
#if USE_COMPILED_IN_NATIVES
// Cross Module References
COREUOBJECT_API class UClass* Z_Construct_UClass_UObject_NoRegister();
ENGINE_API class UClass* Z_Construct_UClass_UBlueprintFunctionLibrary();
SLATECORE_API class UScriptStruct* Z_Construct_UScriptStruct_FCharacterEvent();
ENGINE_API class UClass* Z_Construct_UClass_UMaterialInstanceDynamic_NoRegister();
ENGINE_API class UClass* Z_Construct_UClass_UTexture2D_NoRegister();
SLATECORE_API class UScriptStruct* Z_Construct_UScriptStruct_FKeyEvent();
COREUOBJECT_API class UScriptStruct* Z_Construct_UScriptStruct_FVector2D();
COREUOBJECT_API class UClass* Z_Construct_UClass_UObject();
ENGINE_API class UClass* Z_Construct_UClass_UMaterialInterface_NoRegister();
BLU_API class UFunction* Z_Construct_UFunction_UBluBlueprintFunctionLibrary_JSONToString();
BLU_API class UFunction* Z_Construct_UFunction_UBluBlueprintFunctionLibrary_NewBluEye();
BLU_API class UFunction* Z_Construct_UFunction_UBluBlueprintFunctionLibrary_NewBluJSONObj();
BLU_API class UFunction* Z_Construct_UFunction_UBluBlueprintFunctionLibrary_ParseJSON();
BLU_API class UFunction* Z_Construct_UFunction_UBluBlueprintFunctionLibrary_RunBluEventLoop();
BLU_API class UClass* Z_Construct_UClass_UBluBlueprintFunctionLibrary_NoRegister();
BLU_API class UClass* Z_Construct_UClass_UBluBlueprintFunctionLibrary();
BLU_API class UFunction* Z_Construct_UDelegateFunction_Blu_ScriptEvent__DelegateSignature();
BLU_API class UEnum* Z_Construct_UEnum_Blu_EBluSpecialKeys();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_CharKeyPress();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_CloseBrowser();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_ExecuteJS();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_ExecuteJSMethodWithParams();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_GetMaterialInstance();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_GetTexture();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_init();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_IsBrowserLoading();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_KeyDown();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_KeyPress();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_KeyUp();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_LoadURL();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_NavBack();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_NavForward();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_RawCharKeyPress();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_ReloadBrowser();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_ResizeBrowser();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_SpecialKeyPress();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_TriggerLeftClick();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_TriggerLeftMouseDown();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_TriggerLeftMouseUp();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_TriggerMouseMove();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_TriggerMouseWheel();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_TriggerRightClick();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_TriggerRightMouseDown();
BLU_API class UFunction* Z_Construct_UFunction_UBluEye_TriggerRightMouseUp();
BLU_API class UClass* Z_Construct_UClass_UBluEye_NoRegister();
BLU_API class UClass* Z_Construct_UClass_UBluEye();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_getBooleanArray();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_getBooleanValue();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_getNestedObject();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_getNumArray();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_getNumValue();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_getStringArray();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_getStringValue();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_setBooleanValue();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_setNestedObject();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_setNumValue();
BLU_API class UFunction* Z_Construct_UFunction_UBluJsonObj_setStringValue();
BLU_API class UClass* Z_Construct_UClass_UBluJsonObj_NoRegister();
BLU_API class UClass* Z_Construct_UClass_UBluJsonObj();
BLU_API class UPackage* Z_Construct_UPackage__Script_Blu();
UFunction* Z_Construct_UFunction_UBluBlueprintFunctionLibrary_JSONToString()
{
struct BluBlueprintFunctionLibrary_eventJSONToString_Parms
{
UBluJsonObj* ObjectToParse;
FString ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluBlueprintFunctionLibrary();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("JSONToString"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04022401, 65535, sizeof(BluBlueprintFunctionLibrary_eventJSONToString_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(ReturnValue, BluBlueprintFunctionLibrary_eventJSONToString_Parms), 0x0010000000000580);
UProperty* NewProp_ObjectToParse = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ObjectToParse"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(ObjectToParse, BluBlueprintFunctionLibrary_eventJSONToString_Parms), 0x0010000000000080, Z_Construct_UClass_UBluJsonObj_NoRegister());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("DisplayName"), TEXT("JSON To String"));
MetaData->SetValue(ReturnFunction, TEXT("Keywords"), TEXT("blui blu eye json parse string"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluBlueprintFunctionLibrary.h"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluBlueprintFunctionLibrary_NewBluEye()
{
struct BluBlueprintFunctionLibrary_eventNewBluEye_Parms
{
UObject* WorldContextObject;
UBluEye* ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluBlueprintFunctionLibrary();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("NewBluEye"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x14022401, 65535, sizeof(BluBlueprintFunctionLibrary_eventNewBluEye_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(ReturnValue, BluBlueprintFunctionLibrary_eventNewBluEye_Parms), 0x0010000000000580, Z_Construct_UClass_UBluEye_NoRegister());
UProperty* NewProp_WorldContextObject = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("WorldContextObject"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(WorldContextObject, BluBlueprintFunctionLibrary_eventNewBluEye_Parms), 0x0010000000000080, Z_Construct_UClass_UObject_NoRegister());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("CompactNodeTitle"), TEXT("BluEye"));
MetaData->SetValue(ReturnFunction, TEXT("DefaultToSelf"), TEXT("WorldContextObject"));
MetaData->SetValue(ReturnFunction, TEXT("DisplayName"), TEXT("Create BluEye"));
MetaData->SetValue(ReturnFunction, TEXT("HidePin"), TEXT("WorldContextObject"));
MetaData->SetValue(ReturnFunction, TEXT("Keywords"), TEXT("new create blu eye blui"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluBlueprintFunctionLibrary.h"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluBlueprintFunctionLibrary_NewBluJSONObj()
{
struct BluBlueprintFunctionLibrary_eventNewBluJSONObj_Parms
{
UObject* WorldContextObject;
UBluJsonObj* ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluBlueprintFunctionLibrary();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("NewBluJSONObj"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x14022401, 65535, sizeof(BluBlueprintFunctionLibrary_eventNewBluJSONObj_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(ReturnValue, BluBlueprintFunctionLibrary_eventNewBluJSONObj_Parms), 0x0010000000000580, Z_Construct_UClass_UBluJsonObj_NoRegister());
UProperty* NewProp_WorldContextObject = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("WorldContextObject"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(WorldContextObject, BluBlueprintFunctionLibrary_eventNewBluJSONObj_Parms), 0x0010000000000080, Z_Construct_UClass_UObject_NoRegister());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("CompactNodeTitle"), TEXT("JSON"));
MetaData->SetValue(ReturnFunction, TEXT("DefaultToSelf"), TEXT("WorldContextObject"));
MetaData->SetValue(ReturnFunction, TEXT("DisplayName"), TEXT("Create BluJSON Obj"));
MetaData->SetValue(ReturnFunction, TEXT("HidePin"), TEXT("WorldContextObject"));
MetaData->SetValue(ReturnFunction, TEXT("Keywords"), TEXT("new create blu eye blui json"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluBlueprintFunctionLibrary.h"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluBlueprintFunctionLibrary_ParseJSON()
{
struct BluBlueprintFunctionLibrary_eventParseJSON_Parms
{
FString JSONString;
UBluJsonObj* ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluBlueprintFunctionLibrary();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("ParseJSON"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04022401, 65535, sizeof(BluBlueprintFunctionLibrary_eventParseJSON_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(ReturnValue, BluBlueprintFunctionLibrary_eventParseJSON_Parms), 0x0010000000000580, Z_Construct_UClass_UBluJsonObj_NoRegister());
UProperty* NewProp_JSONString = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("JSONString"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(JSONString, BluBlueprintFunctionLibrary_eventParseJSON_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("DisplayName"), TEXT("Parse JSON String"));
MetaData->SetValue(ReturnFunction, TEXT("Keywords"), TEXT("blui blu eye json parse"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluBlueprintFunctionLibrary.h"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluBlueprintFunctionLibrary_RunBluEventLoop()
{
UObject* Outer=Z_Construct_UClass_UBluBlueprintFunctionLibrary();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("RunBluEventLoop"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04022401, 65535);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("DisplayName"), TEXT("Run BLUI Tick"));
MetaData->SetValue(ReturnFunction, TEXT("Keywords"), TEXT("blui blu eye blui tick"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluBlueprintFunctionLibrary.h"));
#endif
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UBluBlueprintFunctionLibrary_NoRegister()
{
return UBluBlueprintFunctionLibrary::StaticClass();
}
UClass* Z_Construct_UClass_UBluBlueprintFunctionLibrary()
{
static UClass* OuterClass = NULL;
if (!OuterClass)
{
Z_Construct_UClass_UBlueprintFunctionLibrary();
Z_Construct_UPackage__Script_Blu();
OuterClass = UBluBlueprintFunctionLibrary::StaticClass();
if (!(OuterClass->ClassFlags & CLASS_Constructed))
{
UObjectForceRegistration(OuterClass);
OuterClass->ClassFlags |= 0x20100080;
OuterClass->LinkChild(Z_Construct_UFunction_UBluBlueprintFunctionLibrary_JSONToString());
OuterClass->LinkChild(Z_Construct_UFunction_UBluBlueprintFunctionLibrary_NewBluEye());
OuterClass->LinkChild(Z_Construct_UFunction_UBluBlueprintFunctionLibrary_NewBluJSONObj());
OuterClass->LinkChild(Z_Construct_UFunction_UBluBlueprintFunctionLibrary_ParseJSON());
OuterClass->LinkChild(Z_Construct_UFunction_UBluBlueprintFunctionLibrary_RunBluEventLoop());
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluBlueprintFunctionLibrary_JSONToString(), "JSONToString"); // 2455699459
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluBlueprintFunctionLibrary_NewBluEye(), "NewBluEye"); // 341377363
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluBlueprintFunctionLibrary_NewBluJSONObj(), "NewBluJSONObj"); // 865703471
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluBlueprintFunctionLibrary_ParseJSON(), "ParseJSON"); // 3565523184
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluBlueprintFunctionLibrary_RunBluEventLoop(), "RunBluEventLoop"); // 3317621447
OuterClass->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = OuterClass->GetOutermost()->GetMetaData();
MetaData->SetValue(OuterClass, TEXT("BlueprintType"), TEXT("true"));
MetaData->SetValue(OuterClass, TEXT("ClassGroupNames"), TEXT("Blu"));
MetaData->SetValue(OuterClass, TEXT("IncludePath"), TEXT("BluBlueprintFunctionLibrary.h"));
MetaData->SetValue(OuterClass, TEXT("IsBlueprintBase"), TEXT("true"));
MetaData->SetValue(OuterClass, TEXT("ModuleRelativePath"), TEXT("Public/BluBlueprintFunctionLibrary.h"));
#endif
}
}
check(OuterClass->GetClass());
return OuterClass;
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UBluBlueprintFunctionLibrary(Z_Construct_UClass_UBluBlueprintFunctionLibrary, &UBluBlueprintFunctionLibrary::StaticClass, TEXT("UBluBlueprintFunctionLibrary"), false, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UBluBlueprintFunctionLibrary);
UFunction* Z_Construct_UDelegateFunction_Blu_ScriptEvent__DelegateSignature()
{
struct _Script_Blu_eventScriptEvent_Parms
{
FString EventName;
FString EventMessage;
};
UObject* Outer=Z_Construct_UPackage__Script_Blu();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("ScriptEvent__DelegateSignature"), RF_Public|RF_Transient|RF_MarkAsNative) UDelegateFunction(FObjectInitializer(), NULL, 0x00130000, 65535, sizeof(_Script_Blu_eventScriptEvent_Parms));
UProperty* NewProp_EventMessage = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("EventMessage"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(EventMessage, _Script_Blu_eventScriptEvent_Parms), 0x0010000000000080);
UProperty* NewProp_EventName = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("EventName"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(EventName, _Script_Blu_eventScriptEvent_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
#endif
}
return ReturnFunction;
}
UEnum* Z_Construct_UEnum_Blu_EBluSpecialKeys()
{
UPackage* Outer=Z_Construct_UPackage__Script_Blu();
extern uint32 Get_Z_Construct_UEnum_Blu_EBluSpecialKeys_CRC();
static UEnum* ReturnEnum = FindExistingEnumIfHotReloadOrDynamic(Outer, TEXT("EBluSpecialKeys"), 0, Get_Z_Construct_UEnum_Blu_EBluSpecialKeys_CRC(), false);
if (!ReturnEnum)
{
ReturnEnum = new(EC_InternalUseOnlyConstructor, Outer, TEXT("EBluSpecialKeys"), RF_Public|RF_Transient|RF_MarkAsNative) UEnum(FObjectInitializer());
TArray<TPair<FName, uint8>> EnumNames;
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("backspacekey")), 8));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("tabkey")), 9));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("enterkey")), 13));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("pausekey")), 19));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("escapekey")), 27));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("pageupkey")), 33));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("pagedownkey")), 34));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("endkey")), 35));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("homekey")), 36));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("leftarrowkey")), 37));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("rightarrowkey")), 38));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("downarrowkey")), 39));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("uparrowkey")), 40));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("insertkey")), 45));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("deletekey")), 46));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("numlockkey")), 144));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("scrolllockkey")), 145));
EnumNames.Add(TPairInitializer<FName, uint8>(FName(TEXT("EBluSpecialKeys_MAX")), 146));
ReturnEnum->SetEnums(EnumNames, UEnum::ECppForm::Regular);
ReturnEnum->CppType = TEXT("EBluSpecialKeys");
#if WITH_METADATA
UMetaData* MetaData = ReturnEnum->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnEnum, TEXT("backspacekey.DisplayName"), TEXT("Backspace"));
MetaData->SetValue(ReturnEnum, TEXT("BlueprintType"), TEXT("true"));
MetaData->SetValue(ReturnEnum, TEXT("deletekey.DisplayName"), TEXT("Delete"));
MetaData->SetValue(ReturnEnum, TEXT("downarrowkey.DisplayName"), TEXT("Down Arrow"));
MetaData->SetValue(ReturnEnum, TEXT("endkey.DisplayName"), TEXT("End"));
MetaData->SetValue(ReturnEnum, TEXT("enterkey.DisplayName"), TEXT("Enter"));
MetaData->SetValue(ReturnEnum, TEXT("escapekey.DisplayName"), TEXT("Escape"));
MetaData->SetValue(ReturnEnum, TEXT("homekey.DisplayName"), TEXT("Home"));
MetaData->SetValue(ReturnEnum, TEXT("insertkey.DisplayName"), TEXT("Insert"));
MetaData->SetValue(ReturnEnum, TEXT("leftarrowkey.DisplayName"), TEXT("Left Arrow"));
MetaData->SetValue(ReturnEnum, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnEnum, TEXT("numlockkey.DisplayName"), TEXT("Num Lock"));
MetaData->SetValue(ReturnEnum, TEXT("pagedownkey.DisplayName"), TEXT("Page Down"));
MetaData->SetValue(ReturnEnum, TEXT("pageupkey.DisplayName"), TEXT("Page Up"));
MetaData->SetValue(ReturnEnum, TEXT("pausekey.DisplayName"), TEXT("Pause"));
MetaData->SetValue(ReturnEnum, TEXT("rightarrowkey.DisplayName"), TEXT("Right Arrow"));
MetaData->SetValue(ReturnEnum, TEXT("scrolllockkey.DisplayName"), TEXT("Scroll Lock"));
MetaData->SetValue(ReturnEnum, TEXT("tabkey.DisplayName"), TEXT("Tab"));
MetaData->SetValue(ReturnEnum, TEXT("uparrowkey.DisplayName"), TEXT("Up Arrow"));
#endif
}
return ReturnEnum;
}
uint32 Get_Z_Construct_UEnum_Blu_EBluSpecialKeys_CRC() { return 1476204016U; }
UFunction* Z_Construct_UFunction_UBluEye_CharKeyPress()
{
struct BluEye_eventCharKeyPress_Parms
{
FCharacterEvent CharEvent;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("CharKeyPress"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventCharKeyPress_Parms));
UProperty* NewProp_CharEvent = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("CharEvent"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(CharEvent, BluEye_eventCharKeyPress_Parms), 0x0010000000000080, Z_Construct_UScriptStruct_FCharacterEvent());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a character key event"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_CloseBrowser()
{
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("CloseBrowser"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Close the browser"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_ExecuteJS()
{
struct BluEye_eventExecuteJS_Parms
{
FString code;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("ExecuteJS"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventExecuteJS_Parms));
UProperty* NewProp_code = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("code"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(code, BluEye_eventExecuteJS_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Execute JS code inside the browser"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_ExecuteJSMethodWithParams()
{
struct BluEye_eventExecuteJSMethodWithParams_Parms
{
FString methodName;
TArray<FString> params;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("ExecuteJSMethodWithParams"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventExecuteJSMethodWithParams_Parms));
UProperty* NewProp_params = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("params"), RF_Public|RF_Transient|RF_MarkAsNative) UArrayProperty(CPP_PROPERTY_BASE(params, BluEye_eventExecuteJSMethodWithParams_Parms), 0x0010000000000082);
UProperty* NewProp_params_Inner = new(EC_InternalUseOnlyConstructor, NewProp_params, TEXT("params"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(FObjectInitializer(), EC_CppProperty, 0, 0x0000000000000000);
UProperty* NewProp_methodName = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("methodName"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(methodName, BluEye_eventExecuteJSMethodWithParams_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("DisplayName"), TEXT("Execute Javascript With Params"));
MetaData->SetValue(ReturnFunction, TEXT("Keywords"), TEXT("js javascript parameters"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Execute a JS function/method by name with FString Array as params.\nEach element in the array will be passed into the function in order and separated by a ,\nIf you want to pass a JSON string as an object, simply don't put quotes around the outside braces {\"foo\" : \"bar\"}\nIf you want to pass a number, do similar: 10.5\nTo pass as a string, place quotes around the param when adding to the array: \"10.5\" and \"hello\" are strings"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_GetMaterialInstance()
{
struct BluEye_eventGetMaterialInstance_Parms
{
UMaterialInstanceDynamic* ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("GetMaterialInstance"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x54020401, 65535, sizeof(BluEye_eventGetMaterialInstance_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(ReturnValue, BluEye_eventGetMaterialInstance_Parms), 0x0010000000000580, Z_Construct_UClass_UMaterialInstanceDynamic_NoRegister());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("DeprecatedFunction"), TEXT(""));
MetaData->SetValue(ReturnFunction, TEXT("DeprecatedNode"), TEXT(""));
MetaData->SetValue(ReturnFunction, TEXT("DeprecationMessage"), TEXT("Please use raw texture using GetTexture method. GetMaterialInstance will be removed in the next release!"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_GetTexture()
{
struct BluEye_eventGetTexture_Parms
{
UTexture2D* ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("GetTexture"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x54020401, 65535, sizeof(BluEye_eventGetTexture_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(ReturnValue, BluEye_eventGetTexture_Parms), 0x0010000000000580, Z_Construct_UClass_UTexture2D_NoRegister());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Get the texture data from our UI component"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_init()
{
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("init"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Initialize function, should be called after properties are set"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_IsBrowserLoading()
{
struct BluEye_eventIsBrowserLoading_Parms
{
bool ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("IsBrowserLoading"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventIsBrowserLoading_Parms));
CPP_BOOL_PROPERTY_BITMASK_STRUCT(ReturnValue, BluEye_eventIsBrowserLoading_Parms, bool);
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(ReturnValue, BluEye_eventIsBrowserLoading_Parms), 0x0010000000000580, CPP_BOOL_PROPERTY_BITMASK(ReturnValue, BluEye_eventIsBrowserLoading_Parms), sizeof(bool), true);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Check if the browser is still loading"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_KeyDown()
{
struct BluEye_eventKeyDown_Parms
{
FKeyEvent InKey;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("KeyDown"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventKeyDown_Parms));
UProperty* NewProp_InKey = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("InKey"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(InKey, BluEye_eventKeyDown_Parms), 0x0010000000000080, Z_Construct_UScriptStruct_FKeyEvent());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a key down event"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_KeyPress()
{
struct BluEye_eventKeyPress_Parms
{
FKeyEvent InKey;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("KeyPress"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventKeyPress_Parms));
UProperty* NewProp_InKey = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("InKey"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(InKey, BluEye_eventKeyPress_Parms), 0x0010000000000080, Z_Construct_UScriptStruct_FKeyEvent());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a key press event"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_KeyUp()
{
struct BluEye_eventKeyUp_Parms
{
FKeyEvent InKey;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("KeyUp"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventKeyUp_Parms));
UProperty* NewProp_InKey = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("InKey"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(InKey, BluEye_eventKeyUp_Parms), 0x0010000000000080, Z_Construct_UScriptStruct_FKeyEvent());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a key up event"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_LoadURL()
{
struct BluEye_eventLoadURL_Parms
{
FString newURL;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("LoadURL"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventLoadURL_Parms));
UProperty* NewProp_newURL = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("newURL"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(newURL, BluEye_eventLoadURL_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Load a new URL into the browser"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_NavBack()
{
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("NavBack"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Navigate back in this web view's history"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_NavForward()
{
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("NavForward"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Navigate forward in this web view's history"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_RawCharKeyPress()
{
struct BluEye_eventRawCharKeyPress_Parms
{
FString charToPress;
bool isRepeat;
bool LeftShiftDown;
bool RightShiftDown;
bool LeftControlDown;
bool RightControlDown;
bool LeftAltDown;
bool RightAltDown;
bool LeftCommandDown;
bool RightCommandDown;
bool CapsLocksOn;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("RawCharKeyPress"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventRawCharKeyPress_Parms));
CPP_BOOL_PROPERTY_BITMASK_STRUCT(CapsLocksOn, BluEye_eventRawCharKeyPress_Parms, bool);
UProperty* NewProp_CapsLocksOn = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("CapsLocksOn"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(CapsLocksOn, BluEye_eventRawCharKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(CapsLocksOn, BluEye_eventRawCharKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(RightCommandDown, BluEye_eventRawCharKeyPress_Parms, bool);
UProperty* NewProp_RightCommandDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("RightCommandDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(RightCommandDown, BluEye_eventRawCharKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(RightCommandDown, BluEye_eventRawCharKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(LeftCommandDown, BluEye_eventRawCharKeyPress_Parms, bool);
UProperty* NewProp_LeftCommandDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("LeftCommandDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(LeftCommandDown, BluEye_eventRawCharKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(LeftCommandDown, BluEye_eventRawCharKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(RightAltDown, BluEye_eventRawCharKeyPress_Parms, bool);
UProperty* NewProp_RightAltDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("RightAltDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(RightAltDown, BluEye_eventRawCharKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(RightAltDown, BluEye_eventRawCharKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(LeftAltDown, BluEye_eventRawCharKeyPress_Parms, bool);
UProperty* NewProp_LeftAltDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("LeftAltDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(LeftAltDown, BluEye_eventRawCharKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(LeftAltDown, BluEye_eventRawCharKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(RightControlDown, BluEye_eventRawCharKeyPress_Parms, bool);
UProperty* NewProp_RightControlDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("RightControlDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(RightControlDown, BluEye_eventRawCharKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(RightControlDown, BluEye_eventRawCharKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(LeftControlDown, BluEye_eventRawCharKeyPress_Parms, bool);
UProperty* NewProp_LeftControlDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("LeftControlDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(LeftControlDown, BluEye_eventRawCharKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(LeftControlDown, BluEye_eventRawCharKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(RightShiftDown, BluEye_eventRawCharKeyPress_Parms, bool);
UProperty* NewProp_RightShiftDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("RightShiftDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(RightShiftDown, BluEye_eventRawCharKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(RightShiftDown, BluEye_eventRawCharKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(LeftShiftDown, BluEye_eventRawCharKeyPress_Parms, bool);
UProperty* NewProp_LeftShiftDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("LeftShiftDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(LeftShiftDown, BluEye_eventRawCharKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(LeftShiftDown, BluEye_eventRawCharKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(isRepeat, BluEye_eventRawCharKeyPress_Parms, bool);
UProperty* NewProp_isRepeat = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("isRepeat"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(isRepeat, BluEye_eventRawCharKeyPress_Parms), 0x0010000000000080, CPP_BOOL_PROPERTY_BITMASK(isRepeat, BluEye_eventRawCharKeyPress_Parms), sizeof(bool), true);
UProperty* NewProp_charToPress = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("charToPress"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(charToPress, BluEye_eventRawCharKeyPress_Parms), 0x0010000000000082);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("AdvancedDisplay"), TEXT("2"));
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a raw keypress via a character"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_ReloadBrowser()
{
struct BluEye_eventReloadBrowser_Parms
{
bool IgnoreCache;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("ReloadBrowser"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventReloadBrowser_Parms));
CPP_BOOL_PROPERTY_BITMASK_STRUCT(IgnoreCache, BluEye_eventReloadBrowser_Parms, bool);
UProperty* NewProp_IgnoreCache = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("IgnoreCache"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(IgnoreCache, BluEye_eventReloadBrowser_Parms), 0x0010000000000080, CPP_BOOL_PROPERTY_BITMASK(IgnoreCache, BluEye_eventReloadBrowser_Parms), sizeof(bool), true);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Reloads the browser's current page"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_ResizeBrowser()
{
struct BluEye_eventResizeBrowser_Parms
{
int32 NewWidth;
int32 NewHeight;
UTexture2D* ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("ResizeBrowser"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventResizeBrowser_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(ReturnValue, BluEye_eventResizeBrowser_Parms), 0x0010000000000580, Z_Construct_UClass_UTexture2D_NoRegister());
UProperty* NewProp_NewHeight = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("NewHeight"), RF_Public|RF_Transient|RF_MarkAsNative) UIntProperty(CPP_PROPERTY_BASE(NewHeight, BluEye_eventResizeBrowser_Parms), 0x0010000000000082);
UProperty* NewProp_NewWidth = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("NewWidth"), RF_Public|RF_Transient|RF_MarkAsNative) UIntProperty(CPP_PROPERTY_BASE(NewWidth, BluEye_eventResizeBrowser_Parms), 0x0010000000000082);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Resize the browser's viewport"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_SpecialKeyPress()
{
struct BluEye_eventSpecialKeyPress_Parms
{
TEnumAsByte<EBluSpecialKeys> key;
bool LeftShiftDown;
bool RightShiftDown;
bool LeftControlDown;
bool RightControlDown;
bool LeftAltDown;
bool RightAltDown;
bool LeftCommandDown;
bool RightCommandDown;
bool CapsLocksOn;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("SpecialKeyPress"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluEye_eventSpecialKeyPress_Parms));
CPP_BOOL_PROPERTY_BITMASK_STRUCT(CapsLocksOn, BluEye_eventSpecialKeyPress_Parms, bool);
UProperty* NewProp_CapsLocksOn = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("CapsLocksOn"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(CapsLocksOn, BluEye_eventSpecialKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(CapsLocksOn, BluEye_eventSpecialKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(RightCommandDown, BluEye_eventSpecialKeyPress_Parms, bool);
UProperty* NewProp_RightCommandDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("RightCommandDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(RightCommandDown, BluEye_eventSpecialKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(RightCommandDown, BluEye_eventSpecialKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(LeftCommandDown, BluEye_eventSpecialKeyPress_Parms, bool);
UProperty* NewProp_LeftCommandDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("LeftCommandDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(LeftCommandDown, BluEye_eventSpecialKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(LeftCommandDown, BluEye_eventSpecialKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(RightAltDown, BluEye_eventSpecialKeyPress_Parms, bool);
UProperty* NewProp_RightAltDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("RightAltDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(RightAltDown, BluEye_eventSpecialKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(RightAltDown, BluEye_eventSpecialKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(LeftAltDown, BluEye_eventSpecialKeyPress_Parms, bool);
UProperty* NewProp_LeftAltDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("LeftAltDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(LeftAltDown, BluEye_eventSpecialKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(LeftAltDown, BluEye_eventSpecialKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(RightControlDown, BluEye_eventSpecialKeyPress_Parms, bool);
UProperty* NewProp_RightControlDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("RightControlDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(RightControlDown, BluEye_eventSpecialKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(RightControlDown, BluEye_eventSpecialKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(LeftControlDown, BluEye_eventSpecialKeyPress_Parms, bool);
UProperty* NewProp_LeftControlDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("LeftControlDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(LeftControlDown, BluEye_eventSpecialKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(LeftControlDown, BluEye_eventSpecialKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(RightShiftDown, BluEye_eventSpecialKeyPress_Parms, bool);
UProperty* NewProp_RightShiftDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("RightShiftDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(RightShiftDown, BluEye_eventSpecialKeyPress_Parms), 0x0010040000000080, CPP_BOOL_PROPERTY_BITMASK(RightShiftDown, BluEye_eventSpecialKeyPress_Parms), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(LeftShiftDown, BluEye_eventSpecialKeyPress_Parms, bool);
UProperty* NewProp_LeftShiftDown = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("LeftShiftDown"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(LeftShiftDown, BluEye_eventSpecialKeyPress_Parms), 0x0010000000000080, CPP_BOOL_PROPERTY_BITMASK(LeftShiftDown, BluEye_eventSpecialKeyPress_Parms), sizeof(bool), true);
UProperty* NewProp_key = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("key"), RF_Public|RF_Transient|RF_MarkAsNative) UByteProperty(CPP_PROPERTY_BASE(key, BluEye_eventSpecialKeyPress_Parms), 0x0010000000000080, Z_Construct_UEnum_Blu_EBluSpecialKeys());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("AdvancedDisplay"), TEXT("2"));
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_TriggerLeftClick()
{
struct BluEye_eventTriggerLeftClick_Parms
{
FVector2D pos;
float scale;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("TriggerLeftClick"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04C20401, 65535, sizeof(BluEye_eventTriggerLeftClick_Parms));
UProperty* NewProp_scale = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("scale"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(scale, BluEye_eventTriggerLeftClick_Parms), 0x0010000000000082);
UProperty* NewProp_pos = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("pos"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(pos, BluEye_eventTriggerLeftClick_Parms), 0x0010000008000182, Z_Construct_UScriptStruct_FVector2D());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("CPP_Default_scale"), TEXT("1.000000"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a LEFT click in the browser via a Vector2D"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_TriggerLeftMouseDown()
{
struct BluEye_eventTriggerLeftMouseDown_Parms
{
FVector2D pos;
float scale;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("TriggerLeftMouseDown"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04C20401, 65535, sizeof(BluEye_eventTriggerLeftMouseDown_Parms));
UProperty* NewProp_scale = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("scale"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(scale, BluEye_eventTriggerLeftMouseDown_Parms), 0x0010000000000082);
UProperty* NewProp_pos = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("pos"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(pos, BluEye_eventTriggerLeftMouseDown_Parms), 0x0010000008000182, Z_Construct_UScriptStruct_FVector2D());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("CPP_Default_scale"), TEXT("1.000000"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a LEFT MOUSE DOWN in the browser via a Vector2D"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_TriggerLeftMouseUp()
{
struct BluEye_eventTriggerLeftMouseUp_Parms
{
FVector2D pos;
float scale;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("TriggerLeftMouseUp"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04C20401, 65535, sizeof(BluEye_eventTriggerLeftMouseUp_Parms));
UProperty* NewProp_scale = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("scale"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(scale, BluEye_eventTriggerLeftMouseUp_Parms), 0x0010000000000082);
UProperty* NewProp_pos = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("pos"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(pos, BluEye_eventTriggerLeftMouseUp_Parms), 0x0010000008000182, Z_Construct_UScriptStruct_FVector2D());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("CPP_Default_scale"), TEXT("1.000000"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a LEFT MOUSE UP in the browser via a Vector2D"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_TriggerMouseMove()
{
struct BluEye_eventTriggerMouseMove_Parms
{
FVector2D pos;
float scale;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("TriggerMouseMove"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04C20401, 65535, sizeof(BluEye_eventTriggerMouseMove_Parms));
UProperty* NewProp_scale = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("scale"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(scale, BluEye_eventTriggerMouseMove_Parms), 0x0010000000000082);
UProperty* NewProp_pos = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("pos"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(pos, BluEye_eventTriggerMouseMove_Parms), 0x0010000008000182, Z_Construct_UScriptStruct_FVector2D());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("CPP_Default_scale"), TEXT("1.000000"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Move the mouse in the browser"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_TriggerMouseWheel()
{
struct BluEye_eventTriggerMouseWheel_Parms
{
float MouseWheelDelta;
FVector2D pos;
float scale;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("TriggerMouseWheel"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04C20401, 65535, sizeof(BluEye_eventTriggerMouseWheel_Parms));
UProperty* NewProp_scale = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("scale"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(scale, BluEye_eventTriggerMouseWheel_Parms), 0x0010000000000082);
UProperty* NewProp_pos = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("pos"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(pos, BluEye_eventTriggerMouseWheel_Parms), 0x0010000008000182, Z_Construct_UScriptStruct_FVector2D());
UProperty* NewProp_MouseWheelDelta = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("MouseWheelDelta"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(MouseWheelDelta, BluEye_eventTriggerMouseWheel_Parms), 0x0010000000000082);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("CPP_Default_scale"), TEXT("1.000000"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Move the mouse in the browser"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_TriggerRightClick()
{
struct BluEye_eventTriggerRightClick_Parms
{
FVector2D pos;
float scale;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("TriggerRightClick"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04C20401, 65535, sizeof(BluEye_eventTriggerRightClick_Parms));
UProperty* NewProp_scale = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("scale"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(scale, BluEye_eventTriggerRightClick_Parms), 0x0010000000000082);
UProperty* NewProp_pos = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("pos"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(pos, BluEye_eventTriggerRightClick_Parms), 0x0010000008000182, Z_Construct_UScriptStruct_FVector2D());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("CPP_Default_scale"), TEXT("1.000000"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a RIGHT click in the browser via a Vector2D"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_TriggerRightMouseDown()
{
struct BluEye_eventTriggerRightMouseDown_Parms
{
FVector2D pos;
float scale;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("TriggerRightMouseDown"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04C20401, 65535, sizeof(BluEye_eventTriggerRightMouseDown_Parms));
UProperty* NewProp_scale = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("scale"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(scale, BluEye_eventTriggerRightMouseDown_Parms), 0x0010000000000082);
UProperty* NewProp_pos = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("pos"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(pos, BluEye_eventTriggerRightMouseDown_Parms), 0x0010000008000182, Z_Construct_UScriptStruct_FVector2D());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("CPP_Default_scale"), TEXT("1.000000"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a RIGHT MOUSE DOWN in the browser via a Vector2D"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluEye_TriggerRightMouseUp()
{
struct BluEye_eventTriggerRightMouseUp_Parms
{
FVector2D pos;
float scale;
};
UObject* Outer=Z_Construct_UClass_UBluEye();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("TriggerRightMouseUp"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04C20401, 65535, sizeof(BluEye_eventTriggerRightMouseUp_Parms));
UProperty* NewProp_scale = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("scale"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(scale, BluEye_eventTriggerRightMouseUp_Parms), 0x0010000000000082);
UProperty* NewProp_pos = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("pos"), RF_Public|RF_Transient|RF_MarkAsNative) UStructProperty(CPP_PROPERTY_BASE(pos, BluEye_eventTriggerRightMouseUp_Parms), 0x0010000008000182, Z_Construct_UScriptStruct_FVector2D());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("CPP_Default_scale"), TEXT("1.000000"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Trigger a RIGHT MOUSE UP in the browser via a Vector2D"));
#endif
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UBluEye_NoRegister()
{
return UBluEye::StaticClass();
}
UClass* Z_Construct_UClass_UBluEye()
{
static UClass* OuterClass = NULL;
if (!OuterClass)
{
Z_Construct_UClass_UObject();
Z_Construct_UPackage__Script_Blu();
OuterClass = UBluEye::StaticClass();
if (!(OuterClass->ClassFlags & CLASS_Constructed))
{
UObjectForceRegistration(OuterClass);
OuterClass->ClassFlags |= 0x20900080;
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_CharKeyPress());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_CloseBrowser());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_ExecuteJS());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_ExecuteJSMethodWithParams());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_GetMaterialInstance());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_GetTexture());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_init());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_IsBrowserLoading());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_KeyDown());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_KeyPress());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_KeyUp());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_LoadURL());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_NavBack());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_NavForward());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_RawCharKeyPress());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_ReloadBrowser());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_ResizeBrowser());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_SpecialKeyPress());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_TriggerLeftClick());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_TriggerLeftMouseDown());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_TriggerLeftMouseUp());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_TriggerMouseMove());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_TriggerMouseWheel());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_TriggerRightClick());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_TriggerRightMouseDown());
OuterClass->LinkChild(Z_Construct_UFunction_UBluEye_TriggerRightMouseUp());
PRAGMA_DISABLE_DEPRECATION_WARNINGS
UProperty* NewProp_ScriptEventEmitter = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("ScriptEventEmitter"), RF_Public|RF_Transient|RF_MarkAsNative) UMulticastDelegateProperty(CPP_PROPERTY_BASE(ScriptEventEmitter, UBluEye), 0x0010000010080000, Z_Construct_UDelegateFunction_Blu_ScriptEvent__DelegateSignature());
UProperty* NewProp_TextureParameterName = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("TextureParameterName"), RF_Public|RF_Transient|RF_MarkAsNative) UNameProperty(CPP_PROPERTY_BASE(TextureParameterName, UBluEye), 0x0010000000000015);
UProperty* NewProp_BaseMaterial = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("BaseMaterial"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(BaseMaterial, UBluEye), 0x0010000000000005, Z_Construct_UClass_UMaterialInterface_NoRegister());
UProperty* NewProp_Height = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("Height"), RF_Public|RF_Transient|RF_MarkAsNative) UIntProperty(CPP_PROPERTY_BASE(Height, UBluEye), 0x0010000000000005);
UProperty* NewProp_Width = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("Width"), RF_Public|RF_Transient|RF_MarkAsNative) UIntProperty(CPP_PROPERTY_BASE(Width, UBluEye), 0x0010000000000005);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(bIsTransparent, UBluEye, bool);
UProperty* NewProp_bIsTransparent = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("bIsTransparent"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(bIsTransparent, UBluEye), 0x0010000000000005, CPP_BOOL_PROPERTY_BITMASK(bIsTransparent, UBluEye), sizeof(bool), true);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(bEnabled, UBluEye, bool);
UProperty* NewProp_bEnabled = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("bEnabled"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(bEnabled, UBluEye), 0x0010000000000005, CPP_BOOL_PROPERTY_BITMASK(bEnabled, UBluEye), sizeof(bool), true);
UProperty* NewProp_DefaultURL = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("DefaultURL"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(DefaultURL, UBluEye), 0x0010000000000005);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_CharKeyPress(), "CharKeyPress"); // 1720114840
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_CloseBrowser(), "CloseBrowser"); // 1443944086
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_ExecuteJS(), "ExecuteJS"); // 3896424227
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_ExecuteJSMethodWithParams(), "ExecuteJSMethodWithParams"); // 2784729437
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_GetMaterialInstance(), "GetMaterialInstance"); // 3939815410
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_GetTexture(), "GetTexture"); // 912088920
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_init(), "init"); // 1668392446
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_IsBrowserLoading(), "IsBrowserLoading"); // 4163191882
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_KeyDown(), "KeyDown"); // 3915154997
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_KeyPress(), "KeyPress"); // 336200321
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_KeyUp(), "KeyUp"); // 2695892105
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_LoadURL(), "LoadURL"); // 2536390581
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_NavBack(), "NavBack"); // 1096638336
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_NavForward(), "NavForward"); // 2904846886
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_RawCharKeyPress(), "RawCharKeyPress"); // 718012764
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_ReloadBrowser(), "ReloadBrowser"); // 3106267812
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_ResizeBrowser(), "ResizeBrowser"); // 2700804454
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_SpecialKeyPress(), "SpecialKeyPress"); // 2787689863
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_TriggerLeftClick(), "TriggerLeftClick"); // 1860866471
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_TriggerLeftMouseDown(), "TriggerLeftMouseDown"); // 1120655087
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_TriggerLeftMouseUp(), "TriggerLeftMouseUp"); // 2726371396
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_TriggerMouseMove(), "TriggerMouseMove"); // 1488487703
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_TriggerMouseWheel(), "TriggerMouseWheel"); // 2751107935
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_TriggerRightClick(), "TriggerRightClick"); // 602408020
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_TriggerRightMouseDown(), "TriggerRightMouseDown"); // 3754757475
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluEye_TriggerRightMouseUp(), "TriggerRightMouseUp"); // 1766705648
OuterClass->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = OuterClass->GetOutermost()->GetMetaData();
MetaData->SetValue(OuterClass, TEXT("BlueprintType"), TEXT("true"));
MetaData->SetValue(OuterClass, TEXT("ClassGroupNames"), TEXT("Blu"));
MetaData->SetValue(OuterClass, TEXT("IncludePath"), TEXT("BluEye.h"));
MetaData->SetValue(OuterClass, TEXT("IsBlueprintBase"), TEXT("true"));
MetaData->SetValue(OuterClass, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(NewProp_ScriptEventEmitter, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(NewProp_ScriptEventEmitter, TEXT("ToolTip"), TEXT("Javascript event emitter"));
MetaData->SetValue(NewProp_TextureParameterName, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(NewProp_TextureParameterName, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(NewProp_TextureParameterName, TEXT("ToolTip"), TEXT("Name of parameter to load UI texture into material"));
MetaData->SetValue(NewProp_BaseMaterial, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(NewProp_BaseMaterial, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(NewProp_BaseMaterial, TEXT("ToolTip"), TEXT("Material that will be instanced to load UI texture into it"));
MetaData->SetValue(NewProp_Height, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(NewProp_Height, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(NewProp_Height, TEXT("ToolTip"), TEXT("Height of the view resolution"));
MetaData->SetValue(NewProp_Width, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(NewProp_Width, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(NewProp_Width, TEXT("ToolTip"), TEXT("Width of the view resolution"));
MetaData->SetValue(NewProp_bIsTransparent, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(NewProp_bIsTransparent, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(NewProp_bIsTransparent, TEXT("ToolTip"), TEXT("Should this be rendered in game to be transparent?"));
MetaData->SetValue(NewProp_bEnabled, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(NewProp_bEnabled, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(NewProp_bEnabled, TEXT("ToolTip"), TEXT("Is this UI component current active?"));
MetaData->SetValue(NewProp_DefaultURL, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(NewProp_DefaultURL, TEXT("ModuleRelativePath"), TEXT("Public/BluEye.h"));
MetaData->SetValue(NewProp_DefaultURL, TEXT("ToolTip"), TEXT("The default URL this UI component will load"));
#endif
}
}
check(OuterClass->GetClass());
return OuterClass;
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UBluEye(Z_Construct_UClass_UBluEye, &UBluEye::StaticClass, TEXT("UBluEye"), false, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UBluEye);
UFunction* Z_Construct_UFunction_UBluJsonObj_getBooleanArray()
{
struct BluJsonObj_eventgetBooleanArray_Parms
{
FString index;
TArray<bool> ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("getBooleanArray"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventgetBooleanArray_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UArrayProperty(CPP_PROPERTY_BASE(ReturnValue, BluJsonObj_eventgetBooleanArray_Parms), 0x0010000000000580);
UProperty* NewProp_ReturnValue_Inner = new(EC_InternalUseOnlyConstructor, NewProp_ReturnValue, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, 0, 0x0000000000000000, 0, sizeof(bool), true);
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventgetBooleanArray_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Gets an Array of booleans for the key given"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluJsonObj_getBooleanValue()
{
struct BluJsonObj_eventgetBooleanValue_Parms
{
FString index;
bool ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("getBooleanValue"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventgetBooleanValue_Parms));
CPP_BOOL_PROPERTY_BITMASK_STRUCT(ReturnValue, BluJsonObj_eventgetBooleanValue_Parms, bool);
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(ReturnValue, BluJsonObj_eventgetBooleanValue_Parms), 0x0010000000000580, CPP_BOOL_PROPERTY_BITMASK(ReturnValue, BluJsonObj_eventgetBooleanValue_Parms), sizeof(bool), true);
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventgetBooleanValue_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Gets a Boolean value for the key given"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluJsonObj_getNestedObject()
{
struct BluJsonObj_eventgetNestedObject_Parms
{
FString index;
UBluJsonObj* ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("getNestedObject"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventgetNestedObject_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(ReturnValue, BluJsonObj_eventgetNestedObject_Parms), 0x0010000000000580, Z_Construct_UClass_UBluJsonObj_NoRegister());
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventgetNestedObject_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Gets a Nested JSON Object value for the key given"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluJsonObj_getNumArray()
{
struct BluJsonObj_eventgetNumArray_Parms
{
FString index;
TArray<float> ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("getNumArray"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventgetNumArray_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UArrayProperty(CPP_PROPERTY_BASE(ReturnValue, BluJsonObj_eventgetNumArray_Parms), 0x0010000000000580);
UProperty* NewProp_ReturnValue_Inner = new(EC_InternalUseOnlyConstructor, NewProp_ReturnValue, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(FObjectInitializer(), EC_CppProperty, 0, 0x0000000000000000);
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventgetNumArray_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Gets an Array of floats or numbers for the key given"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluJsonObj_getNumValue()
{
struct BluJsonObj_eventgetNumValue_Parms
{
FString index;
float ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("getNumValue"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventgetNumValue_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(ReturnValue, BluJsonObj_eventgetNumValue_Parms), 0x0010000000000580);
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventgetNumValue_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Gets a Numerical value for the key given"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluJsonObj_getStringArray()
{
struct BluJsonObj_eventgetStringArray_Parms
{
FString index;
TArray<FString> ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("getStringArray"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventgetStringArray_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UArrayProperty(CPP_PROPERTY_BASE(ReturnValue, BluJsonObj_eventgetStringArray_Parms), 0x0010000000000580);
UProperty* NewProp_ReturnValue_Inner = new(EC_InternalUseOnlyConstructor, NewProp_ReturnValue, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(FObjectInitializer(), EC_CppProperty, 0, 0x0000000000000000);
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventgetStringArray_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Gets an Array of strings for the key given"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluJsonObj_getStringValue()
{
struct BluJsonObj_eventgetStringValue_Parms
{
FString index;
FString ReturnValue;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("getStringValue"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventgetStringValue_Parms));
UProperty* NewProp_ReturnValue = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("ReturnValue"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(ReturnValue, BluJsonObj_eventgetStringValue_Parms), 0x0010000000000580);
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventgetStringValue_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Gets a String value for the key given"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluJsonObj_setBooleanValue()
{
struct BluJsonObj_eventsetBooleanValue_Parms
{
bool value;
FString index;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("setBooleanValue"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventsetBooleanValue_Parms));
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventsetBooleanValue_Parms), 0x0010000000000080);
CPP_BOOL_PROPERTY_BITMASK_STRUCT(value, BluJsonObj_eventsetBooleanValue_Parms, bool);
UProperty* NewProp_value = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("value"), RF_Public|RF_Transient|RF_MarkAsNative) UBoolProperty(FObjectInitializer(), EC_CppProperty, CPP_BOOL_PROPERTY_OFFSET(value, BluJsonObj_eventsetBooleanValue_Parms), 0x0010000000000082, CPP_BOOL_PROPERTY_BITMASK(value, BluJsonObj_eventsetBooleanValue_Parms), sizeof(bool), true);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Sets or Adds a Boolean value to this JSON object"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluJsonObj_setNestedObject()
{
struct BluJsonObj_eventsetNestedObject_Parms
{
UBluJsonObj* value;
FString index;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("setNestedObject"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventsetNestedObject_Parms));
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventsetNestedObject_Parms), 0x0010000000000080);
UProperty* NewProp_value = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("value"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(value, BluJsonObj_eventsetNestedObject_Parms), 0x0010000000000080, Z_Construct_UClass_UBluJsonObj_NoRegister());
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Sets or Adds a Nested JSON Object value to this JSON object"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluJsonObj_setNumValue()
{
struct BluJsonObj_eventsetNumValue_Parms
{
float value;
FString index;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("setNumValue"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventsetNumValue_Parms));
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventsetNumValue_Parms), 0x0010000000000080);
UProperty* NewProp_value = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("value"), RF_Public|RF_Transient|RF_MarkAsNative) UFloatProperty(CPP_PROPERTY_BASE(value, BluJsonObj_eventsetNumValue_Parms), 0x0010000000000082);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Sets or Adds a Numerical value to this JSON object"));
#endif
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UBluJsonObj_setStringValue()
{
struct BluJsonObj_eventsetStringValue_Parms
{
FString value;
FString index;
};
UObject* Outer=Z_Construct_UClass_UBluJsonObj();
static UFunction* ReturnFunction = NULL;
if (!ReturnFunction)
{
ReturnFunction = new(EC_InternalUseOnlyConstructor, Outer, TEXT("setStringValue"), RF_Public|RF_Transient|RF_MarkAsNative) UFunction(FObjectInitializer(), NULL, 0x04020401, 65535, sizeof(BluJsonObj_eventsetStringValue_Parms));
UProperty* NewProp_index = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("index"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(index, BluJsonObj_eventsetStringValue_Parms), 0x0010000000000080);
UProperty* NewProp_value = new(EC_InternalUseOnlyConstructor, ReturnFunction, TEXT("value"), RF_Public|RF_Transient|RF_MarkAsNative) UStrProperty(CPP_PROPERTY_BASE(value, BluJsonObj_eventsetStringValue_Parms), 0x0010000000000080);
ReturnFunction->Bind();
ReturnFunction->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = ReturnFunction->GetOutermost()->GetMetaData();
MetaData->SetValue(ReturnFunction, TEXT("Category"), TEXT("Blu"));
MetaData->SetValue(ReturnFunction, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
MetaData->SetValue(ReturnFunction, TEXT("ToolTip"), TEXT("Sets or Adds a String value to this JSON object"));
#endif
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UBluJsonObj_NoRegister()
{
return UBluJsonObj::StaticClass();
}
UClass* Z_Construct_UClass_UBluJsonObj()
{
static UClass* OuterClass = NULL;
if (!OuterClass)
{
Z_Construct_UClass_UObject();
Z_Construct_UPackage__Script_Blu();
OuterClass = UBluJsonObj::StaticClass();
if (!(OuterClass->ClassFlags & CLASS_Constructed))
{
UObjectForceRegistration(OuterClass);
OuterClass->ClassFlags |= 0x20100080;
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_getBooleanArray());
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_getBooleanValue());
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_getNestedObject());
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_getNumArray());
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_getNumValue());
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_getStringArray());
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_getStringValue());
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_setBooleanValue());
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_setNestedObject());
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_setNumValue());
OuterClass->LinkChild(Z_Construct_UFunction_UBluJsonObj_setStringValue());
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_getBooleanArray(), "getBooleanArray"); // 1493338020
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_getBooleanValue(), "getBooleanValue"); // 2592504616
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_getNestedObject(), "getNestedObject"); // 3991546015
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_getNumArray(), "getNumArray"); // 3292419894
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_getNumValue(), "getNumValue"); // 1932752527
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_getStringArray(), "getStringArray"); // 3414875131
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_getStringValue(), "getStringValue"); // 3954641223
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_setBooleanValue(), "setBooleanValue"); // 648236400
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_setNestedObject(), "setNestedObject"); // 3402231739
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_setNumValue(), "setNumValue"); // 3398514653
OuterClass->AddFunctionToFunctionMapWithOverriddenName(Z_Construct_UFunction_UBluJsonObj_setStringValue(), "setStringValue"); // 1679346739
OuterClass->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = OuterClass->GetOutermost()->GetMetaData();
MetaData->SetValue(OuterClass, TEXT("BlueprintType"), TEXT("true"));
MetaData->SetValue(OuterClass, TEXT("ClassGroupNames"), TEXT("Blu"));
MetaData->SetValue(OuterClass, TEXT("IncludePath"), TEXT("BluJsonObj.h"));
MetaData->SetValue(OuterClass, TEXT("IsBlueprintBase"), TEXT("true"));
MetaData->SetValue(OuterClass, TEXT("ModuleRelativePath"), TEXT("Public/BluJsonObj.h"));
#endif
}
}
check(OuterClass->GetClass());
return OuterClass;
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UBluJsonObj(Z_Construct_UClass_UBluJsonObj, &UBluJsonObj::StaticClass, TEXT("UBluJsonObj"), false, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UBluJsonObj);
UPackage* Z_Construct_UPackage__Script_Blu()
{
static UPackage* ReturnPackage = NULL;
if (!ReturnPackage)
{
ReturnPackage = CastChecked<UPackage>(StaticFindObjectFast(UPackage::StaticClass(), NULL, FName(TEXT("/Script/Blu")), false, false));
ReturnPackage->SetPackageFlags(PKG_CompiledIn | 0x00000000);
FGuid Guid;
Guid.A = 0x1F88CDD9;
Guid.B = 0xA696BD4A;
Guid.C = 0x00000000;
Guid.D = 0x00000000;
ReturnPackage->SetGuid(Guid);
Z_Construct_UDelegateFunction_Blu_ScriptEvent__DelegateSignature();
}
return ReturnPackage;
}
#endif
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| 68.399353 | 501 | 0.80906 | [
"object"
] |
f4db0eaf31f974aa28fa737f720318908c0a31cc | 925 | cpp | C++ | Brio/src/Brio/Renderer/Texture.cpp | Ckyre/brio | 77a41a2a9d16c20542b60b2425e44525d3f4eef8 | [
"Apache-2.0"
] | null | null | null | Brio/src/Brio/Renderer/Texture.cpp | Ckyre/brio | 77a41a2a9d16c20542b60b2425e44525d3f4eef8 | [
"Apache-2.0"
] | null | null | null | Brio/src/Brio/Renderer/Texture.cpp | Ckyre/brio | 77a41a2a9d16c20542b60b2425e44525d3f4eef8 | [
"Apache-2.0"
] | null | null | null | #include "brpch.h"
#include "Texture.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLTexture.h"
namespace Brio
{
Ref<Texture2D> Texture2D::Create(const std::string& path)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: BR_CORE_ASSERT(false, "No graphics API selected"); return nullptr;
case RendererAPI::API::OpenGL: return std::make_shared<OpenGLTexture2D>(path);
}
BR_CORE_ASSERT(false, "No graphics API selected");
return nullptr;
}
Ref<TextureCube> TextureCube::Create(const std::string& partialPath, const std::vector<std::string> facesFilesName)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: BR_CORE_ASSERT(false, "No graphics API selected"); return nullptr;
case RendererAPI::API::OpenGL: return std::make_shared<OpenGLTextureCube>(partialPath, facesFilesName);
}
BR_CORE_ASSERT(false, "No graphics API selected");
return nullptr;
}
} | 28.90625 | 116 | 0.72973 | [
"vector"
] |
f4e08e35c9c471d7d470ef43858f1ae648adc292 | 864 | hpp | C++ | include/aikido/robot/InverseKinematics.hpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | null | null | null | include/aikido/robot/InverseKinematics.hpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | null | null | null | include/aikido/robot/InverseKinematics.hpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | null | null | null | #ifndef AIKIDO_ROBOT_IK_INVERSEKINEMATICS_HPP_
#define AIKIDO_ROBOT_IK_INVERSEKINEMATICS_HPP_
namespace aikido {
namespace robot {
/// Interface for IK solvers used with the Robot class.
class InverseKinematics
{
public:
/// Returns a set of IK solutions for the given pose. Note that *at most*
/// \c maxSolutions solutions are returned, but fewer may be (and possibly
/// none if solving fails).
///
/// \param targetPose End-effector pose to solve inverse kinematics for.
/// \param maxSolutions Upper limit on how many solutions to find and return.
/// \return solution configurations that reach the target pose.
virtual std::vector<Eigen::VectorXd> getSolutions(
const Eigen::Isometry3d& targetPose, const size_t maxSolutions) const = 0;
};
} // namespace robot
} // namespace aikido
#endif // AIKIDO_ROBOT_IK_INVERSEKINEMATICS_HPP_
| 33.230769 | 80 | 0.756944 | [
"vector"
] |
f4e29a5da25e203aaddd065763ed8cead0c1ace1 | 537 | hh | C++ | userFiles/simu/io/opti/functions/OptiGeneration.hh | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null | userFiles/simu/io/opti/functions/OptiGeneration.hh | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null | userFiles/simu/io/opti/functions/OptiGeneration.hh | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null | /*!
* ''author Nicolas Van der Noot
* ''file OptiResults.hh
* ''brief OptiResults
*/
#ifndef _OPTI_GENERATION_HH_
#define _OPTI_GENERATION_HH_
#include "OptiInputs.hh"
#include <vector>
/*! ''brief Inputs of the optimization: results generated after an optimization
*/
class OptiGeneration: public OptiInputs
{
public:
OptiGeneration();
virtual ~OptiGeneration();
virtual void set_opti();
void set_optiParams(std::vector<double> values) { optiParams = values; }
private:
std::vector<double> optiParams;
};
#endif
| 17.9 | 79 | 0.726257 | [
"vector"
] |
f4ec611124c9d47a1825b5ba03976ea69f795d61 | 1,284 | hpp | C++ | inc/optimization.hpp | samcoppini/xrfc | 34055b3f8673dac17f9b59de90d2eb17163f25f1 | [
"BSL-1.0"
] | null | null | null | inc/optimization.hpp | samcoppini/xrfc | 34055b3f8673dac17f9b59de90d2eb17163f25f1 | [
"BSL-1.0"
] | null | null | null | inc/optimization.hpp | samcoppini/xrfc | 34055b3f8673dac17f9b59de90d2eb17163f25f1 | [
"BSL-1.0"
] | null | null | null | #pragma once
#include "xrf-chunk.hpp"
namespace xrf {
/**
* Performs chunk-level optimizations on the provided list of chunks. This
* looks at each chunk individually and tries to optimize it as best as it can,
* by performing optimizations like eliminating unnecessary swap operations, or
* setting a known jump location for the chunk if it is known.
*
* @param chunks
* The list of chunks to optimize.
*
* @return
* An optimized version of the chunks.
*/
std::vector<Chunk> optimizeChunks(const std::vector<Chunk> &chunks);
/**
* Performs program-level optimizations on the provided list of chunks. This
* will do things to look at flows of chunks to condense chunks. So, for
* instance, if there is a series of five chunks that each add 2 to the second
* value of the stack, it will condense it to add 10 to the second value of the
* stack and jump to the chunk following those chunks.
*
* @param chunks
* The list of chunks to optimize. It is expected that these chunks have
* already gone through chunk-level optimizations, otherwise the program
* level optimizations will not work.
*
* @return
* An optimized version of the chunks.
*/
std::vector<Chunk> optimizeProgram(const std::vector<Chunk> &chunks);
} // namespace xrf
| 32.923077 | 79 | 0.725857 | [
"vector"
] |
f4f824405024cd0708e7a07ad025147bb167d41e | 56,465 | cpp | C++ | src/LifeCycle.cpp | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | 11 | 2017-06-06T23:02:48.000Z | 2021-08-17T20:13:05.000Z | src/LifeCycle.cpp | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | 1 | 2017-06-06T23:08:05.000Z | 2017-06-07T09:28:08.000Z | src/LifeCycle.cpp | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | null | null | null | /*
Author: Remi Matthey-Doret
MIT License
Copyright (c) 2017 Remi Matthey-Doret
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.
*/
void LifeCycle::BREEDING_SELECTION_DISPERSAL(Pop& Offspring_pop, Pop& Parent_pop)
{
//if (GP->CurrentGeneration >= 0) std::cout << "Enters in 'BREEDING_SELECTION_DISPERSAL'\n";
#ifdef DEBUG
std::cout << "Enters in 'BREEDING_SELECTION_DISPERSAL'\n";
#endif
/*
std::cout << "Parent_pop...";
SSP->T8Tree.printT8IDs(Parent_pop);
std::cout << "Offspring_pop...";
SSP->T8Tree.printT8IDs(Offspring_pop);
SSP->T8Tree.printT8IDs();
*/
//std::cout << "\nParent_pop.getPatch(0).getInd(2).getHaplo(0).T8ID = " << Parent_pop.getPatch(0).getInd(2).getHaplo(0).T8ID << "\n";
/*
std::cout << "patchSize when entering LifeCycle::BREEDING_SELECTION_DISPERSAL: ";
for (auto& e : SSP->patchSize) std::cout << e << " ";
std::cout << "\n";
*/
SSP->T56_memManager.setGenerationInfo();
if (SSP->whenDidExtinctionOccur == -1 && SSP->Gmap.T8_nbLoci > 0)
{
SSP->T8Tree.announceStartOfGeneration();
}
//uint32_t nbSwaps = 0;
//std::cout << "\nBEGIN: Offspring_pop.getPatch(0).getInd(2).getHaplo(0).T4ID = " << Offspring_pop.getPatch(0).getInd(2).getHaplo(0).T4ID << "\n";
//std::cout << "BEGIN: Parent_pop.getPatch(0).getInd(2).getHaplo(0).T4ID = " << Parent_pop.getPatch(0).getInd(2).getHaplo(0).T4ID << "\n";
// Calculate fitness
//SSP->simTracker.prepareT1SitesForFitness(Parent_pop);
if (SSP->isAnySelection && SSP->selectionOn != 1) Parent_pop.CalculateFitnesses(); // also set Index First Male; Will compute fitness only if it is needed
// 0. ReSet Dispersal info if patch size may vary and // 2. Compute patch size for next generation
const std::vector<int>& patchSizeNextGeneration = SSP->dispersalData.setBackwardMigrationIfNeededAndGetNextGenerationPatchSizes(Parent_pop.CumSumFits);
assert(patchSizeNextGeneration.size() == GP->PatchNumber);
//std::cout << "patchSizeNextGeneration[0] = " << patchSizeNextGeneration[0] << "\n";
//std::cout << "SSP->patchSize[0] = " << SSP->patchSize[0] << "\n";
//SSP->dispersalData.print();
// 4.5 Genealogy
if (SSP->genealogy.isTime())
SSP->genealogy.startNewGeneration();
// Loop through each patch and through each individual offspring to be created
//#pragma omp parallel for
if (SSP->SwapInLifeCycle && SSP->selectionOn == 0) // no selection on viability
{
findAllParents(Parent_pop, patchSizeNextGeneration); // set PD (of class ParentsData)
} else
{
PD.resizeCloneInfo(patchSizeNextGeneration);
}
// Create offsprings
SSP->TotalpatchSize = 0;
for (int patch_index = 0 ; patch_index < GP->PatchNumber ; ++patch_index)
{
SSP->TotalpatchSize += patchSizeNextGeneration[patch_index];
// Prepare Next Generation CumSumFits and Index First Male.
//Offspring_pop.prepareNextGenerationAndIndexFirstMale(patch_index, patchSizeNextGeneration);
for (int offspring_index = 0 ; offspring_index < patchSizeNextGeneration[patch_index] ; ++offspring_index)
{
//std::cout << "Creating offspring " << offspring_index << " of patch " << patch_index << "...\n";
//std::cout << "patchSizeNextGeneration["<<patch_index<<"] = " << patchSizeNextGeneration[patch_index] << "\n";
//std::cout << "LifeCycle line 74 offspring_index = "<<offspring_index<<"\n";
//std::cout << " patchSizeNextGeneration["<<patch_index<<"] = " << patchSizeNextGeneration[patch_index] << " GP->PatchNumber = "<<GP->PatchNumber<<"\n";
// Get offspring haplotypes
Individual& Offspring = Offspring_pop.getPatch(patch_index).getInd(offspring_index);
Haplotype& Offspring_mHaplo = Offspring.getHaplo(0); // maternally inherited haplotype
Haplotype& Offspring_fHaplo = Offspring.getHaplo(1); // paternally inherited haplotype
//std::cout << "Before: Offspring_mHaplo.T4ID = " << Offspring_mHaplo.T4ID << "\n";
//std::cout << "Offspring_fHaplo.T4ID = " << Offspring_fHaplo.T4ID << "\n";
//std::cout << "\n\n\n\n\n\nBegin Offspring_mHaplo.nbT56muts() = "<< Offspring_mHaplo.nbT56muts() << "\n";
//std::cout << "Begin Offspring_fHaplo.nbT56muts() = "<< Offspring_fHaplo.nbT56muts() << "\n";
redoOffspring:
// Get parents
auto&& CD = SSP->SwapInLifeCycle ? PD.couples[patch_index][offspring_index] : findCouple(Parent_pop,patch_index, offspring_index, PD, patchSizeNextGeneration[patch_index]);
auto& mother = Parent_pop.getPatch(CD.mother.patch).getInd(CD.mother.ind);
auto& father = Parent_pop.getPatch(CD.father.patch).getInd(CD.father.ind);
/*
std::cout << "Sample mother " << CD.mother.patch << ":" << CD.mother.ind << ":" << CD.mother.segregationIndex << "\n";
std::cout << "Sample father " << CD.father.patch << ":" << CD.father.ind << ":" << CD.father.segregationIndex << "\n";
*/
//std::cout << "mother.getHaplo0(0).T4ID = " << mother.getHaplo(0).T4ID << "\n";
//std::cout << "mother.getHaplo0(1).T4ID = " << mother.getHaplo(1).T4ID << "\n";
/*
std::cout << "mother.getHaplo0(0).T8ID = " << mother.getHaplo(0).T8ID << "\n";
std::cout << "mother.getHaplo0(1).T8ID = " << mother.getHaplo(1).T8ID << "\n";
std::cout << "father.getHaplo0(0).T8ID = " << father.getHaplo(0).T8ID << "\n";
std::cout << "father.getHaplo0(1).T8ID = " << father.getHaplo(1).T8ID << "\n";
std::cout << "Generation = " << GP->CurrentGeneration << "\n";
*/
//std::cout << "Begin mother.getHaplo(CD.mother.segregationIndex).nbT56muts() = "<< mother.getHaplo(CD.mother.segregationIndex).nbT56muts() << "\n";
//std::cout << "Begin father.getHaplo(CD.father.segregationIndex).nbT56muts() = "<< father.getHaplo(CD.father.segregationIndex).nbT56muts() << "\n";
//std::cout << "M: " << CD.mother.patch << " " << CD.mother.ind << " " << CD.mother.segregationIndex << " | " << CD.father.patch << " " << CD.father.ind << " " << CD.father.segregationIndex << "\n";
// Clear T56 vectors
if (SSP->Gmap.T56sel_nbLoci || SSP->Gmap.T56ntrl_nbLoci)
{
Offspring_mHaplo.clearT56Alleles();
Offspring_fHaplo.clearT56Alleles();
}
if (PD.shouldIClone(patch_index, offspring_index))
{
assert(CD.mother.patch == CD.father.patch);
assert(CD.mother.ind == CD.father.ind);
assert(CD.mother.segregationIndex != CD.father.segregationIndex);
assert(CD.mother.nbRecs == 0);
assert(CD.father.nbRecs == 0);
std::vector<uint32_t> breakpoints = {std::numeric_limits<uint32_t>::max()};
if (SSP->SwapInLifeCycle && CD.mother.nbRecs == 0 && PD.isLastOffspring(CD.mother, patch_index, offspring_index,0))
{
//nbSwaps+=2;
//std::cout << "swap both\n";
assert(PD.isLastOffspring(CD.father, patch_index, offspring_index,1));
reproduceThroughSwap(mother, Offspring_mHaplo, CD.mother, patch_index);
reproduceThroughSwap(father, Offspring_fHaplo, CD.father, patch_index);
} else
{
//std::cout << "Copy both mother and father\n";
reproduceThroughCopy(
mother,
Offspring_mHaplo,
CD.mother,
patch_index
);
reproduceThroughCopy(
father,
Offspring_fHaplo,
CD.father,
patch_index
);
}
} else
{
// Mother
if (SSP->SwapInLifeCycle && CD.mother.nbRecs == 0 && PD.isLastOffspring(CD.mother, patch_index, offspring_index, 0))
{
//nbSwaps++;
//std::cout << "swaps mother\n";
reproduceThroughSwap(mother, Offspring_mHaplo, CD.mother, patch_index);
} else
{
//std::cout << "copies mother\n";
reproduceThroughCopy(
mother,
Offspring_mHaplo,
CD.mother,
patch_index
);
}
// Father
if (SSP->SwapInLifeCycle && CD.father.nbRecs == 0 && PD.isLastOffspring(CD.father, patch_index, offspring_index,1))
{
//nbSwaps++;
//std::cout << "swaps father\n";
reproduceThroughSwap(father, Offspring_fHaplo, CD.father, patch_index);
} else
{
//std::cout << "copies father\n";
reproduceThroughCopy(
father,
Offspring_fHaplo,
CD.father,
patch_index
);
}
} // end of if else should I clone
// Fitness for next generation. Set fitness to zero if the habitat has changed. Could do better here as not all of them will necessarily have habitat specific selection
if (SSP->Habitats[patch_index] != SSP->Habitats[CD.mother.patch])
{
if (SSP->T1_isLocalSelection && SSP->T1_isMultiplicitySelection)
{
Offspring_mHaplo.setAllW_T1(-1.0);
}
if (SSP->T2_isLocalSelection && SSP->T2_isSelection)
{
Offspring_mHaplo.setAllW_T2(-1.0);
}
if (SSP->T56_isLocalSelection && SSP->T56_isMultiplicitySelection)
{
Offspring_mHaplo.setAllW_T56(-1.0);
}
}
if (SSP->Habitats[patch_index] != SSP->Habitats[CD.father.patch])
{
if (SSP->T1_isLocalSelection && SSP->T1_isMultiplicitySelection)
{
Offspring_fHaplo.setAllW_T1(-1.0);
}
if (SSP->T2_isLocalSelection && SSP->T2_isSelection)
{
Offspring_fHaplo.setAllW_T2(-1.0);
}
if (SSP->T56_isLocalSelection && SSP->T56_isMultiplicitySelection)
{
Offspring_fHaplo.setAllW_T56(-1.0);
}
}
//std::cout << "just before mutation Offspring_mHaplo.nbT56muts() = "<< Offspring_mHaplo.nbT56muts() << "\n";
//std::cout << "just before mutation Offspring_fHaplo.nbT56muts() = "<< Offspring_fHaplo.nbT56muts() << "\n";
Mutate(
Offspring_mHaplo,
SSP->Habitats[patch_index] // needs the habitat to adjust the fitness
);
Mutate(
Offspring_fHaplo,
SSP->Habitats[patch_index] // needs the habitat to adjust the fitness
);
//std::cout << "line 235: Offspring_mHaplo.T4ID = " << Offspring_mHaplo.T4ID << "\n";
//std::cout << "just after mutation Offspring_mHaplo.nbT56muts() = "<< Offspring_mHaplo.nbT56muts() << "\n";
//std::cout << "just after mutation Offspring_fHaplo.nbT56muts() = "<< Offspring_fHaplo.nbT56muts() << "\n";
// Selection on viability
if (SSP->selectionOn != 0)
{
double fitness = Offspring_pop.getPatch(patch_index).getInd(offspring_index).CalculateFitness(patch_index);
if (GP->rngw.uniform_real_distribution(1.0) > fitness)
{
CD = findCouple(Parent_pop, patch_index, offspring_index, PD, patchSizeNextGeneration[patch_index]); // Will modify cloneInfo too.
if (SSP->SwapInLifeCycle)
{
PD.couples[patch_index][offspring_index] = CD;
}
goto redoOffspring;
}
}
SSP->T56_memManager.doStuff(Offspring_mHaplo);
SSP->T56_memManager.doStuff(Offspring_fHaplo);
// 4.5 Genealogy. Will do something only if the last isTime was true
SSP->genealogy.addOffspringIfIsTime(patch_index, offspring_index, CD.mother.patch, CD.mother.ind, CD.father.patch, CD.father.ind);
//std::cout << "End Offspring_mHaplo.nbT56muts() = "<< Offspring_mHaplo.nbT56muts() << "\n";
//std::cout << "End Offspring_fHaplo.nbT56muts() = "<< Offspring_fHaplo.nbT56muts() << "\n";
//std::cout << "Begin mother.getHaplo(CD.mother.segregationIndex).nbT56muts() = "<< mother.getHaplo(CD.mother.segregationIndex).nbT56muts() << "\n";
//std::cout << "Begin father.getHaplo(CD.father.segregationIndex).nbT56muts() = "<< father.getHaplo(CD.father.segregationIndex).nbT56muts() << "\n\n\n\n\n";
}
}
// 4.5 Genealogy. Will do something only if the last isTime was true
//std::cout << "line 184\n";
SSP->genealogy.printBufferIfIsTime();
//std::cout << "line 186\n";
// Check if species is extinct and set patch size
if (SSP->fecundityForFitnessOfOne != -1.0)
{
assert(SSP->whenDidExtinctionOccur == -1); // assert it has nt gone extinct yet
bool didGetExtinct = true;
for (int patch_index = 0 ; patch_index < GP->PatchNumber ; ++patch_index)
{
SSP->patchSize[patch_index] = patchSizeNextGeneration[patch_index];
if (patchSizeNextGeneration[patch_index] > 0)
{
didGetExtinct = false;
}
}
if (didGetExtinct)
{
SSP->whenDidExtinctionOccur = GP->CurrentGeneration;
}
}
//std::cout << "END0: Offspring_pop.getPatch(0).getInd(2).getHaplo(0).T4ID = " << Offspring_pop.getPatch(0).getInd(2).getHaplo(0).T4ID << "\n";
//std::cout << "END0: Parent_pop.getPatch(0).getInd(2).getHaplo(0).T4ID = " << Parent_pop.getPatch(0).getInd(2).getHaplo(0).T4ID << "\n";
if (SSP->whenDidExtinctionOccur == -1 && SSP->Gmap.T4_nbLoci > 0)
{
SSP->T4Tree.simplify_ifNeeded(Offspring_pop);
}
if (SSP->whenDidExtinctionOccur == -1 && SSP->Gmap.T8_nbLoci > 0)
{
SSP->T8Tree.announceEndOfGeneration();
}
if (SSP->whenDidExtinctionOccur == -1 && SSP->Gmap.T56_nbLoci)
{
Offspring_pop.toggleT56MutationsIfNeeded();
}
/*
std::cout << "patchSize when Exiting LifeCycle::BREEDING_SELECTION_DISPERSAL: ";
for (auto& e : SSP->patchSize) std::cout << e << " ";
std::cout << "\n";
*/
//std::cout << "nbSwaps = " << nbSwaps << "\n";
}
void LifeCycle::reproduceThroughSwap(Individual& parent, Haplotype& offspringHaplotype, HaplotypeData& parentHaploData, int& patch_index)
{
//std::cout << "swap\n";
auto& parentalHaplo = parent.getHaplo(parentHaploData.segregationIndex);
auto parentalT4ID = parentalHaplo.T4ID; // only used for T4
auto parentalT8ID = parentalHaplo.T8ID; // only used for T8
parentalHaplo.swap(offspringHaplotype);
if (SSP->Gmap.T4_nbLoci > 0)
{
//std::cout <<"\tLIFECYCLE - CLONING!!! b = NA: SSP->Gmap.T4_nbLoci = "<<SSP->Gmap.T4_nbLoci<<"\n";
std::vector<uint32_t> RecPos = {std::numeric_limits<uint32_t>::max()};
offspringHaplotype.T4ID = SSP->T4Tree.addHaplotype(RecPos, {parentalT4ID, std::numeric_limits<std::uint32_t>::max()}, patch_index);
}
if (SSP->Gmap.T8_nbLoci > 0)
{
std::vector<uint32_t> RecPos = {std::numeric_limits<uint32_t>::max()};
offspringHaplotype.dealWithT8Info(SSP->T8Tree.addOffspring(parentalT8ID, parentalT8ID, RecPos));
}
}
/*int LifeCycle::recombination_nbRecs()
{
#ifdef CALLENTRANCEFUNCTIONS
std::cout << "Enters in 'recombination_nbRecs'\n";
#endif
int nbRecs;
if (SSP->TotalRecombinationRate != 0)
{
nbRecs = SSP->rpois_nbRecombination(GP->rngw.getRNG()); // For the moment does not allow variation in recombination rate.
} else
{
nbRecs = 0;
}
return nbRecs;
}*/
void LifeCycle::recombination_RecPositions(int& nbRecs, Individual& parent)
{
#ifdef CALLENTRANCEFUNCTIONS
std::cout << "Enters in 'recombination_RecPositions'\n";
#endif
// Find positions (here a position is a separation between bit or between a bit and a byte or anything of interest) where recombination occurs
if (nbRecs == 0)
{
recombination_breakpoints.resize(1);
recombination_breakpoints[0] = std::numeric_limits<uint32_t>::max();
} else
{
recombination_breakpoints.resize(0);
//recombination_breakpoints.reserve(nbRecs+1);
//std::cout << "nbRecs = "<< nbRecs << std::endl;
std::vector<int> RecPositions;
RecPositions.reserve(nbRecs);
for (int i = 0 ; i < nbRecs ; i++)
{
RecPositions.push_back(SSP->geneticSampler.get_recombinationPosition());
}
/*
while(true)
{
if (SSP->RecombinationRate.size() == 1) // Constant value
{
RecPosition = SSP->runiform_int_ForRecPos(GP->rngw.getRNG()); // is bounded between 0 and size - 1.
} else // Not constant
{
assert(SSP->RecombinationRate.size() == SSP->Gmap.TotalNbLoci - 1);
rnd = SSP->runiform_double_ForRecPos(GP->rngw.getRNG()); // is bounded between 0 and total_recombinationRate.
// binary search SSP->RecombinationRate must be cumulative
RecPosition = distance(
SSP->RecombinationRate.begin(),
std::upper_bound(
SSP->RecombinationRate.begin(),
SSP->RecombinationRate.end(),
rnd
)
);
}
assert(RecPosition >= 0 && RecPosition < SSP->Gmap.TotalNbLoci - 1);
if (SSP->recRateOnMismatch_bool)
{
int fromT1Locus = std::max(0,RecPosition - SSP->recRateOnMismatch_halfWindow);
int toT1Locus = std::min(SSP->Gmap.T1_nbLoci,RecPosition + SSP->recRateOnMismatch_halfWindow);
//std::cout << fromT1Locus << " " << toT1Locus << " | ";
double sumAtExponentTerm = 0.0;
for (int T1Locus = fromT1Locus ; T1Locus < toT1Locus ; T1Locus++)
{
if (parent.getHaplo(0).getT1_Allele(T1Locus) != parent.getHaplo(1).getT1_Allele(T1Locus))
{
sumAtExponentTerm += 1 / abs(T1Locus - RecPosition);
}
}
double probabilityToKeepRecEvent = exp(SSP->recRateOnMismatch_factor * sumAtExponentTerm);
assert(probabilityToKeepRecEvent >= 0.0 & probabilityToKeepRecEvent <= 1.0);
//std::cout << "probabilityToKeepRecEvent = " << probabilityToKeepRecEvent << std::endl;
if (probabilityToKeepRecEvent > GP->rngw.uniform_real_distribution(1.0));
{
RecPositions.push_back(RecPosition);
break;
} // else keep looping over the while(true) loop
} else
{
RecPositions.push_back(RecPosition);
break;
}
}*/
// sort positions
sort( RecPositions.begin(), RecPositions.end() );
// Keep only odd number of recombinations
assert(RecPositions.size() == nbRecs);
int nbRepeats = 1;
for (int i = 1 ; i < RecPositions.size() ; i++)
{
if (RecPositions[i-1] == RecPositions[i])
{
nbRepeats++;
} else
{
if (nbRepeats % 2)
{
recombination_breakpoints.push_back(RecPositions[i-1]);
}
nbRepeats = 1;
}
}
if (nbRepeats % 2)
{
//std::cout << RecPositions.back() << "\n";
assert(RecPositions.back() >= 0 && RecPositions.back() < SSP->Gmap.TotalNbLoci);
recombination_breakpoints.push_back(RecPositions.back());
}
// Add segregation
//if (SSP->ChromosomeBoundaries.size() != 0) assert(SSP->ChromosomeBoundaries.back() != std::numeric_limits<uint32_t>::max());
//if (breakpoints.size()!=0) assert(breakpoints.back() != std::numeric_limits<uint32_t>::max());
/*
for (int b : SSP->ChromosomeBoundaries)
{
if (GP->rngw.get_1b())
{
recombination_breakpoints.insert(
std::upper_bound(recombination_breakpoints.begin(), recombination_breakpoints.end(), b),
b
);
}
}
*/
// add upper bound
recombination_breakpoints.push_back(std::numeric_limits<uint32_t>::max());
}
}
void LifeCycle::copyOver(Individual& parent, Haplotype& TransmittedChrom, int segregationIndex)
{
assert(segregationIndex == 0 || segregationIndex == 1 );
#ifdef CALLENTRANCEFUNCTIONS
std::cout << "Enters in 'copyOver'\n";
#endif
if (recombination_breakpoints.size()==1)
{
//if (GP->CurrentGeneration >= 50) std::cout << "parent.getHaplo(segregationIndex).getW_T1(0) = " << parent.getHaplo(segregationIndex).getW_T1(0) << "\n";
TransmittedChrom = parent.getHaplo(segregationIndex);
//if (GP->CurrentGeneration >= 50) std::cout << "TransmittedChrom.getW_T1(0) = " << TransmittedChrom.getW_T1(0) << "\n";
} else if (recombination_breakpoints.size()>1)
{
//std::cout << "breakpoints.size() " << breakpoints.size() << "\n";
#ifdef DEBUG
long long Safety_T1_Absolutefrom = std::numeric_limits<uint32_t>::max();
long long Safety_T1_Absoluteto = -1;
long long Safety_T2_Absolutefrom = std::numeric_limits<uint32_t>::max();
long long Safety_T2_Absoluteto = -1;
long long Safety_T3_Absolutefrom = std::numeric_limits<uint32_t>::max();
long long Safety_T3_Absoluteto = -1;
long long Safety_T4_Absolutefrom = std::numeric_limits<uint32_t>::max();
long long Safety_T4_Absoluteto = -1;
long long Safety_T56ntrl_Absolutefrom = std::numeric_limits<uint32_t>::max();
long long Safety_T56ntrl_Absoluteto = -1;
long long Safety_T56sel_Absolutefrom = std::numeric_limits<uint32_t>::max();
long long Safety_T56sel_Absoluteto = -1;
#endif
uint32_t T1_from = 0;
uint32_t T2_from = 0;
uint32_t T3_from = 0;
uint32_t T4_from = 0;
uint32_t T56ntrl_from = 0;
uint32_t T56sel_from = 0;
uint32_t T1_to = 0;
uint32_t T2_to = 0;
uint32_t T3_to = 0;
uint32_t T4_to = 0;
uint32_t T56ntrl_to = 0;
uint32_t T56sel_to = 0;
uint32_t fitnessMapIndexFrom = 0;
int haplo_index = segregationIndex; // There is really no reason for copying segregationIndex. I could just use segregationIndex all the way through...but he.... whatever!
/*std::cout << "\t";
for (auto& b : breakpoints)
std::cout << b << " ";
std::cout << std::endl;*/
for (auto b : recombination_breakpoints)
{
// Get positions for the two traits
if (b == std::numeric_limits<uint32_t>::max())
{
// Copy is over the range [from, to)
T1_to = SSP->Gmap.T1_nbLoci;
T2_to = SSP->Gmap.T2_nbLoci;
T3_to = SSP->Gmap.T3_nbLoci;
T4_to = SSP->Gmap.T4_nbLoci;
T56ntrl_to = SSP->Gmap.T56ntrl_nbLoci;
T56sel_to = SSP->Gmap.T56sel_nbLoci;
b = SSP->Gmap.TotalNbLoci - 1;
} else
{
assert(b >= 0);
// because copy is over the range [from, to) and if recombination happens at position 4, then the 4th element belongs to the previous stretch of DNA while the 5th element belongs to the next stretch of DNA.
T1_to = SSP->Gmap.FromLocusToNextT1Locus(b);
T2_to = SSP->Gmap.FromLocusToNextT2Locus(b);
T3_to = SSP->Gmap.FromLocusToNextT3Locus(b);
T4_to = SSP->Gmap.FromLocusToNextT4Locus(b);
T56ntrl_to = SSP->Gmap.FromLocusToNextT56ntrlLocus(b);
T56sel_to = SSP->Gmap.FromLocusToNextT56selLocus(b);
}
#ifdef DEBUG
assert(T1_to <= SSP->Gmap.T1_nbLoci);
assert(T2_to <= SSP->Gmap.T2_nbLoci);
assert(T3_to <= SSP->Gmap.T3_nbLoci);
assert(T4_to <= SSP->Gmap.T4_nbLoci);
assert(T56ntrl_to <= SSP->Gmap.T56ntrl_nbLoci);
assert(T56sel_to <= SSP->Gmap.T56sel_nbLoci);
#endif
//////////////////
// Set Fitnesses//
//////////////////
if (SSP->T1_isMultiplicitySelection || SSP->T2_isSelection || SSP->T56_isMultiplicitySelection)
{
//// Find from to and what to recompute if anything
int fitnessMapIndexToRecompute;
int fitnessMapIndexTo;
// Before
int fitnessMapIndexBefore = SSP->FromLocusToFitnessMapIndex[b];
// After
int fitnessMapIndexAfter;
if (b == SSP->Gmap.TotalNbLoci-1)
{
fitnessMapIndexAfter = SSP->NbElementsInFitnessMap;
assert(SSP->FromLocusToFitnessMapIndex[b]+1 == fitnessMapIndexAfter);
} else
{
fitnessMapIndexAfter = SSP->FromLocusToFitnessMapIndex[b+1];
}
// Figure out if there is a need to recompute a fitnessMap value (if the crossover happened in between two fitnessMapIndex, then there is no need to recompute anything)
if (fitnessMapIndexBefore == fitnessMapIndexAfter && fitnessMapIndexBefore >= fitnessMapIndexFrom) // ' && fitnessMapIndexBefore >= fitnessMapIndexFrom' is actually not needed normally
{
fitnessMapIndexToRecompute = fitnessMapIndexBefore; // Must force recalculation of fitness
assert(b < SSP->Gmap.TotalNbLoci-1);
} else
{
fitnessMapIndexToRecompute = -1; // no need to recompute fitness
}
// Figure out end of things to copy over (fitnessMapIndexTo, excluded)
fitnessMapIndexTo = fitnessMapIndexBefore + 1; // excluded. (fitnessMapIndexBefore + 1 will rarely equal fitnessMapIndexAfter but it can.)
// Figure out beginning of things to copy over (fitnessMapIndexFrom, included)
assert(fitnessMapIndexFrom <= fitnessMapIndexTo);
assert(fitnessMapIndexToRecompute == -1 || (fitnessMapIndexToRecompute >= fitnessMapIndexFrom && fitnessMapIndexToRecompute < fitnessMapIndexTo));
/*if (fitnessMapIndexFrom > fitnessMapIndexTo)
{
assert(fitnessMapIndexFrom == fitnessMapIndexTo + 1);
fitnessMapIndexFrom = fitnessMapIndexAfter;
}*/
//// Set fitnesses for each type of trait
if (fitnessMapIndexFrom < fitnessMapIndexTo)
{
if (SSP->T1_isMultiplicitySelection)
{
/*
std::cout << "fitnessMapIndexToRecompute = " << fitnessMapIndexToRecompute << "\n";
std::cout << "fitnessMapIndexFrom = " << fitnessMapIndexFrom << "\n";
std::cout << "fitnessMapIndexTo = " << fitnessMapIndexTo << "\n";
*/
// Copy fitnesses that can be copied
for (int fitnessMapIndex = fitnessMapIndexFrom; fitnessMapIndex < fitnessMapIndexTo ; fitnessMapIndex++)
{
//std::cout << "Assgning FMI "<<fitnessMapIndex<< " to ";
if (fitnessMapIndex != fitnessMapIndexToRecompute)
{
//std::cout << parent.getHaplo(haplo_index).getW_T1(fitnessMapIndex) << "\n";
TransmittedChrom.setW_T1(
parent.getHaplo(haplo_index).getW_T1(fitnessMapIndex),
fitnessMapIndex
);
} else
{
//std::cout << "-1.0" << "\n";
TransmittedChrom.setW_T1(-1.0,fitnessMapIndexToRecompute);
}
}
}
if (SSP->T2_isSelection)
{
// Copy fitnesses that can be copied
for (int fitnessMapIndex = fitnessMapIndexFrom; fitnessMapIndex < fitnessMapIndexTo ; fitnessMapIndex++)
{
if (fitnessMapIndex != fitnessMapIndexToRecompute)
{
//std::cout << "Assgning FMI = " << fitnessMapIndex << "\n";
TransmittedChrom.setW_T2(
parent.getHaplo(haplo_index).getW_T2(fitnessMapIndex),
fitnessMapIndex
);
} else
{
TransmittedChrom.setW_T2(-1.0, fitnessMapIndexToRecompute);
}
}
}
if (SSP->T56_isMultiplicitySelection)
{
// Copy fitnesses that can be copied
for (int fitnessMapIndex = fitnessMapIndexFrom; fitnessMapIndex < fitnessMapIndexTo ; fitnessMapIndex++)
{
if (fitnessMapIndex != fitnessMapIndexToRecompute)
{
//std::cout << "Assigning FMI = " << fitnessMapIndex << "\n";
TransmittedChrom.setW_T56(
parent.getHaplo(haplo_index).getW_T56(fitnessMapIndex),
fitnessMapIndex
);
} else
{
TransmittedChrom.setW_T56(-1.0, fitnessMapIndexToRecompute);
}
}
}
}
//// Set fitnessMapIndexFrom for next breakpoint
fitnessMapIndexFrom = fitnessMapIndexTo;
}
//////////
// Copy //
//////////
//std::cout << "In copyOver: T1_from = "<< T1_from <<" T1_to = "<< T1_to << std::endl;
//std::cout << "In copyOver: T2_from = "<< T2_from <<" T2_to = "<< T2_to << std::endl;
// Copy for T1. from included, to excluded
if (T1_from < T1_to)
{
assert(T1_to > 0 && T1_to <= SSP->Gmap.T1_nbLoci + 1);
TransmittedChrom.copyIntoT1(T1_from, T1_to, parent.getHaplo(haplo_index));
#ifdef DEBUG
Safety_T1_Absolutefrom = myMin(Safety_T1_Absolutefrom, T1_from);
Safety_T1_Absoluteto = myMax(Safety_T1_Absoluteto, T1_to);
#endif
}
// Copy for T2. from included, to excluded
if (T2_from < T2_to)
{
assert(T2_to > 0 && T2_to <= SSP->Gmap.T2_nbLoci + 1);
TransmittedChrom.copyIntoT2(T2_from, T2_to, parent.getHaplo(haplo_index));
#ifdef DEBUG
Safety_T2_Absolutefrom = myMin(Safety_T2_Absolutefrom, T2_from);
Safety_T2_Absoluteto = myMax(Safety_T2_Absoluteto, T2_to);
#endif
}
// Copy for T3. from included, to excluded
if (T3_from < T3_to)
{
assert(T3_to > 0 && T3_to <= SSP->Gmap.T3_nbLoci + 1);
TransmittedChrom.copyIntoT3(T3_from, T3_to, parent.getHaplo(haplo_index));
#ifdef DEBUG
Safety_T3_Absolutefrom = myMin(Safety_T3_Absolutefrom, T3_from);
Safety_T3_Absoluteto = myMax(Safety_T3_Absoluteto, T3_to);
#endif
}
// Copy for T4. from included, to excluded
if (T4_from < T4_to)
{
// nothing to do
assert(T4_to > 0 && T4_to <= SSP->Gmap.T4_nbLoci + 1);
//std::cout <<"\tLIFECYCLE!! b = "<<b<<" T4_from = "<<T4_from<<" T4_to = "<<T4_to<<"\n";
#ifdef DEBUG
Safety_T4_Absolutefrom = myMin(Safety_T4_Absolutefrom, T4_from);
Safety_T4_Absoluteto = myMax(Safety_T4_Absoluteto, T4_to);
#endif
}
// Copy for T56ntrl. from included, to excluded
if (T56ntrl_from < T56ntrl_to)
{
assert(T56ntrl_to > 0 && T56ntrl_to <= SSP->Gmap.T56ntrl_nbLoci + 1);
TransmittedChrom.copyIntoT56ntrl(T56ntrl_from, T56ntrl_to, parent.getHaplo(haplo_index));
#ifdef DEBUG
Safety_T56ntrl_Absolutefrom = myMin(Safety_T56ntrl_Absolutefrom, T56ntrl_from);
Safety_T56ntrl_Absoluteto = myMax(Safety_T56ntrl_Absoluteto, T56ntrl_to);
#endif
}
// Copy for T56sel. from included, to excluded
if (T56sel_from < T56sel_to)
{
assert(T56sel_to > 0 && T56sel_to <= SSP->Gmap.T56sel_nbLoci + 1);
TransmittedChrom.copyIntoT56sel(T56sel_from, T56sel_to, parent.getHaplo(haplo_index));
#ifdef DEBUG
Safety_T56sel_Absolutefrom = myMin(Safety_T56sel_Absolutefrom, T56sel_from);
Safety_T56sel_Absoluteto = myMax(Safety_T56sel_Absoluteto, T56sel_to);
#endif
}
// Set new 'from'
T1_from = T1_to;
T2_from = T2_to;
T3_from = T3_to;
T4_from = T4_to;
T56ntrl_from = T56ntrl_to;
T56sel_from = T56sel_to;
// Switch parent chromosome
haplo_index = !haplo_index;
}
#ifdef DEBUG
// Security Checks
if (SSP->Gmap.T1_nbChars)
{
assert(T1_to == SSP->Gmap.T1_nbLoci);
assert(Safety_T1_Absoluteto == SSP->Gmap.T1_nbLoci);
assert(Safety_T1_Absolutefrom == 0);
}
if (SSP->Gmap.T2_nbLoci)
{
assert(T2_to == SSP->Gmap.T2_nbLoci);
assert(Safety_T2_Absoluteto == SSP->Gmap.T2_nbLoci);
assert(Safety_T2_Absolutefrom == 0);
}
if (SSP->Gmap.T3_nbLoci)
{
assert(T3_to == SSP->Gmap.T3_nbLoci);
assert(Safety_T3_Absoluteto == SSP->Gmap.T3_nbLoci);
assert(Safety_T3_Absolutefrom == 0);
}
if (SSP->Gmap.T4_nbLoci)
{
assert(T4_to == SSP->Gmap.T4_nbLoci);
assert(Safety_T4_Absoluteto == SSP->Gmap.T4_nbLoci);
assert(Safety_T4_Absolutefrom == 0);
}
if (SSP->Gmap.T56ntrl_nbLoci)
{
assert(T56ntrl_to == SSP->Gmap.T56ntrl_nbLoci);
assert(Safety_T56ntrl_Absoluteto == SSP->Gmap.T56ntrl_nbLoci);
assert(Safety_T56ntrl_Absolutefrom == 0);
}
if (SSP->Gmap.T56sel_nbLoci)
{
assert(T56sel_to == SSP->Gmap.T56sel_nbLoci);
assert(Safety_T56sel_Absoluteto == SSP->Gmap.T56sel_nbLoci);
assert(Safety_T56sel_Absolutefrom == 0);
}
#endif
} else
{
std::cout << "Internal error. 'breakpoints' has size of zero. It should always contain at least the element std::numeric_limits<uint32_t>::max()\n";
abort();
}
#ifdef DEBUG
TransmittedChrom.assertT5orderAndUniqueness();
#endif
}
void LifeCycle::reproduceThroughCopy(Individual& parent, Haplotype& TransmittedChrom, HaplotypeData& parentData, int& patch_index)
{
#ifdef CALLENTRANCEFUNCTIONS
std::cout << "Enters in 'reproduceThroughCopy'\n";
#endif
//std::cout << "copy\n";
//std::cout << "TransmittedChrom.T4ID = " << TransmittedChrom.T4ID << "\n";
//std::cout << "parent.getHaplo(parentData.segregationIndex).T4ID = " << parent.getHaplo(parentData.segregationIndex).T4ID<< "\n";
//std::cout << "parent.getHaplo(!parentData.segregationIndex).T4ID = " << parent.getHaplo(!parentData.segregationIndex).T4ID<< "\n";
recombination_RecPositions(parentData.nbRecs, parent); // parent is used if recRateOnMismatch_bool
// copy from parents chromosomes to TransmittedChrom. The function also set the new values for W_T1 and W_T2
if (SSP->Gmap.nbNonPedigreeLoci) copyOver(parent, TransmittedChrom, parentData.segregationIndex); // This will copy data from parents to offspring so it must always run
if (SSP->Gmap.T4_nbLoci > 0)
{
TransmittedChrom.T4ID = SSP->T4Tree.addHaplotype(recombination_breakpoints, {parent.getHaplo(parentData.segregationIndex).T4ID, parent.getHaplo(!parentData.segregationIndex).T4ID}, patch_index);
}
if (SSP->Gmap.T8_nbLoci > 0)
{
TransmittedChrom.dealWithT8Info(
SSP->T8Tree.addOffspring(
parent.getHaplo(parentData.segregationIndex).T8ID,
parent.getHaplo(!parentData.segregationIndex).T8ID,
recombination_breakpoints
)
);
}
}
void LifeCycle::Mutate(Haplotype& TransmittedChrom, int Habitat)
{
if (SSP->T1_Total_Mutation_rate>0) Mutate_T1(TransmittedChrom, Habitat);
if (SSP->T2_Total_Mutation_rate>0) Mutate_T2(TransmittedChrom, Habitat);
if (SSP->T3_Total_Mutation_rate>0) Mutate_T3(TransmittedChrom);
if (SSP->T56_Total_Mutation_rate>0) Mutate_T56(TransmittedChrom, Habitat);
if (SSP->T7mutpars.totalMutationRatePerGene>0) Mutate_T7(TransmittedChrom);
}
void LifeCycle::Mutate_T7(Haplotype& TransmittedChrom)
{
// deletion
if (SSP->T7mutpars.deletion > 0 && TransmittedChrom.nbT7Genes())
{
auto nbMuts = GP->rngw.poisson(SSP->T7mutpars.deletion * TransmittedChrom.nbT7Genes());
if (nbMuts >= TransmittedChrom.nbT7Genes())
{
TransmittedChrom.clearT7Genes();
} else
{
for (size_t muti = 0 ; muti < nbMuts ; ++muti)
{
auto pos = GP->rngw.uniform_int_distribution(TransmittedChrom.nbT7Genes());
TransmittedChrom.removeT7Gene(pos);
}
}
}
// Duplications
if (SSP->T7mutpars.duplication > 0 && TransmittedChrom.nbT7Genes() > 0 && TransmittedChrom.nbT7Genes() < SSP->Gmap.T7_nbLoci)
{
auto nbMuts = GP->rngw.poisson(SSP->T7mutpars.duplication * TransmittedChrom.nbT7Genes());
for (size_t muti = 0 ; muti < nbMuts ; ++muti)
{
auto pos = GP->rngw.uniform_int_distribution(TransmittedChrom.nbT7Genes());
TransmittedChrom.duplicateT7Gene(pos);
}
}
// Normal mutations
for (size_t geneIndex = 0 ; geneIndex < TransmittedChrom.nbT7Genes() ; ++geneIndex)
{
TransmittedChrom.getT7_Allele(geneIndex).attemptMutation();
}
}
void LifeCycle::Mutate_T1(Haplotype& TransmittedChrom, int Habitat)
{
#ifdef CALLENTRANCEFUNCTIONS
std::cout << "Enters in 'Mutate_T1'\n";
#endif
int nbMuts = SSP->geneticSampler.get_T1_nbMuts();
//std::cout << "nbMuts = " << nbMuts << "\n";
for (int i = 0 ; i < nbMuts ; i++)
{
auto MutPosition = SSP->geneticSampler.get_T1_mutationPosition();
// Make the mutation
TransmittedChrom.mutateT1_Allele(MutPosition, Habitat); // toggle bit
// TransmittedChrom.setT1_AlleleToOne(byte_index,bit_index,); // set bit to one
}
}
void LifeCycle::Mutate_T2(Haplotype& TransmittedChrom, int Habitat)
{
#ifdef CALLENTRANCEFUNCTIONS
std::cout << "Enters in 'Mutate_T2'\n";
#endif
int nbMuts = SSP->geneticSampler.get_T2_nbMuts();
for (int i = 0 ; i < nbMuts ; i++)
{
auto MutPosition = SSP->geneticSampler.get_T2_mutationPosition();
// Make the mutation
//std::cout << "MutPosition = " << MutPosition << " SSP->Gmap.T2_nbLoci = " << SSP->Gmap.T2_nbLoci << "\n";
assert(MutPosition < SSP->Gmap.T2_nbLoci);
TransmittedChrom.AddMutT2_Allele(MutPosition, Habitat); // add 1 and changes T2_W
}
}
void LifeCycle::Mutate_T3(Haplotype& TransmittedChrom)
{
#ifdef CALLENTRANCEFUNCTIONS
std::cout << "Enters in 'Mutate_T3'\n";
#endif
int nbMuts = SSP->geneticSampler.get_T3_nbMuts();
//std::cout << "nbMuts = " << nbMuts << "\n";
for (int i = 0 ; i < nbMuts ; i++)
{
auto MutPosition = SSP->geneticSampler.get_T3_mutationPosition();
// Make the mutation
//std::cout << "MutPosition = " << MutPosition << " SSP->Gmap.T3_nbLoci = " << SSP->Gmap.T3_nbLoci << "\n";
assert(MutPosition < SSP->Gmap.T3_nbLoci);
TransmittedChrom.mutateT3_Allele(MutPosition); // add 1 and changes T2_W
}
}
/*void LifeCycle::Mutate_T56(Haplotype& TransmittedChrom, int Habitat)
{
#ifdef CALLENTRANCEFUNCTIONS
std::cout << "Enters in 'Mutate_T56'\n";
#endif
int nbMuts = SSP->T56_rpois_nbMut(GP->rngw.getRNG());
//std::cout << "nbMuts = " << nbMuts << "\n";
std::vector<int> T5ntrlMutations;
if (SSP->Gmap.T5ntrl_nbLoci)
T5ntrlMutations.reserve(nbMuts);
for (int i = 0 ; i < nbMuts ; i++)
{
//std::cout << "nbMuts = " << nbMuts << "\n";
int MutPosition;
double rnd;
// Find Position
//std::cout << "SSP->T56_MutationRate.size() = " << SSP->T56_MutationRate.size() << "\n";
if (SSP->T56_MutationRate.size() == 1)
{
MutPosition = SSP->T56_runiform_int_ForMutPos(GP->rngw.getRNG());
} else
{
rnd = SSP->T56_runiform_double_ForMutPos(GP->rngw.getRNG());
// binary search
MutPosition = distance(SSP->T56_MutationRate.begin(),
std::upper_bound(SSP->T56_MutationRate.begin(), SSP->T56_MutationRate.end(), rnd)
);
}
// Make the mutation - toggle bit
//std::cout << "MutPosition = " << MutPosition << "\n";
auto& locusGender = SSP->FromT56LocusToT56genderLocus[MutPosition];
//std::cout << "locusGender.second = " << locusGender.second << "\n";
if (locusGender.first)
{
if (SSP->Gmap.isT56ntrlCompress)
{
TransmittedChrom.mutateT56ntrl_Allele(locusGender.second);
} else
{
auto it = std::lower_bound(T5ntrlMutations.begin(), T5ntrlMutations.end(), locusGender.second);
if (it == T5ntrlMutations.end())
{
T5ntrlMutations.push_back(locusGender.second);
} else
{
if (*it == locusGender.second)
{
T5ntrlMutations.erase(it);
} else
{
T5ntrlMutations.insert(it, locusGender.second);
}
}
}
} else
{
TransmittedChrom.mutateT56sel_Allele(locusGender.second, Habitat);
}
}
// T5ntrlMutations and selMutations are already sorted an without duplicates
if (T5ntrlMutations.size())
TransmittedChrom.mutateT5ntrl_Allele(T5ntrlMutations);
}*/
void LifeCycle::Mutate_T56(Haplotype& TransmittedChrom, int Habitat)
{
#ifdef CALLENTRANCEFUNCTIONS
std::cout << "Enters in 'Mutate_T56'\n";
#endif
int nbMuts = SSP->geneticSampler.get_T56_nbMuts();;
//std::cout << "nbMuts = " << nbMuts << "\n";
for (int i = 0 ; i < nbMuts ; i++)
{
auto MutPosition = SSP->geneticSampler.get_T56_mutationPosition();
// Make the mutation - toggle bit
//std::cout << "MutPosition = " << MutPosition << "\n";
auto locusGender = SSP->Gmap.FromT56LocusToT56genderLocus(MutPosition);
//std::cout << "locusGender.second = " << locusGender.second << "\n";
if (locusGender.isNtrl)
{
TransmittedChrom.mutateT56ntrl_Allele(locusGender.locusInGender);
} else
{
TransmittedChrom.mutateT56sel_Allele(locusGender.locusInGender, Habitat);
}
}
/*
if (nbMuts == 0) return;
if (nbMuts == 1)
{
auto MutPosition = SSP->geneticSampler.get_T56_mutationPosition();
auto locusGender = SSP->Gmap.FromT56LocusToT56genderLocus(MutPosition);
if (locusGender.isNtrl)
{
TransmittedChrom.mutateT56ntrl_Allele(locusGender.locusInGender);
} else
{
TransmittedChrom.mutateT56sel_Allele(locusGender.locusInGender, Habitat);
}
} else
{
std::vector<uint32_t> ntrlMuts;
std::vector<uint32_t> selMuts;
for (int i = 0 ; i < nbMuts ; i++)
{
auto MutPosition = SSP->geneticSampler.get_T56_mutationPosition();
// Make the mutation - toggle bit
//std::cout << "MutPosition = " << MutPosition << "\n";
auto locusGender = SSP->Gmap.FromT56LocusToT56genderLocus(MutPosition);
//std::cout << "locusGender.second = " << locusGender.second << "\n";
if (locusGender.isNtrl)
{
ntrlMuts.push_back(locusGender.locusInGender);
} else
{
selMuts.push_back(locusGender.locusInGender);
}
}
if (ntrlMuts.size())
{
if (ntrlMuts.size() == 1)
{
TransmittedChrom.mutateT56ntrl_Allele(ntrlMuts.front());
} else
{
TransmittedChrom.mutateT56ntrl_Allele(ntrlMuts);
}
}
if (selMuts.size())
{
if (selMuts.size() == 1)
{
TransmittedChrom.mutateT56sel_Allele(selMuts.front());
} else
{
TransmittedChrom.mutateT56sel_Allele(selMuts);
}
}
}
*/
}
void LifeCycle::findAllParents(Pop& pop, const std::vector<int>& patchSizeNextGeneration)
{
PD.resizeForNewGeneration(patchSizeNextGeneration);
assert(patchSizeNextGeneration.size() == GP->PatchNumber);
for (int patch_index = 0 ; patch_index < GP->PatchNumber ; ++patch_index)
{
for (int offspring_index = 0 ; offspring_index < patchSizeNextGeneration[patch_index] ; ++offspring_index)
{
CoupleData CD = findCouple(pop, patch_index, offspring_index, PD, patchSizeNextGeneration[patch_index]); // Give PD for cloneInfo
PD.lastOffspring[CD.mother.segregationIndex][CD.mother.patch][CD.mother.ind] = HaplotypeData(patch_index, offspring_index, 0, CD.mother.nbRecs);
if (CD.mother.nbRecs > 0)
{
PD.lastOffspring[!CD.mother.segregationIndex][CD.mother.patch][CD.mother.ind] = HaplotypeData(patch_index, offspring_index, 0, CD.mother.nbRecs);
}
PD.lastOffspring[CD.father.segregationIndex][CD.father.patch][CD.father.ind] = HaplotypeData(patch_index, offspring_index, 1, CD.father.nbRecs);
if (CD.father.nbRecs > 0)
{
PD.lastOffspring[!CD.father.segregationIndex][CD.father.patch][CD.father.ind] = HaplotypeData(patch_index, offspring_index, 1, CD.father.nbRecs);
}
PD.couples[patch_index][offspring_index] = CD;
}
}
/*{
assert(GP->PatchNumber == 1);
std::vector<uint32_t> count(2*SSP->TotalpatchSize,0);
for (uint32_t ind_index = 0 ; ind_index < patchSizeNextGeneration[0] ; ++ind_index)
{
auto& CD = PD.couples[0][ind_index];
++(count[2 * CD.mother.ind + CD.mother.segregationIndex]);
++(count[2 * CD.father.ind + CD.father.segregationIndex]);
}
std::vector<uint32_t> dist(2*SSP->TotalpatchSize,0);
for (uint32_t i = 0 ; i < count.size(); ++i)
{
++(dist[count[i]]);
}
std::cout << "\n";
uint32_t nbChildren = 0;
for (uint32_t i = 0 ; i < dist.size(); ++i)
{
nbChildren += i * dist[i];
if (dist[i]) std::cout << i << ": " << dist[i] << "\n";
//for (uint32_t j = 0 ; j < dist[i] ; ++j)
//{
// std::cout << "*";
//}
//std::cout << std::endl;
}
assert(nbChildren == 2*patchSizeNextGeneration[0]);
}*/
}
LifeCycle::CoupleData LifeCycle::findCouple(Pop& pop, int& patch_index, int& offspring_index, ParentsData& PD, const int& nextGenPatchSize)
{
int mother_patch_from;
if (SSP->isStochasticMigration)
mother_patch_from = Pop::SelectionOriginPatch(patch_index);
else
mother_patch_from = Pop::SelectionOriginPatch(patch_index, nextGenPatchSize==1 ? 0 : (double) offspring_index / (double) (nextGenPatchSize-1) );
#ifdef DEBUG
if (mother_patch_from != patch_index) NBMIGRANTS++;
#endif
// Select the mother
int mother_index = pop.SelectionParent(mother_patch_from, 0); // Selection on fertility (if applicable) in there
if (SSP->cloningRate != 0.0 && (SSP->cloningRate == 1.0 || (GP->rngw.uniform_real_distribution(1.0) < SSP->cloningRate)))
{
// Cloning
PD.cloneInfo[patch_index][offspring_index] = true;
int segregationIndex = GP->rngw.get_1b();
return CoupleData(
HaplotypeData(mother_patch_from, mother_index, segregationIndex, 0), // mother
HaplotypeData(mother_patch_from, mother_index, !segregationIndex, 0) // father
);
} else
{
// Not cloning
if (SSP->cloningRate != 0.0)
{
PD.cloneInfo[patch_index][offspring_index] = false;
}
int father_patch_from;
int father_index;
if (SSP->selfingRate > 0.0 && GP->rngw.uniform_real_distribution(1.0) < SSP->selfingRate)
{
// selfing
father_patch_from = mother_patch_from;
father_index = mother_index;
} else
{
// not selfing
if (SSP->selfingRate == 0.0)
{
// No selfing at all -> Not even following Wright-Fisher model
father_index = -1;
father_patch_from = -1;
while (father_index == mother_index && father_patch_from == mother_patch_from)
{
if (SSP->gameteDispersal)
{
if (SSP->isStochasticMigration)
father_patch_from = Pop::SelectionOriginPatch(patch_index);
else
father_patch_from = Pop::SelectionOriginPatch(patch_index, nextGenPatchSize==1 ? 0 : (double) offspring_index / (double) (nextGenPatchSize-1) );
} else
{
father_patch_from = mother_patch_from;
}
father_index = pop.SelectionParent(father_patch_from, SSP->malesAndFemales); // selection on fertility in there
}
assert(father_index >= 0);
assert(father_patch_from >= 0);
} else
{
// Wright-Fisher model. slefing with prob 1/2N (assuming neutrality) -> Default
if (SSP->gameteDispersal)
{
if (SSP->isStochasticMigration)
father_patch_from = Pop::SelectionOriginPatch(patch_index);
else
father_patch_from = Pop::SelectionOriginPatch(patch_index, nextGenPatchSize==1 ? 0 : (double) offspring_index / (double) (nextGenPatchSize-1) );
} else
{
father_patch_from = mother_patch_from;
}
father_index = pop.SelectionParent(father_patch_from, SSP->malesAndFemales); // selection on fertility in there
}
}
//std::cout << "FC: " << mother_patch_from << " " << mother_index << " | " << father_patch_from << " " << father_index << "\n";
auto segregationIndexA = GP->rngw.get_1b();
auto segregationIndexB = GP->rngw.get_1b();
auto nbRecsA = SSP->geneticSampler.get_nbRecombinations();
auto nbRecsB = SSP->geneticSampler.get_nbRecombinations();
// I set these values before because the order of evaluation is compiler dependent otherwise which would make simulations not reproducible
return CoupleData(
HaplotypeData(mother_patch_from, mother_index, segregationIndexA, nbRecsA), // mother
HaplotypeData(father_patch_from, father_index, segregationIndexB, nbRecsB) // father
);
}
}
| 40.622302 | 222 | 0.550642 | [
"vector",
"model"
] |
76013e28ff5622e9da208ea1976c2b8a37605d9f | 3,853 | cpp | C++ | esphome/components/inkbird_ibsth1_mini/inkbird_ibsth1_mini.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 249 | 2018-04-07T12:04:11.000Z | 2019-01-25T01:11:34.000Z | esphome/components/inkbird_ibsth1_mini/inkbird_ibsth1_mini.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 243 | 2018-04-11T16:37:11.000Z | 2019-01-25T16:50:37.000Z | esphome/components/inkbird_ibsth1_mini/inkbird_ibsth1_mini.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 40 | 2018-04-10T05:50:14.000Z | 2019-01-25T15:20:36.000Z | #include "inkbird_ibsth1_mini.h"
#include "esphome/core/log.h"
#ifdef USE_ESP32
namespace esphome {
namespace inkbird_ibsth1_mini {
static const char *const TAG = "inkbird_ibsth1_mini";
void InkbirdIbstH1Mini::dump_config() {
ESP_LOGCONFIG(TAG, "Inkbird IBS TH1 MINI");
LOG_SENSOR(" ", "Temperature", this->temperature_);
LOG_SENSOR(" ", "External Temperature", this->external_temperature_);
LOG_SENSOR(" ", "Humidity", this->humidity_);
LOG_SENSOR(" ", "Battery Level", this->battery_level_);
}
bool InkbirdIbstH1Mini::parse_device(const esp32_ble_tracker::ESPBTDevice &device) {
// The below is based on my research and reverse engineering of a single device
// It is entirely possible that some of that may be inaccurate or incomplete
// for Inkbird IBS-TH1 Mini device we expect
// 1) expected mac address
// 2) device address type == PUBLIC
// 3) no service data
// 4) one manufacturer data
// 5) the manufacturer data should contain a 16-bit uuid amd a 7-byte data vector
// 6) the 7-byte data component should have data[2] == 0 and data[6] == 8
// the address should match the address we declared
if (device.address_uint64() != this->address_) {
ESP_LOGVV(TAG, "parse_device(): unknown MAC address.");
return false;
}
if (device.get_address_type() != BLE_ADDR_TYPE_PUBLIC) {
ESP_LOGVV(TAG, "parse_device(): address is not public");
return false;
}
if (!device.get_service_datas().empty()) {
ESP_LOGVV(TAG, "parse_device(): service_data is expected to be empty");
return false;
}
auto mnf_datas = device.get_manufacturer_datas();
if (mnf_datas.size() != 1) {
ESP_LOGVV(TAG, "parse_device(): manufacturer_datas is expected to have a single element");
return false;
}
auto mnf_data = mnf_datas[0];
if (mnf_data.uuid.get_uuid().len != ESP_UUID_LEN_16) {
ESP_LOGVV(TAG, "parse_device(): manufacturer data element is expected to have uuid of length 16");
return false;
}
if (mnf_data.data.size() != 7) {
ESP_LOGVV(TAG, "parse_device(): manufacturer data element length is expected to be of length 7");
return false;
}
if (mnf_data.data[6] != 8) {
ESP_LOGVV(TAG, "parse_device(): unexpected data");
return false;
}
// sensor output encoding
// data[5] is a battery level
// data[0] and data[1] is humidity * 100 (in pct)
// uuid is a temperature * 100 (in Celsius)
// when data[2] == 0 temperature is from internal sensor (IBS-TH1 or IBS-TH1 Mini)
// when data[2] == 1 temperature is from external sensor (IBS-TH1 only)
// Create empty variables to pass automatic checks
auto temperature = NAN;
auto external_temperature = NAN;
// Read bluetooth data into variable
auto measured_temperature = ((int16_t) mnf_data.uuid.get_uuid().uuid.uuid16) / 100.0f;
// Set temperature or external_temperature based on which sensor is in use
if (mnf_data.data[2] == 0) {
temperature = measured_temperature;
} else if (mnf_data.data[2] == 1) {
external_temperature = measured_temperature;
} else {
ESP_LOGVV(TAG, "parse_device(): unknown sensor type");
return false;
}
auto battery_level = mnf_data.data[5];
auto humidity = ((mnf_data.data[1] << 8) + mnf_data.data[0]) / 100.0f;
// Send temperature only if the value is set
if (!std::isnan(temperature) && this->temperature_ != nullptr) {
this->temperature_->publish_state(temperature);
}
if (!std::isnan(external_temperature) && this->external_temperature_ != nullptr) {
this->external_temperature_->publish_state(external_temperature);
}
if (this->humidity_ != nullptr) {
this->humidity_->publish_state(humidity);
}
if (this->battery_level_ != nullptr) {
this->battery_level_->publish_state(battery_level);
}
return true;
}
} // namespace inkbird_ibsth1_mini
} // namespace esphome
#endif
| 34.711712 | 102 | 0.697379 | [
"vector"
] |
7610cd32c59edad5589c39a8407ddfd3fc3adfd4 | 7,237 | cpp | C++ | controller/src/rpiMgr.cpp | rayray2002/LightDance-RPi | 266d6709f2ff0ee70da307dc6e7ab09679a207fe | [
"MIT"
] | null | null | null | controller/src/rpiMgr.cpp | rayray2002/LightDance-RPi | 266d6709f2ff0ee70da307dc6e7ab09679a207fe | [
"MIT"
] | null | null | null | controller/src/rpiMgr.cpp | rayray2002/LightDance-RPi | 266d6709f2ff0ee70da307dc6e7ab09679a207fe | [
"MIT"
] | null | null | null | #include "rpiMgr.h"
#include "OFrgba_to_rgb.hpp"
RPiMgr::RPiMgr(const string& dancerName) : _dancerName(dancerName) {}
bool RPiMgr::setDancer() {
string path = "../data/dancers/" + _dancerName + ".json";
ifstream infile(path.c_str());
if (!infile) {
cout << "Cannot open file: " << path << endl;
return false;
}
json j;
infile >> j;
// LED
ledPlayers.clear();
for (json::iterator it = j["LEDPARTS"].begin(); it != j["LEDPARTS"].end(); ++it)
ledPlayers.push_back(LEDPlayer(it.key(), it.value()["len"], it.value()["id"]));
vector<uint16_t> nLEDs(TOTAL_LED_PARTS);
for (auto& lp : ledPlayers)
nLEDs[lp.channelId] = lp.len;
LEDBuf.resize(nLEDs.size());
for (int i = 0; i < LEDBuf.size(); ++i)
LEDBuf[i].resize(nLEDs[i] * 3, (char)0);
// OF
ofPlayer.init(j["OFPARTS"]);
OFBuf.resize(NUM_OF);
for (int i = 0; i < OFBuf.size(); ++i)
OFBuf[i].resize(NUM_OF_PARAMS);
// hardware
led_strip = new LED_Strip;
led_strip->initialize(nLEDs);
of = new PCA;
return true;
}
void RPiMgr::pause() {
_playing = false;
}
void RPiMgr::load(const string& path) {
// While playing, you cannot load
if (_playing) {
logger->error("Load", "Cannot load while playing");
return;
}
// Files
ifstream LEDfile(path + "LED.json");
ifstream OFfile(path + "OF.json");
string msg = "Loading dir: " + path;
if (!LEDfile) {
msg += "\nFailed to open file: " + path + "LED.json";
logger->error("Load", msg);
return;
}
if (!OFfile) {
msg += "\nFailed to open file: " + path + "OF.json";
logger->error("Load", msg);
return;
}
// LED
json _LEDJson, _OFJson;
LEDfile >> _LEDJson;
for (auto& lp : ledPlayers)
lp.load(_LEDJson[lp.name]);
// OF
OFfile >> _OFJson;
ofPlayer.load(_OFJson);
_loaded = true;
logger->success("Load", msg);
}
void RPiMgr::play(const bool& givenStartTime, const unsigned& start, const unsigned& delay) {
long timeIntoFunc = getsystime();
if (!_loaded) {
logger->error("Play", "Play failed, need to load first");
return;
}
size_t totalLedFrame = 0;
size_t ledEndTime = 0;
for (auto& lp : ledPlayers) {
totalLedFrame += lp.getFrameNum();
ledEndTime = max(ledEndTime, lp.getEndTime());
}
if (totalLedFrame == 0 && ofPlayer.getFrameNum() == 0) {
logger->log("Play", "Warning: LED.json and OF.json is empty\nend of play");
return;
}
if (givenStartTime)
_startTime = start;
if (_startTime > max(ledEndTime, ofPlayer.getEndTime())) {
logger->log("Play", "Warning: startTime excess both LED.json and OF.json totalTime\nend of playing");
return;
}
long hadDelay = getsystime() - timeIntoFunc;
if (hadDelay < delay)
this_thread::sleep_for(chrono::microseconds(delay - hadDelay));
logger->success("Play", "Start play loop thread");
for (auto& lp : ledPlayers)
lightLEDStatus(lp.getFrame(_startTime), lp.channelId);
lightOFStatus(ofPlayer.getFrame(_startTime));
long sysStartTime = getsystime();
_playing = true;
long startTime = (long)_startTime;
cout << "start play loop\n";
thread loop(&RPiMgr::playLoop, this, startTime);
loop.detach();
return;
}
void RPiMgr::stop() {
_playing = false;
_startTime = 0;
darkAll();
return;
}
void RPiMgr::statuslight() {
// TODO
}
void RPiMgr::LEDtest(const int& channel, int colorCode, int alpha) {
// Will change led buf;
const float _alpha = float(alpha) / ALPHA_RANGE;
char R, G, B;
colorCode2RGB(colorCode, R, G, B);
ledDark();
for (int i = 0; i < LEDBuf[channel].size() / 3; ++i)
LEDrgba_to_rgb(LEDBuf[channel], i, R, G, B, _alpha);
led_strip->sendToStrip(LEDBuf);
return;
}
void RPiMgr::OFtest(const int& channel, int colorCode, int alpha) {
// Will not change of buf
vector<char> buf(6);
char R, G, B;
colorCode2RGB(colorCode, R, G, B);
// ofDark();
OFrgba2rgbiref(buf, R, G, B, alpha);
// OFrgba2rgbiref(OFBuf[channel], R, G, B, alpha);
// of->WriteAll(OFBuf);
of->WriteChannel(buf, channel);
return;
}
void RPiMgr::list() {
string mes = "LEDPARTS:\n";
for (auto& lp : ledPlayers) {
string part = "\t";
part += lp.name;
for (int i = 0; i < 15 - lp.name.size(); ++i)
part += ' ';
part += "channel: " + to_string(lp.channelId) + ", len: " + to_string(lp.len) + '\n';
mes += part;
}
mes += "OFPARTS:\n";
mes += ofPlayer.getParts();
logger->success("List", mes);
return;
}
void RPiMgr::quit() {
return;
}
void RPiMgr::darkAll() {
ledDark();
ofDark();
}
void RPiMgr::lightAll(int colorCode, int alpha) {
char R, G, B;
const float _alpha = float(alpha) / ALPHA_RANGE;
colorCode2RGB(colorCode, R, G, B);
for (int i = 0; i < LEDBuf.size(); ++i)
for (int j = 0; j < LEDBuf[i].size(); ++j)
LEDrgba_to_rgb(LEDBuf[i], j, R, G, B, _alpha);
for (int i = 0; i < OFBuf.size(); ++i)
OFrgba2rgbiref(OFBuf[i], R, G, B, alpha);
led_strip->sendToStrip(LEDBuf);
of->WriteAll(OFBuf);
return;
}
// private function
void RPiMgr::lightLEDStatus(const LEDPlayer::Frame& frame, const int& channelId) {
for (int i = 0; i < frame.status.size(); ++i) {
char R, G, B;
const float alpha = float(frame.status[i].alpha) / ALPHA_RANGE;
colorCode2RGB(frame.status[i].colorCode, R, G, B);
LEDrgba_to_rgb(LEDBuf[channelId], i, R, G, B, alpha);
}
led_strip->sendToStrip(LEDBuf);
}
void RPiMgr::lightOFStatus(const OFPlayer::Frame& frame) {
for (auto it = frame.status.begin(); it != frame.status.end(); ++it) {
char R, G, B;
const float alpha = float(it->second.alpha);
colorCode2RGB(it->second.colorCode, R, G, B);
OFrgba2rgbiref(OFBuf[ofPlayer.getChannelId(it->first)], R, G, B, alpha);
}
of->WriteAll(OFBuf);
}
void RPiMgr::ledDark() {
for (int i = 0; i < LEDBuf.size(); ++i)
for (int j = 0; j < LEDBuf[i].size(); ++j)
LEDBuf[i][j] = 0;
led_strip->sendToStrip(LEDBuf);
}
void RPiMgr::ofDark() {
for (int i = 0; i < OFBuf.size(); ++i)
for (int j = 0; j < OFBuf[i].size(); ++j)
OFBuf[i][j] = 0;
of->WriteAll(OFBuf);
}
// For threading
void RPiMgr::playLoop(const long startTime) {
const long sysStartTime = getsystime();
const long localStartTime = startTime;
while (_playing) {
bool isFinished = ofPlayer.isFinished();
for (auto& lp : ledPlayers)
isFinished &= lp.isFinished();
if (isFinished) {
_playing = false;
_startTime = 0;
break;
}
// LED
for (auto& lp : ledPlayers)
lightLEDStatus(lp.getFrame(_startTime), lp.channelId);
// OF
lightOFStatus(ofPlayer.getFrame(_startTime));
// Calculate startTime
_startTime = localStartTime + (getsystime() - sysStartTime);
}
cout << "end playing\n";
} | 27.412879 | 109 | 0.577311 | [
"vector"
] |
7615a175349bc242d7190634949a11ad6b3decfa | 3,671 | cpp | C++ | src/User Code/Tank.cpp | anunez97/fergilnad-game-engine | 75528633d32aed41223e0f52d8d7715073d9210a | [
"MIT"
] | null | null | null | src/User Code/Tank.cpp | anunez97/fergilnad-game-engine | 75528633d32aed41223e0f52d8d7715073d9210a | [
"MIT"
] | null | null | null | src/User Code/Tank.cpp | anunez97/fergilnad-game-engine | 75528633d32aed41223e0f52d8d7715073d9210a | [
"MIT"
] | null | null | null | // Tank
#include "Tank.h"
#include "ModelManager.h"
#include "TextureManager.h"
#include "ShaderManager.h"
#include "SceneManager.h"
#include "Scene.h"
#include "BulletFactory.h"
#include "SceneTest.h"
Tank::Tank()
:speed(1.0f), rotAngle(0.05f), turretOffset(7.0f), turretend(0, 2.0f, 15.0f)
{
Vect color(1.5f, 1.5f, 1.5f);
Vect lightpos(1.0f, 1.0f, 1.0f);
pBody = new GraphicsObject_TextureFlat(ModelManager::Get("tank2"), ShaderManager::Get("TextureLight"), TextureManager::Get("red"), TextureManager::Get("red"), TextureManager::Get("red"));
//pTurret = new GraphicsObject_TextureFlat(ModelManager::Get("tankturret"), ShaderManager::Get("TextureFlat"), TextureManager::Get("darkblue"), TextureManager::Get("blue"), TextureManager::Get("blue"));
//ScaleMat.set(SCALE, 0.05f, 0.05f, 0.05f);
ScaleMat.set(SCALE, 0.5f, 0.5f, 0.5f);
RotateMat.set(ROT_X, 30.0f);
// tank body
Pos.set(-100, -50, -100);
WorldMat = ScaleMat * RotateMat * Matrix(TRANS, Pos);
pBody->SetWorld(WorldMat);
/*// tank turret
WorldMat = ScaleMat * RotateMat * Matrix(TRANS, Pos + Vect(0, turretOffset, 0));
pTurret->SetWorld(WorldMat);
//*/
Updatable::SubmitUpdateRegistration();
Drawable::SubmitDrawRegistration();
//Inputable::SubmitKeyRegistration(AZUL_KEY::KEY_SPACE, EVENT_TYPE::KEY_PRESS);
//Inputable::SubmitKeyRegistration(AZUL_KEY::KEY_ENTER, EVENT_TYPE::KEY_PRESS);
Collidable::SetCollidableGroup<Tank>();
Collidable::SetColliderModel(pBody->getModel(), AABB);
//Collidable::SubmitCollisionRegistration();
//UpdateCollisionData(WorldMat);
}
Tank::~Tank()
{
delete pBody;
//delete pTurret;
}
void Tank::Update()
{
/*
if (Keyboard::GetKeyState(AZUL_KEY::KEY_W))
{
Pos += Vect(0, 0, 1) * RotateMat * speed;
}
else if (Keyboard::GetKeyState(AZUL_KEY::KEY_S))
{
Pos += Vect(0, 0, 1) * RotateMat * -speed;
}
if (Keyboard::GetKeyState(AZUL_KEY::KEY_A))
{
RotateMat *= Matrix(ROT_Y, rotAngle);
}
else if (Keyboard::GetKeyState(AZUL_KEY::KEY_D))
{
RotateMat *= Matrix(ROT_Y, -rotAngle);
}*/
//RotateMat *= Matrix(ROT_X, 0.01f);
//SceneManager::GetCurrentScene()->UpdateCameraPos(Vect(0.0f, 1.0f, 0.0f), Pos, Pos * Matrix(TRANS, Vect(0, 50.0f, -150.0f)));
WorldMat = ScaleMat * RotateMat * Matrix(TRANS, Pos);
pBody->SetWorld(WorldMat);
UpdateCollisionData(WorldMat);
//WorldMat = ScaleMat * Matrix(IDENTITY) * Matrix(TRANS, Pos + Vect(0, turretOffset, 0));
//pTurret->SetWorld(WorldMat);
}
void Tank::Draw()
{
//ShowNode();
pBody->Render(SceneManager::GetCurrentScene()->GetCurrentCamera());
//pTurret->Render(SceneManager::GetCurrentScene()->GetCurrentCamera());
}
void Tank::KeyPressed(AZUL_KEY k)
{
switch (k)
{
case AZUL_KEY::KEY_SPACE:
//BulletFactory::CreateBullet(RotateMat, Pos + Vect(0, turretOffset, 0));
break;
case AZUL_KEY::KEY_ENTER:
SceneManager::SetNextScene(new SceneTest);
}
}
void Tank::KeyReleased(AZUL_KEY k)
{
k;
}
void Tank::Collision(Frigate* fri)
{
fri;
DebugMsg::out("Collision Tank with Frigate\n");
}
void Tank::Collision(Tank* t)
{
t;
DebugMsg::out("Collision Tank with Tank\n");
}
void Tank::MoveTo(Vect pos)
{
this->Pos = pos;
WorldMat = ScaleMat * RotateMat * Matrix(TRANS, Pos);
UpdateCollisionData(WorldMat);
}
void Tank::RegisterCollision()
{
SubmitCollisionRegistration();
}
void Tank::UpdateWorld(Matrix rotate, Vect pos)
{
WorldMat = ScaleMat, rotate, Matrix(TRANS, Pos);
pBody->SetWorld(WorldMat);
//WorldMat = ScaleMat * Matrix(IDENTITY) * Matrix(TRANS, Pos + Vect(0, turretOffset, 0));
//pTurret->SetWorld(WorldMat);
} | 26.601449 | 204 | 0.676655 | [
"render"
] |
761d49b83c385f86fafdc1e5c5090278683a714f | 7,654 | cpp | C++ | CM2005 Object Oriented Programming/Midterm/Merkelrex-TradingBot/OrderBook.cpp | LevDoesCode/UoL | 312b2d1096af4925c94b81d656e5d326dbad939e | [
"MIT"
] | null | null | null | CM2005 Object Oriented Programming/Midterm/Merkelrex-TradingBot/OrderBook.cpp | LevDoesCode/UoL | 312b2d1096af4925c94b81d656e5d326dbad939e | [
"MIT"
] | null | null | null | CM2005 Object Oriented Programming/Midterm/Merkelrex-TradingBot/OrderBook.cpp | LevDoesCode/UoL | 312b2d1096af4925c94b81d656e5d326dbad939e | [
"MIT"
] | null | null | null | #include "OrderBook.h"
#include "CSVReader.h"
#include <map>
#include <algorithm>
#include <iostream>
/** construct, reading a csv data file */
OrderBook::OrderBook(std::string filename)
{
orders = CSVReader::readCSV(filename);
std::map<std::string, bool> prodMap;
for (OrderBookEntry &e : orders)
{
prodMap[e.product] = true;
}
// now flatten the map to a vector of strings
for (auto const &e : prodMap)
{
knownProducts.push_back(e.first);
}
}
/** return vector of all know products in the dataset*/
std::vector<std::string> OrderBook::getKnownProducts()
{
return knownProducts;
}
/** return vector of Orders according to the sent filters*/
std::vector<OrderBookEntry> OrderBook::getOrders(OrderBookType type, std::string product, std::string timestamp)
{
std::vector<OrderBookEntry> orders_sub;
for (OrderBookEntry &e : orders)
{
if (e.orderType == type &&
e.product == product &&
e.timestamp == timestamp)
{
orders_sub.push_back(e);
}
}
return orders_sub;
}
double OrderBook::getHighPrice(std::vector<OrderBookEntry> &orders)
{
double max = orders[0].price;
for (OrderBookEntry &e : orders)
{
if (e.price > max)
max = e.price;
}
return max;
}
double OrderBook::getLowPrice(std::vector<OrderBookEntry> &orders)
{
double min = orders[0].price;
for (OrderBookEntry &e : orders)
{
if (e.price < min)
min = e.price;
}
return min;
}
std::string OrderBook::getEarliestTime()
{
return orders[0].timestamp;
}
std::string OrderBook::getNextTime(std::string timestamp)
{
std::string next_timestamp = "";
for (OrderBookEntry &e : orders)
{
if (e.timestamp > timestamp)
{
next_timestamp = e.timestamp;
break;
}
}
if (next_timestamp == "")
{
next_timestamp = orders[0].timestamp;
}
// break the loop by comparing the argument timestamp with the timestamp found
if (timestamp > next_timestamp)
{
return "END";
}
return next_timestamp;
}
void OrderBook::insertOrder(OrderBookEntry &order)
{
orders.push_back(order);
std::sort(orders.begin(), orders.end(), OrderBookEntry::compareByTimestamp);
}
// Remove order from the order book
void OrderBook::removeOrder(OrderBookEntry &order)
{
for(int i=0; i<orders.size(); ++i)
{
if (orders[i].username == order.username &&
orders[i].timestamp == order.timestamp &&
orders[i].orderType == order.orderType &&
orders[i].product == order.product &&
orders[i].price == order.price &&
orders[i].amount == order.amount
)
{
orders.erase(orders.begin() + i);
--i;
}
}
return;
}
std::vector<OrderBookEntry> OrderBook::matchAsksToBids(std::string product, std::string timestamp)
{
// asks = orderbook.asks
std::vector<OrderBookEntry> asks = getOrders(OrderBookType::ask, product, timestamp);
// bids = orderbook.bids
std::vector<OrderBookEntry> bids = getOrders(OrderBookType::bid, product, timestamp);
// sales = []
std::vector<OrderBookEntry> sales;
// I put in a little check to ensure we have bids and asks
// to process.
if (asks.size() == 0 || bids.size() == 0)
{
std::cout << " OrderBook::matchAsksToBids no bids or asks" << std::endl;
return sales;
}
// sort asks lowest first
std::sort(asks.begin(), asks.end(), OrderBookEntry::compareByPriceAsc);
// sort bids highest first
std::sort(bids.begin(), bids.end(), OrderBookEntry::compareByPriceDesc);
// for ask in asks:
std::cout << "max ask " << asks[asks.size() - 1].price << std::endl;
std::cout << "min ask " << asks[0].price << std::endl;
std::cout << "max bid " << bids[0].price << std::endl;
std::cout << "min bid " << bids[bids.size() - 1].price << std::endl;
for (OrderBookEntry &ask : asks)
{
// for bid in bids:
for (OrderBookEntry &bid : bids)
{
// if bid.price >= ask.price # we have a match
if (bid.price >= ask.price)
{
// sale = new order()
// sale.price = ask.price
OrderBookEntry sale{ask.price, 0, timestamp, product, OrderBookType::asksale};
if (bid.username == "simuser")
{
sale.username = "simuser";
sale.orderType = OrderBookType::bidsale;
}
if (ask.username == "simuser")
{
sale.username = "simuser";
sale.orderType = OrderBookType::asksale;
}
// # now work out how much was sold and
// # create new bids and asks covering
// # anything that was not sold
// if bid.amount == ask.amount: # bid completely clears ask
if (bid.amount == ask.amount)
{
// sale.amount = ask.amount
sale.amount = ask.amount;
// sales.append(sale)
sales.push_back(sale);
// bid.amount = 0 # make sure the bid is not processed again
bid.amount = 0;
// # can do no more with this ask
// # go onto the next ask
// break
break;
}
// if bid.amount > ask.amount: # ask is completely gone slice the bid
if (bid.amount > ask.amount)
{
// sale.amount = ask.amount
sale.amount = ask.amount;
// sales.append(sale)
sales.push_back(sale);
// # we adjust the bid in place
// # so it can be used to process the next ask
// bid.amount = bid.amount - ask.amount
bid.amount = bid.amount - ask.amount;
// # ask is completely gone, so go to next ask
// break
break;
}
// if bid.amount < ask.amount # bid is completely gone, slice the ask
if (bid.amount < ask.amount &&
bid.amount > 0)
{
// sale.amount = bid.amount
sale.amount = bid.amount;
// sales.append(sale)
sales.push_back(sale);
// # update the ask
// # and allow further bids to process the remaining amount
// ask.amount = ask.amount - bid.amount
ask.amount = ask.amount - bid.amount;
// bid.amount = 0 # make sure the bid is not processed again
bid.amount = 0;
// # some ask remains so go to the next bid
// continue
continue;
}
}
}
}
return sales;
} | 33.423581 | 112 | 0.491116 | [
"vector"
] |
761ee00c374a10389ef9d0d21f32113e611f62e3 | 359 | cpp | C++ | CodeForces/Complete/500-599/523A-RotateFlipAndZoom.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/500-599/523A-RotateFlipAndZoom.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/500-599/523A-RotateFlipAndZoom.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <cstdio>
#include <iostream>
#include <vector>
int main(){
int w, h; scanf("%d %d\n", &w, &h);
std::vector<std::string> s(h);
for(int p = 0; p < h; p++){getline(std::cin, s[p]);}
for(int p = 0; p < 2 * w; p++){
for(int q = 0; q < 2 * h; q++){std::cout << s[q/2][p/2];}
std::cout << std::endl;
}
return 0;
}
| 21.117647 | 65 | 0.462396 | [
"vector"
] |
7623aa6b3077534c5f531b86e3887d0501b38421 | 17,079 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/view/InputConnectionWrapper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/view/InputConnectionWrapper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/view/InputConnectionWrapper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "elastos/droid/internal/view/InputConnectionWrapper.h"
#include "elastos/droid/internal/view/CInputContextCallback.h"
#include "elastos/droid/os/SystemClock.h"
#include <elastos/core/AutoLock.h>
#include <elastos/utility/logging/Logger.h>
using Elastos::Droid::Os::EIID_IBinder;
using Elastos::Droid::Os::SystemClock;
using Elastos::Droid::View::InputMethod::EIID_IInputConnection;
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace Internal {
namespace View {
static AutoPtr<InputConnectionWrapper::InputContextCallback> InitCallback()
{
AutoPtr<CInputContextCallback> callback;
CInputContextCallback::NewByFriend((CInputContextCallback**)&callback);
return callback;
}
const String InputConnectionWrapper::InputContextCallback::TAG("InputConnectionWrapper.ICC");
AutoPtr<InputConnectionWrapper::InputContextCallback> InputConnectionWrapper::InputContextCallback::sInstance = InitCallback();
Int32 InputConnectionWrapper::InputContextCallback::sSequenceNumber = 1;
Object InputConnectionWrapper::InputContextCallback::sLock;
CAR_INTERFACE_IMPL_2(InputConnectionWrapper::InputContextCallback, Object, IIInputContextCallback, IBinder)
InputConnectionWrapper::InputContextCallback::InputContextCallback()
: mSeq(0)
, mHaveValue(FALSE)
, mCursorCapsMode(0)
, mRequestUpdateCursorAnchorInfoResult(FALSE)
{
}
ECode InputConnectionWrapper::InputContextCallback::constructor()
{
return NOERROR;
}
AutoPtr<InputConnectionWrapper::InputContextCallback>
InputConnectionWrapper::InputContextCallback::GetInstance()
{
AutoLock lock(sLock);
// Return sInstance if it's non-NULL, otherwise construct a new callback
AutoPtr<InputContextCallback> callback;
if (sInstance != NULL) {
callback = sInstance;
sInstance = NULL;
// Reset the callback
callback->mHaveValue = FALSE;
}
else {
callback = InitCallback();
}
// Set the sequence number
callback->mSeq = sSequenceNumber++;
return callback;
}
/**
* Makes the given InputContextCallback available for use in the future.
*/
void InputConnectionWrapper::InputContextCallback::Dispose()
{
AutoLock lock(sLock);
// If sInstance is non-NULL, just let this object be garbage-collected
if (sInstance == NULL) {
// Allow any objects being held to be gc'ed
mTextAfterCursor = NULL;
mTextBeforeCursor = NULL;
mExtractedText = NULL;
sInstance = this;
}
}
ECode InputConnectionWrapper::InputContextCallback::SetTextBeforeCursor(
/* [in] */ ICharSequence* textBeforeCursor,
/* [in] */ Int32 seq)
{
AutoLock lock(this);
if (seq == mSeq) {
mTextBeforeCursor = textBeforeCursor;
mHaveValue = TRUE;
NotifyAll();
}
else {
Logger::I(TAG, "Got out-of-sequence callback %d (expected %d)"
" in setTextBeforeCursor, ignoring.", seq, mSeq);
}
return NOERROR;
}
ECode InputConnectionWrapper::InputContextCallback::SetTextAfterCursor(
/* [in] */ ICharSequence* textAfterCursor,
/* [in] */ Int32 seq)
{
AutoLock lock(this);
if (seq == mSeq) {
mTextAfterCursor = textAfterCursor;
mHaveValue = TRUE;
NotifyAll();
}
else {
Logger::I(TAG, "Got out-of-sequence callback %d (expected %d)"
" in setTextAfterCursor, ignoring.", seq, mSeq);
}
return NOERROR;
}
ECode InputConnectionWrapper::InputContextCallback::SetSelectedText(
/* [in] */ ICharSequence* selectedText,
/* [in] */ Int32 seq)
{
AutoLock lock(this);
if (seq == mSeq) {
mSelectedText = selectedText;
mHaveValue = TRUE;
NotifyAll();
}
else {
Logger::I(TAG, "Got out-of-sequence callback %d (expected %d)"
" in SetSelectedText, ignoring.", seq, mSeq);
}
return NOERROR;
}
ECode InputConnectionWrapper::InputContextCallback::SetCursorCapsMode(
/* [in] */ Int32 capsMode,
/* [in] */ Int32 seq)
{
AutoLock lock(this);
if (seq == mSeq) {
mCursorCapsMode = capsMode;
mHaveValue = TRUE;
NotifyAll();
}
else {
Logger::I(TAG, "Got out-of-sequence callback %d (expected %d)"
" in SetCursorCapsMode, ignoring.", seq, mSeq);
}
return NOERROR;
}
ECode InputConnectionWrapper::InputContextCallback::SetExtractedText(
/* [in] */ IExtractedText* extractedText,
/* [in] */ Int32 seq)
{
AutoLock lock(this);
if (seq == mSeq) {
mExtractedText = extractedText;
mHaveValue = TRUE;
NotifyAll();
}
else {
Logger::I(TAG, "Got out-of-sequence callback %d (expected %d)"
" in SetExtractedText, ignoring.", seq, mSeq);
}
return NOERROR;
}
ECode InputConnectionWrapper::InputContextCallback::SetRequestUpdateCursorAnchorInfoResult(
/* [in] */ Boolean result,
/* [in] */ Int32 seq)
{
AutoLock lock(this);
if (seq == mSeq) {
mRequestUpdateCursorAnchorInfoResult = result;
mHaveValue = TRUE;
NotifyAll();
}
else {
Logger::I(TAG, "Got out-of-sequence callback %d (expected %d)"
" in SetRequestUpdateCursorAnchorInfoResult, ignoring.", seq, mSeq);
}
return NOERROR;
}
void InputConnectionWrapper::InputContextCallback::WaitForResultLocked()
{
Int64 startTime = SystemClock::GetUptimeMillis();
Int64 endTime = startTime + InputConnectionWrapper::MAX_WAIT_TIME_MILLIS;
while (!mHaveValue) {
Int64 remainingTime = endTime - SystemClock::GetUptimeMillis();
if (remainingTime <= 0) {
Logger::W(TAG, "Timed out waiting on IIInputContextCallback");
return;
}
// try {
Wait(remainingTime);
// } catch (InterruptedException e) {
// }
}
}
ECode InputConnectionWrapper::InputContextCallback::ToString(
/* [out] */ String* str)
{
return Object::ToString(str);
}
const Int32 InputConnectionWrapper::MAX_WAIT_TIME_MILLIS = 2000;
CAR_INTERFACE_IMPL(InputConnectionWrapper, Object, IInputConnection)
ECode InputConnectionWrapper::constructor(
/* [in] */ IIInputContext* inputContext)
{
// assert(inputContext != NULL);
mIInputContext = inputContext;
return NOERROR;
}
ECode InputConnectionWrapper::GetTextAfterCursor(
/* [in] */ Int32 n,
/* [in] */ Int32 flags,
/* [out] */ ICharSequence** text)
{
VALIDATE_NOT_NULL(text);
*text = NULL;
AutoPtr<InputContextCallback> callback = InputContextCallback::GetInstance();
if (FAILED(mIInputContext->GetTextAfterCursor(n, flags, callback->mSeq, callback.Get())))
return NOERROR;
{
AutoLock lock(callback);
callback->WaitForResultLocked();
if (callback->mHaveValue) {
*text = callback->mTextAfterCursor;
}
}
callback->Dispose();
// catch (RemoteException e) {
// return NULL;
// }
REFCOUNT_ADD(*text);
return NOERROR;
}
ECode InputConnectionWrapper::GetTextBeforeCursor(
/* [in] */ Int32 n,
/* [in] */ Int32 flags,
/* [out] */ ICharSequence** text)
{
VALIDATE_NOT_NULL(text);
*text = NULL;
AutoPtr<InputContextCallback> callback = InputContextCallback::GetInstance();
if (FAILED(mIInputContext->GetTextBeforeCursor(n, flags, callback->mSeq, callback.Get())))
return NOERROR;
{
AutoLock lock(callback);
callback->WaitForResultLocked();
if (callback->mHaveValue) {
*text = callback->mTextBeforeCursor;
REFCOUNT_ADD(*text);
}
}
callback->Dispose();
// } catch (RemoteException e) {
// return NULL;
// }
return NOERROR;
}
ECode InputConnectionWrapper::GetSelectedText(
/* [in] */ Int32 flags,
/* [out] */ ICharSequence** text)
{
VALIDATE_NOT_NULL(text);
*text = NULL;
AutoPtr<InputContextCallback> callback = InputContextCallback::GetInstance();
if (FAILED(mIInputContext->GetSelectedText(flags, callback->mSeq, callback.Get())))
return NOERROR;
{
AutoLock lock(callback);
callback->WaitForResultLocked();
if (callback->mHaveValue) {
*text = callback->mSelectedText;
}
}
callback->Dispose();
// } catch (RemoteException e) {
// return NULL;
// }
REFCOUNT_ADD(*text);
return NOERROR;
}
ECode InputConnectionWrapper::GetCursorCapsMode(
/* [in] */ Int32 reqModes,
/* [out] */ Int32* capsMode)
{
VALIDATE_NOT_NULL(capsMode);
*capsMode = 0;
AutoPtr<InputContextCallback> callback = InputContextCallback::GetInstance();
if (FAILED(mIInputContext->GetCursorCapsMode(reqModes, callback->mSeq, callback.Get())))
return NOERROR;
{
AutoLock lock(callback);
callback->WaitForResultLocked();
if (callback->mHaveValue) {
*capsMode = callback->mCursorCapsMode;
}
}
callback->Dispose();
// } catch (RemoteException e) {
// return 0;
// }
return NOERROR;
}
ECode InputConnectionWrapper::GetExtractedText(
/* [in] */ IExtractedTextRequest* request,
/* [in] */ Int32 flags,
/* [out] */ IExtractedText** extractedText)
{
VALIDATE_NOT_NULL(extractedText);
*extractedText = NULL;
AutoPtr<InputContextCallback> callback = InputContextCallback::GetInstance();
if (FAILED(mIInputContext->GetExtractedText(request, flags, callback->mSeq, callback.Get())))
return NOERROR;
{
AutoLock lock(callback);
callback->WaitForResultLocked();
if (callback->mHaveValue) {
*extractedText = callback->mExtractedText;
}
}
callback->Dispose();
// } catch (RemoteException e) {
// return NULL;
// }
REFCOUNT_ADD(*extractedText);
return NOERROR;
}
ECode InputConnectionWrapper::CommitText(
/* [in] */ ICharSequence* text,
/* [in] */ Int32 newCursorPosition,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->CommitText(text, newCursorPosition);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::CommitCompletion(
/* [in] */ ICompletionInfo* text,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->CommitCompletion(text);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::CommitCorrection(
/* [in] */ ICorrectionInfo* correctionInfo,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->CommitCorrection(correctionInfo);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::SetSelection(
/* [in] */ Int32 start,
/* [in] */ Int32 end,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->SetSelection(start, end);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::PerformEditorAction(
/* [in] */ Int32 editorAction,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->PerformEditorAction(editorAction);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::PerformContextMenuAction(
/* [in] */ Int32 id,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->PerformContextMenuAction(id);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::SetComposingRegion(
/* [in] */ Int32 start,
/* [in] */ Int32 end,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->SetComposingRegion(start, end);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::SetComposingText(
/* [in] */ ICharSequence* text,
/* [in] */ Int32 newCursorPosition,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->SetComposingText(text, newCursorPosition);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::FinishComposingText(
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->FinishComposingText();
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::BeginBatchEdit(
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->BeginBatchEdit();
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::EndBatchEdit(
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->EndBatchEdit();
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::SendKeyEvent(
/* [in] */ IKeyEvent* event,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->SendKeyEvent(event);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::ClearMetaKeyStates(
/* [in] */ Int32 states,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->ClearMetaKeyStates(states);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::DeleteSurroundingText(
/* [in] */ Int32 leftLength,
/* [in] */ Int32 rightLength,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->DeleteSurroundingText(leftLength, rightLength);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::ReportFullscreenMode(
/* [in] */ Boolean enabled,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->ReportFullscreenMode(enabled);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::PerformPrivateCommand(
/* [in] */ const String& action,
/* [in] */ IBundle* data,
/* [out] */ Boolean* flag)
{
VALIDATE_NOT_NULL(flag);
// try {
ECode ec = mIInputContext->PerformPrivateCommand(action, data);
*flag = SUCCEEDED(ec) ? TRUE : FALSE;
return ec;
// } catch (RemoteException e) {
// return FALSE;
// }
}
ECode InputConnectionWrapper::RequestCursorUpdates(
/* [in] */ Int32 cursorUpdateMode,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
*result = FALSE;
AutoPtr<InputContextCallback> callback = InputContextCallback::GetInstance();
if (FAILED(mIInputContext->RequestUpdateCursorAnchorInfo(
cursorUpdateMode, callback->mSeq, callback)))
return NOERROR;
{
AutoLock lock(callback);
callback->WaitForResultLocked();
if (callback->mHaveValue) {
*result = callback->mRequestUpdateCursorAnchorInfoResult;
}
}
callback->Dispose();
return NOERROR;
}
} // namespace View
} // namespace Internal
} // namespace Droid
} // namespace Elastos
| 26.47907 | 127 | 0.631243 | [
"object"
] |
7623c8ec9ed31d9e96f78ae27c9eb3130125d8a3 | 3,407 | cpp | C++ | src/demo/main.cpp | N4G170/sdl_gui | a3541d372a7884d0375df360f9244682a98a0de3 | [
"MIT"
] | null | null | null | src/demo/main.cpp | N4G170/sdl_gui | a3541d372a7884d0375df360f9244682a98a0de3 | [
"MIT"
] | null | null | null | src/demo/main.cpp | N4G170/sdl_gui | a3541d372a7884d0375df360f9244682a98a0de3 | [
"MIT"
] | null | null | null | #include <iostream>
#include "SDL.h"
#include "sdl_init.hpp"
#include "sdl_gui_demo.hpp"
#include <chrono>
int main(int argc, char* argv[])
{
SDL_Window* window{nullptr};
SDL_Renderer* renderer{nullptr};
//init SDL subsystems
SDLInitConfig sdl_config{};//load default values
bool init_result = InitSDL(window, renderer, sdl_config);
if(!init_result)//failed to initialize sdl subsystems
{
//terminate any initialized sdl subsystems
TerminateSDL();
DeleteSDLPointers(window, renderer);//they are deleted in a sepecific way
window = nullptr;
renderer = nullptr;
return -2;
}
else//sdl started ok
{
//sdl_gui vars
sdl_gui::ResourceManager resource_manager{ renderer };
GuiDemo demo{ renderer, &resource_manager, sdl_config };
bool quit{false};
//Create Event handler
SDL_Event event;
float frame_cap {1.f / 60 * 1000};
float last_frame_time {0.f};
float fixed_frame_time {0.03f};
float accumulated_time {0.f};
while(!quit)
{
auto start_time(std::chrono::high_resolution_clock::now());
float fps{0};
accumulated_time += last_frame_time;
//Handle events on queue
while( SDL_PollEvent( &event ) != 0 )
{
// SDL_Texture* f1 = SDL_CreateTextureFromSurface(renderer.get(), TTF_RenderText_Blended(f, std::u32string("Ups \u00c0 tester"), {255,255,255,255}));
//TODO:0 send exit code to states
//User requests quit
if( event.type == SDL_QUIT)
quit = true;
else if(event.type == SDL_KEYDOWN)
{
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE: quit = true; break;
}
}
demo.Input(event);
}
//Fixed time step Logic
while(accumulated_time >= fixed_frame_time)
{
demo.FixedLogic(fixed_frame_time);
accumulated_time -= fixed_frame_time;
}
//Variable time step Logic
demo.Logic(last_frame_time);
//Clear screen
SDL_SetRenderDrawColor( renderer, 0x00, 0x00, 0x00, 0x00 );
SDL_RenderClear( renderer );
demo.Render(renderer, last_frame_time);
//Update screen
SDL_RenderPresent( renderer );
//Update frame timers
auto delta_time(std::chrono::high_resolution_clock::now() - start_time);
float frame_time = std::chrono::duration_cast< std::chrono::duration<float, std::milli> >(delta_time).count();
//fps cap
if(frame_time < frame_cap)
{
SDL_Delay(frame_cap - frame_time);
frame_time = frame_cap;
}
frame_time /= 1000.f;
fps = 1.f / frame_time;
last_frame_time = frame_time;
SDL_SetWindowTitle(window, ( sdl_config.window_name +" - "+ std::to_string(fps)+" FPS").c_str() );
}// while(!quit)
}
//terminate SDL subsystems
TerminateSDL();
DeleteSDLPointers(window, renderer);//they are deleted in a sepecific way
window = nullptr;
renderer = nullptr;
return 0;
}
| 29.37069 | 165 | 0.560611 | [
"render"
] |
7629d58be54a4ad1acc3423e8e09579ecee4b5a4 | 1,413 | cpp | C++ | Algorithms/Easy/590.n-ary-tree-postorder-traversal.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | Algorithms/Easy/590.n-ary-tree-postorder-traversal.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | Algorithms/Easy/590.n-ary-tree-postorder-traversal.cpp | jtcheng/leetcode | db58973894757789d060301b589735b5985fe102 | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=590 lang=cpp
*
* [590] N-ary Tree Postorder Traversal
*
* https://leetcode.com/problems/n-ary-tree-postorder-traversal/description/
*
* algorithms
* Easy (67.16%)
* Likes: 275
* Dislikes: 37
* Total Accepted: 37.4K
* Total Submissions: 55.5K
* Testcase Example: '{"$id":"1","children":[{"$id":"2","children":[{"$id":"5","children":[],"val":5},{"$id":"6","children":[],"val":6}],"val":3},{"$id":"3","children":[],"val":2},{"$id":"4","children":[],"val":4}],"val":1}'
*
* Given an n-ary tree, return the postorder traversal of its nodes' values.
*
* For example, given a 3-ary tree:
*
*
*
*
*
*
*
* Return its postorder traversal as: [5,6,3,2,4,1].
*
*
* Note:
*
* Recursive solution is trivial, could you do it iteratively?
*
*/
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node *root) {
if (root == nullptr) {
return nodes;
}
_postorder(root);
return nodes;
}
private:
void _postorder(Node *node) {
for (auto child : node->children) {
_postorder(child);
}
nodes.push_back(node->val);
}
private:
vector<int> nodes;
};
| 19.901408 | 225 | 0.553432 | [
"vector"
] |
762fd10e34c01cad30dcd8b0205915dd6e99e92e | 6,110 | cpp | C++ | src/analysis/processing/qgsalgorithmshortestpathlayertopoint.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/analysis/processing/qgsalgorithmshortestpathlayertopoint.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/analysis/processing/qgsalgorithmshortestpathlayertopoint.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | /***************************************************************************
qgsalgorithmshortestpathlayertopoint.cpp
---------------------
begin : July 2018
copyright : (C) 2018 by Alexander Bruy
email : alexander dot bruy at gmail dot com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsalgorithmshortestpathlayertopoint.h"
#include "qgsgraphanalyzer.h"
#include "qgsmessagelog.h"
///@cond PRIVATE
QString QgsShortestPathLayerToPointAlgorithm::name() const
{
return QStringLiteral( "shortestpathlayertopoint" );
}
QString QgsShortestPathLayerToPointAlgorithm::displayName() const
{
return QObject::tr( "Shortest path (layer to point)" );
}
QStringList QgsShortestPathLayerToPointAlgorithm::tags() const
{
return QObject::tr( "network,path,shortest,fastest" ).split( ',' );
}
QString QgsShortestPathLayerToPointAlgorithm::shortHelpString() const
{
return QObject::tr( "This algorithm computes optimal (shortest or fastest) route from multiple start points defined by vector layer and given end point." );
}
QgsShortestPathLayerToPointAlgorithm *QgsShortestPathLayerToPointAlgorithm::createInstance() const
{
return new QgsShortestPathLayerToPointAlgorithm();
}
void QgsShortestPathLayerToPointAlgorithm::initAlgorithm( const QVariantMap & )
{
addCommonParams();
addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "START_POINTS" ), QObject::tr( "Vector layer with start points" ), QList< int >() << QgsProcessing::TypeVectorPoint ) );
addParameter( new QgsProcessingParameterPoint( QStringLiteral( "END_POINT" ), QObject::tr( "End point" ) ) );
addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Shortest path" ), QgsProcessing::TypeVectorLine ) );
}
QVariantMap QgsShortestPathLayerToPointAlgorithm::processAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
loadCommonParams( parameters, context, feedback );
QgsPointXY endPoint = parameterAsPoint( parameters, QStringLiteral( "END_POINT" ), context, mNetwork->sourceCrs() );
std::unique_ptr< QgsFeatureSource > startPoints( parameterAsSource( parameters, QStringLiteral( "START_POINTS" ), context ) );
if ( !startPoints )
throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "START_POINTS" ) ) );
QgsFields fields = startPoints->fields();
fields.append( QgsField( QStringLiteral( "start" ), QVariant::String ) );
fields.append( QgsField( QStringLiteral( "end" ), QVariant::String ) );
fields.append( QgsField( QStringLiteral( "cost" ), QVariant::Double ) );
QString dest;
std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, QgsWkbTypes::LineString, mNetwork->sourceCrs() ) );
if ( !sink )
throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
QVector< QgsPointXY > points;
points.push_front( endPoint );
QHash< int, QgsAttributes > sourceAttributes;
loadPoints( startPoints.get(), points, sourceAttributes, context, feedback );
feedback->pushInfo( QObject::tr( "Building graph…" ) );
QVector< QgsPointXY > snappedPoints;
mDirector->makeGraph( mBuilder.get(), points, snappedPoints, feedback );
feedback->pushInfo( QObject::tr( "Calculating shortest paths…" ) );
QgsGraph *graph = mBuilder->graph();
int idxEnd = graph->findVertex( snappedPoints[0] );
int idxStart;
int currentIdx;
QVector< int > tree;
QVector< double > costs;
QVector<QgsPointXY> route;
double cost;
QgsFeature feat;
feat.setFields( fields );
QgsAttributes attributes;
int step = points.size() > 0 ? 100.0 / points.size() : 1;
for ( int i = 1; i < points.size(); i++ )
{
if ( feedback->isCanceled() )
{
break;
}
idxStart = graph->findVertex( snappedPoints[i] );
QgsGraphAnalyzer::dijkstra( graph, idxStart, 0, &tree, &costs );
if ( tree.at( idxEnd ) == -1 )
{
feedback->reportError( QObject::tr( "There is no route from start point (%1) to end point (%2)." )
.arg( points[i].toString(),
endPoint.toString() ) );
feat.clearGeometry();
attributes = sourceAttributes.value( i );
attributes.append( points[i].toString() );
feat.setAttributes( attributes );
sink->addFeature( feat, QgsFeatureSink::FastInsert );
continue;
}
route.clear();
route.push_front( graph->vertex( idxEnd ).point() );
cost = costs.at( idxEnd );
currentIdx = idxEnd;
while ( currentIdx != idxStart )
{
currentIdx = graph->edge( tree.at( currentIdx ) ).fromVertex();
route.push_front( graph->vertex( currentIdx ).point() );
}
QgsGeometry geom = QgsGeometry::fromPolylineXY( route );
QgsFeature feat;
feat.setFields( fields );
attributes = sourceAttributes.value( i );
attributes.append( points[i].toString() );
attributes.append( endPoint.toString() );
attributes.append( cost / mMultiplier );
feat.setAttributes( attributes );
feat.setGeometry( geom );
sink->addFeature( feat, QgsFeatureSink::FastInsert );
feedback->setProgress( i * step );
}
QVariantMap outputs;
outputs.insert( QStringLiteral( "OUTPUT" ), dest );
return outputs;
}
///@endcond
| 38.427673 | 193 | 0.634534 | [
"vector"
] |
7635f8f66e241cb465ecb59f668a760b734da714 | 10,548 | cpp | C++ | src/single_net/PreRoute.cpp | limbo018/dr-cu | 7ea9d4f019dd3fd75676c69395df3bfe88958f9f | [
"Unlicense"
] | null | null | null | src/single_net/PreRoute.cpp | limbo018/dr-cu | 7ea9d4f019dd3fd75676c69395df3bfe88958f9f | [
"Unlicense"
] | null | null | null | src/single_net/PreRoute.cpp | limbo018/dr-cu | 7ea9d4f019dd3fd75676c69395df3bfe88958f9f | [
"Unlicense"
] | 1 | 2020-04-13T18:44:39.000Z | 2020-04-13T18:44:39.000Z | #include "PreRoute.h"
db::RouteStatus PreRoute::run(int numPitchForGuideExpand) {
// expand guides uniformally
auto& guides = localNet.routeGuides;
for (int i = 0; i < guides.size(); ++i) {
int expand = localNet.dbNet.routeGuideVios[i] ? numPitchForGuideExpand : db::setting.defaultGuideExpand;
database.expandBox(guides[i], numPitchForGuideExpand);
}
// add diff-layer guides
if (db::rrrIterSetting.addDiffLayerGuides) {
int oriSize = guides.size();
for (int i = 0; i < oriSize; ++i) {
int j = guides[i].layerIdx;
if (localNet.dbNet.routeGuideVios[i] >= db::setting.diffLayerGuideVioThres) {
if (j > 2) guides.emplace_back(j - 1, guides[i]); // do not add to layers 0, 1
if ((j + 1) < database.getLayerNum()) guides.emplace_back(j + 1, guides[i]);
db::routeStat.increment(db::RouteStage::PRE, db::MiscRouteEvent::ADD_DIFF_LAYER_GUIDE_1, 1);
}
if (localNet.dbNet.routeGuideVios[i] >= db::setting.diffLayerGuideVioThres * 2) {
if (j > 3) guides.emplace_back(j - 2, guides[i]); // do not add to layers 0, 1
if ((j + 2) < database.getLayerNum()) guides.emplace_back(j + 2, guides[i]);
db::routeStat.increment(db::RouteStage::PRE, db::MiscRouteEvent::ADD_DIFF_LAYER_GUIDE_2, 1);
}
}
}
// expand guides by cross layer connection
expandGuidesToMargin();
db::RouteStatus status = db::RouteStatus::SUCC_NORMAL;
if (localNet.numOfPins() < 2) {
status = db::RouteStatus::SUCC_ONE_PIN;
} else {
// expand guides to cover pin
status = expandGuidesToCoverPins();
if (db::isSucc(status)) {
// init localNet and check
localNet.initGridBoxes();
localNet.initConn(localNet.gridPinAccessBoxes, localNet.gridRouteGuides);
localNet.initNumOfVertices();
if (!localNet.checkPin()) {
status = db::RouteStatus::FAIL_PIN_OUT_OF_GRID;
} else if (!localNet.checkPinGuideConn()) {
status = db::RouteStatus::FAIL_DETACHED_PIN;
} else if (!checkGuideConnTrack()) {
status = db::RouteStatus::FAIL_DETACHED_GUIDE;
}
}
}
printWarnMsg(status, localNet.dbNet);
return status;
}
db::RouteStatus PreRoute::runIterative() {
db::RouteStatus status = run(db::rrrIterSetting.defaultGuideExpand);
int iter = 0;
int numPitchForGuideExpand = db::rrrIterSetting.defaultGuideExpand;
utils::timer singleNetTimer;
while (status == +db::RouteStatus::FAIL_DETACHED_GUIDE && iter < db::setting.guideExpandIterLimit) {
iter++;
numPitchForGuideExpand += iter;
status = run(numPitchForGuideExpand);
}
if (iter >= 1) {
log() << "Warning: Net " << localNet.getName() << " expands " << iter << " iterations"
<< ", which takes " << singleNetTimer.elapsed() << " s in total." << std::endl;
if (status == +db::RouteStatus::FAIL_DETACHED_GUIDE) {
log() << "Error: Exceed the guideExpandIterLimit, but still FAIL_DETACHED_GUIDE" << std::endl;
}
}
db::routeStat.increment(db::RouteStage::PRE, status);
return status;
}
void PreRoute::expandGuidesToMargin() {
vector<db::BoxOnLayer>& guides = localNet.routeGuides;
vector<vector<int>> crossLayerConn(guides.size());
for (unsigned g1 = 0; g1 < guides.size(); g1++) {
db::BoxOnLayer& box1 = guides[g1];
for (unsigned g2 = g1 + 1; g2 < guides.size(); g2++) {
db::BoxOnLayer& box2 = guides[g2];
if (abs(box1.layerIdx - box2.layerIdx) == 1 && box1.HasIntersectWith(box2)) {
crossLayerConn[g1].push_back(g2);
}
}
}
for (unsigned g1 = 0; g1 < guides.size(); g1++) {
for (auto g2 : crossLayerConn[g1]) {
Dimension dir1 = database.getLayerDir(guides[g1].layerIdx);
Dimension dir2 = database.getLayerDir(guides[g2].layerIdx);
guides[g1][dir2].Update(guides[g2][dir2].low);
guides[g1][dir2].Update(guides[g2][dir2].high);
guides[g2][dir1].Update(guides[g1][dir1].low);
guides[g2][dir1].Update(guides[g1][dir1].high);
}
}
}
db::RouteStatus PreRoute::expandGuidesToCoverPins() {
db::RouteStatus status = db::RouteStatus::SUCC_NORMAL;
for (int i = 0; i < localNet.numOfPins(); ++i) {
int bestAB = -1;
int bestGuide = -1;
DBU bestDist = std::numeric_limits<DBU>::max();
for (int j = 0; j < localNet.pinAccessBoxes[i].size(); ++j) {
const auto& accessBox = localNet.pinAccessBoxes[i][j];
for (int k = 0; k < localNet.routeGuides.size(); ++k) {
const auto& guide = localNet.routeGuides[k];
if (abs(guide.layerIdx - accessBox.layerIdx) > 1 || !guide.IsValid()) continue;
DBU dist = Dist(accessBox, guide);
if (dist < bestDist) {
bestDist = dist;
bestAB = j;
bestGuide = k;
if (bestDist == 0) {
break;
}
}
}
}
if (bestDist > 0) {
if (bestAB == -1) {
return db::RouteStatus::FAIL_DETACHED_PIN;
} else {
localNet.routeGuides[bestGuide] = {
localNet.routeGuides[bestGuide].layerIdx,
localNet.routeGuides[bestGuide].UnionWith(localNet.pinAccessBoxes[i][bestAB])};
db::routeStat.increment(db::RouteStage::PRE, db::MiscRouteEvent::FIX_DETACHED_PIN, 1);
}
}
}
return status;
}
bool PreRoute::checkGuideConnTrack() const {
// init to all false
vector<char> pinVisited(localNet.pinGuideConn.size(), false);
vector<vector<char>> guideVisited(localNet.guideConn.size());
for (int i = 0; i < localNet.guideConn.size(); i++) {
guideVisited[i].resize(localNet.gridRouteGuides[i].trackRange.range() + 1, false);
}
// define recursive std::functions VisitPin & VisitGuide
std::function<void(int)> VisitPin;
std::function<void(int, utils::IntervalT<int>)> VisitGuide;
VisitPin = [&](int pinIdx) {
pinVisited[pinIdx] = true;
for (const auto& ga : localNet.pinGuideConn[pinIdx]) {
int guideIdx = ga.first;
utils::IntervalT<int> trackInterval = localNet.gridRouteGuides[ga.first].trackRange.IntersectWith(
localNet.gridPinAccessBoxes[pinIdx][ga.second].trackRange);
bool isVisited = true;
int trackLowIdx = localNet.gridRouteGuides[ga.first].trackRange.low;
for (int t = trackInterval.low - trackLowIdx; t <= trackInterval.high - trackLowIdx; t++) {
if (guideVisited[ga.first][t] == false) {
isVisited = false;
guideVisited[ga.first][t] = true;
}
}
if (!isVisited) {
VisitGuide(guideIdx, trackInterval);
}
}
};
VisitGuide = [&](int guideIdx, utils::IntervalT<int> trackRange) {
for (int adjGuideIdx : localNet.guideConn[guideIdx]) {
// to upper layer
if (localNet.gridRouteGuides[guideIdx].layerIdx < localNet.gridRouteGuides[adjGuideIdx].layerIdx) {
utils::IntervalT<int> upperCpInterval =
database.getLayer(localNet.gridRouteGuides[guideIdx].layerIdx).getUpperCrossPointRange(trackRange);
if (localNet.gridRouteGuides[adjGuideIdx].crossPointRange.IntersectWith(upperCpInterval).IsValid()) {
db::ViaBox viaBox = database.getViaBoxBetween(localNet.gridRouteGuides[guideIdx],
localNet.gridRouteGuides[adjGuideIdx]);
bool isVisited = true;
int trackLowIdx = localNet.gridRouteGuides[adjGuideIdx].trackRange.low;
for (int t = viaBox.upper.trackRange.low - trackLowIdx;
t <= viaBox.upper.trackRange.high - trackLowIdx;
t++) {
if (guideVisited[adjGuideIdx][t] == false) {
isVisited = false;
guideVisited[adjGuideIdx][t] = true;
}
}
if (!isVisited) {
VisitGuide(adjGuideIdx, viaBox.upper.trackRange);
}
}
}
if (localNet.gridRouteGuides[guideIdx].layerIdx > localNet.gridRouteGuides[adjGuideIdx].layerIdx) {
utils::IntervalT<int> lowerCpInterval =
database.getLayer(localNet.gridRouteGuides[guideIdx].layerIdx).getLowerCrossPointRange(trackRange);
if (localNet.gridRouteGuides[adjGuideIdx].crossPointRange.IntersectWith(lowerCpInterval).IsValid()) {
db::ViaBox viaBox = database.getViaBoxBetween(localNet.gridRouteGuides[adjGuideIdx],
localNet.gridRouteGuides[guideIdx]);
bool isVisited = true;
int trackLowIdx = localNet.gridRouteGuides[adjGuideIdx].trackRange.low;
for (int t = viaBox.lower.trackRange.low - trackLowIdx;
t <= viaBox.lower.trackRange.high - trackLowIdx;
t++) {
if (guideVisited[adjGuideIdx][t] == false) {
isVisited = false;
guideVisited[adjGuideIdx][t] = true;
}
}
if (!isVisited) {
VisitGuide(adjGuideIdx, viaBox.lower.trackRange);
}
}
}
}
for (const auto& pa : localNet.guidePinConn[guideIdx]) {
utils::IntervalT<int> trackInterval =
trackRange.IntersectWith(localNet.gridPinAccessBoxes[pa.first][pa.second].trackRange);
if (trackInterval.IsValid() && !pinVisited[pa.first]) {
VisitPin(pa.first);
}
}
};
// DFS from pin 0
VisitPin(0);
return all_of(pinVisited.begin(), pinVisited.end(), [](bool visited) { return visited; });
}
| 44.885106 | 119 | 0.558589 | [
"vector"
] |
764bd883880f0e454ef179fadb41edab81926b60 | 596 | cpp | C++ | tools/ruleTree/List.cpp | riyadhariwal1/Gaming-Engine | 96cbebe52979d822828585911f8c1a67a639dc83 | [
"MIT"
] | null | null | null | tools/ruleTree/List.cpp | riyadhariwal1/Gaming-Engine | 96cbebe52979d822828585911f8c1a67a639dc83 | [
"MIT"
] | null | null | null | tools/ruleTree/List.cpp | riyadhariwal1/Gaming-Engine | 96cbebe52979d822828585911f8c1a67a639dc83 | [
"MIT"
] | null | null | null | #include "include/List.h"
List:: List(){
}
List::List (string value){
this -> value = value;
}
void List :: execute(State& state){
//TODO: get the list from game state
list = state.getStateList(value);
//TODO: Interpreter for configuration.Rounds.upfrom(1)
}
void List :: accept(AstVisitor& visitor, State& gameState)
{
visitor.visit(*this, gameState);
}
void List::accept(AstVisitor& visitor, State& , List&, Element&) {}
vector<GameVariant> List:: getList()
{
return list;
}
string List::getValue()
{
return value;
}
void List::print() {
cout << value;
}
| 17.028571 | 67 | 0.651007 | [
"vector"
] |
764cea74de97244e94dcab5356cb61a0cc59304e | 1,119 | cpp | C++ | src/solver.cpp | Aldrog/math-modelling | 97ee1855368a0789f269da6aa758df0f2e88a37f | [
"MIT"
] | null | null | null | src/solver.cpp | Aldrog/math-modelling | 97ee1855368a0789f269da6aa758df0f2e88a37f | [
"MIT"
] | null | null | null | src/solver.cpp | Aldrog/math-modelling | 97ee1855368a0789f269da6aa758df0f2e88a37f | [
"MIT"
] | null | null | null | /*
* Copyright © 2017 Andrew Penkrat
*
* Distributed under the terms of MIT License.
*
* You should have received a copy of the MIT License along with the application.
* If not, see <http://opensource.org/licenses/MIT>.
*/
#include "solver.h"
#include <QElapsedTimer>
#include <QThread>
#include <QDebug>
Solver::Solver(QObject *parent) : QObject(parent)
{
}
void Solver::run()
{
// QElapsedTimer timer;
// timer.start();
Model::State k1 = model.derivative(model.currentState, model.currentTime);
Model::State k2 = model.derivative(model.currentState + k1 * stepSize / 2, model.currentTime + stepSize / 2);
Model::State k3 = model.derivative(model.currentState + k2 * stepSize / 2, model.currentTime + stepSize / 2);
Model::State k4 = model.derivative(model.currentState + k3 * stepSize , model.currentTime + stepSize);
model.currentState = model.currentState + (k1 + k2*2 + k3*2 + k4) * stepSize / 6;
model.currentTime += stepSize;
emit stateReady(model.currentState);
// qint64 processTime = timer.elapsed();
// qDebug() << "Time to process:" << processTime;
}
| 31.083333 | 113 | 0.685433 | [
"model"
] |
7652f28c641a8e7d97d479efad3ef3458326f2d1 | 1,027 | hpp | C++ | third_party/boost/simd/function/split_low.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 6 | 2018-02-25T22:23:33.000Z | 2021-01-15T15:13:12.000Z | third_party/boost/simd/function/split_low.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | third_party/boost/simd/function/split_low.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 7 | 2017-12-12T12:36:31.000Z | 2020-02-10T14:27:07.000Z | //==================================================================================================
/**
Copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_SPLIT_LOW_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_SPLIT_LOW_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-swar
Function object implementing split_low capabilities
SIMD register type-based split_low
@par Header <boost/simd/function/split_low.hpp>
@c split_low extract the lower half of a SIMD register and convert it
to the appropriate SIMD register type of corresponding cardinal.
@see split_high, split, slice
**/
upgrade_t<Value> split_low(Value const& x);
} }
#endif
#include <boost/simd/function/simd/split_low.hpp>
#endif
| 29.342857 | 100 | 0.610516 | [
"object"
] |
76628becc2d73d426b486f54dc296c6fec281056 | 5,794 | cpp | C++ | TestIrrlicht/main.cpp | jbvovau/test-irrlicht | 826ab8be97c4d7a013278992e042d96bb2e252fa | [
"MIT"
] | null | null | null | TestIrrlicht/main.cpp | jbvovau/test-irrlicht | 826ab8be97c4d7a013278992e042d96bb2e252fa | [
"MIT"
] | null | null | null | TestIrrlicht/main.cpp | jbvovau/test-irrlicht | 826ab8be97c4d7a013278992e042d96bb2e252fa | [
"MIT"
] | 1 | 2018-06-11T14:57:27.000Z | 2018-06-11T14:57:27.000Z |
#ifdef _IRR_WINDOWS_
#pragma comment(lib, "Irrlicht.lib")
#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
#endif
#include <irrlicht.h>
#include "prout.h"
#include "event.h"
using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;
int main() {
//http://irrlicht.sourceforge.net/docu/example001.html
EventReceiver receiver;
IrrlichtDevice *device =
createDevice(
video::EDT_DIRECT3D9, //deviceType: Type of the device. This can currently be the Null-device, one of the two software renderers, D3D8, D3D9, or OpenGL. In this example we use EDT_SOFTWARE, but to try out, you might want to change it to EDT_BURNINGSVIDEO, EDT_NULL, EDT_DIRECT3D8, EDT_DIRECT3D9, or EDT_OPENGL.
dimension2d<u32>(1920, 1080), //windowSize: Size of the Window or screen in FullScreenMode to be created. In this example we use 640x480.
32, //bits: Amount of color bits per pixel.This should be 16 or 32. The parameter is often ignored when running in windowed mode.
true, //fullscreen: Specifies if we want the device to run in fullscreen mode or not.
false, //stencilbuffer: Specifies if we want to use the stencil buffer (for drawing shadows).
false, //vsync : Specifies if we want to have vsync enabled, this is only useful in fullscreen mode.
0); //eventReceiver: An object to receive events. We do not want to use this parameter here, and set it to 0.
if (!device)
return 1;
device->setWindowCaption(L"Hello World! - Irrlicht Engine Demo");
IVideoDriver* driver = device->getVideoDriver();
ISceneManager* smgr = device->getSceneManager();
IGUIEnvironment* guienv = device->getGUIEnvironment();
//register scene manager
receiver.setSceneManager(smgr);
//skybox
ISceneNode * skybox = smgr->addSkyBoxSceneNode(
driver->getTexture("Img/hw_lagoon/lagoon_up.tga"), //top
driver->getTexture("Img/hw_lagoon/lagoon_dn.tga") , //bottom
//
driver->getTexture("Img/hw_lagoon/lagoon_rt.tga") ,//left ok
driver->getTexture("Img/hw_lagoon/lagoon_lf.tga") ,//right
driver->getTexture("Img/hw_lagoon/lagoon_ft.tga"), // front ok
driver->getTexture("Img/hw_lagoon/lagoon_bk.tga") //back
);
//
SKeyMap keyMap[9];
keyMap[0].Action = EKA_MOVE_FORWARD;
keyMap[0].KeyCode = KEY_UP;
keyMap[1].Action = EKA_MOVE_FORWARD;
keyMap[1].KeyCode = KEY_KEY_Z;
keyMap[2].Action = EKA_MOVE_BACKWARD;
keyMap[2].KeyCode = KEY_DOWN;
keyMap[3].Action = EKA_MOVE_BACKWARD;
keyMap[3].KeyCode = KEY_KEY_S;
keyMap[4].Action = EKA_STRAFE_LEFT;
keyMap[4].KeyCode = KEY_LEFT;
keyMap[5].Action = EKA_STRAFE_LEFT;
keyMap[5].KeyCode = KEY_KEY_Q;
keyMap[6].Action = EKA_STRAFE_RIGHT;
keyMap[6].KeyCode = KEY_RIGHT;
keyMap[7].Action = EKA_STRAFE_RIGHT;
keyMap[7].KeyCode = KEY_KEY_D;
//jump ?
keyMap[8].Action = EKA_JUMP_UP;
keyMap[8].KeyCode = KEY_SPACE;
//add camera
ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(0,
70, //roateSpeed
0.02f, //movespeed
-1, //id
keyMap, //key map
9, //mapsize
true, //noVerticalMovement ,
0.03f, //jump speed
false, //invert mouse
true //make active
);
camera->setNearValue(0.1f);
camera->setPosition(vector3df(4, 0, 0));
//fog
driver->setFog(SColor(128, 32, 32,32), E_FOG_TYPE::EFT_FOG_LINEAR, 80.f, 300.0f, 0.05f, false);
//texture wall
ITexture* textureMur = driver->getTexture("Img/mur.png");
ITexture* textureSol = driver->getTexture("Img/dry.png");
//test scene irrlicht
//bool loaded = smgr->loadScene("scene.irr");
auto p = new Prout();
s32 v = p->getTrenteDeux();
s32 a = p->getNimp();
p->nimp();
ISceneCollisionManager* collManager = smgr->getSceneCollisionManager();
//light
smgr->setAmbientLight(SColor(255, 255, 255, 255));
driver->setAmbientLight(SColor(255, 100, 255, 255));
//test obj
IAnimatedMesh* meshBlob = smgr->getMesh("Map/blob2.obj");
ISceneNode * complix = smgr->addMeshSceneNode(meshBlob);
complix->setPosition(vector3df(0, 0, 0));
complix->setMaterialFlag(E_MATERIAL_FLAG::EMF_LIGHTING, false);
complix->setMaterialFlag(E_MATERIAL_FLAG::EMF_FOG_ENABLE, true);
//complix->setMaterialTexture(0, textureMur);
//complix->setScale(vector3df(1, 1, 1) / 16);
scene::IMeshSceneNode* q3node = 0;
q3node = smgr->addOctreeSceneNode(meshBlob);
ITriangleSelector* selector = smgr->createOctreeTriangleSelector(
meshBlob, q3node, 128);
q3node->setTriangleSelector(selector);
scene::ISceneNodeAnimator* anim = smgr->createCollisionResponseAnimator(selector,
camera,
core::vector3df(1, 1, 1), //size of body (camera)
core::vector3df(0, -0.2f, 0), //gravity
core::vector3df(0, 1, 0) //position
);
camera->addAnimator(anim);
anim->drop();
selector->drop();
device->getCursorControl()->setVisible(false);
auto monster = smgr->addBillboardSceneNode(0, vector2df(2, 2), vector3df(4, 0, 4), 0);
monster->setMaterialTexture(0, driver->getTexture("Img/dragon.png"));
monster->setMaterialFlag(E_MATERIAL_FLAG::EMF_LIGHTING, false);
monster->setMaterialType(E_MATERIAL_TYPE::EMT_TRANSPARENT_ALPHA_CHANNEL);
ISceneNodeAnimator* fly = smgr->createFlyStraightAnimator(vector3df(0, 0, 0), vector3df(4, 4, 4), 3000, true, true);
monster->addAnimator(fly);
fly->drop();
auto meshExited = smgr->getMesh("Map/hips.b3d");
auto exited = smgr->addAnimatedMeshSceneNode(meshExited, 0, -1, vector3df(6, 0, 0));
exited->setMaterialTexture(0, driver->getTexture("Map/hips.png"));
exited->setFrameLoop(1,200);
exited->setAnimationSpeed(24);
bool alive = true;
while (device->run() && alive) {
//tmp
driver->beginScene(true, true, SColor(255, 100, 101, 140));
smgr->drawAll();
guienv->drawAll();
driver->endScene();
if (camera->getPosition().Y < -300.f) {
alive = false;
}
}
device->drop();
return 0;
} | 30.983957 | 313 | 0.719537 | [
"object"
] |
7663f0432e17c1331fa0067c7005075f38e90644 | 25,067 | cpp | C++ | openbabel-2.4.1/src/formats/mol2format.cpp | sxhexe/reaction-route-search | f7694c84ca1def4a133ade3e1e2e09705cd28312 | [
"MIT"
] | 1 | 2017-09-16T07:36:29.000Z | 2017-09-16T07:36:29.000Z | openbabel-2.4.1/src/formats/mol2format.cpp | sxhexe/reaction-route-search | f7694c84ca1def4a133ade3e1e2e09705cd28312 | [
"MIT"
] | null | null | null | openbabel-2.4.1/src/formats/mol2format.cpp | sxhexe/reaction-route-search | f7694c84ca1def4a133ade3e1e2e09705cd28312 | [
"MIT"
] | null | null | null | /**********************************************************************
Copyright (C) 1998-2001 by OpenEye Scientific Software, Inc.
Some portions Copyright (C) 2001-2007 by Geoffrey R. Hutchison
Some portions Copyright (C) 2004 by Chris Morley
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
***********************************************************************/
#include <openbabel/babelconfig.h>
#include <openbabel/obmolecformat.h>
using namespace std;
namespace OpenBabel
{
//The routine WriteSmiOrderedMol2() in the original mol2.cpp is presumably
//another output format, but was not made available in version 100.1.2, nor
//is it here.
class MOL2Format : public OBMoleculeFormat
{
public:
//Register this format type ID
MOL2Format()
{
OBConversion::RegisterFormat("mol2",this, "chemical/x-mol2");
OBConversion::RegisterFormat("ml2",this);
OBConversion::RegisterFormat("sy2",this);
OBConversion::RegisterOptionParam("c", NULL, 0, OBConversion::INOPTIONS);
OBConversion::RegisterOptionParam("c", NULL, 0, OBConversion::OUTOPTIONS);
OBConversion::RegisterOptionParam("l", NULL, 0, OBConversion::OUTOPTIONS);
}
virtual const char* Description() //required
{
return
"Sybyl Mol2 format\n"
"Read Options e.g. -ac\n"
" c Read UCSF Dock scores saved in comments preceeding molecules\n\n"
"Write Options e.g. -xl\n"
" l Output ignores residue information (only ligands)\n\n";
" c Write UCSF Dock scores saved in comments preceeding molecules\n\n";
};
virtual const char* SpecificationURL()
{
return "http://www.tripos.com/data/support/mol2.pdf";
}; //optional
virtual const char* GetMIMEType()
{ return "chemical/x-mol2"; };
virtual int SkipObjects(int n, OBConversion* pConv);
//*** This section identical for most OBMol conversions ***
////////////////////////////////////////////////////
/// The "API" interface functions
virtual bool ReadMolecule(OBBase* pOb, OBConversion* pConv);
virtual bool WriteMolecule(OBBase* pOb, OBConversion* pConv);
};
//***
//Make an instance of the format class
MOL2Format theMOL2Format;
// Helper function for ReadMolecule
// \return Is this atom a sulfur in a (di)thiocarboxyl (-CS2, -COS, CS2H or COSH) group?
static bool IsThiocarboxylSulfur(OBAtom* queryatom)
{
if (!queryatom->IsSulfur())
return(false);
if (queryatom->GetHvyValence() != 1)
return(false);
OBAtom *atom = NULL;
OBBond *bond;
OBBondIterator i;
for (bond = queryatom->BeginBond(i); bond; bond = queryatom->NextBond(i))
if ((bond->GetNbrAtom(queryatom))->IsCarbon())
{
atom = bond->GetNbrAtom(queryatom);
break;
}
if (!atom)
return(false);
if (!(atom->CountFreeSulfurs() == 2)
&& !(atom->CountFreeOxygens() == 1 && atom->CountFreeSulfurs() == 1))
return(false);
//atom is connected to a carbon that has a total
//of 2 attached free sulfurs or 1 free oxygen and 1 free sulfur
return(true);
}
/////////////////////////////////////////////////////////////////
bool MOL2Format::ReadMolecule(OBBase* pOb, OBConversion* pConv)
{
OBMol* pmol = pOb->CastAndClear<OBMol>();
if(pmol==NULL)
return false;
//Define some references so we can use the old parameter names
istream &ifs = *pConv->GetInStream();
OBMol &mol = *pmol;
//Old code follows...
bool foundAtomLine = false;
char buffer[BUFF_SIZE];
char *comment = NULL;
string str,str1;
vector<string> vstr;
int len;
mol.BeginModify();
for (;;)
{
if (!ifs.getline(buffer,BUFF_SIZE))
return(false);
if (pConv->IsOption("c", OBConversion::INOPTIONS)!=NULL && EQn(buffer,"###########",10))
{
char attr[32], val[32];
sscanf(buffer, "########## %[^:]:%s", attr, val);
OBPairData *dd = new OBPairData;
dd->SetAttribute(attr);
dd->SetValue(val);
dd->SetOrigin(fileformatInput);
mol.SetData(dd);
}
if (EQn(buffer,"@<TRIPOS>MOLECULE",17))
break;
}
// OK, just read MOLECULE line
int lcount;
int natoms,nbonds;
bool hasPartialCharges = true;
for (lcount=0;;lcount++)
{
if (!ifs.getline(buffer,BUFF_SIZE))
return(false);
if (EQn(buffer,"@<TRIPOS>ATOM",13))
{
foundAtomLine = true;
break;
}
if (lcount == 0)
{
tokenize(vstr,buffer);
if (!vstr.empty())
mol.SetTitle(buffer);
}
else if (lcount == 1)
sscanf(buffer,"%d%d",&natoms,&nbonds);
else if (lcount == 3) // charge descriptions
{
// Annotate origin of partial charges
OBPairData *dp = new OBPairData;
dp->SetAttribute("PartialCharges");
dp->SetValue(buffer);
dp->SetOrigin(fileformatInput);
mol.SetData(dp);
if (strncasecmp(buffer, "NO_CHARGES", 10) == 0)
hasPartialCharges = false;
}
else if (lcount == 4) //energy (?)
{
tokenize(vstr,buffer);
if (!vstr.empty() && vstr.size() == 3)
if (vstr[0] == "Energy")
mol.SetEnergy(atof(vstr[2].c_str()));
}
else if (lcount == 5) //comment
{
if ( buffer[0] )
{
len = (int) strlen(buffer)+1;
//! @todo allow better multi-line comments
// which don't allow ill-formed data to consume memory
// Thanks to Andrew Dalke for the pointer
if (comment != NULL)
delete [] comment;
comment = new char [len];
memcpy(comment,buffer,len);
}
}
}
if (!foundAtomLine)
{
mol.EndModify();
mol.Clear();
obErrorLog.ThrowError(__FUNCTION__, "Unable to read Mol2 format file. No atoms found.", obWarning);
return(false);
}
mol.ReserveAtoms(natoms);
int i;
vector3 v;
OBAtom atom;
double x,y,z,pcharge;
char temp_type[BUFF_SIZE], resname[BUFF_SIZE], atmid[BUFF_SIZE];
int elemno, resnum = -1;
int isotope = 0;
ttab.SetFromType("SYB");
for (i = 0;i < natoms;i++)
{
if (!ifs.getline(buffer,BUFF_SIZE))
return(false);
sscanf(buffer," %*s %1024s %lf %lf %lf %1024s %d %1024s %lf",
atmid, &x,&y,&z, temp_type, &resnum, resname, &pcharge);
atom.SetVector(x, y, z);
atom.SetFormalCharge(0);
// Handle "CL" and "BR" and other mis-typed atoms
str = temp_type;
if (strncmp(temp_type, "CL", 2) == 0) {
str = "Cl";
} else if (strncmp(temp_type,"BR",2) == 0) {
str = "Br";
} else if (strncmp(temp_type,"S.o2", 4) == 0) {
str = "S.O2";
} else if (strncmp(temp_type,"S.o", 3) == 0) {
str = "S.O";
} else if (strncmp(temp_type,"SI", 2) == 0) {
str = "Si";
// The following cases are entries which are not in openbabel/data/types.txt
// and should probably be added there
} else if (strncmp(temp_type,"S.1", 3) == 0) {
str = "S.2"; // no idea what the best type might be here
} else if (strncmp(temp_type,"P.", 2) == 0) {
str = "P.3";
} else if (strncasecmp(temp_type,"Ti.", 3) == 0) { // e.g. Ti.th
str = "Ti";
} else if (strncasecmp(temp_type,"Ru.", 3) == 0) { // e.g. Ru.oh
str = "Ru";
// Fixes PR#3557898
} else if (strncmp(temp_type, "N.4", 3) == 0) {
atom.SetFormalCharge(1);
}
ttab.SetToType("ATN");
ttab.Translate(str1,str);
elemno = atoi(str1.c_str());
ttab.SetToType("IDX");
// We might have missed some SI or FE type things above, so here's
// another check
if( !elemno && isupper(temp_type[1]) )
{
temp_type[1] = (char)tolower(temp_type[1]);
str = temp_type;
ttab.SetToType("ATN");
ttab.Translate(str1,str);
elemno = atoi(str1.c_str());
ttab.SetToType("IDX");
}
// One last check if there isn't a period in the type,
// it's a malformed atom type, but it may be the element symbol
// GaussView does this (PR#1739905)
if ( !elemno ) {
// check if it's "Du" or "Xx" and the element is in the atom name
if (str == "Du" || str == "Xx") {
str = atmid;
for (unsigned int i = 0; i < str.length(); ++i)
if (!isalpha(str[i])) {
str.erase(i);
break; // we've erased the end of the string
}
}
std::stringstream errorMsg;
errorMsg << "This Mol2 file is non-standard. Problem with molecule: "
<< mol.GetTitle()
<< " Cannot interpret atom types correctly, instead attempting to interpret atom type: "
<< str << " as elements instead.";
obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obWarning);
string::size_type dotPos = str.find('.');
if (dotPos == string::npos) {
elemno = etab.GetAtomicNum(str.c_str(), isotope);
}
}
atom.SetAtomicNum(elemno);
if (isotope)
atom.SetIsotope(isotope);
ttab.SetToType("INT");
ttab.Translate(str1,str);
atom.SetType(str1);
atom.SetPartialCharge(pcharge);
// MMFF94 has different atom types for Cu(I) and Cu(II)
// as well as for Fe(II) and Fe(III), so the correct formal
// charge is needed for correct atom type assignment
if (str1 == "Cu" || str1 == "Fe")
atom.SetFormalCharge((int)pcharge);
if (!mol.AddAtom(atom))
return(false);
if (!IsNearZero(pcharge))
hasPartialCharges = true;
// Add residue information if it exists
if (resnum != -1 && resnum != 0 &&
strlen(resname) != 0 && strncmp(resname,"<1>", 3) != 0)
{
OBResidue *res = (mol.NumResidues() > 0) ?
mol.GetResidue(mol.NumResidues()-1) : NULL;
if (res == NULL || res->GetName() != resname ||
static_cast<int>(res->GetNum()) != resnum)
{
vector<OBResidue*>::iterator ri;
for (res = mol.BeginResidue(ri) ; res ; res = mol.NextResidue(ri))
if (res->GetName() == resname &&
static_cast<int>(res->GetNum()) == resnum)
break;
if (res == NULL)
{
res = mol.NewResidue();
res->SetName(resname);
res->SetNum(resnum);
}
}
OBAtom *atomPtr = mol.GetAtom(mol.NumAtoms());
res->AddAtom(atomPtr);
res->SetAtomID(atomPtr, atmid);
} // end adding residue info
}
for (;;)
{
if (!ifs.getline(buffer,BUFF_SIZE))
return(false);
str = buffer;
if (!strncmp(buffer,"@<TRIPOS>BOND",13))
break;
}
int start,end,order;
for (i = 0; i < nbonds; i++)
{
if (!ifs.getline(buffer,BUFF_SIZE))
return(false);
sscanf(buffer,"%*d %d %d %1024s",&start,&end,temp_type);
str = temp_type;
order = 1;
if (str == "ar" || str == "AR" || str == "Ar")
order = 5;
else if (str == "AM" || str == "am" || str == "Am")
order = 1;
else
order = atoi(str.c_str());
mol.AddBond(start,end,order);
}
// Make a pass to ensure that there are no double bonds
// between atoms which are also involved in aromatic bonds
// as that may ill-condition kekulization (fixes potential
// issues with molecules like CEWYIM30 (MMFF94 validation suite)
// Patch by Paolo Tosco 2012-06-07
int idx1, idx2;
bool idx1arom, idx2arom;
FOR_BONDS_OF_MOL(bond, mol) {
if (bond->GetBO() != 2)
continue;
idx1 = bond->GetBeginAtom()->GetIdx();
idx2 = bond->GetEndAtom()->GetIdx();
idx1arom = idx2arom = false;
FOR_BONDS_OF_MOL(bond2, mol) {
if (&*bond == &*bond2)
continue;
if ((bond2->GetBeginAtom()->GetIdx() == idx1 || bond2->GetEndAtom()->GetIdx() == idx1)
&& bond2->GetBO() == 5)
idx1arom = true;
else if ((bond2->GetBeginAtom()->GetIdx() == idx2 || bond2->GetEndAtom()->GetIdx() == idx2)
&& bond2->GetBO() == 5)
idx2arom = true;
if (idx1arom && idx2arom) {
bond->SetBO(1);
break;
}
}
}
// Now that bonds are added, make a pass to "de-aromatize" carboxylates
// and (di)thiocarboxylates
// Fixes PR#3092368
OBAtom *carboxylCarbon, *oxysulf;
FOR_BONDS_OF_MOL(bond, mol)
{
if (bond->GetBO() != 5)
continue;
if (bond->GetBeginAtom()->IsCarboxylOxygen() || IsThiocarboxylSulfur(bond->GetBeginAtom())) {
carboxylCarbon = bond->GetEndAtom();
oxysulf = bond->GetBeginAtom();
}
else if (bond->GetEndAtom()->IsCarboxylOxygen() || IsThiocarboxylSulfur(bond->GetEndAtom())) {
carboxylCarbon = bond->GetBeginAtom();
oxysulf = bond->GetEndAtom();
} else // not a carboxylate
continue;
if (carboxylCarbon->HasDoubleBond()) { // we've already picked a double bond
bond->SetBO(1); // this should be a single bond, not "aromatic"
continue;
}
// We need to choose a double bond
if (oxysulf->ExplicitHydrogenCount() == 1 || oxysulf->GetFormalCharge() == -1) { // single only
bond->SetBO(1);
continue;
} else
bond->SetBO(2); // we have to pick one, let's use this one
}
// Make a pass to fix aromatic bond orders and formal charges
// involving nitrogen and oxygen atoms - before this patch
// the aromaticity of a molecule as simple as pyridinium
// cation could not be correctly perceived
// Patch by Paolo Tosco 2012-06-07
OBAtom *carbon, *partner, *boundToNitrogen;
OBBitVec bv;
bv.SetBitOn(nbonds);
bv.Clear();
FOR_BONDS_OF_MOL(bond, mol)
{
if (bv[bond->GetIdx()] || (bond->GetBO() != 5))
continue;
// only bother for 6 membered rings (e.g., pyridinium)
// 5-membered rings like pyrrole, imidazole, or triazole are OK with nH
OBRing *ring = bond->FindSmallestRing();
if ( !ring || ring->Size() != 6 )
continue;
if ((bond->GetBeginAtom()->IsCarbon() && bond->GetEndAtom()->IsNitrogen())
|| (bond->GetBeginAtom()->IsNitrogen() && bond->GetEndAtom()->IsCarbon())) {
carbon = (bond->GetBeginAtom()->IsCarbon() ? bond->GetBeginAtom() : bond->GetEndAtom());
int min_n_h_bonded = 100;
int min_idx = mol.NumAtoms() + 1;
FOR_BONDS_OF_ATOM(bond2, carbon) {
if (bond2->GetBO() != 5)
continue;
partner = (bond2->GetBeginAtom() == carbon ? bond2->GetEndAtom() : bond2->GetBeginAtom());
if (!ring->IsMember(partner))
continue; // not in the same 6-membered ring
if (partner->IsNitrogen() && partner->GetValence() == 3 && partner->GetFormalCharge() == 0) {
int n_h_bonded = 0;
FOR_BONDS_OF_ATOM(bond3, partner) {
boundToNitrogen = (bond3->GetBeginAtom() == partner ? bond3->GetEndAtom() : bond3->GetBeginAtom());
if (boundToNitrogen->IsHydrogen())
n_h_bonded++;
}
if (n_h_bonded < min_n_h_bonded || (n_h_bonded == min_n_h_bonded && partner->GetIdx() < min_idx)) {
min_n_h_bonded = n_h_bonded;
min_idx = partner->GetIdx();
}
}
}
FOR_BONDS_OF_ATOM(bond2, carbon) {
if (bond2->GetBO() != 5)
continue;
partner = (bond2->GetBeginAtom() == carbon ? bond2->GetEndAtom() : bond2->GetBeginAtom());
if (partner->IsNitrogen() && partner->GetValence() == 3 && partner->GetFormalCharge() == 0) {
int n_ar_bond = 0;
FOR_BONDS_OF_ATOM(bond3, partner) {
boundToNitrogen = (bond3->GetBeginAtom() == partner ? bond3->GetEndAtom() : bond3->GetBeginAtom());
if (boundToNitrogen->IsOxygen() && boundToNitrogen->GetValence() == 1) {
n_ar_bond = -1;
break;
}
if (bond3->GetBO() == 5)
++n_ar_bond;
}
if (n_ar_bond == -1)
continue;
if (partner->GetIdx() == min_idx) {
partner->SetFormalCharge(1);
if (n_ar_bond == 1) {
bond2->SetBO(2);
}
}
else if (n_ar_bond == 1) {
bond2->SetBO(1);
}
}
bv.SetBitOn(bond2->GetIdx());
}
} else if ((bond->GetBeginAtom()->IsCarbon() && bond->GetEndAtom()->IsOxygen())
|| (bond->GetBeginAtom()->IsOxygen() && bond->GetEndAtom()->IsCarbon())) {
OBAtom *atom1, *atom2;
atom1 = bond->GetBeginAtom();
atom2 = bond->GetEndAtom();
// set formal charges for pyrilium
// (i.e., this bond is a 6-membered ring, aromatic, and C-O)
if (atom1->IsOxygen() && atom1->IsInRingSize(6))
atom1->SetFormalCharge(1);
else if (atom2->IsOxygen() && atom2->IsInRingSize(6))
atom2->SetFormalCharge(1);
}
}
// Suggestion by Liu Zhiguo 2008-01-26
// Mol2 files define atom types -- there is no need to re-perceive
mol.SetAtomTypesPerceived();
mol.EndModify();
//must add generic data after end modify - otherwise it will be blown away
if (comment)
{
OBCommentData *cd = new OBCommentData;
cd->SetData(comment);
cd->SetOrigin(fileformatInput);
mol.SetData(cd);
delete [] comment;
comment = NULL;
}
if (hasPartialCharges)
mol.SetPartialChargesPerceived();
/* Disabled due to PR#3048758 -- seekg is very slow with gzipped mol2
// continue untill EOF or untill next molecule record
streampos pos;
for(;;)
{
pos = ifs.tellg();
if (!ifs.getline(buffer,BUFF_SIZE))
break;
if (EQn(buffer,"@<TRIPOS>MOLECULE",17))
break;
}
ifs.seekg(pos); // go back to the end of the molecule
*/
return(true);
}
////////////////////////////////////////////////////////////////
bool MOL2Format::WriteMolecule(OBBase* pOb, OBConversion* pConv)
{
OBMol* pmol = dynamic_cast<OBMol*>(pOb);
if(pmol==NULL)
return false;
//Define some references so we can use the old parameter names
ostream &ofs = *pConv->GetOutStream();
OBMol &mol = *pmol;
bool ligandsOnly = pConv->IsOption("l", OBConversion::OUTOPTIONS)!=NULL;
//The old code follows....
string str,str1;
char buffer[BUFF_SIZE],label[BUFF_SIZE];
char rnum[BUFF_SIZE],rlabel[BUFF_SIZE];
//Check if UCSF Dock style coments are on
if(pConv->IsOption("c", OBConversion::OUTOPTIONS)!=NULL) {
vector<OBGenericData*>::iterator k;
vector<OBGenericData*> vdata = mol.GetData();
ofs << endl;
for (k = vdata.begin();k != vdata.end();++k) {
if ((*k)->GetDataType() == OBGenericDataType::PairData
&& (*k)->GetOrigin()!=local //internal OBPairData is not written
&& (*k)->GetAttribute()!="PartialCharges")
{
ofs << "##########\t" << (*k)->GetAttribute() << ":\t" << ((OBPairData*)(*k))->GetValue() << endl;
}
}
ofs << endl;
}
ofs << "@<TRIPOS>MOLECULE" << endl;
str = mol.GetTitle();
if (str.empty())
ofs << "*****" << endl;
else
ofs << str << endl;
snprintf(buffer, BUFF_SIZE," %d %d 0 0 0", mol.NumAtoms(),mol.NumBonds());
ofs << buffer << endl;
ofs << "SMALL" << endl; // TODO: detect if we have protein, biopolymer, etc.
OBPairData *dp = (OBPairData*)mol.GetData("PartialCharges");
if (dp != NULL) {
// Tripos spec says:
// NO_CHARGES, DEL_RE, GASTEIGER, GAST_HUCK, HUCKEL, PULLMAN,
// GAUSS80_CHARGES, AMPAC_CHARGES, MULLIKEN_CHARGES, DICT_ CHARGES,
// MMFF94_CHARGES, USER_CHARGES
if (strcasecmp(dp->GetValue().c_str(),"Mulliken") == 0)
ofs << "MULLIKEN_CHARGES" << endl;
else if (strcasecmp(dp->GetValue().c_str(),"MMFF94") == 0)
ofs << "MMFF94_CHARGES" << endl;
else if (strcasecmp(dp->GetValue().c_str(),"ESP") == 0)
ofs << "USER_CHARGES" << endl;
else if (strcasecmp(dp->GetValue().c_str(),"Gasteiger") == 0)
ofs << "GASTEIGER" << endl;
else // ideally, code should pick from the Tripos types
ofs << "USER_CHARGES" << endl;
}
else { // No idea what these charges are... all our code sets "PartialCharges"
ofs << "GASTEIGER" << endl;
}
// ofs << "Energy = " << mol.GetEnergy() << endl;
if (mol.HasData(OBGenericDataType::CommentData))
{
ofs << "****\n"; // comment line printed, so we need to add "no status bits set"
OBCommentData *cd = (OBCommentData*)mol.GetData(OBGenericDataType::CommentData);
ofs << cd->GetData();
}
ofs << endl;
ofs << "@<TRIPOS>ATOM" << endl;
OBAtom *atom;
OBResidue *res;
vector<OBAtom*>::iterator i;
vector<int> labelcount;
labelcount.resize( etab.GetNumberOfElements() );
ttab.SetFromType("INT");
ttab.SetToType("SYB");
for (atom = mol.BeginAtom(i);atom;atom = mol.NextAtom(i))
{
//
// Use sequentially numbered atom names if no residues
//
snprintf(label,BUFF_SIZE, "%s%d",
etab.GetSymbol(atom->GetAtomicNum()),
++labelcount[atom->GetAtomicNum()]);
strcpy(rlabel,"<1>");
strcpy(rnum,"1");
str = atom->GetType();
ttab.Translate(str1,str);
//
// Use original atom names if there are residues
//
if (!ligandsOnly && (res = atom->GetResidue()) )
{
// use original atom names defined by residue
snprintf(label,BUFF_SIZE,"%s",(char*)res->GetAtomID(atom).c_str());
// make sure that residue name includes its number
snprintf(rlabel,BUFF_SIZE,"%s%d",res->GetName().c_str(), res->GetNum());
snprintf(rnum,BUFF_SIZE,"%d",res->GetNum());
}
snprintf(buffer,BUFF_SIZE,"%7d %-6s %9.4f %9.4f %9.4f %-5s %3s %-8s %9.4f",
atom->GetIdx(),label,
atom->GetX(),atom->GetY(),atom->GetZ(),
str1.c_str(),
rnum,rlabel,
atom->GetPartialCharge());
ofs << buffer << endl;
}
ofs << "@<TRIPOS>BOND" << endl;
OBBond *bond;
vector<OBBond*>::iterator j;
OBSmartsPattern pat;
string s1, s2;
for (bond = mol.BeginBond(j);bond;bond = mol.NextBond(j))
{
s1 = bond->GetBeginAtom()->GetType();
s2 = bond->GetEndAtom()->GetType();
if (bond->IsAromatic() || s1 == "O.co2" || s2 == "O.co2")
strcpy(label,"ar");
else if (bond->IsAmide())
strcpy(label,"am");
else
snprintf(label,BUFF_SIZE,"%d",bond->GetBO());
snprintf(buffer, BUFF_SIZE,"%6d %5d %5d %2s",
bond->GetIdx()+1,bond->GetBeginAtomIdx(),bond->GetEndAtomIdx(),
label);
ofs << buffer << endl;
}
// NO trailing blank line (PR#1868929).
// ofs << endl;
return(true);
}
int MOL2Format::SkipObjects(int n, OBConversion* pConv)
{
const char txt[] = "@<TRIPOS>MOLECULE";
istream& ifs = *pConv->GetInStream();
if(!ifs)
return -1;
if(n>0 && ifs.peek()==txt[0])
ifs.ignore(); // move past '@' so that next mol will be found
do {
ignore(ifs, txt);
} while(ifs && (--n)>0);
if(!ifs.eof())
ifs.seekg(1-sizeof(txt), ios::cur);//1 for '/0'
char ch = ifs.peek();
return 1;
}
} //namespace OpenBabel
| 34.244536 | 114 | 0.5372 | [
"vector"
] |
7667a6458c1c1b0604c1d8804af4c4f0c8987ed5 | 1,077 | cpp | C++ | SimpleEngine/SimpleEngine/SimpleEngine.cpp | Akara4ok/-__- | b6f76ae2d0e180429eb2c64911327056aa1c8357 | [
"MIT"
] | null | null | null | SimpleEngine/SimpleEngine/SimpleEngine.cpp | Akara4ok/-__- | b6f76ae2d0e180429eb2c64911327056aa1c8357 | [
"MIT"
] | null | null | null | SimpleEngine/SimpleEngine/SimpleEngine.cpp | Akara4ok/-__- | b6f76ae2d0e180429eb2c64911327056aa1c8357 | [
"MIT"
] | null | null | null | #include <iostream>
#include <ctime>
#include "BMPWriter.h"
#include "Scene.h"
#include "LightSource.h"
#include "Box.h"
int main() {
int start = clock();
int end;
Camera camera(0.08, 0.09, 0.16, 1080, 1920);
Ray player(Vector3(0, 1, 0), Vector3(0, -1, 0));
//Ray player(Vector3(3, 3, 4), Vector3(-3, -3, -4));
LightSource light(Vector3(3, 3, 3), Pixel_triplet(255, 255, 255), 2, 0.1);
std::vector<LightSource> lightSources;
lightSources.push_back(light);
camera.setScreen(player);
Scene scene(camera, lightSources);
end = clock();
std::cout << "Scene created - " << end - start << "ms\n";
scene.addObj("D:\\test", "cow.obj");
end = clock();
std::cout << "Object parsed - " << end - start << "ms\n";
Pixel_triplet** res = scene.getFrame();
end = clock();
std::cout << "Got frame - " << end - start << "ms\n";
BMPWriter::writePicture(res, camera.getPixelH(), camera.getPixelW(), "D:\\test\\bmp.bmp");
end = clock();
std::cout << "Wrote picture - " << end - start << "ms\n";
end = clock();
std::cout << "Total: " << end - start << "ms\n";
return 0;
}
| 29.108108 | 91 | 0.612813 | [
"object",
"vector"
] |
766dc416d24a4ef3eb44d33369b93bde7961c10f | 2,327 | cpp | C++ | problemsets/Live Archive/Central Europe - 2007/billboard.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/Live Archive/Central Europe - 2007/billboard.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/Live Archive/Central Europe - 2007/billboard.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | /**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define FOR(i,m,n) for((i)=m;(i)<(n);(i)++)
#define FORN(i,m,n) for((i)=(n)-1;(i)>=m;(i)--)
#define _FORIT(it, b, e) for (__typeof(b) it = (b); it != (e); it++)
#define FORIT(x...) _FORIT(x)
#define ALL(v) (v).begin(), (v).end()
#define RALL(v) (v).rbegin(), (v).rend()
#define SI(a) ((a).size())
#define PB push_back
#define MP make_pair
#define CLR(a,v) memset((a),(v),sizeof(a))
#define TLE while(1);
#define RTE printf("%d", 1/0);
using namespace std;
typedef vector<int> VI; typedef vector<double> VD; typedef vector<string> VS;
typedef vector<vector<int> > VVI; typedef vector<vector<string> > VVS;
typedef set<int> SI; typedef set<double> SD; typedef set<string> SS;
typedef pair<int,int> PII;
typedef signed long long i64; typedef unsigned long long u64;
#define EPS 1E-14
#define INF 0x3F3F3F3F
#define DINF 1E16
#define NULO -1
inline int cmp(double x, double y = 0, double tol = EPS) {
return (x <= y + tol) ? (x + tol < y) ? -1 : 0 : 1;
}
#define MAX 20
int r, c;
char board[MAX][MAX];
char bill[MAX][MAX];
int mini;
int main() {
int i, j, m, n, mask;
for (; scanf("%d %d", &r, &c), r+c; ) {
FOR(i,0,r) scanf("%s", board[i]); mask = 1<<c; mini = INF;
FOR(m,0,mask) {
FOR(i,0,r) FOR(j,0,c) bill[i][j] = board[i][j]=='X';
n = 0;
FOR(j,0,c) if ((1<<j)&m) {
n++; bill[0][j]^=1; bill[1][j]^=1;
if (j>0) bill[0][j-1]^=1; if (j<c-1) bill[0][j+1]^=1;
}
if (n>=mini) goto OUT;
FOR(i,1,r) FOR(j,0,c) {
if (bill[i-1][j]) {
n++; bill[i][j]^=1; if (i<r-1) bill[i+1][j]^=1;
if (j>0) bill[i][j-1]^=1; if (j<c-1) bill[i][j+1]^=1;
}
if (n>=mini) goto OUT;
}
FOR(j,0,c) if(bill[r-1][j]) break;
if (j==c) mini<?=n;
OUT:;
}
if (mini==INF) printf("Damaged billboard.\n");
else printf("You have to tap %d tiles.\n", mini);
}
return 0;
}
| 27.05814 | 77 | 0.525999 | [
"vector"
] |
7673110d89094433ae9bc0ce8f77479f23cf9f86 | 64 | cpp | C++ | spotify_stream/src/web/model/artist.cpp | Yanick-Salzmann/carpi | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | [
"Apache-2.0"
] | 2 | 2020-06-07T16:47:20.000Z | 2021-03-20T10:41:34.000Z | spotify_stream/src/web/model/artist.cpp | Yanick-Salzmann/carpi | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | [
"Apache-2.0"
] | null | null | null | spotify_stream/src/web/model/artist.cpp | Yanick-Salzmann/carpi | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | [
"Apache-2.0"
] | null | null | null | #include "artist.hpp"
namespace carpi::spotify::web::model {
} | 12.8 | 38 | 0.703125 | [
"model"
] |
7674910a99dd97af84d27664c99ae1bd3ff329cf | 785 | cpp | C++ | archive/4/un.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | 2 | 2019-05-04T09:37:09.000Z | 2019-05-22T18:07:28.000Z | archive/4/un.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | archive/4/un.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const size_t MAX_M = 256;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
uint32_t n, q;
cin >> n >> q;
const size_t Q = ceil(sqrt(n)) + 1;
vector<int32_t> A(n);
vector<vector<int32_t>> S(MAX_M, vector<int32_t>(Q + 1, 1));
for (uint32_t i = 0; i < n; i++) {
cin >> A[i];
for (uint32_t m = 1; m < MAX_M; m++) S[m][i / Q] *= A[i], S[m][i / Q] %= m;
}
while (q-- > 0) {
uint32_t x, y;
int64_t m;
cin >> x >> y >> m;
x--;
y--;
int64_t r = 1;
for (uint32_t i = x; i <= y; i++) {
if (n > 4 and i % Q == 0 and i + Q - 1 <= y)
r *= int64_t(S[m][i / Q]);
else
r *= int64_t(A[i]);
r %= m;
}
cout << r << "\n";
}
}
| 18.255814 | 79 | 0.453503 | [
"vector"
] |
7674f22e3bee19db7494267a3af9a36a4e775d97 | 2,964 | hpp | C++ | src/Factory/Simulation/EXIT/EXIT.hpp | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | 1 | 2022-02-17T08:47:47.000Z | 2022-02-17T08:47:47.000Z | src/Factory/Simulation/EXIT/EXIT.hpp | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | null | null | null | src/Factory/Simulation/EXIT/EXIT.hpp | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | 1 | 2022-02-15T23:32:39.000Z | 2022-02-15T23:32:39.000Z | #if !defined(AFF3CT_8BIT_PREC) && !defined(AFF3CT_16BIT_PREC)
#ifndef FACTORY_SIMULATION_EXIT_HPP_
#define FACTORY_SIMULATION_EXIT_HPP_
#include <vector>
#include <string>
#include <map>
#include "Tools/Arguments/Argument_tools.hpp"
#include "Tools/auto_cloned_unique_ptr.hpp"
#include "Factory/Module/Source/Source.hpp"
#include "Factory/Module/Modem/Modem.hpp"
#include "Factory/Module/Channel/Channel.hpp"
#include "Factory/Module/Quantizer/Quantizer.hpp"
#include "Factory/Module/Monitor/EXIT/Monitor_EXIT.hpp"
#include "Factory/Module/Codec/Codec_SISO.hpp"
#include "Factory/Tools/Display/Terminal/Terminal.hpp"
#include "Factory/Simulation/Simulation.hpp"
namespace aff3ct
{
namespace simulation
{
template <typename B, typename R>
class EXIT;
}
}
namespace aff3ct
{
namespace factory
{
extern const std::string EXIT_name;
extern const std::string EXIT_prefix;
struct EXIT : Simulation
{
class parameters : public Simulation::parameters
{
public:
// ------------------------------------------------------------------------------------------------- PARAMETERS
// required parameters
std::vector<float> sig_a_range;
// optional parameters
std::string snr_type = "ES";
// module parameters
tools::auto_cloned_unique_ptr<Source ::parameters> src;
tools::auto_cloned_unique_ptr<Codec_SISO ::parameters> cdc;
tools::auto_cloned_unique_ptr<Modem ::parameters> mdm;
tools::auto_cloned_unique_ptr<Channel ::parameters> chn;
tools::auto_cloned_unique_ptr<Quantizer ::parameters> qnt;
tools::auto_cloned_unique_ptr<Monitor_EXIT::parameters> mnt;
tools::auto_cloned_unique_ptr<Terminal ::parameters> ter;
// ---------------------------------------------------------------------------------------------------- METHODS
explicit parameters(const std::string &p = EXIT_prefix);
virtual ~parameters() = default;
virtual EXIT::parameters* clone() const;
virtual std::vector<std::string> get_names () const;
virtual std::vector<std::string> get_short_names() const;
virtual std::vector<std::string> get_prefixes () const;
// setters
void set_src(Source ::parameters *src);
void set_cdc(Codec_SISO ::parameters *cdc);
void set_mdm(Modem ::parameters *mdm);
void set_chn(Channel ::parameters *chn);
void set_qnt(Quantizer ::parameters *qnt);
void set_mnt(Monitor_EXIT::parameters *mnt);
void set_ter(Terminal ::parameters *ter);
// parameters construction
void get_description(tools::Argument_map_info &args) const;
void store (const tools::Argument_map_value &vals);
void get_headers (std::map<std::string,header_list>& headers, const bool full = true) const;
// builder
template <typename B = int, typename R = float>
simulation::EXIT<B,R>* build() const;
};
template <typename B = int, typename R = float>
static simulation::EXIT<B,R>* build(const parameters ¶ms);
};
}
}
#endif /* FACTORY_SIMULATION_EXIT_HPP_ */
#endif | 31.870968 | 113 | 0.689609 | [
"vector"
] |
768d9d7bca822e8ca09e9ff1c2eec794f5be6d7b | 2,323 | hh | C++ | src/mvn.hh | ScottishCovidResponse/BEEPmbp | 784f96dc6415710e7d969717f1a08434c7b33c10 | [
"BSD-2-Clause"
] | null | null | null | src/mvn.hh | ScottishCovidResponse/BEEPmbp | 784f96dc6415710e7d969717f1a08434c7b33c10 | [
"BSD-2-Clause"
] | 13 | 2020-07-13T20:03:24.000Z | 2021-04-11T12:24:15.000Z | src/mvn.hh | ScottishCovidResponse/BEEPmbp | 784f96dc6415710e7d969717f1a08434c7b33c10 | [
"BSD-2-Clause"
] | 2 | 2020-09-02T09:50:00.000Z | 2022-03-07T02:29:39.000Z | #ifndef BEEPMBP__MVN_HH
#define BEEPMBP__MVN_HH
#include "struct.hh"
class MVN // Multivariate normal
{
public:
string name; // The name of the multivariate normal
unsigned int ntr, nac, nbo; // Keeps track of acceptance of proposals
double size; // The size of the proposal
unsigned int number; // Used to give the number of proposals for sim-only approach
ParamType type; // The paramter type of the proposal
MVNType mvntype; // Single or multiple variable update
double ac_rate, bo_rate; // Acceptance rates (across all MPI processes)
MVN(string name, const vector <unsigned int> &var_, double size_, ParamType type_, MVNType mvntype_);
void setup(const vector <ParamSample> ¶m_samp);
void setup(const vector <ParamSample> ¶m_samp, const vector <double> &w);
vector <double> propose(const vector <double> ¶mval) const;
double probability(const vector<double> &pend,const vector<double> &pstart) const;
vector <double> langevin_shift(const vector <double> ¶mv, const Model &model) const;
Status propose_langevin(vector <double> ¶m_propose, const vector <double> ¶mval, double &probif, const Model &model) const;
double get_probfi(const vector <double> ¶m_propose, const vector <double> ¶mval, const Model &model);
Status MH(const double al, const ParamUpdate pup);
Status sigma_propose(vector <double> ¶m_propose, const vector <double> ¶mval, const Model &model);
private:
// public:
unsigned int nvar; // The number of variables which can change
vector <unsigned int> var; // The variables of the MVN
vector < vector <double> > M; // The covariance matrix
vector < vector <double> > cholesky_matrix; // The matrix for Cholesky decompostion
vector < vector <double> > inv_M; // The inverse of the covarience matrixc
void covariance_matrix(const vector <ParamSample> ¶m_samp);
void covariance_matrix(const vector <ParamSample> ¶m_samp, const vector <double> &w);
void calculate_cholesky_matrix();
void output_M(const string file);
};
#endif
| 49.425532 | 132 | 0.662936 | [
"vector",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.