blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0dd7e53c2ec0a70138a639a69f9c94268d8069f8
|
ac8e9e12c592f47cfa413d81215048b3a5f62a66
|
/rotate array.cpp
|
359f03e47f7fa1eca78cd912670e377e5e937fe4
|
[] |
no_license
|
ankitAMD/c-
|
5a0eed141b1c486d32317f520993692e2d1b13dd
|
099cd2c7d304940c6eadf594b9113c31436453f7
|
refs/heads/master
| 2020-05-30T16:05:14.769600
| 2019-08-22T15:28:25
| 2019-08-22T15:28:25
| 189,838,463
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,195
|
cpp
|
rotate array.cpp
|
#Program for array rotation
/*Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements.
Array
Rotation of the above array by 2 will make array
ArrayRotation1
Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7
1) Store d elements in a temp array
temp[] = [1, 2]
2) Shift rest of the arr[]
arr[] = [3, 4, 5, 6, 7, 6, 7]
3) Store back the d elements
arr[] = [3, 4, 5, 6, 7, 1, 2]
*/
#include <iostream>
using namespace std;
void reverse(int arr[], int start ,int end)
{
while(start<end)
{
int temp =arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
}
void rotate(int arr[], int d, int n)
{
reverse(arr, 0, d-1);
reverse(arr, d, n-1);
reverse(arr, 0, n-1);
}
int main() {
// your code goes
int n,d,arr[10];
cout<<"enter the no of number you want to enter and n="<<endl;
cin>>n;
cout<<"enter the position you want to rotate and d="<<endl;
cin>>d;
cout<<"enter the array of number\n";
for(int i=0;i<n;i++)
{
cin>>arr[i];
cout<<arr[i]<<" ";
}
cout<<"\n";
rotate(arr, d, n);
for(int i=0;i<n;i++)
{
cin>>arr[i];
cout<<arr[i]<<" ";
}
return 0;
}
|
54ccec3f2524cfa629ac9a39ff5c1adcf066a048
|
8755afdb93cfeb229d059dcd3dd52ac3ed14bfeb
|
/Pyramid.cpp
|
cc1e72ebf7d6833a339d3f4d4ad6bb2bc3a1ed90
|
[] |
no_license
|
amanbkm/Basic-Cpp-Programs
|
6c9efa71163941a91c12907c5bf19398842d8e6e
|
3097d1e6e0e8303e29f42ebfc9ea1cee30eb4e5f
|
refs/heads/master
| 2022-12-24T22:18:21.812181
| 2020-10-01T13:15:19
| 2020-10-01T13:15:19
| 281,060,485
| 0
| 1
| null | 2020-10-01T13:15:21
| 2020-07-20T08:32:12
|
C++
|
UTF-8
|
C++
| false
| false
| 337
|
cpp
|
Pyramid.cpp
|
#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
int n,count=1;
cout<<"Enter the number of rows\t";
cin>>n;
cout<<"\n";
for(int i=1;i<n;++i)
{
for(int space=1;space<n-i;space++)
{
cout<<" ";
}
for(int j=1;j<=i;++j)
{
cout<<count<<" ";
count++;
}
cout<<"\n";
}
}
|
94ef9759bbc0d65386d19625b309dd35bd6bfc0e
|
fa13d2b871fbf78ad068bc55e1de8e2b57eee012
|
/src/proc/proc_functions.h
|
03c274648817c0b40828af566aa2843992199221
|
[] |
no_license
|
DenisPlima/noctweak
|
b5c2fc1b6a80ba36f904ba49844c085c3e4b41e3
|
9b64f63ea8f857059bd167aaa37124c828b6555e
|
refs/heads/master
| 2022-03-26T00:11:36.019445
| 2019-10-25T01:23:48
| 2019-10-25T01:23:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,334
|
h
|
proc_functions.h
|
/*
* proc_functions.h
*
* Created on: Aug 18, 2011
* Author: anhttran
*/
#ifndef PROC_FUNCTIONS_H_
#define PROC_FUNCTIONS_H_
#include "../definition.h"
#include "../common_functions.h"
#include "proc_parameters.h"
#include "synthetic/synthetic_parameters.h"
using namespace std;
// random interval of packet injection times with exponential distribution
int inter_injection_time(double flit_rate, int type);
Flit *create_head_flit_random(int _src_x, int _src_y, int _time);
Flit *create_head_flit_transpose(int _src_x, int _src_y, int _time);
Flit *create_head_flit_bit_complement(int _src_x, int _src_y, int _time);
Flit *create_head_flit_bit_reversal(int _src_x, int _src_y, int _time);
Flit *create_head_flit_tornado(int _src_x, int _src_y, int _time);
Flit *create_head_flit_regional(int _src_x, int _src_y, int _time);
Flit *create_head_flit_neighbor(int _src_x, int _src_y, int _time);
Flit *create_head_flit_hotspot(int _src_x, int _src_y, int _time);
Flit *create_head_flit_shuffle(int _src_x, int _src_y, int _time);
Flit *create_head_flit_rotate(int _src_x, int _src_y, int _time);
Flit *create_head_flit_ACK(int _src_x, int _src_y, int _dst_x, int _dst_y, int _time);
Flit *create_head_flit_fixed_dest(int _src_x, int _src_y, int _dst_x, int _dst_y, int _time);
#endif /* PROC_FUNCTIONS_H_ */
|
950db5b212f9f27494ce36ceede953d2630b2e77
|
cd2d52dcd62f30f80b1bc6b0a7450dbb71b9addc
|
/src/sprite.cpp
|
8de3512330b27a5abc7faa7fc689d9deed3db1f8
|
[] |
no_license
|
DCubix/Mikro
|
b359553fd74c16cc2887622e0d6cfacc69bb6705
|
aec5c86c8cb309fd8e466405ce7c8652027b834b
|
refs/heads/master
| 2020-06-13T06:19:13.576949
| 2019-07-17T16:41:34
| 2019-07-17T16:41:34
| 194,568,384
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,471
|
cpp
|
sprite.cpp
|
#include "sprite.h"
#include "png.inl"
#include "log.h"
#include <fstream>
#include <iterator>
#include <cmath>
namespace mik {
namespace util {
u8 dither(i32 x, i32 y, u8 comp) {
return u8(std::max(std::min(comp + DITHER_4x4[(x % 4) + (y % 4) * 4], 255.0), 0.0));
}
u8 palette(u8 r, u8 g, u8 b) {
#ifdef MIK_PRECISE_RGB
u8 closest = 0;
u8 minR = 255;
u8 minG = 255;
u8 minB = 255;
for (u8 i = 0; i < MikPaletteSize; i++) {
i32 pcol = i32(PALETTE[i]);
i32 pr = (pcol & 0xFF0000) >> 16;
i32 pg = (pcol & 0x00FF00) >> 8;
i32 pb = (pcol & 0x0000FF);
u8 dx = std::abs(r - pr);
u8 dy = std::abs(g - pg);
u8 dz = std::abs(b - pb);
if ((dx + dy + dz) < (minR + minG + minB)) {
minR = dx;
minG = dy;
minB = dz;
closest = i;
}
}
return closest;
#else
r = r > 5 ? componentConvert(r) : r;
g = g > 5 ? componentConvert(g) : g;
b = b > 5 ? componentConvert(b) : b;
return (r * 36 + g * 6 + b) % MikPaletteSize;
#endif
}
u8 componentConvert(u8 comp) {
return u8(std::round((f32(comp) / 255.0f) * 5.0f));
}
u8 rgbConvert(u8 comp) {
return u8(std::round((f32(comp) / 5.0f) * 255.0f));
}
}
Sprite::Sprite(std::string const& fileName) {
std::ifstream fp(fileName, std::ios::binary);
if (fp.good()) {
fp.unsetf(std::ios::skipws);
fp.seekg(0, std::ios::end);
auto sz = fp.tellg();
fp.seekg(0, std::ios::beg);
std::vector<u8> data;
data.reserve(sz);
data.insert(data.begin(), std::istream_iterator<u8>(fp), std::istream_iterator<u8>());
fp.close();
load(data);
} else {
LogE("Failed to load \"", fileName, "\": Not found.");
}
}
Sprite::Sprite(std::vector<u8> const& data) {
load(data);
}
void Sprite::load(std::vector<u8> const& data) {
std::vector<unsigned char> pngData;
unsigned long width, height;
if (decodePNG(pngData, width, height, data.data(), data.size()) != 0) {
LogE("Failed to load. Invalid PNG image.");
return;
}
m_data.reserve(width * height);
for (u32 i = 0; i < pngData.size(); i += 4) {
u32 j = i / 4;
u32 x = j % width;
u32 y = j / width;
u8 r = util::componentConvert(util::dither(x, y, pngData[i + 0]));
u8 g = util::componentConvert(util::dither(x, y, pngData[i + 1]));
u8 b = util::componentConvert(util::dither(x, y, pngData[i + 2]));
if (pngData[i + 3] < 127) {
r = 5; g = 0; b = 5;
}
u8 index = util::palette(r, g, b);
m_data.push_back(index);
}
m_width = u32(width);
m_height = u32(height);
}
Sprite::Sprite(u32 width, u32 height) {
m_width = width;
m_height = height;
m_data.reserve(m_width * m_height);
for (u32 i = 0; i < m_width * m_height; i++) {
m_data.push_back(0);
}
}
void Sprite::dot(i32 x, i32 y, u8 r, u8 g, u8 b) {
if (x < 0 || x >= m_width || y < 0 || y >= m_height) return;
const u32 i = x + y * m_width;
const u8 index = util::palette(r, g, b);
m_data[i] = index;
}
void Sprite::clear(u8 r, u8 g, u8 b) {
const u8 index = util::palette(r, g, b);
std::fill(m_data.begin(), m_data.end(), index);
}
Color Sprite::get(i32 x, i32 y) {
x = math::wrap(x, 0, i32(m_width));
y = math::wrap(y, 0, i32(m_height));
const u32 i = x + y * m_width;
u32 pcol = PALETTE[m_data[i]];
Color col;
col.r = util::componentConvert((pcol & 0xFF0000) >> 16);
col.g = util::componentConvert((pcol & 0x00FF00) >> 8);
col.b = util::componentConvert((pcol & 0x0000FF));
return col;
}
}
|
2e7a12bcdd0fa395be7a892d088cdc1c968ceef3
|
3534c6fbc1264029ccd0a9f46557506c3dbfccde
|
/CSC340/second_semester_project/src/Target.cpp
|
c7cf3efeb1dcb1e0dc01c7daf75f8335ddf97216
|
[] |
no_license
|
EatMoreCookies/SDSMT
|
354c6086c89dc7c6e72da105b65eabee39226d80
|
e3f95afa4dfc79485e86b600b23f2eae0af7d640
|
refs/heads/master
| 2023-06-23T07:43:09.228087
| 2021-05-10T14:47:17
| 2021-05-10T14:47:17
| 191,276,320
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 732
|
cpp
|
Target.cpp
|
#include "Target.h"
#include <iostream>
Target::Target() {}
Target::~Target() {}
direction Target::move(MapData map, PositionData status)
{
direction ret = STAY;
return ret;
}
direction Target::attack(MapData map, PositionData status)
{
direction ret = STAY;
return ret;
}
attributes Target::setAttribute(int pointsAvailable, attributes baseStats)
{
attributes tankAttributes;
myStats = baseStats;
tankAttributes.tankHealth += pointsAvailable;
return tankAttributes;
}
int Target::spendAP(MapData map, PositionData status)
{
return 4; // just sit and reload
}
#ifdef DYNAMIC
extern "C" //required for runtime linking
{
Actor * maker()
{
return new Target;
}
}
#endif
|
04240db4921bf263f8d154e6fdb702868c1fe06f
|
bcfb9510826cb5cc8df3b44d01ed26e046f827ed
|
/ModbusDatabaseCreaterCode/scenemgrdialog.h
|
788aa73a747083ed9aa8c923d55447cfc6035a4f
|
[] |
no_license
|
519984307/Modbus-monitoring-tool
|
041db93e08d8f418d04e7888fdbae5af67274af0
|
eb46ef103aacbcc37db94abcc5076c9edb7919e0
|
refs/heads/master
| 2023-03-18T14:38:52.832778
| 2020-12-15T06:16:26
| 2020-12-15T06:16:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 569
|
h
|
scenemgrdialog.h
|
#ifndef SCENEMGRDIALOG_H
#define SCENEMGRDIALOG_H
#include <QDialog>
#include <QSqlDatabase>
namespace Ui {
class SceneMgrDialog;
}
class SceneMgrDialog : public QDialog
{
Q_OBJECT
public:
explicit SceneMgrDialog(QWidget *parent = nullptr);
~SceneMgrDialog();
public:
void TableInit();
void TableBindDb(QString DB);
QSqlDatabase db;
signals:
void Send_Scene_Choose_Info(QString&);
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::SceneMgrDialog *ui;
};
#endif // SCENEMGRDIALOG_H
|
4d4713a72c7372c878982fb14db0eb5a33403144
|
b718ea3950d0ff50af08708c2d67cc9aa539745e
|
/Dados/ui_arkanoidgame.h
|
c12e0447795c27faec38bb8257bf7462610b1a2e
|
[] |
no_license
|
jeansantana/ArkanoidGame
|
792f0afe31361bd17f01a8101f53d533d631cf83
|
806dd400ba01cc2fbdeac4fd17a88258ec7791ee
|
refs/heads/master
| 2016-09-03T06:40:12.820709
| 2014-10-26T17:26:11
| 2014-10-26T17:26:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,784
|
h
|
ui_arkanoidgame.h
|
/********************************************************************************
** Form generated from reading UI file 'arkanoidgame.ui'
**
** Created: Fri Nov 9 00:27:16 2012
** by: Qt User Interface Compiler version 4.8.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_ARKANOIDGAME_H
#define UI_ARKANOIDGAME_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QMainWindow>
#include <QtGui/QMenu>
#include <QtGui/QMenuBar>
#include <QtGui/QWidget>
#include "ArkanoidView.h"
QT_BEGIN_NAMESPACE
class Ui_ArkanoidGame
{
public:
QAction *actionNovo_jogo;
QAction *actionHigh_Scores;
QAction *actionQuit;
QAction *actionInstru_es;
QAction *actionAbout;
QWidget *centralWidget;
QGridLayout *gridLayout;
ArkanoidView *widget;
QMenuBar *menuBar;
QMenu *menuGame;
QMenu *menuHelp;
void setupUi(QMainWindow *ArkanoidGame)
{
if (ArkanoidGame->objectName().isEmpty())
ArkanoidGame->setObjectName(QString::fromUtf8("ArkanoidGame"));
ArkanoidGame->resize(800, 600);
QSizePolicy sizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(ArkanoidGame->sizePolicy().hasHeightForWidth());
ArkanoidGame->setSizePolicy(sizePolicy);
ArkanoidGame->setMinimumSize(QSize(800, 600));
ArkanoidGame->setMaximumSize(QSize(800, 600));
actionNovo_jogo = new QAction(ArkanoidGame);
actionNovo_jogo->setObjectName(QString::fromUtf8("actionNovo_jogo"));
actionHigh_Scores = new QAction(ArkanoidGame);
actionHigh_Scores->setObjectName(QString::fromUtf8("actionHigh_Scores"));
actionQuit = new QAction(ArkanoidGame);
actionQuit->setObjectName(QString::fromUtf8("actionQuit"));
actionInstru_es = new QAction(ArkanoidGame);
actionInstru_es->setObjectName(QString::fromUtf8("actionInstru_es"));
actionAbout = new QAction(ArkanoidGame);
actionAbout->setObjectName(QString::fromUtf8("actionAbout"));
centralWidget = new QWidget(ArkanoidGame);
centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
gridLayout = new QGridLayout(centralWidget);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
widget = new ArkanoidView(centralWidget);
widget->setObjectName(QString::fromUtf8("widget"));
QSizePolicy sizePolicy1(QSizePolicy::Expanding, QSizePolicy::Preferred);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(widget->sizePolicy().hasHeightForWidth());
widget->setSizePolicy(sizePolicy1);
gridLayout->addWidget(widget, 0, 0, 1, 1);
ArkanoidGame->setCentralWidget(centralWidget);
menuBar = new QMenuBar(ArkanoidGame);
menuBar->setObjectName(QString::fromUtf8("menuBar"));
menuBar->setGeometry(QRect(0, 0, 800, 25));
menuGame = new QMenu(menuBar);
menuGame->setObjectName(QString::fromUtf8("menuGame"));
menuHelp = new QMenu(menuBar);
menuHelp->setObjectName(QString::fromUtf8("menuHelp"));
ArkanoidGame->setMenuBar(menuBar);
menuBar->addAction(menuGame->menuAction());
menuBar->addAction(menuHelp->menuAction());
menuGame->addAction(actionNovo_jogo);
menuGame->addAction(actionHigh_Scores);
menuGame->addAction(actionQuit);
menuHelp->addAction(actionInstru_es);
menuHelp->addAction(actionAbout);
retranslateUi(ArkanoidGame);
QMetaObject::connectSlotsByName(ArkanoidGame);
} // setupUi
void retranslateUi(QMainWindow *ArkanoidGame)
{
ArkanoidGame->setWindowTitle(QApplication::translate("ArkanoidGame", "Arkanoid Game", 0, QApplication::UnicodeUTF8));
actionNovo_jogo->setText(QApplication::translate("ArkanoidGame", "Novo jogo", 0, QApplication::UnicodeUTF8));
actionNovo_jogo->setShortcut(QApplication::translate("ArkanoidGame", "Ctrl+N", 0, QApplication::UnicodeUTF8));
actionHigh_Scores->setText(QApplication::translate("ArkanoidGame", "High Scores", 0, QApplication::UnicodeUTF8));
actionHigh_Scores->setShortcut(QApplication::translate("ArkanoidGame", "Ctrl+H", 0, QApplication::UnicodeUTF8));
actionQuit->setText(QApplication::translate("ArkanoidGame", "Sair", 0, QApplication::UnicodeUTF8));
actionQuit->setShortcut(QApplication::translate("ArkanoidGame", "Ctrl+Q", 0, QApplication::UnicodeUTF8));
actionInstru_es->setText(QApplication::translate("ArkanoidGame", "Instru\303\247\303\265es", 0, QApplication::UnicodeUTF8));
actionInstru_es->setShortcut(QApplication::translate("ArkanoidGame", "Ctrl+I", 0, QApplication::UnicodeUTF8));
actionAbout->setText(QApplication::translate("ArkanoidGame", "About", 0, QApplication::UnicodeUTF8));
actionAbout->setShortcut(QApplication::translate("ArkanoidGame", "Ctrl+A", 0, QApplication::UnicodeUTF8));
menuGame->setTitle(QApplication::translate("ArkanoidGame", "Game", 0, QApplication::UnicodeUTF8));
menuHelp->setTitle(QApplication::translate("ArkanoidGame", "Help", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class ArkanoidGame: public Ui_ArkanoidGame {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_ARKANOIDGAME_H
|
11e029e01f527c90c105bd751f85f4a0032bbaab
|
4cc6eb0a4e776f88d946995ff79bb3438e7d7b83
|
/process_exit_event.cpp
|
9decd26ee284044d6cc676c6f299c63e3b2787ed
|
[] |
no_license
|
alejandraklachquin/bitlivery
|
0366fcfb08b3657a0cd769c7d9dbfc0d9392f56a
|
e07baa90699243ac64581e8a19527313eb8adde0
|
refs/heads/master
| 2021-01-22T07:06:34.229249
| 2019-01-30T20:41:05
| 2019-01-30T20:41:05
| 12,369,744
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,576
|
cpp
|
process_exit_event.cpp
|
int process_exit_event(event *temp_event_exits, event *exits, event *events, client clients_vector[NUMBER_CLIENTS], int connections[][NUMBER_CLIENTS], int clients_state[NUMBER_CLIENTS], int servers_state[NUMBER_SERVERS], int *servers_up, int *number_events, int event_id, int end_host, int *clients_up )
{
int i,j, client_id, server_id;
double when,exp_paramenter;
struct event *temp_event, *temp_event2;
struct event **ant, **pont;
ant = ( event **) malloc(sizeof ( event *));
pont = ( event **) malloc(sizeof ( event *));
if(event_id==CLIENT_EXIT_EVENT)
{
client_id=end_host;
//if(DEBUG_LEVEL>0) printf("%f CLIENT_EXIT_EVENT %d\n", t, client_id);
if(clients_state[client_id]==0) printf("ERROR: %f CLIENT_EXIT_EVENT %d\n", t, client_id);
clients_state[client_id]=0;
client_exit_time[client_id]=t;
(*clients_up)--;
if(DEBUG_LEVEL>3) printf("%f CLIENT_EXIT_EVENT %d\n", client_exit_time[client_id], client_id);
//gerar eventos de desconexao com delta 3 para todos os servidores i conectados a client
for(i=0;i<NUMBER_SERVERS;i++)
{
//cada cliente possui um vetor own_connections[]
//se os dois valores sao iguais a 1, a conexao esta ativa e nao ha pedidos de desconexao ja alocados
if((connections[i][client_id]==1) && (clients_vector[client_id].own_connections[i]==1))
{
//criando evento de desconexao para cliente no vetor de eventos
while(true)
{
exp_paramenter = (float)(1/(float)DELTA3);
when = t+gera_aleatorio(exp_paramenter);
if( when < t )
{
printf("ERROR: %f ERROR_TIME_EVENT - DISCONNECTION_EVENT %d %d %f\n", t, i, client_id, when);
return 1;
}
busca_tempo (events, when, ant, pont);
if(*pont==NULL) break;
}
//if(DEBUG_LEVEL>0) printf( "\n%f 1 REMAINING EVENTS TO PROCESS %d\n", t, (*number_events));
insere(events,DISCONNECTION_EVENT,when,i,client_id);
(*number_events)++;
if(DEBUG_LEVEL>3) printf("%f PUSH DISCONNECTION_EVENT %d %d %f\n", t, i, client_id, when);
//if(DEBUG_LEVEL>0) printf( "\n%f 2 REMAINING EVENTS TO PROCESS %d\n", t, (*number_events));
}
}
//deletar evento de saida da lista de saidas
i = erase(exits,temp_event_exits) ;
if( i == 1 ) return 1;
(*number_events)--;
//if(DEBUG_LEVEL>0) printf( "\n%f 3 REMAINING EVENTS TO PROCESS %d\n", t, (*number_events));
//deletar evento de fluxo relativo ao cliente que saiu do sistema
//passar endereco da estrura
temp_event = clients_vector[client_id].flow_event;
if(clients_vector[client_id].flow_event_alloc==1)
{
//neste caso, o evento de fluxo estava alocado na lista de eventos
//tirar da lista de eventos, eventos de fluxo nao sao desalocados pela funcao erase
i = erase(events,temp_event);
if( i == 1 ) return 1;
(*number_events)--;
clients_vector[client_id].flow_event_alloc=0;
//puts("removendo evento de fluxo");
}
free(temp_event);
clients_vector[client_id].flow_event=NULL;
clients_vector[client_id].exit_event=NULL;
//puts("saindo de exit event");
//verificar se ficou algum pedido de conexao pendente e cancelar
temp_event = get_next(events);
while(temp_event != NULL)
{
event_id = get_event_id(temp_event);
i = get_client_id(temp_event);
if( (event_id == CONNECTION_EVENT) && ( i == client_id) )
{
temp_event2 = temp_event;
temp_event = get_next(temp_event);
i = erase(events,temp_event2);
if( i == 1 ) return 1;
(*number_events)--;
//puts("apagando evento de conexao");
}
else{
temp_event = get_next(temp_event);}
}
}
else if(event_id==SERVER_EXIT_EVENT)
{
server_id=end_host;
if(servers_state[server_id]==0) printf("ERROR: %f SERVER_EXIT_EVENT %d\n", t, server_id);
//if(DEBUG_LEVEL>0) printf("%f SERVER_EXIT_EVENT %d\n", t, server_id);
(*servers_up)--;
servers_state[server_id]=0;
server_exit_time[server_id]=t;
if(DEBUG_LEVEL>0) printf("%f SERVER_EXIT_EVENT %d\n", server_exit_time[server_id], server_id);
//gerar eventos de desconexao com delta 3 para todos os servidores i conectados a client
for(j=0;j<NUMBER_CLIENTS;j++)
{
//cada cliente possui um vetor own_connections[]
//se os dois valores sao iguais a 1, a conexao esta ativa e nao ha pedidos de desconexao ja alocados
if((connections[server_id][j]==1) && (clients_vector[j].own_connections[server_id]==1))
{
//criando evento de desconexao para cliente no vetor de eventos
while(true)
{
exp_paramenter = (float)(1/(float)DELTA3);
when = t+gera_aleatorio(exp_paramenter);
if( when < t )
{
printf("ERROR: %f ERROR_TIME_EVENT - DISCONNECTION_EVENT %d %d %f\n", t, server_id, j, when);
return 1;
}
busca_tempo (events, when, ant, pont);
if(*pont==NULL) break;
}
clients_vector[j].own_connections[server_id]=0;
insere(events,DISCONNECTION_EVENT,when,server_id,j);
(*number_events)++;
if(DEBUG_LEVEL>0) printf("%f PUSH DISCONNECTION_EVENT %d %d %f\n", t, server_id, j, when);
//atualizando tempo do ultimo evento de conexao
if( when > clients_vector[j].last_connection_scheduled ) clients_vector[j].last_connection_scheduled = when;
}
}
//deletar evento de saida da lista de saidas
i = erase(events,temp_event_exits) ;
if( i == 1 ) return 1;
(*number_events)--;
//verificar se ficou algum pedido de conexao pendente e cancelar
temp_event = get_next(events);
while(temp_event != NULL)
{
event_id = get_event_id(temp_event);
i = get_server_id(temp_event);
//printf("%f PUSH DISCONNECTION_EVENT %d %d %f\n", t, server_id, j, when);
if( (event_id == CONNECTION_EVENT) && ( i == server_id) )
{
temp_event2 = temp_event;
temp_event = get_next(temp_event);
i = erase(events,temp_event2);
if( i == 1 ) return 1;
(*number_events)--;
}
else{
temp_event = get_next(temp_event);}
}
}
return 0;
}
|
2afaed802251ad753060d1aa3eaaaafe343e9d92
|
f20e965e19b749e84281cb35baea6787f815f777
|
/LHCb/Det/MuonDet/src/Lib/SortPairTileInTU.h
|
918bee700aeadd7fbfc5e823fb47ffbd7088b7cf
|
[] |
no_license
|
marromlam/lhcb-software
|
f677abc9c6a27aa82a9b68c062eab587e6883906
|
f3a80ecab090d9ec1b33e12b987d3d743884dc24
|
refs/heads/master
| 2020-12-23T15:26:01.606128
| 2016-04-08T15:48:59
| 2016-04-08T15:48:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,058
|
h
|
SortPairTileInTU.h
|
// $Id: SortPairTileInTU.h,v 1.1 2008-06-30 11:45:30 asatta Exp $
#ifndef LIB_SORTPAIRTILEINTU_H
#define LIB_SORTPAIRTILEINTU_H 1
#include <iostream>
#include <functional>
#include "Kernel/MuonTileID.h"
// Include files
/** @class SortPairTileInTU SortPairTileInTU.h Lib/SortPairTileInTU.h
*
*
* @author
* @date 2008-02-24
*/
class SortPairTileInTU :
public
std::binary_function<std::pair<LHCb::MuonTileID,LHCb::MuonTileID>
,std::pair<LHCb::MuonTileID,LHCb::MuonTileID>,bool>{ public :
bool operator()( const std::pair<LHCb::MuonTileID,LHCb::MuonTileID>&
first, const std::pair<LHCb::MuonTileID,LHCb::MuonTileID> & second )
const;
};
bool SortPairTileInTU::operator()(const
std::pair<LHCb::MuonTileID,LHCb::MuonTileID> & one,
const
std::pair<LHCb::MuonTileID,LHCb::MuonTileID> & two )const{
if(one.first.nY()<two.first.nY())return true;
if(one.first.nY()>two.first.nY())return false;
if(one.first.nX()<=two.first.nX())return true;
return false;
}
#endif // LIB_SORTPAIRTILEINTU_H
|
96d9ae9732ac16f9746e08faa7b0baeb25541d51
|
40dd73e1392e722f0f4e2122eed65da2a5aebadd
|
/PointerReferenceAndArthemetic.cpp
|
3433a85ef4b75ff6c9da3c9f83dbeaf7d7694219
|
[] |
no_license
|
manojmula/Cpp
|
ddf239e576747e68ba50339c8b2e27dffeae1e61
|
44c0c4ff1bbd300692cb9d87c8728768e205923a
|
refs/heads/master
| 2023-02-09T07:35:07.169007
| 2020-12-28T10:13:17
| 2020-12-28T10:13:17
| 283,914,927
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,334
|
cpp
|
PointerReferenceAndArthemetic.cpp
|
/**
* As discussed in chapter 3 there are sunstantial number of arthemetic that can be performed with pointer
* c++ allows to perform the following arthemtic using pointer
* A pointer can be incremented ++ or decremented ++
* Any integere can be added to orr subtarcted from pointer
* One pointer can be sunstracted ffrom another
* int a[6];
* int *aptr;
* aptr = &a[0];
* obvisouly the pointer aptr refers ti the base address of the varable a
* We can increment the pointer varaibel as shown below
* aptr++
* ++aptr
* This statment moves the pointer to the next memory address
* Similary we can decrement the pointer varaible as follows
* aptr-- or --aptr
*
* this statment moves the pointer to the previous memory address alos
* if two pointer varaibles point to the same array then they can be substarcted from each other
* We cannot perform pointer arthimetic on the varobles that are not stored in contigues memory location
*
*
*
* **/
#include<iostream>
int main()
{
int num[] = {56,75,22,18,90};
int *ptr;
int i;
std::cout<<"The array values are :"<<std::endl;
for(i = 0;i<5;i++)
{
std::cout<<num[i]<<std::endl;
}
ptr = num;
i=0;
while(i<5)
{
std::cout<<"The value of ptr:"<<*ptr<<std::endl;
ptr++;
i++;
}
}
|
887e19afae81af8ed7c575d7bc8def3d8ed3b628
|
abc890e58719c78d41bb5661bae1fa9eedbc4124
|
/cdfA.cpp
|
c3f8c738a8e5e1e05c601ccbf8c94214c23788c6
|
[] |
no_license
|
MHaq23/CC_Solutions-Codechef-Codeforces-
|
2d8337dbddda088a66114dd9f07271d05ee895cf
|
f8b5cf1310c4892d627267766478fc375582fbe4
|
refs/heads/master
| 2021-01-02T18:36:47.403032
| 2020-02-11T11:45:13
| 2020-02-11T11:45:13
| 239,746,342
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 278
|
cpp
|
cdfA.cpp
|
#include<bits/stdc++.h>
using namespace std ;
#define int long long
signed main(){
int q;
cin>>q;
while(q--)
{
int n,ans;cin>>n;double t;
if(n==2)
ans=2;
else
{
ans=n%2;
}
cout<<ans<<endl;
}
return 0 ;
}
|
5d8dabcf099789b9e321925b0d422f38067f2a9f
|
15ab1546d22a8ef8bb77d2be978b86e1be366db3
|
/yevent_cc/Thread.cc
|
a1fbd70ae8f9d4d118f6f8fe7df6b2637010300b
|
[] |
no_license
|
olym/yevent
|
624406eea765afda5fd01e08f47e8823ad1c6f7e
|
3019eec4bef2d28d4cbec3e42b132bbf809ebd30
|
refs/heads/master
| 2021-01-22T05:16:15.003232
| 2012-10-08T07:40:54
| 2012-10-08T07:40:54
| 3,303,073
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,433
|
cc
|
Thread.cc
|
/*
* =====================================================================================
*
* Filename: Thread.cc
*
* Description:
*
* Version: 1.0
* Created: 2012年05月24日 15时42分52秒
* Revision: none
* Compiler: gcc
*
* Author: Yin Zhongxing (olym), zhongxing.yin@cs2c.com.cn
* Company: www.CS2C.com.cn
*
* =====================================================================================
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <assert.h>
#include <string>
#include "Thread.h"
#include "Utility.h"
namespace yevent {
}
using namespace yevent;
using std::string;
Thread::Thread(ThreadFunc func, void *args, string name) :
threadId_(-1),
tid_(-1),
threadFunc_(func),
args_(args),
name_(name),
isRunning_(false)
{
}
Thread::~Thread()
{
}
void Thread::start()
{
assert(!isRunning_);
int ret = -1;
ret = pthread_create(&threadId_, NULL, &startThread, this);
if (ret != 0)
fprintf(stderr, "pthread_create error\n");
}
int Thread::join()
{
assert(isRunning_);
return pthread_join(threadId_, NULL);
}
void *Thread::startThread(void *args)
{
Thread *thread = static_cast<Thread *>(args);
thread->runInThread();
return NULL;
}
void *Thread::runInThread()
{
isRunning_ = true;
tid_ = util::gettid();
threadFunc_(args_);
}
|
38f65ebce7bbac2597377fb19783adc1e694e808
|
f4bfac4a89ca71b84768254df4de5809741beee1
|
/13. Circuit Board Price.cpp
|
c10aaf161df4f2d3bed5d13c29496ab98476b7bb
|
[] |
no_license
|
mikhaputri/Review-Chapter-2
|
0a69587d651c12cfcbd7a19fa752aa1e79d29537
|
19f2be713073fa8232d7725602b40a5bac10709e
|
refs/heads/master
| 2021-01-10T23:29:33.242293
| 2016-10-12T01:43:59
| 2016-10-12T01:43:59
| 70,602,864
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 459
|
cpp
|
13. Circuit Board Price.cpp
|
//
// 13.cpp
// REVIEW BAGUS
//
// Created by Mikha Yupikha on 11/10/2016.
// Copyright © 2016 Mikha Yupikha. All rights reserved.
//
#include <iostream>
using namespace std;
int main ()
{
float percentProfit = 0.35;
float productPrice = 14.95;
float sellingPrice = productPrice + (productPrice*percentProfit);
cout<< "The selling price of a circuit board that costs $14.95 is $"<<sellingPrice<<endl;
return 0;
}
|
45d7c3493b93caa8245862c020b6ce42ab3472bb
|
5b94cf771f7150bf1ebac3b51b76a306622529a8
|
/zencrypt_aes.h
|
a60cde761692543f939b8ad8344fe0af4f635441
|
[] |
no_license
|
erezsh/zodengine
|
79dc8b2825d5a751587c154ec9ca3e9ab3023b38
|
27d29020b9a187a090860e21bf52f8e7a91771e7
|
refs/heads/master
| 2023-09-03T09:16:49.748391
| 2013-04-13T11:25:02
| 2013-04-13T11:25:17
| 5,296,561
| 7
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,307
|
h
|
zencrypt_aes.h
|
/*
Main code taken from www.hoozi.com
Main code written by Niyaz PK at niyazlife@gmail.com
*/
#ifndef _AES_ENCRYPT_H_
#define _AES_ENCRYPT_H_
class ZEncryptAES
{
private:
int Nr; // The number of rounds in AES Cipher. It is simply initiated to zero. The actual value is recieved in the program.
int Nk; // The number of 32 bit words in the key. It is simply initiated to zero. The actual value is recieved in the program.
unsigned char *in, *out, state[4][4];
unsigned char RoundKey[240]; // The array that stores the round keys.
unsigned char Key[32]; // The Key input to the AES Program
//universal stuff
inline int getSBoxInvert(int num);
inline int getSBoxValue(int num);
inline void KeyExpansion();
inline void AddRoundKey(int round);
//decrypt stuff
inline void InvSubBytes();
inline void InvShiftRows();
inline void InvCipher();
inline void InvMixColumns();
//encrypt stuff
inline void SubBytes();
inline void ShiftRows();
inline void MixColumns();
inline void Cipher();
public:
ZEncryptAES()
{
Nr=0;
Nk=0;
}
//public stuff
int Init_Key(unsigned char *key, int size);
void AES_Encrypt(char * input, int in_size, char *output);
void AES_Decrypt(char * input, int in_size, char *output);
};
#endif
|
afba8dfd53a70d44af91c865a3067a7b5ccfd817
|
89f91ac3de03a78a7158bfa87b0d4d84a3c47109
|
/355.cpp
|
416f240688a28722d3aea82a99c0f55b4fb24f6b
|
[] |
no_license
|
xyuanlu/Cultivation
|
65a8b098f407443aa35b2fe6d5d77419a1ab0e73
|
9a2dadc56ec17d5af1c780e9224936f1afa86786
|
refs/heads/master
| 2021-07-06T08:07:11.071012
| 2020-11-08T23:55:46
| 2020-11-08T23:55:46
| 201,869,574
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,306
|
cpp
|
355.cpp
|
/*
* 355. Design Twitter
* Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods:
*
* postTweet(userId, tweetId): Compose a new tweet.
* getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the user's news feed. Each
* item in the news feed must be posted by users who the user followed or by the user herself.
* Tweets must be ordered from most recent to least recent.
* follow(followerId, followeeId): Follower follows a followee.
* unfollow(followerId, followeeId): Follower unfollows a followee.
*/
class Twitter {
public:
class T{
public:
int id;
int t;
};
class P{
public:
int userId;
int idx; // idx in tweet queue
};
/** Initialize your data structure here. */
Twitter() {
_t = 0;
K = 10;
}
/** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
if(m[userId].size() == K) {
m[userId].pop_front();
}
m[userId].push_back({tweetId, _t++});
}
/** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
vector<int> getNewsFeed(int userId) {
auto compare = [this](const P& p1, const P& p2){
return m[p1.userId][p1.idx].t < m[p2.userId][p2.idx].t;
};
priority_queue<P, vector<P>, decltype(compare)> pq(compare);
vector<int> res;
if (m[userId].size()!=0)
pq.push({userId, m[userId].size()-1});
for(auto id:f[userId]) {
//cout<<m[id].size()-1<<endl;
if(m[id].size()!=0)
pq.push({id, m[id].size()-1});
}
while(res.size()!=K && !pq.empty()) {
res.push_back(m[pq.top().userId][pq.top().idx].id);
if (pq.top().idx!=0)
pq.push({pq.top().userId, pq.top().idx-1});
pq.pop();
}
return res;
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
void follow(int followerId, int followeeId) {
if(followeeId == followerId)
return;
f[followerId].insert(followeeId);
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
void unfollow(int followerId, int followeeId) {
f[followerId].erase(followeeId);
}
private:
int _t;
int K;
/*
* Deque:
* Random access - constant O(1)
* Insertion or removal of elements at the end or beginning - constant O(1)
* Insertion or removal of elements - linear O(n)
*/
unordered_map<int, deque<T>> m;
// user key follows a set of users
unordered_map<int, unordered_set<int>> f;
};
/**
* Your Twitter object will be instantiated and called as such:
* Twitter* obj = new Twitter();
* obj->postTweet(userId,tweetId);
* vector<int> param_2 = obj->getNewsFeed(userId);
* obj->follow(followerId,followeeId);
* obj->unfollow(followerId,followeeId);
*/
|
045fc767281b6ce32946769033e782ad56dbd059
|
bc1e0e56cd6cc337d4d60a1040d87c8634e4f99e
|
/src/text/text-renderer.cpp
|
6e40cb25776c86d5a01d23ee24398d9eaa517bbb
|
[] |
no_license
|
spacekitcat/isometric-sdl-demo
|
dfbda7e1806417fa7c85d030ca62939b9eaf4b10
|
a1e3aefb0f6dd145e4804319660bdef73a4bfc98
|
refs/heads/main
| 2023-08-13T22:35:41.421884
| 2021-10-09T16:41:16
| 2021-10-09T16:41:16
| 380,589,963
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 869
|
cpp
|
text-renderer.cpp
|
#include "text-renderer.hpp"
TextRenderer::TextRenderer(std::shared_ptr<SDLManager> sdlManager) {
_sdlManager = sdlManager;
assert(_sdlManager != nullptr);
SDL_Color textFgColor = {255, 255, 255};
SDL_Color textBgColor = {0, 0, 0};
FC_Style style = {.fontSize = 16,
.outline = 1,
.color = textFgColor,
.outline_color = textBgColor};
_backgroundFont = FC_CreateFont();
FC_LoadFontFromStyle(_backgroundFont, _sdlManager->getRenderer(),
"./assets/fonts/Lato-Bold.ttf", &style);
}
TextRenderer::~TextRenderer() {
// delete _backgroundFont;
}
void TextRenderer::renderText(std::string text,
std::pair<float, float> position) {
FC_Draw(_backgroundFont, _sdlManager->getRenderer(), position.first,
position.second, text.c_str());
}
|
4690109ea6c3675c62fcb536220567c1a309674c
|
a7a6807b822eb96ee0fef0dbe336d35b7ff291f9
|
/SimpleQuad/GLTex1D.cpp
|
20c5485d6df30ee19fa9b3693e0daa44d9650bf8
|
[] |
no_license
|
jiatingxiu/LearnOpenGL
|
48a11c901bfdcfa3defb127b28a1ee739f8b0252
|
1d624c1b1520ff10e1d8a7ed48a03f6b4cc18257
|
refs/heads/master
| 2021-01-21T12:35:34.197221
| 2017-09-01T07:49:28
| 2018-05-21T03:17:29
| 102,088,317
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,498
|
cpp
|
GLTex1D.cpp
|
#include "GLTex1D.h"
#include <GL/glew.h>
GLTex1D::GLTex1D(void)
{
m_TexID = 0;
m_TextureUnit = 0;
}
GLTex1D::~GLTex1D(void)
{
Delete();
}
void GLTex1D::Create(int texSize)
{
Create(texSize, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR, GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, 0);
}
void GLTex1D::Create(int texSize, void* texData)
{
Create(texSize, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR, GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, texData);
}
void GLTex1D::Create(int texSize, int texInternalFormat, int texFormat, int texType)
{
Create(texSize, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR, texInternalFormat, texFormat, texType, 0);
}
void GLTex1D::Create(int texSize, int texInternalFormat, int texFormat, int texType, void* texData)
{
Create(texSize, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR, texInternalFormat, texFormat, texType, texData);
}
void GLTex1D::Create(int texSize, int clampMode, int minFilter, int magFilter, int texInternalFormat, int texFormat, int texType)
{
Create(texSize, clampMode, minFilter, magFilter, texInternalFormat, texFormat, texType, 0);
}
void GLTex1D::Create(int texSize, int clampMode, int minFilter, int magFilter, int texInternalFormat, int texFormat, int texType, void* texData)
{
//Generate name or ID of texture object
glGenTextures(1, &m_TexID);
//Bind this texture object
glBindTexture(GL_TEXTURE_1D, m_TexID);
//Clamp mode setting
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, clampMode);
//Filter setting for min and mag
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, magFilter);
//GL_TEXTURE_ENV_MODE defaults to GL_MODULATE. We need to modify it to GL_REPLACE.
//Note: This function is deprecated.
//States such as GL_TEXTURE_WRAP_S, GL_TEXTURE_WRAP_T, GL_TEXTURE_MAG_FILTER,
//GL_TEXTURE_MIN_FILTER are part of the texture object.
//glTexEnv is part of the texture image unit (TIU), not the texture object.
//When you set this it will effect any texture attached to the TIU and it only has
//effect during rendering.
//You can select a TIU with glActiveTexture(GL_TEXTURE0+i).
//Also keep in mind that glTexEnvi has no effect when a fragment shader is bound.
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
//Transfer the texture data to GPU memory. You can set the last parameter as null to
//setup the texture format only.
glTexImage1D(GL_TEXTURE_1D, 0, texInternalFormat, texSize, 0, texFormat, texType, texData);
//These parameters are needed in Update() function
m_TexSize = texSize;
m_TexFormat = texFormat;
m_TexType = texType;
}
//Delete this texture object
void GLTex1D::Delete()
{
if (m_TexID != 0)
glDeleteTextures(1, &m_TexID);
}
//Bind this texture object
void GLTex1D::Bind()
{
glBindTexture(GL_TEXTURE_1D, m_TexID);
}
//First active the texture unit, then bind the texture object
void GLTex1D::ActiveAndBind()
{
glActiveTexture(GL_TEXTURE0 + m_TextureUnit);
glBindTexture(GL_TEXTURE_1D, m_TexID);
}
//Unbind this texture object
void GLTex1D::BindToZero()
{
glBindTexture(GL_TEXTURE_1D, 0);
}
//Update using PBO. Copy the contents from PBO buffer to texture object.
//Using offset instead of pointer.
void GLTex1D::Update()
{
glTexSubImage1D(GL_TEXTURE_1D, 0, 0, m_TexSize, m_TexFormat, m_TexType, 0);
}
//Update the whole texture using TexSubImage
void GLTex1D::Update(void* texData)
{
glTexSubImage1D(GL_TEXTURE_1D, 0, 0, m_TexSize, m_TexFormat, m_TexType, texData);
}
|
cbdaae8e96ad3a5828d4f43fddf6743726025858
|
cc4678f1abdd833306389a9a6c72a088ab0bb55d
|
/bin/android/obj/include/native/display/BitmapData.h
|
d59a9207e98892a79fecff7f00593505790f0c6b
|
[] |
no_license
|
shrekshrek/gamebox-haxe
|
78330b90493b0cc7a4e11a229aead7922b55f538
|
7c1567c66a1f9f63b95affe57bdad52dc3b70067
|
refs/heads/master
| 2020-04-02T20:42:30.421023
| 2016-07-10T09:11:39
| 2016-07-10T09:12:20
| 62,990,806
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,094
|
h
|
BitmapData.h
|
#ifndef INCLUDED_native_display_BitmapData
#define INCLUDED_native_display_BitmapData
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#include <native/display/IBitmapDrawable.h>
HX_DECLARE_CLASS2(haxe,io,Bytes)
HX_DECLARE_CLASS2(native,display,BitmapData)
HX_DECLARE_CLASS2(native,display,BlendMode)
HX_DECLARE_CLASS2(native,display,IBitmapDrawable)
HX_DECLARE_CLASS2(native,filters,BitmapFilter)
HX_DECLARE_CLASS2(native,geom,ColorTransform)
HX_DECLARE_CLASS2(native,geom,Matrix)
HX_DECLARE_CLASS2(native,geom,Point)
HX_DECLARE_CLASS2(native,geom,Rectangle)
HX_DECLARE_CLASS2(native,utils,ByteArray)
HX_DECLARE_CLASS2(native,utils,IDataInput)
HX_DECLARE_CLASS2(native,utils,IMemoryRange)
namespace native{
namespace display{
class BitmapData_obj : public hx::Object{
public:
typedef hx::Object super;
typedef BitmapData_obj OBJ_;
BitmapData_obj();
Void __construct(int inWidth,int inHeight,hx::Null< bool > __o_inTransparent,Dynamic inFillRGBA,Dynamic inGPUMode);
public:
static hx::ObjectPtr< BitmapData_obj > __new(int inWidth,int inHeight,hx::Null< bool > __o_inTransparent,Dynamic inFillRGBA,Dynamic inGPUMode);
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
~BitmapData_obj();
HX_DO_RTTI;
static void __boot();
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
inline operator ::native::display::IBitmapDrawable_obj *()
{ return new ::native::display::IBitmapDrawable_delegate_< BitmapData_obj >(this); }
hx::Object *__ToInterface(const type_info &inType);
::String __ToString() const { return HX_CSTRING("BitmapData"); }
virtual bool get_transparent( );
Dynamic get_transparent_dyn();
virtual int get_height( );
Dynamic get_height_dyn();
virtual int get_width( );
Dynamic get_width_dyn();
virtual ::native::geom::Rectangle get_rect( );
Dynamic get_rect_dyn();
virtual Void noise( int randomSeed,hx::Null< int > low,hx::Null< int > high,hx::Null< int > channelOptions,hx::Null< bool > grayScale);
Dynamic noise_dyn();
virtual Void setFormat( int format);
Dynamic setFormat_dyn();
virtual Void unlock( ::native::geom::Rectangle changeRect);
Dynamic unlock_dyn();
virtual Void setVector( ::native::geom::Rectangle rect,Array< int > inPixels);
Dynamic setVector_dyn();
virtual Void setPixels( ::native::geom::Rectangle rect,::native::utils::ByteArray pixels);
Dynamic setPixels_dyn();
virtual Void setPixel32( int inX,int inY,int inColour);
Dynamic setPixel32_dyn();
virtual Void setPixel( int inX,int inY,int inColour);
Dynamic setPixel_dyn();
virtual Void setFlags( int inFlags);
Dynamic setFlags_dyn();
virtual Void scroll( int inDX,int inDY);
Dynamic scroll_dyn();
virtual Void perlinNoise( Float baseX,Float baseY,int numOctaves,int randomSeed,bool stitch,bool fractalNoise,hx::Null< int > channelOptions,hx::Null< bool > grayScale,Array< ::native::geom::Point > offsets);
Dynamic perlinNoise_dyn();
virtual Void nmeDrawToSurface( Dynamic inSurface,::native::geom::Matrix matrix,::native::geom::ColorTransform colorTransform,::String blendMode,::native::geom::Rectangle clipRect,bool smoothing);
Dynamic nmeDrawToSurface_dyn();
virtual Void lock( );
Dynamic lock_dyn();
virtual Array< int > getVector( ::native::geom::Rectangle rect);
Dynamic getVector_dyn();
virtual ::native::utils::ByteArray getPixels( ::native::geom::Rectangle rect);
Dynamic getPixels_dyn();
virtual int getPixel32( int x,int y);
Dynamic getPixel32_dyn();
virtual int getPixel( int x,int y);
Dynamic getPixel_dyn();
virtual ::native::geom::Rectangle getColorBoundsRect( int mask,int color,hx::Null< bool > findColor);
Dynamic getColorBoundsRect_dyn();
virtual ::native::geom::Rectangle generateFilterRect( ::native::geom::Rectangle sourceRect,::native::filters::BitmapFilter filter);
Dynamic generateFilterRect_dyn();
virtual Void fillRectEx( ::native::geom::Rectangle rect,int inColour,hx::Null< int > inAlpha);
Dynamic fillRectEx_dyn();
virtual Void fillRect( ::native::geom::Rectangle rect,int inColour);
Dynamic fillRect_dyn();
virtual ::native::utils::ByteArray encode( ::String inFormat,hx::Null< Float > inQuality);
Dynamic encode_dyn();
virtual Void dumpBits( );
Dynamic dumpBits_dyn();
virtual Void draw( ::native::display::IBitmapDrawable source,::native::geom::Matrix matrix,::native::geom::ColorTransform colorTransform,::native::display::BlendMode blendMode,::native::geom::Rectangle clipRect,hx::Null< bool > smoothing);
Dynamic draw_dyn();
virtual Void dispose( );
Dynamic dispose_dyn();
virtual Void destroyHardwareSurface( );
Dynamic destroyHardwareSurface_dyn();
virtual Void createHardwareSurface( );
Dynamic createHardwareSurface_dyn();
virtual Void copyPixels( ::native::display::BitmapData sourceBitmapData,::native::geom::Rectangle sourceRect,::native::geom::Point destPoint,::native::display::BitmapData alphaBitmapData,::native::geom::Point alphaPoint,hx::Null< bool > mergeAlpha);
Dynamic copyPixels_dyn();
virtual Void copyChannel( ::native::display::BitmapData sourceBitmapData,::native::geom::Rectangle sourceRect,::native::geom::Point destPoint,int inSourceChannel,int inDestChannel);
Dynamic copyChannel_dyn();
virtual Void colorTransform( ::native::geom::Rectangle rect,::native::geom::ColorTransform colorTransform);
Dynamic colorTransform_dyn();
virtual ::native::display::BitmapData clone( );
Dynamic clone_dyn();
virtual Void clear( int color);
Dynamic clear_dyn();
virtual Void applyFilter( ::native::display::BitmapData sourceBitmapData,::native::geom::Rectangle sourceRect,::native::geom::Point destPoint,::native::filters::BitmapFilter filter);
Dynamic applyFilter_dyn();
Dynamic nmeHandle; /* REM */
int width; /* REM */
bool transparent; /* REM */
::native::geom::Rectangle rect; /* REM */
int height; /* REM */
static int CLEAR; /* REM */
static int BLACK; /* REM */
static int WHITE; /* REM */
static int RED; /* REM */
static int GREEN; /* REM */
static int BLUE; /* REM */
static ::String PNG; /* REM */
static ::String JPG; /* REM */
static int TRANSPARENT; /* REM */
static int HARDWARE; /* REM */
static int FORMAT_8888; /* REM */
static int FORMAT_4444; /* REM */
static int FORMAT_565; /* REM */
static int createColor( int inRGB,hx::Null< int > inAlpha);
static Dynamic createColor_dyn();
static int extractAlpha( int v);
static Dynamic extractAlpha_dyn();
static int extractColor( int v);
static Dynamic extractColor_dyn();
static ::native::utils::ByteArray getRGBAPixels( ::native::display::BitmapData bitmapData);
static Dynamic getRGBAPixels_dyn();
static ::native::display::BitmapData load( ::String inFilename,hx::Null< int > format);
static Dynamic load_dyn();
static ::native::display::BitmapData loadFromBytes( ::native::utils::ByteArray inBytes,::native::utils::ByteArray inRawAlpha);
static Dynamic loadFromBytes_dyn();
static ::native::display::BitmapData loadFromHaxeBytes( ::haxe::io::Bytes inBytes,::haxe::io::Bytes inRawAlpha);
static Dynamic loadFromHaxeBytes_dyn();
static Dynamic nme_bitmap_data_create; /* REM */
static Dynamic &nme_bitmap_data_create_dyn() { return nme_bitmap_data_create;}
static Dynamic nme_bitmap_data_load; /* REM */
static Dynamic &nme_bitmap_data_load_dyn() { return nme_bitmap_data_load;}
static Dynamic nme_bitmap_data_from_bytes; /* REM */
static Dynamic &nme_bitmap_data_from_bytes_dyn() { return nme_bitmap_data_from_bytes;}
static Dynamic nme_bitmap_data_clear; /* REM */
static Dynamic &nme_bitmap_data_clear_dyn() { return nme_bitmap_data_clear;}
static Dynamic nme_bitmap_data_clone; /* REM */
static Dynamic &nme_bitmap_data_clone_dyn() { return nme_bitmap_data_clone;}
static Dynamic nme_bitmap_data_apply_filter; /* REM */
static Dynamic &nme_bitmap_data_apply_filter_dyn() { return nme_bitmap_data_apply_filter;}
static Dynamic nme_bitmap_data_color_transform; /* REM */
static Dynamic &nme_bitmap_data_color_transform_dyn() { return nme_bitmap_data_color_transform;}
static Dynamic nme_bitmap_data_copy; /* REM */
static Dynamic &nme_bitmap_data_copy_dyn() { return nme_bitmap_data_copy;}
static Dynamic nme_bitmap_data_copy_channel; /* REM */
static Dynamic &nme_bitmap_data_copy_channel_dyn() { return nme_bitmap_data_copy_channel;}
static Dynamic nme_bitmap_data_fill; /* REM */
static Dynamic &nme_bitmap_data_fill_dyn() { return nme_bitmap_data_fill;}
static Dynamic nme_bitmap_data_get_pixels; /* REM */
static Dynamic &nme_bitmap_data_get_pixels_dyn() { return nme_bitmap_data_get_pixels;}
static Dynamic nme_bitmap_data_get_pixel; /* REM */
static Dynamic &nme_bitmap_data_get_pixel_dyn() { return nme_bitmap_data_get_pixel;}
static Dynamic nme_bitmap_data_get_pixel32; /* REM */
static Dynamic &nme_bitmap_data_get_pixel32_dyn() { return nme_bitmap_data_get_pixel32;}
static Dynamic nme_bitmap_data_get_pixel_rgba; /* REM */
static Dynamic nme_bitmap_data_get_array; /* REM */
static Dynamic &nme_bitmap_data_get_array_dyn() { return nme_bitmap_data_get_array;}
static Dynamic nme_bitmap_data_get_color_bounds_rect; /* REM */
static Dynamic &nme_bitmap_data_get_color_bounds_rect_dyn() { return nme_bitmap_data_get_color_bounds_rect;}
static Dynamic nme_bitmap_data_scroll; /* REM */
static Dynamic &nme_bitmap_data_scroll_dyn() { return nme_bitmap_data_scroll;}
static Dynamic nme_bitmap_data_set_pixel; /* REM */
static Dynamic &nme_bitmap_data_set_pixel_dyn() { return nme_bitmap_data_set_pixel;}
static Dynamic nme_bitmap_data_set_pixel32; /* REM */
static Dynamic &nme_bitmap_data_set_pixel32_dyn() { return nme_bitmap_data_set_pixel32;}
static Dynamic nme_bitmap_data_set_pixel_rgba; /* REM */
static Dynamic nme_bitmap_data_set_bytes; /* REM */
static Dynamic &nme_bitmap_data_set_bytes_dyn() { return nme_bitmap_data_set_bytes;}
static Dynamic nme_bitmap_data_set_format; /* REM */
static Dynamic &nme_bitmap_data_set_format_dyn() { return nme_bitmap_data_set_format;}
static Dynamic nme_bitmap_data_set_array; /* REM */
static Dynamic &nme_bitmap_data_set_array_dyn() { return nme_bitmap_data_set_array;}
static Dynamic nme_bitmap_data_create_hardware_surface; /* REM */
static Dynamic &nme_bitmap_data_create_hardware_surface_dyn() { return nme_bitmap_data_create_hardware_surface;}
static Dynamic nme_bitmap_data_destroy_hardware_surface; /* REM */
static Dynamic &nme_bitmap_data_destroy_hardware_surface_dyn() { return nme_bitmap_data_destroy_hardware_surface;}
static Dynamic nme_bitmap_data_generate_filter_rect; /* REM */
static Dynamic &nme_bitmap_data_generate_filter_rect_dyn() { return nme_bitmap_data_generate_filter_rect;}
static Dynamic nme_render_surface_to_surface; /* REM */
static Dynamic &nme_render_surface_to_surface_dyn() { return nme_render_surface_to_surface;}
static Dynamic nme_bitmap_data_height; /* REM */
static Dynamic &nme_bitmap_data_height_dyn() { return nme_bitmap_data_height;}
static Dynamic nme_bitmap_data_width; /* REM */
static Dynamic &nme_bitmap_data_width_dyn() { return nme_bitmap_data_width;}
static Dynamic nme_bitmap_data_get_transparent; /* REM */
static Dynamic &nme_bitmap_data_get_transparent_dyn() { return nme_bitmap_data_get_transparent;}
static Dynamic nme_bitmap_data_set_flags; /* REM */
static Dynamic &nme_bitmap_data_set_flags_dyn() { return nme_bitmap_data_set_flags;}
static Dynamic nme_bitmap_data_encode; /* REM */
static Dynamic &nme_bitmap_data_encode_dyn() { return nme_bitmap_data_encode;}
static Dynamic nme_bitmap_data_dump_bits; /* REM */
static Dynamic &nme_bitmap_data_dump_bits_dyn() { return nme_bitmap_data_dump_bits;}
static Dynamic nme_bitmap_data_noise; /* REM */
static Dynamic &nme_bitmap_data_noise_dyn() { return nme_bitmap_data_noise;}
};
} // end namespace native
} // end namespace display
#endif /* INCLUDED_native_display_BitmapData */
|
75bec49e60fc9fbf65dcd042842fb087333e93ee
|
9264ad419b73883a69fb02688ddc3ee40c53edbd
|
/CF/902D.cpp
|
c6001138d7ea364beea214db199d54b69c1cddd1
|
[] |
no_license
|
manish1997/Competitive-Programming
|
6d5e7fb6081d1a09f8658638bddcd1c72495c396
|
b7048f770f7db8ac0bc871d59f1973482f79668f
|
refs/heads/master
| 2021-01-13T04:31:13.082435
| 2020-03-22T20:32:04
| 2020-03-22T20:32:04
| 79,900,759
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,675
|
cpp
|
902D.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define pi 3.1415926535897
#define ll long long
#define tr1(n) cout << n << endl
#define tr2(n1,n2) cout << n1 << " " << n2 << endl
#define mem(A,i) memset(A, i, sizeof(A))
#define rep(i, start, end) for(int i=start; i<end; i++)
#define repDown(i, start, end) for(int i=start; i>=end; i--)
#define mod 1000000007
#define MAX 1000005
#define s second
#define f first
#define pb push_back
#define fast_in std::ios::sync_with_stdio(false);
#define fast_cin fast_in; ios_base::sync_with_stdio(false); cin.tie(NULL);
int ans[200][200];
void solve(){
//solve the problem. You can and you will :) give your best shot..
int n;
cin >> n;
ans[1][1]=1;
ans[0][0]=1;
if(n==1){
tr1(1);
cout << "0 1" << endl;
tr1(0);
cout << "1" << endl;
return;
}
rep(i,2,n+1){
rep(j,0,200) ans[i][j]=ans[i-1][j];
int temp=ans[i][0];
repDown(j,198,0){
ans[i][j+1]=ans[i][j];
}
ans[i][0]=0;
rep(j,0,200) ans[i][j]+=ans[i-2][j];
}
int first=-1;
repDown(i,199,0) if(ans[n][i]%2){
first=i;
break;
}
tr1(first);
rep(i,0,first+1) cout << (ans[n][i]%2) << " ";
cout << endl;
repDown(i,199,0) if(ans[n-1][i]%2){
first=i;
break;
}
tr1(first);
rep(i,0,first+1) cout << (ans[n-1][i]%2) << " ";
}
int main(){
clock_t clk;
clk = clock();
srand (time(NULL));
int t=1;
// cin >> t;
while(t--){
solve();
}
clk = clock() - clk;
cerr << fixed << setprecision(6) << "Time: " << ((double)clk)/CLOCKS_PER_SEC << "\n";
return 0;
}
|
b0c052be3519850f0c71929b39d0b17967cae940
|
436cb8b9299c84c04b67ea7d5a14f90cbfce8d5f
|
/AnnService/inc/Core/Common/cuda/TailNeighbors.hxx
|
b5b14f30c4e581ed624dc862fc9f0135d5fb51ea
|
[
"MIT"
] |
permissive
|
microsoft/SPTAG
|
43288e49b598734d4dd06f86a2edbc32bacf5806
|
176e7cd12597f860665d169b29e123f65d651670
|
refs/heads/main
| 2023-08-31T13:21:36.685559
| 2023-08-28T03:26:44
| 2023-08-28T03:26:44
| 148,464,499
| 4,804
| 611
|
MIT
| 2023-09-10T08:28:53
| 2018-09-12T10:42:51
|
C++
|
UTF-8
|
C++
| false
| false
| 55,799
|
hxx
|
TailNeighbors.hxx
|
#ifndef _SPTAG_COMMON_CUDA_TAILNEIGHBORS_H
#define _SPTAG_COMMON_CUDA_TAILNEIGHBORS_H
#include "Distance.hxx"
#include "KNN.hxx"
#include <cub/cub.cuh>
#include <chrono>
#include<thrust/execution_policy.h>
#include<thrust/sort.h>
//#include <parallel/algorithm>
using namespace SPTAG;
using namespace std;
// Structure used to re-order queries to improve thread divergence and access locality
class QueryGroup {
public:
int* sizes;
int* offsets;
int* query_ids;
// Expects mem to already be allocated with N + 2*num_groups integers
__device__ void init_mem(size_t N, int num_groups, int* mem) {
sizes = mem;
offsets = &mem[num_groups];
query_ids = &mem[2*num_groups];
}
};
/***********************************************************************************
* Kernel to update the RNG list for each tail vector in the batch. Assumes TPT
* is already created and populated based on the head vectors.
***********************************************************************************/
template<typename T, typename SUMTYPE, int Dim>
__device__ void findTailNeighbors(PointSet<T>* headPS, PointSet<T>* tailPS, TPtree* tptree, int KVAL, DistPair<SUMTYPE>* results, int metric, size_t numTails, int numHeads, QueryGroup* groups, DistPair<SUMTYPE>* threadList, SUMTYPE(*dist_comp)(T*,T*)) {
T query[Dim];
SUMTYPE max_dist = INFTY<SUMTYPE>();
DistPair<SUMTYPE> temp;
int read_id, write_id;
for(int i=0; i<KVAL; i++) {
threadList[i].dist = INFTY<SUMTYPE>();
threadList[i].idx = -1;
}
DistPair<SUMTYPE> target;
DistPair<SUMTYPE> candidate;
int leafId;
bool good;
T* candidate_vec;
// If the queries were re-ordered, use the QueryGroup object to determine order to perform queries
// NOTE: Greatly improves locality and thread divergence
#if REORDER
size_t tailId;
for(size_t orderIdx = blockIdx.x*blockDim.x + threadIdx.x; orderIdx < numTails; orderIdx += gridDim.x*blockDim.x) {
tailId = groups->query_ids[orderIdx];
for(int i=0; i<Dim; ++i) {
query[i] = tailPS->getVec(tailId)[i];
}
leafId = searchForLeaf<T>(tptree, query);
#else
for(size_t tailId = blockIdx.x*blockDim.x + threadIdx.x; tailId < numTails; tailId += gridDim.x*blockDim.x) {
query = tailPS->getVec(tailId, true);
leafId = searchForLeaf<T>(tptree, query);
#endif
size_t leaf_offset = tptree->leafs[leafId].offset;
// Load results from previous iterations into shared memory heap
for(int j=0; j<KVAL; j++) {
threadList[j] = results[(tailId*KVAL)+j];
}
max_dist = threadList[KVAL-1].dist;
for(size_t j=0; j<tptree->leafs[leafId].size; ++j) {
good = true;
candidate.idx = tptree->leaf_points[leaf_offset+j];
candidate_vec = headPS->getVec(candidate.idx);
candidate.dist = dist_comp(query, candidate_vec);
if(max_dist >= candidate.dist && candidate.idx != tailId) { // If it is a candidate to be added to neighbor list
for(read_id=0; candidate.dist > threadList[read_id].dist && good; read_id++) {
if(violatesRNG<T, SUMTYPE>(candidate_vec, headPS->getVec(threadList[read_id].idx), candidate.dist, dist_comp)) {
good = false;
}
}
if(candidate.idx == threadList[read_id].idx) // Ignore duplicates
good = false;
if(good) { // candidate should be in RNG list
target = threadList[read_id];
threadList[read_id] = candidate;
read_id++;
for(write_id = read_id; read_id < KVAL && threadList[read_id].idx != -1; read_id++) {
if(!violatesRNG<T, SUMTYPE>(candidate_vec, headPS->getVec(threadList[read_id].idx), candidate.dist, dist_comp)) {
if(read_id == write_id) {
temp = threadList[read_id];
threadList[write_id] = target;
target = temp;
}
else {
threadList[write_id] = target;
target = threadList[read_id];
}
write_id++;
}
}
if(write_id < KVAL) {
threadList[write_id] = target;
write_id++;
}
for(int k=write_id; k<KVAL && threadList[k].idx != -1; k++) {
threadList[k].dist = INFTY<SUMTYPE>();
threadList[k].idx = -1;
}
max_dist = threadList[KVAL-1].dist;
}
}
}
for(int j=0; j<KVAL; j++) {
results[(size_t)(tailId*KVAL)+j] = threadList[j];
}
}
}
/***********************************************************************************
* Kernel to update the RNG list for each tail vector in the batch. Assumes TPT
* is already created and populated based on the head vectors.
* *** Uses Quantizer ***
***********************************************************************************/
template<int Dim>
__device__ void findTailNeighbors_PQ(PointSet<uint8_t>* headPS, PointSet<uint8_t>* tailPS, TPtree* tptree, int KVAL, DistPair<float>* results, size_t numTails, int numHeads, QueryGroup* groups, DistPair<float>* threadList, GPU_Quantizer* quantizer) {
uint8_t query[Dim];
float max_dist = INFTY<float>();
DistPair<float> temp;
int read_id, write_id;
for(int i=0; i<KVAL; i++) {
threadList[i].dist = INFTY<float>();
threadList[i].idx = -1;
}
DistPair<float> target;
DistPair<float> candidate;
int leafId;
bool good;
uint8_t* candidate_vec;
// If the queries were re-ordered, use the QueryGroup object to determine order to perform queries
// NOTE: Greatly improves locality and thread divergence
#if REORDER
size_t tailId;
for(size_t orderIdx = blockIdx.x*blockDim.x + threadIdx.x; orderIdx < numTails; orderIdx += gridDim.x*blockDim.x) {
tailId = groups->query_ids[orderIdx];
for(int i=0; i<Dim; ++i) {
query[i] = tailPS->getVec(tailId)[i];
}
leafId = searchForLeaf<uint8_t>(tptree, query);
#else
for(size_t tailId = blockIdx.x*blockDim.x + threadIdx.x; tailId < numTails; tailId += gridDim.x*blockDim.x) {
query = tailPS->getVec(tailId, true);
leafId = searchForLeaf<uint8_t>(tptree, query);
#endif
size_t leaf_offset = tptree->leafs[leafId].offset;
// Load results from previous iterations into shared memory heap
for(int j=0; j<KVAL; j++) {
threadList[j] = results[(tailId*KVAL)+j];
}
max_dist = threadList[KVAL-1].dist;
for(size_t j=0; j<tptree->leafs[leafId].size; ++j) {
good = true;
candidate.idx = tptree->leaf_points[leaf_offset+j];
candidate_vec = headPS->getVec(candidate.idx);
candidate.dist = quantizer->dist(query, candidate_vec);
if(candidate.dist < max_dist && candidate.idx != tailId) { // If it is a candidate to be added to neighbor list
for(read_id=0; candidate.dist > threadList[read_id].dist && good; read_id++) {
if(quantizer->violatesRNG(candidate_vec, headPS->getVec(threadList[read_id].idx), candidate.dist)) {
good = false;
}
}
if(candidate.idx == threadList[read_id].idx) // Ignore duplicates
good = false;
if(good) { // candidate should be in RNG list
target = threadList[read_id];
threadList[read_id] = candidate;
read_id++;
for(write_id = read_id; read_id < KVAL && threadList[read_id].idx != -1; read_id++) {
if(!quantizer->violatesRNG(candidate_vec, headPS->getVec(threadList[read_id].idx), candidate.dist)) {
if(read_id == write_id) {
temp = threadList[read_id];
threadList[write_id] = target;
target = temp;
}
else {
threadList[write_id] = target;
target = threadList[read_id];
}
write_id++;
}
}
if(write_id < KVAL) {
threadList[write_id] = target;
write_id++;
}
for(int k=write_id; k<KVAL && threadList[k].idx != -1; k++) {
threadList[k].dist = INFTY<float>();
threadList[k].idx = -1;
}
max_dist = threadList[KVAL-1].dist;
}
}
}
for(int j=0; j<KVAL; j++) {
results[(size_t)(tailId*KVAL)+j] = threadList[j];
}
}
}
__global__ void debug_warm_up_gpu() {
unsigned int tid = blockIdx.x * blockDim.x + threadIdx.x;
float ia, ib;
ia = ib = 0.0f;
ib += ia + tid;
}
// Search each query into the TPTree to get the number of queries for each leaf node. This just generates a histogram
// for each leaf node so that we can compute offsets
template<typename T, typename SUMTYPE>
__global__ void compute_group_sizes(QueryGroup* groups, TPtree* tptree, PointSet<T>* queries, int N, int num_groups, int* queryMem, int dim) {
groups->init_mem(N, num_groups, queryMem);
extern __shared__ char sharememory[];
T* query = (&((T*)sharememory)[threadIdx.x*dim]);
// T query[MAX_DIM];
int leafId;
for(int qidx = blockDim.x*blockIdx.x + threadIdx.x; qidx < N; qidx += blockDim.x*gridDim.x) {
for(int j=0; j<queries->dim;++j) {
query[j] = queries->getVec(qidx)[j];
}
leafId = searchForLeaf<T>(tptree, query);
atomicAdd(&(groups->sizes[leafId]), 1);
}
}
// Given the offsets and sizes of queries assigned to each leaf node, writes the list of queries assigned
// to each leaf. The list of query_ids can then be used during neighborhood search to improve locality
template<typename T, typename SUMTYPE>
__global__ void assign_queries_to_group(QueryGroup* groups, TPtree* tptree, PointSet<T>* queries, int N, int num_groups, int dim) {
extern __shared__ char sharememory[];
T* query = (&((T*)sharememory)[threadIdx.x*dim]);
int leafId;
int idx_in_leaf;
for(int qidx = blockDim.x*blockIdx.x + threadIdx.x; qidx < N; qidx += blockDim.x*gridDim.x) {
for(int j=0; j<queries->dim;++j) {
query[j] = queries->getVec(qidx)[j];
}
leafId = searchForLeaf<T>(tptree, query);
idx_in_leaf = atomicAdd(&(groups->sizes[leafId]), 1);
groups->query_ids[groups->offsets[leafId]+idx_in_leaf] = qidx;
}
}
// Gets the list of queries that are to be searched into each leaf. The QueryGroup structure uses the memory
// provided with queryMem, which is required to be allocated with size N + 2*num_groups.
template<typename T, typename SUMTYPE>
__host__ void get_query_groups(QueryGroup* groups, TPtree* tptree, PointSet<T>* queries, int N, int num_groups, int* queryMem, int NUM_BLOCKS, int NUM_THREADS, int dim) {
CUDA_CHECK(cudaMemset(queryMem, 0, (N+2*num_groups)*sizeof(int)));
compute_group_sizes<T,SUMTYPE><<<NUM_BLOCKS,NUM_THREADS, dim*NUM_THREADS*sizeof(T)>>>(groups, tptree, queries, N, num_groups, queryMem, dim);
CUDA_CHECK(cudaDeviceSynchronize());
// Compute offsets based on sizes
int* h_sizes = new int[num_groups];
CUDA_CHECK(cudaMemcpy(h_sizes, queryMem, num_groups*sizeof(int), cudaMemcpyDeviceToHost));
int* h_offsets = new int[num_groups];
h_offsets[0]=0;
for(int i=1; i<num_groups; ++i) h_offsets[i] = h_offsets[i-1] + h_sizes[i-1];
CUDA_CHECK(cudaMemcpy(&queryMem[num_groups], h_offsets, num_groups*sizeof(int), cudaMemcpyHostToDevice));
// Reset group sizes to use while assigning queires
CUDA_CHECK(cudaMemset(queryMem, 0, num_groups*sizeof(int)));
assign_queries_to_group<T,SUMTYPE><<<NUM_BLOCKS,NUM_THREADS, dim*NUM_THREADS*sizeof(T)>>>(groups, tptree, queries, N, num_groups, dim);
CUDA_CHECK(cudaDeviceSynchronize());
delete[] h_sizes;
delete[] h_offsets;
}
#define RUN_TAIL_KERNEL(size) \
if(dim <= size) { \
SUMTYPE (*dist_comp)(T*,T*); \
dist_comp = &dist<T,SUMTYPE,size,metric>; \
findTailNeighbors<T,SUMTYPE,size>(headPS, tailPS, tptree, \
KVAL, results, metric, curr_batch_size, \
numHeads, groups, threadList, dist_comp); \
return; \
}
#define RUN_TAIL_KERNEL_PQ(size) \
if(dim <= size) { \
findTailNeighbors_PQ<size>(headPS, tailPS, tptree, \
KVAL, results, curr_batch_size, \
numHeads, groups, threadList, quantizer);\
return; \
}
#define MAX_SHAPE 384
template<typename T, typename SUMTYPE, int metric>
__global__ void findTailNeighbors_selector(PointSet<T>* headPS, PointSet<T>* tailPS, TPtree* tptree, int KVAL, DistPair<SUMTYPE>* results, size_t curr_batch_size, size_t numHeads, QueryGroup* groups, int dim) {
extern __shared__ char sharememory[];
DistPair<SUMTYPE>* threadList = (&((DistPair<SUMTYPE>*)sharememory)[KVAL*threadIdx.x]);
RUN_TAIL_KERNEL(64)
RUN_TAIL_KERNEL(100)
RUN_TAIL_KERNEL(MAX_SHAPE)
}
#define MAX_PQ_SHAPE 100
__global__ void findTailNeighbors_PQ_selector(PointSet<uint8_t>* headPS, PointSet<uint8_t>* tailPS, TPtree* tptree, int KVAL, DistPair<float>* results, size_t curr_batch_size, size_t numHeads, QueryGroup* groups, int dim, GPU_Quantizer* quantizer) {
extern __shared__ char sharememory[];
DistPair<float>* threadList = (&((DistPair<float>*)sharememory)[KVAL*threadIdx.x]);
RUN_TAIL_KERNEL_PQ(50);
RUN_TAIL_KERNEL_PQ(MAX_PQ_SHAPE);
}
#define COPY_BUFF_SIZE 100000
template<typename T>
void extractAndCopyHeadRaw_multi(T* dataBuffer, SPTAG::VectorIndex* headIndex, T** d_headRaw, size_t headRows, int dim, int NUM_GPUS) {
T* vecPtr;
size_t copy_size = COPY_BUFF_SIZE;
for(size_t i=0; i<headRows; i+=COPY_BUFF_SIZE) {
if(headRows-i < COPY_BUFF_SIZE) copy_size = headRows-i;
for(int j=0; j<copy_size; ++j) {
vecPtr = (T*)headIndex->GetSample(i+j);
for(int k=0; k<dim; ++k) {
dataBuffer[j*dim+k] = vecPtr[k];
}
}
for(int gpuNum=0; gpuNum < NUM_GPUS; ++gpuNum) {
CUDA_CHECK(cudaSetDevice(gpuNum));
CUDA_CHECK(cudaMemcpy((d_headRaw[gpuNum])+(i*dim), dataBuffer, copy_size*dim*sizeof(T), cudaMemcpyHostToDevice));
}
}
}
/***************
// TODO - Possible issue with ID of vectors in batch not having the offset!
***************/
template<typename T>
void extractAndCopyTailRaw_multi(T* dataBuffer, T* vectors, T** d_tailRaw, size_t tailRows, int dim, int NUM_GPUS) {
T* vecPtr;
size_t copy_size = COPY_BUFF_SIZE;
size_t total_size=0;
for(size_t i=0; i<tailRows; i+=COPY_BUFF_SIZE) {
if(tailRows-i < COPY_BUFF_SIZE) copy_size = tailRows-i;
vecPtr = &vectors[i*dim];
for(int j=0; j<copy_size; ++j) {
for(int k=0; k<dim; ++k) {
dataBuffer[j*dim+k] = vecPtr[j*dim+k];
}
}
// memcpy(dataBuffer, &vectors[i*dim], copy_size*dim);
for(int gpuNum=0; gpuNum < NUM_GPUS; ++gpuNum) {
CUDA_CHECK(cudaSetDevice(gpuNum));
CUDA_CHECK(cudaMemcpy((d_tailRaw[gpuNum])+(i*dim), dataBuffer, copy_size*dim*sizeof(T), cudaMemcpyHostToDevice));
}
}
}
template<typename T, typename SUMTYPE>
void getTailNeighborsTPT(T* vectors, SPTAG::SizeType N, SPTAG::VectorIndex* headIndex, std::unordered_set<int>& headVectorIDS, int dim, int RNG_SIZE, int numThreads, int NUM_TREES, int LEAF_SIZE, int metric, int NUM_GPUS, Edge* selections) {
auto premem_t = std::chrono::high_resolution_clock::now();
int numDevicesOnHost;
CUDA_CHECK(cudaGetDeviceCount(&numDevicesOnHost));
if(numDevicesOnHost < NUM_GPUS) {
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Error, "NumGPUs parameter %d, but only %d devices available on system. Exiting.\n", NUM_GPUS, numDevicesOnHost);
exit(1);
}
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Info, "Building SSD index with %d GPUs...\n", NUM_GPUS);
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "Total of %d GPU devices on system, using %d of them.\n", numDevicesOnHost, NUM_GPUS);
/***** General variables *****/
bool use_q = (headIndex->m_pQuantizer != NULL); // Using quantization?
int resultErr;
size_t headRows;
headRows = headIndex->GetNumSamples();
int TPTlevels = (int)std::log2(headRows/LEAF_SIZE);
const int NUM_THREADS = 32;
int NUM_BLOCKS;
/***** Host variables *****/
// RawDataBuffer to shuttle raw data to GPU
T* dataBuffer = new T[COPY_BUFF_SIZE*dim];
PointSet<T> temp_ps; // Host structure to set before copying to GPU
// Buffer to shuttle results back to CPU and save to selections structure
DistPair<SUMTYPE>* results = new DistPair<SUMTYPE>[((size_t)COPY_BUFF_SIZE*RNG_SIZE)];
std::vector<size_t> pointsPerGPU(NUM_GPUS);
std::vector<size_t> GPUPointOffset(NUM_GPUS);
for(int gpuNum=0; gpuNum < NUM_GPUS; ++gpuNum) {
pointsPerGPU[gpuNum] = N / NUM_GPUS;
if(N % NUM_GPUS > gpuNum) pointsPerGPU[gpuNum]++;
}
GPUPointOffset[0] = 0;
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "GPU 0: points:%lu, offset:%lu\n", pointsPerGPU[0], GPUPointOffset[0]);
for(int gpuNum=1; gpuNum < NUM_GPUS; ++gpuNum) {
GPUPointOffset[gpuNum] = GPUPointOffset[gpuNum-1] + pointsPerGPU[gpuNum-1];
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "GPU %d: points:%lu, offset:%lu\n", gpuNum, pointsPerGPU[gpuNum], GPUPointOffset[gpuNum]);
}
// Streams and memory pointers for each GPU
std::vector<cudaStream_t> streams(NUM_GPUS);
std::vector<size_t> BATCH_SIZE(NUM_GPUS);
/***** Device variables *****/
T** d_headRaw = new T*[NUM_GPUS];
PointSet<T>** d_headPS = new PointSet<T>*[NUM_GPUS];
T** d_tailRaw = new T*[NUM_GPUS];
PointSet<T>** d_tailPS = new PointSet<T>*[NUM_GPUS];
DistPair<SUMTYPE>** d_results = new DistPair<SUMTYPE>*[NUM_GPUS];
TPtree** tptree = new TPtree*[NUM_GPUS];
TPtree** d_tptree = new TPtree*[NUM_GPUS];
// memory on each GPU for QuerySet reordering structures
std::vector<int*> d_queryMem(NUM_GPUS);
std::vector<QueryGroup*> d_queryGroups(NUM_GPUS);
// Quantizer structures only used if quantization is enabled
GPU_Quantizer* d_quantizer = NULL;
GPU_Quantizer* h_quantizer = NULL;
if(use_q) {
h_quantizer = new GPU_Quantizer(headIndex->m_pQuantizer, (DistMetric)metric);
CUDA_CHECK(cudaMalloc(&d_quantizer, sizeof(GPU_Quantizer)));
CUDA_CHECK(cudaMemcpy(d_quantizer, h_quantizer, sizeof(GPU_Quantizer), cudaMemcpyHostToDevice));
}
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Info, "Setting up each of the %d GPUs...\n", NUM_GPUS);
/*** Compute batch sizes and allocate all data on GPU ***/
for(int gpuNum=0; gpuNum < NUM_GPUS; gpuNum++) {
CUDA_CHECK(cudaSetDevice(gpuNum)); // Set current working GPU
CUDA_CHECK(cudaStreamCreate(&streams[gpuNum])); // Create CDUA stream for each GPU
debug_warm_up_gpu<<<1,32,0,streams[gpuNum]>>>();
resultErr = cudaStreamSynchronize(streams[gpuNum]);
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "GPU test/warmup complete - kernel status:%d\n", resultErr);
// Get GPU info to compute batch sizes
cudaDeviceProp prop;
CUDA_CHECK(cudaGetDeviceProperties(&prop, gpuNum));
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Info, "GPU %d - %s\n", gpuNum, prop.name);
size_t freeMem, totalMem;
CUDA_CHECK(cudaMemGetInfo(&freeMem, &totalMem));
// Auto-compute batch size based on available memory on the GPU
size_t headVecSize = headRows*dim*sizeof(T) + sizeof(PointSet<T>);
size_t randSize = (size_t)(min((int)headRows, (int)1024))*48; // Memory used for GPU random number generator
size_t treeSize = 20*headRows + randSize;
size_t tailMemAvail = (freeMem*0.9) - (headVecSize+treeSize); // Only use 90% of total memory to be safe
// memory needed for raw data, pointset, results, and query reorder mem
int maxEltsPerBatch = tailMemAvail / (dim*sizeof(T)+sizeof(PointSet<T>) + RNG_SIZE*sizeof(DistPair<SUMTYPE>) + 2*sizeof(int));
BATCH_SIZE[gpuNum] = min(maxEltsPerBatch, (int)(pointsPerGPU[gpuNum]));
/*****************************************************
* Batch size check and Debug information printing
*****************************************************/
if(BATCH_SIZE[gpuNum] == 0 || ((int)pointsPerGPU[gpuNum]) / BATCH_SIZE[gpuNum] > 10000) {
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Error, "Insufficient GPU memory to build SSD index on GPU %d. Available GPU memory:%lu MB, Head index requires:%lu MB, leaving a maximum batch size of %d elements, which is too small to run efficiently.\n", gpuNum, (freeMem)/1000000, (headVecSize+treeSize)/1000000, maxEltsPerBatch);
exit(1);
}
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Info, "Memory for head vectors:%lu MiB, Memory for TP trees:%lu MiB, Memory left for tail vectors:%lu MiB, total tail vectors:%lu, batch size:%d, total batches:%d\n", headVecSize/1000000, treeSize/1000000, tailMemAvail/1000000, pointsPerGPU[gpuNum], BATCH_SIZE[gpuNum], (((BATCH_SIZE[gpuNum]-1)+pointsPerGPU[gpuNum]) / BATCH_SIZE[gpuNum]));
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "Allocating GPU memory: tail points:%lu MiB, head points:%lu MiB, results:%lu MiB, TPT:%lu MiB, Total:%lu MiB\n", (BATCH_SIZE[gpuNum]*sizeof(T))/1000000, (headRows*sizeof(T))/1000000, (BATCH_SIZE[gpuNum]*RNG_SIZE*sizeof(DistPair<SUMTYPE>))/1000000, (sizeof(TPtree))/1000000, ((BATCH_SIZE[gpuNum]+headRows)*sizeof(T) + (BATCH_SIZE[gpuNum]*RNG_SIZE*sizeof(DistPair<SUMTYPE>)) + (sizeof(TPtree)))/1000000);
// Allocate needed memory on the GPU
CUDA_CHECK(cudaMalloc(&d_headRaw[gpuNum], headRows*dim*sizeof(T)));
CUDA_CHECK(cudaMalloc(&d_headPS[gpuNum], sizeof(PointSet<T>)));
CUDA_CHECK(cudaMalloc(&d_tailRaw[gpuNum], BATCH_SIZE[gpuNum]*dim*sizeof(T)));
CUDA_CHECK(cudaMalloc(&d_tailPS[gpuNum], sizeof(PointSet<T>)));
CUDA_CHECK(cudaMalloc(&d_results[gpuNum], BATCH_SIZE[gpuNum]*RNG_SIZE*sizeof(DistPair<SUMTYPE>)));
// Prepare memory for TPTs
CUDA_CHECK(cudaMalloc(&d_tptree[gpuNum], sizeof(TPtree)));
tptree[gpuNum] = new TPtree;
tptree[gpuNum]->initialize(headRows, TPTlevels, dim);
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "tpt structure initialized for %lu head vectors, %d levels, leaf size:%d\n", headRows, TPTlevels, LEAF_SIZE);
// Alloc memory for QuerySet structure
CUDA_CHECK(cudaMalloc(&d_queryMem[gpuNum], BATCH_SIZE[gpuNum]*sizeof(int) + 2*tptree[gpuNum]->num_leaves*sizeof(int)));
CUDA_CHECK(cudaMalloc(&d_queryGroups[gpuNum], sizeof(QueryGroup)));
// Copy head points to GPU
} // End loop to set up memory on each GPU
// Copy raw head vector data to each GPU
extractAndCopyHeadRaw_multi<T>(dataBuffer, headIndex, d_headRaw, headRows, dim, NUM_GPUS);
// Set and copy PointSet structure to each GPU
temp_ps.dim = dim;
for(int gpuNum=0; gpuNum < NUM_GPUS; ++gpuNum) {
temp_ps.data = d_headRaw[gpuNum];
CUDA_CHECK(cudaMemcpy(d_headPS[gpuNum], &temp_ps, sizeof(PointSet<T>), cudaMemcpyHostToDevice));
}
NUM_BLOCKS = min((int)(BATCH_SIZE[0]/NUM_THREADS), 10240);
std::vector<size_t> curr_batch_size(NUM_GPUS);
std::vector<size_t> offset(NUM_GPUS);
for(int gpuNum=0; gpuNum<NUM_GPUS; ++gpuNum) {
offset[gpuNum] = 0;
}
auto ssd_t1 = std::chrono::high_resolution_clock::now();
bool done = false;
while(!done) { // Continue until all GPUs have completed all of their batches
// Prep next batch for each GPU
for(int gpuNum=0; gpuNum<NUM_GPUS; ++gpuNum) {
curr_batch_size[gpuNum] = BATCH_SIZE[gpuNum];
// Check if final batch is smaller than previous
if(offset[gpuNum]+BATCH_SIZE[gpuNum] > pointsPerGPU[gpuNum]) {
curr_batch_size[gpuNum] = pointsPerGPU[gpuNum]-offset[gpuNum];
}
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Info, "GPU %d - starting batch with GPUOffset:%lu, offset:%lu, total offset:%lu, size:%lu, TailRows:%lld\n", gpuNum, GPUPointOffset[gpuNum], offset[gpuNum], GPUPointOffset[gpuNum]+offset[gpuNum], curr_batch_size[gpuNum], pointsPerGPU[gpuNum]);
cudaSetDevice(gpuNum);
// Copy next batch of tail vectors to corresponding GPU using many small copies to save memory
extractAndCopyTailRaw_multi<T>(dataBuffer, &vectors[(GPUPointOffset[gpuNum]+offset[gpuNum])*dim], d_tailRaw, curr_batch_size[gpuNum], dim, NUM_GPUS);
// Set tail pointset and copy to GPU
temp_ps.data = d_tailRaw[gpuNum];
CUDA_CHECK(cudaMemcpy(d_tailPS[gpuNum], &temp_ps, sizeof(PointSet<T>), cudaMemcpyHostToDevice));
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "Copied %lu tail points to GPU - kernel status:%d\n", curr_batch_size[gpuNum], resultErr);
int copy_size = COPY_BUFF_SIZE*RNG_SIZE;
for(int i=0; i<curr_batch_size[gpuNum]*RNG_SIZE; i+=COPY_BUFF_SIZE*RNG_SIZE) {
if(curr_batch_size[gpuNum]*RNG_SIZE - i < copy_size) copy_size = curr_batch_size[gpuNum]*RNG_SIZE - i;
for(int j=0; j<copy_size; j++) {
results[j].idx=-1;
results[j].dist=INFTY<SUMTYPE>();
}
resultErr = cudaMemcpyAsync(d_results[gpuNum]+i, results, copy_size*sizeof(DistPair<SUMTYPE>), cudaMemcpyHostToDevice, streams[gpuNum]);
}
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "Copying initialized result list to GPU - batch size:%lu - replica count:%d, copy bytes:%lu, GPU offset:%lu, total result offset:%lu, - kernel status:%d\n", curr_batch_size[gpuNum], RNG_SIZE, curr_batch_size[gpuNum]*RNG_SIZE*sizeof(DistPair<SUMTYPE>), GPUPointOffset[gpuNum], (GPUPointOffset[gpuNum]+offset[gpuNum])*RNG_SIZE, resultErr);
}
// OFFSET for batch of vector IDS: GPUPointOffset[gpuNum]+offset[gpuNum];
// For each tree, create a new TPT and use it to refine tail neighbor list of batch
for(int tree_id=0; tree_id < NUM_TREES; ++tree_id) {
NUM_BLOCKS = min((int)(BATCH_SIZE[0]/NUM_THREADS), 10240);
auto t1 = std::chrono::high_resolution_clock::now();
// Create TPT on each GPU
create_tptree_multigpu<T>(tptree, d_headPS, headRows, TPTlevels, NUM_GPUS, streams.data(), 2, headIndex);
CUDA_CHECK(cudaDeviceSynchronize());
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "TPT %d created on all GPUs\n", tree_id);
// Copy TPTs to each GPU
for(int gpuNum=0; gpuNum < NUM_GPUS; ++gpuNum) {
CUDA_CHECK(cudaSetDevice(gpuNum));
CUDA_CHECK(cudaMemcpy(d_tptree[gpuNum], tptree[gpuNum], sizeof(TPtree), cudaMemcpyHostToDevice));
}
auto t2 = std::chrono::high_resolution_clock::now();
#if REORDER
// Compute QuerySet lists based on TPT, which can then be used to improve locality/divergence during RNG search
for(int gpuNum=0; gpuNum < NUM_GPUS; ++gpuNum) {
CUDA_CHECK(cudaSetDevice(gpuNum));
get_query_groups<T,SUMTYPE>(d_queryGroups[gpuNum], d_tptree[gpuNum], d_tailPS[gpuNum], (int)(curr_batch_size[gpuNum]), (int)tptree[gpuNum]->num_leaves, d_queryMem[gpuNum], NUM_BLOCKS, NUM_THREADS, dim);
}
#endif
for(int gpuNum=0; gpuNum < NUM_GPUS; ++gpuNum) {
CUDA_CHECK(cudaSetDevice(gpuNum));
if(!use_q) {
if(dim > MAX_SHAPE) {
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Error, "Input vector dimension is %d, GPU index build of vector dimensions larger than %d not supported.\n", dim, MAX_SHAPE);
}
if(metric == (int)DistMetric::Cosine) {
findTailNeighbors_selector<T,SUMTYPE,(int)DistMetric::Cosine><<<NUM_BLOCKS, NUM_THREADS, sizeof(DistPair<SUMTYPE>)*RNG_SIZE*NUM_THREADS, streams[gpuNum]>>>(d_headPS[gpuNum], d_tailPS[gpuNum], d_tptree[gpuNum], RNG_SIZE, d_results[gpuNum], curr_batch_size[gpuNum], headRows, d_queryGroups[gpuNum], dim);
}
else {
findTailNeighbors_selector<T,SUMTYPE,(int)DistMetric::L2><<<NUM_BLOCKS, NUM_THREADS, sizeof(DistPair<SUMTYPE>)*RNG_SIZE*NUM_THREADS, streams[gpuNum]>>>(d_headPS[gpuNum], d_tailPS[gpuNum], d_tptree[gpuNum], RNG_SIZE, d_results[gpuNum], curr_batch_size[gpuNum], headRows, d_queryGroups[gpuNum], dim);
}
}
else {
if(dim > MAX_PQ_SHAPE) {
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Error, "Input PQ dimension is %d, GPU index build with PQ dimension larger than %d not supported.\n", dim, MAX_SHAPE);
}
findTailNeighbors_PQ_selector<<<NUM_BLOCKS, NUM_THREADS, sizeof(DistPair<float>)*RNG_SIZE*NUM_THREADS, streams[gpuNum]>>>((PointSet<uint8_t>*)d_headPS[gpuNum], (PointSet<uint8_t>*)d_tailPS[gpuNum], d_tptree[gpuNum], RNG_SIZE, (DistPair<float>*)d_results[gpuNum], curr_batch_size[gpuNum], headRows, d_queryGroups[gpuNum], dim, d_quantizer);
}
}
CUDA_CHECK(cudaDeviceSynchronize());
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "All GPUs finished finding neighbors of tails using TPT %d\n", tree_id);
auto t3 = std::chrono::high_resolution_clock::now();
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "Tree %d complete, time to build tree:%.2lf, time to compute tail neighbors:%.2lf\n", tree_id, GET_CHRONO_TIME(t1, t2), GET_CHRONO_TIME(t2, t3));
} // TPT loop
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "Batch complete on all GPUs, copying results back to CPU...\n");
// Copy results of batch from each GPU to CPU result set
for(int gpuNum=0; gpuNum < NUM_GPUS; ++gpuNum) {
CUDA_CHECK(cudaSetDevice(gpuNum));
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "gpu:%d, copying results size %lu to results offset:%d*%d=%d\n", gpuNum, curr_batch_size[gpuNum], GPUPointOffset[gpuNum]+offset[gpuNum],RNG_SIZE, (GPUPointOffset[gpuNum]+offset[gpuNum])*RNG_SIZE);
size_t copy_size=COPY_BUFF_SIZE;
for(int i=0; i<curr_batch_size[gpuNum]; i+=COPY_BUFF_SIZE) {
if(curr_batch_size[gpuNum] - i < copy_size) copy_size = curr_batch_size[gpuNum] - i;
CUDA_CHECK(cudaMemcpy(results, d_results[gpuNum]+(i*RNG_SIZE), copy_size*RNG_SIZE*sizeof(DistPair<SUMTYPE>), cudaMemcpyDeviceToHost));
size_t fullIdx = GPUPointOffset[gpuNum]+offset[gpuNum]+i;
//#pragma omp parallel for
for (size_t j = 0; j < copy_size; j++) {
size_t vecIdx = fullIdx+j;
if (headVectorIDS.count(vecIdx) == 0) {
size_t vecOffset = vecIdx * (size_t)RNG_SIZE;
size_t resOffset = j * (size_t)RNG_SIZE;
for (int resNum = 0; resNum < RNG_SIZE && results[resOffset + resNum].idx != -1; resNum++) {
selections[vecOffset + resNum].node = results[resOffset + resNum].idx;
selections[vecOffset + resNum].distance = (float)results[resOffset + resNum].dist;
}
}
}
}
}
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "Finished copying all batch results back to CPU\n");
// Update all offsets and check if done
done=true;
for(int gpuNum=0; gpuNum < NUM_GPUS; ++gpuNum) {
offset[gpuNum] += curr_batch_size[gpuNum];
if(offset[gpuNum] < pointsPerGPU[gpuNum]) {
done=false;
}
}
} // Batches loop (while !done)
auto ssd_t2 = std::chrono::high_resolution_clock::now();
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "GPU SSD build complete. Freeing GPU memory...\n");
for(int gpuNum=0; gpuNum < NUM_GPUS; ++gpuNum) {
CUDA_CHECK(cudaFree(d_headRaw[gpuNum]));
CUDA_CHECK(cudaFree(d_tailRaw[gpuNum]));
CUDA_CHECK(cudaFree(d_results[gpuNum]));
CUDA_CHECK(cudaFree(d_tptree[gpuNum]));
delete tptree[gpuNum];
}
delete dataBuffer;
delete[] d_headRaw;
delete[] d_tailRaw;
delete[] d_results;
delete[] tptree;
delete[] d_tptree;
delete[] results;
auto ssd_t3 = std::chrono::high_resolution_clock::now();
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Info, "Mam alloc time:%0.2lf, GPU time to build index:%.2lf, Memory free time:%.2lf\n", ((double)std::chrono::duration_cast<std::chrono::seconds>(ssd_t1-premem_t).count()) + ((double)std::chrono::duration_cast<std::chrono::milliseconds>(ssd_t1-premem_t).count())/1000, ((double)std::chrono::duration_cast<std::chrono::seconds>(ssd_t2-ssd_t1).count()) + ((double)std::chrono::duration_cast<std::chrono::milliseconds>(ssd_t2-ssd_t1).count())/1000, ((double)std::chrono::duration_cast<std::chrono::seconds>(ssd_t3-ssd_t2).count()) + ((double)std::chrono::duration_cast<std::chrono::milliseconds>(ssd_t3-ssd_t2).count())/1000);
}
__host__ __device__ struct GPUEdge
{
SizeType node;
float distance;
SizeType tonode;
__host__ __device__ GPUEdge() : node(MaxSize), distance(FLT_MAX/10.0), tonode(MaxSize) {}
};
struct GPU_EdgeCompare {
bool operator()(const GPUEdge& a, int b) const
{
return a.node < b;
};
bool operator()(int a, const GPUEdge& b) const
{
return a < b.node;
};
__host__ __device__ bool operator()(const GPUEdge& a, const GPUEdge& b) {
if (a.node == b.node)
{
if (a.distance == b.distance)
{
return a.tonode < b.tonode;
}
return a.distance < b.distance;
}
return a.node < b.node;
}
} gpu_edgeComparer;
void GPU_SortSelections(std::vector<Edge>* selections) {
size_t N = selections->size();
size_t freeMem, totalMem;
CUDA_CHECK(cudaMemGetInfo(&freeMem, &totalMem));
// Maximum number of elements that can be sorted on GPU
size_t sortBatchSize = (size_t)(freeMem*0.9 / sizeof(GPUEdge))/2;
std::vector<GPUEdge>* new_selections = reinterpret_cast<std::vector<GPUEdge>*>(selections);
int num_batches = (N + (sortBatchSize-1)) / sortBatchSize;
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Info, "Sorting final results. Size of result:%ld elements = %0.2lf GB, Available GPU memory:%0.2lf, sorting in %d batches\n", N, ((double)(N*sizeof(GPUEdge))/1000000000.0), ((double)freeMem)/1000000000.0, num_batches);
int batchNum=0;
GPUEdge* merge_mem;
if(num_batches > 1) {
merge_mem = new GPUEdge[N];
}
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "Allocating %ld bytes on GPU for sorting\n", sortBatchSize*sizeof(GPUEdge));
GPUEdge* d_selections;
CUDA_CHECK(cudaMalloc(&d_selections, sortBatchSize*sizeof(GPUEdge)));
for(size_t startIdx = 0; startIdx < N; startIdx += sortBatchSize) {
auto t1 = std::chrono::high_resolution_clock::now();
size_t batchSize = sortBatchSize;
if(startIdx + batchSize > N) {
batchSize = N - startIdx;
}
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "Sorting batch id:%ld, size:%ld\n", startIdx, batchSize);
GPUEdge* batchPtr = &(new_selections->data()[startIdx]);
CUDA_CHECK(cudaMemcpy(d_selections, batchPtr, batchSize*sizeof(GPUEdge), cudaMemcpyHostToDevice));
try {
thrust::sort(thrust::device, d_selections, d_selections+batchSize, gpu_edgeComparer);
}
catch (thrust::system_error &e){
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Info, "Error: %s \n",e.what());
}
CUDA_CHECK(cudaMemcpy(batchPtr, d_selections, batchSize*sizeof(GPUEdge), cudaMemcpyDeviceToHost));
auto t2 = std::chrono::high_resolution_clock::now();
// For all batches after the first, merge into the final output
if(startIdx > 0) {
std::merge(new_selections->data(), batchPtr, batchPtr, &batchPtr[batchSize], merge_mem, gpu_edgeComparer);
// For faster merging on Linux systems, can use below instead of std::merge (above)
// __gnu_parallel::merge(new_selections->data(), batchPtr, batchPtr, &batchPtr[batchSize], merge_mem, gpu_edgeComparer);
memcpy(new_selections->data(), merge_mem, (startIdx+batchSize)*sizeof(GPUEdge));
}
auto t3 = std::chrono::high_resolution_clock::now();
SPTAGLIB_LOG(SPTAG::Helper::LogLevel::LL_Debug, "Sort batch %d - GPU transfer/sort time:%0.2lf, CPU merge time:%.2lf\n", batchNum, ((double)std::chrono::duration_cast<std::chrono::seconds>(t2-t1).count()) + ((double)std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count())/1000, ((double)std::chrono::duration_cast<std::chrono::seconds>(t3-t2).count()) + ((double)std::chrono::duration_cast<std::chrono::milliseconds>(t3-t2).count())/1000);
batchNum++;
}
if(num_batches > 1) {
delete merge_mem;
}
}
/*************************************************************************************************
* Deprecated code from Hybrid CPU/GPU SSD Index builder
*************************************************************************************************/
/*
// Function to extract head vectors from list and copy them to GPU, using only a small CPU buffer.
// This reduces the CPU memory usage needed to convert all vectors into the Point structure used by GPU
template<typename T, typename SUMTYPE, int MAX_DIM>
void extractAndCopyHeadPoints(Point<T,SUMTYPE,MAX_DIM>* headPointBuffer, T* vectors, SPTAG::VectorIndex* headIndex, Point<T,SUMTYPE,MAX_DIM>* d_headPoints, size_t headRows, int dim) {
size_t copy_size = COPY_BUFF_SIZE;
for(size_t i=0; i<headRows; i+=COPY_BUFF_SIZE) {
if(headRows-i < COPY_BUFF_SIZE) copy_size = headRows-i; // Last copy may be smaller
for(int j=0; j<copy_size; j++) {
headPointBuffer[j].loadChunk((T*)headIndex->GetSample(i+j), dim);
headPointBuffer[j].id = i+j;
}
CUDA_CHECK(cudaMemcpy(d_headPoints+i, headPointBuffer, copy_size*sizeof(Point<T,SUMTYPE,MAX_DIM>), cudaMemcpyHostToDevice));
}
}
// Extracts tail vectors from vector list and copy them to GPU, using only a small CPU buffer for conversion.
// Returns number of tail vectors copied to GPU
template<typename T, typename SUMTYPE, int MAX_DIM>
size_t extractAndCopyTailPoints(Point<T,SUMTYPE,MAX_DIM>* pointBuffer, T* vectors, Point<T,SUMTYPE,MAX_DIM>* d_tailPoints, size_t size, std::unordered_set<int>& headVectorIDS, int dim, size_t batch_offset) {
size_t copy_size = COPY_BUFF_SIZE;
size_t write_idx=0;
int tailIdx;
for(size_t i=0; i<size; i+=COPY_BUFF_SIZE) {
if(size-i < COPY_BUFF_SIZE) copy_size = size-i; // Last copy may be smaller
for(size_t j=0; j<copy_size; ++j) {
pointBuffer[j].loadChunk(&vectors[(i+j)*dim], dim);
pointBuffer[j].id = i+j+batch_offset;
}
CUDA_CHECK(cudaMemcpy(d_tailPoints+i, pointBuffer, copy_size*sizeof(Point<T,SUMTYPE,MAX_DIM>), cudaMemcpyHostToDevice));
write_idx+=copy_size;
}
return write_idx;
}
*/
/*
template <typename SUMTYPE>
class CandidateElt {
public:
int id;
bool checked;
__device__ CandidateElt& operator=(const CandidateElt& other) {
id = other.id;
checked = other.checked;
return *this;
}
};
template<typename T, typename SUMTYPE, int MAX_DIM, int NEAR_SIZE, int FAR_SIZE>
__global__ void compressToRNG(Point<T,SUMTYPE,MAX_DIM>* tailPoints, Point<T,SUMTYPE,MAX_DIM>* headPoints, CandidateElt<SUMTYPE>* near, CandidateElt<SUMTYPE>* far, DistPair<SUMTYPE>* results, int resultsPerVector, size_t batch_size, int metric) {
Point<T,SUMTYPE,MAX_DIM> tail;
int resultIdx, candidateIdx;
extern __shared__ DistPair<SUMTYPE> RNGlist[];
DistPair<SUMTYPE>* threadList = &RNGlist[threadIdx.x*resultsPerVector];
bool good;
for(size_t i=blockIdx.x*blockDim.x + threadIdx.x; i<batch_size; i+=gridDim.x*blockDim.x) {
for(int j=0; j<resultsPerVector; j++) {
threadList[j].idx=-1;
threadList[j].dist=INFTY<SUMTYPE>();
}
if(near[NEAR_SIZE*i].id > -1) { // TODO - see if can remove unnecessary checks like this?
tail = tailPoints[i];
threadList[0].idx = near[i*NEAR_SIZE].id;
threadList[0].dist = tail.dist(&headPoints[threadList[0].idx], metric);
resultIdx=1;
candidateIdx=1;
// First go through near list
while(resultIdx < resultsPerVector && candidateIdx < NEAR_SIZE) {
threadList[resultIdx].idx = near[i*NEAR_SIZE + candidateIdx].id;
if(threadList[resultIdx].idx <= -1) {
candidateIdx++;
continue;
}
threadList[resultIdx].dist = tail.dist(&headPoints[threadList[resultIdx].idx], metric);
good=true;
for(int j=0; j<resultIdx; j++) {
if(violatesRNG(headPoints, threadList[resultIdx], threadList[j], metric)) {
good=false;
j=resultIdx;
}
}
if(good) {
resultIdx++;
}
candidateIdx++;
}
candidateIdx=0;
// Then far list if needed
while(resultIdx < resultsPerVector && candidateIdx < FAR_SIZE) {
threadList[resultIdx].idx = far[i*FAR_SIZE + candidateIdx].id;
if(threadList[resultIdx].idx <= -1) {
candidateIdx++;
continue;
}
threadList[resultIdx].dist = tail.dist(&headPoints[threadList[resultIdx].idx], metric);
good=true;
for(int j=0; j<resultIdx; j++) {
if(violatesRNG(headPoints, threadList[resultIdx], threadList[j], metric)) {
good=false;
j=resultIdx;
}
}
if(good) {
resultIdx++;
}
candidateIdx++;
}
}
for(size_t j=0; j<resultsPerVector; j++) {
results[i*resultsPerVector + j] = threadList[j];
}
}
}
template<typename SUMTYPE>
__device__ void markDuplicates(CandidateElt<SUMTYPE>* near, int NEAR_SIZE, CandidateElt<SUMTYPE>* far, int FAR_SIZE) {
for(int i=threadIdx.x+1; i<NEAR_SIZE+FAR_SIZE; i+=blockDim.x) {
if(i<NEAR_SIZE) {
if(near[i].id == near[i-1].id) {
near[i].id=-1;
near[i].checked=true;
}
}
else if(i==NEAR_SIZE) {
if(far[0].id == near[NEAR_SIZE-1].id) {
far[0].id = -1;
}
}
else {
if(far[i].id == far[i-1].id) {
far[i].id=-1;
}
}
}
}
template<typename T, typename SUMTYPE, int MAX_DIM, int NEAR_SIZE, int FAR_SIZE, int SORT_THREADS>
__global__ void sortCandidates(Point<T,SUMTYPE,MAX_DIM>* tailPoints, Point<T,SUMTYPE,MAX_DIM>* headPoints, CandidateElt<SUMTYPE>* near, CandidateElt<SUMTYPE>* far, int* nearest, size_t batch_size, int metric, int depth) {
const int SORT_SIZE = NEAR_SIZE+FAR_SIZE;
SUMTYPE dist[SORT_SIZE/SORT_THREADS];
CandidateElt<SUMTYPE> sortVal[SORT_SIZE/SORT_THREADS];
const int numNearest = FAR_SIZE/32;
__shared__ bool print_debug;
print_debug=false;
typedef cub::BlockRadixSort<SUMTYPE, SORT_SIZE, SORT_SIZE/SORT_THREADS, CandidateElt<SUMTYPE>> BlockRadixSort;
__shared__ typename BlockRadixSort::TempStorage temp_storage;
Point<T,SUMTYPE,MAX_DIM> query;
for(size_t i=blockIdx.x; i<batch_size; i+=gridDim.x) {
query = tailPoints[i];
if(query.id < 0) printf("query id:%d, i:%d\n", query.id, i);
__syncthreads();
for(int j=0; j<SORT_SIZE/SORT_THREADS; j++) {
int readIdx = threadIdx.x + SORT_THREADS*j;
if(readIdx < NEAR_SIZE) { // Fill registers with all values from NEAR and FAR lists
sortVal[j] = near[i*NEAR_SIZE + readIdx];
}
else {
bool dup=false;
for(int k=0; k<NEAR_SIZE; k++) {
if(near[i*NEAR_SIZE+k].id == far[i*FAR_SIZE + (readIdx - NEAR_SIZE)].id) {
sortVal[j].id=-1;
sortVal[j].checked=true;
dup=true;
break;
}
}
if(!dup)
sortVal[j] = far[i*FAR_SIZE + (readIdx - NEAR_SIZE)];
}
}
// Compute distances for all points to sort
for(int j=0; j<SORT_SIZE/SORT_THREADS; j++) {
if(sortVal[j].id <= -1) {
dist[j] = INFTY<SUMTYPE>();
}
else {
dist[j] = query.dist(&headPoints[sortVal[j].id], metric);
}
}
__syncthreads();
BlockRadixSort(temp_storage).Sort(dist, sortVal);
__syncthreads();
// Place sorted values back into near and far lists (closest in near)
for(int j=0; j<SORT_SIZE/SORT_THREADS; j++) {
int readIdx = threadIdx.x + SORT_THREADS*j;
if(readIdx < NEAR_SIZE) { // Fill registers with all values from NEAR and FAR lists
near[i*NEAR_SIZE + readIdx] = sortVal[j];
}
else {
far[i*FAR_SIZE + (readIdx - NEAR_SIZE)] = sortVal[j];
}
}
// __syncthreads();
// markDuplicates<SUMTYPE>(&near[i*NEAR_SIZE], NEAR_SIZE, &far[i*FAR_SIZE], FAR_SIZE);
__syncthreads();
if(threadIdx.x==0) { // Set nearest to the first non-checked element
int nearIdx=0;
for(int j=0; j<numNearest; j++) {
nearest[i*numNearest + j]=-1;
for(; nearIdx<NEAR_SIZE && near[i*NEAR_SIZE + nearIdx].checked; nearIdx++); // Find next non-checked
if(nearIdx < NEAR_SIZE) {
nearest[i*numNearest + j] = near[i*NEAR_SIZE + nearIdx].id;
near[i*NEAR_SIZE + nearIdx].checked=true;
}
}
}
}
}
#define RNG_BLOCKS 4096
#define RNG_THREADS 64
#define NEAR_SIZE 128
#define FAR_SIZE 32
#define SEEDS 128
#define SORT_THREADS 160
template<typename T, typename SUMTYPE, int MAX_DIM>
void getTailNeighborsGPU(T* vectors, SPTAG::SizeType N, std::shared_ptr<SPTAG::VectorIndex>& headIndex, std::unordered_set<int> headVectorIDS, int dim, DistPair<SUMTYPE>* results, int resultsPerVector, int BATCH_SIZE, int searchDepth, int numThreads, int metric) {
auto t1 = std::chrono::high_resolution_clock::now();
int NUM_THREADS = 32;
int NUM_BLOCKS = min(BATCH_SIZE/NUM_THREADS, 128);
Point<T,SUMTYPE,MAX_DIM>* headPoints = extractHeadPoints<T,SUMTYPE,MAX_DIM>(vectors, N, headVectorIDS, dim);
Point<T,SUMTYPE,MAX_DIM>* tailPoints = extractTailPoints<T,SUMTYPE,MAX_DIM>(vectors, N, headVectorIDS, dim);
Point<T,SUMTYPE,MAX_DIM>* d_tailPoints;
cudaMalloc(&d_tailPoints, BATCH_SIZE*sizeof(Point<T,SUMTYPE,MAX_DIM>));
Point<T,SUMTYPE,MAX_DIM>* d_headPoints;
cudaMalloc(&d_headPoints, headVectorIDS.size()*sizeof(Point<T,SUMTYPE,MAX_DIM>));
cudaMemcpy(d_headPoints, headPoints, headVectorIDS.size()*sizeof(Point<T,SUMTYPE,MAX_DIM>), cudaMemcpyHostToDevice);
// Memory to store batch of candidate IDs
std::vector<CandidateElt<SUMTYPE>> candidates_near;
candidates_near.reserve(BATCH_SIZE * NEAR_SIZE);
std::vector<CandidateElt<SUMTYPE>> candidates_far;
candidates_far.reserve(BATCH_SIZE * FAR_SIZE);
const int numNearest = FAR_SIZE/32;
std::vector<int> nearest;
nearest.reserve(BATCH_SIZE*numNearest);
// Allocate temp memory for each batch on the GPU
CandidateElt<SUMTYPE>* d_near;
cudaMallocManaged(&d_near, BATCH_SIZE*NEAR_SIZE*sizeof(CandidateElt<SUMTYPE>));
CandidateElt<SUMTYPE>* d_far;
cudaMalloc(&d_far, BATCH_SIZE*FAR_SIZE*sizeof(CandidateElt<SUMTYPE>));
int* d_nearest;
cudaMallocManaged(&d_nearest, BATCH_SIZE*numNearest*sizeof(int));
DistPair<SUMTYPE>* d_results;
cudaMalloc(&d_results, BATCH_SIZE*resultsPerVector*sizeof(DistPair<SUMTYPE>));
size_t curr_batch_size = BATCH_SIZE;
double sort_time=0;
double copy_search_time=0;
double compress_time=0;
auto t1b = std::chrono::high_resolution_clock::now();
printf("Initialization time:%.2lf\n", ((double)std::chrono::duration_cast<std::chrono::seconds>(t1b-t1).count()) + ((double)std::chrono::duration_cast<std::chrono::milliseconds>(t1b-t1).count())/1000);
// Start of batch computation
for(size_t offset=0; offset<(N-headVectorIDS.size()); offset+=BATCH_SIZE) {
if(offset+BATCH_SIZE > (N-headVectorIDS.size())) {
curr_batch_size = (N-headVectorIDS.size())-offset;
}
printf("batch offset:%d, batch size:%d, total tail size:%d\n", offset, curr_batch_size, N-headVectorIDS.size());
auto t2 = std::chrono::high_resolution_clock::now();
// Copy tail vectors for batch to GPU
cudaMemcpy(d_tailPoints, &tailPoints[offset], curr_batch_size*sizeof(Point<T,SUMTYPE,MAX_DIM>), cudaMemcpyHostToDevice);
// Get candidates from search on CPU
#pragma omp parallel for num_threads(numThreads) schedule(dynamic,10)
for(size_t fullID=0; fullID < curr_batch_size; fullID++) {
SPTAG::COMMON::QueryResultSet<T> query((T*)&tailPoints[offset+fullID].coords[0], SEEDS);
headIndex->SearchTree(query);
// Just use all seeds for initial candidate list
if(NEAR_SIZE < SEEDS) {
for(size_t i=0; i<NEAR_SIZE; i++) {
candidates_near[fullID*NEAR_SIZE+i].id = query.GetResult(i)->VID;
candidates_near[fullID*NEAR_SIZE+i].checked=false;
}
for(size_t i=0; i<(SEEDS-NEAR_SIZE); i++) {
candidates_far[fullID*FAR_SIZE+i].id = query.GetResult(NEAR_SIZE+i)->VID;
candidates_far[fullID*FAR_SIZE+i].checked=false;
}
for(size_t i=(SEEDS-NEAR_SIZE); i<FAR_SIZE; i++) {
candidates_far[fullID*FAR_SIZE+i].id = -1;
candidates_far[fullID*FAR_SIZE+i].checked=true;
}
}
else {
for(size_t i=0; i<SEEDS; i++) {
candidates_near[fullID*NEAR_SIZE+i].id = query.GetResult(i)->VID;
candidates_near[fullID*NEAR_SIZE+i].checked=false;
}
for(size_t i=SEEDS; i<NEAR_SIZE; i++) {
candidates_near[fullID*NEAR_SIZE+i].id = -1;
candidates_near[fullID*NEAR_SIZE+i].checked=true;
}
for(size_t i=0; i<FAR_SIZE; i++) {
candidates_far[fullID*FAR_SIZE+i].id = -1;
candidates_far[fullID*FAR_SIZE+i].checked=true;
}
}
}
// Copy initial far values
cudaMemcpy(d_near, candidates_near.data(), curr_batch_size*NEAR_SIZE*sizeof(CandidateElt<SUMTYPE>), cudaMemcpyHostToDevice);
cudaMemcpy(d_far, candidates_far.data(), curr_batch_size*FAR_SIZE*sizeof(CandidateElt<SUMTYPE>), cudaMemcpyHostToDevice);
auto t3 = std::chrono::high_resolution_clock::now();
printf("Tree candidate time:%.2lf\n", ((double)std::chrono::duration_cast<std::chrono::seconds>(t3-t2).count()) + ((double)std::chrono::duration_cast<std::chrono::milliseconds>(t3-t2).count())/1000);
// Continue searching graph to desired depth
for(int depth=0; depth<searchDepth; depth++) {
auto l1 = std::chrono::high_resolution_clock::now();
// TODO - get rid of hard-coded values and have some max value or something, with error reporting when value is wrong...
sortCandidates<T,SUMTYPE,MAX_DIM,NEAR_SIZE,FAR_SIZE,SORT_THREADS><<<NUM_BLOCKS, SORT_THREADS>>>(d_tailPoints, d_headPoints, d_near, d_far, d_nearest, curr_batch_size, metric, depth);
cudaDeviceSynchronize();
auto l2 = std::chrono::high_resolution_clock::now();
sort_time += (double)std::chrono::duration_cast<std::chrono::seconds>(l2-l1).count();
sort_time += ((double)(std::chrono::duration_cast<std::chrono::milliseconds>(l2-l1).count())/1000.0);
// Copy nearest neighbor back to CPU to find more candidates
cudaMemcpy(nearest.data(), d_nearest, curr_batch_size*numNearest*sizeof(int), cudaMemcpyDeviceToHost);
#pragma omp parallel for num_threads(numThreads)
for(size_t fullID=0; fullID < curr_batch_size; fullID++) {
for(size_t j=0; j<numNearest; j++) {
if (nearest[fullID*numNearest + j] > -1) {
// Get neighbors of nearest candidates
SizeType* neighborList = headIndex->GetNeighborList(nearest[fullID*numNearest + j]);
for(size_t i=0; i<32; i++) {
if(neighborList[i] > -1) {
candidates_far[fullID*FAR_SIZE + j*32 + i].id = neighborList[i];
candidates_far[fullID*FAR_SIZE + j*32 + i].checked=false;
}
}
}
}
}
cudaMemcpy(d_far, candidates_far.data(), curr_batch_size*FAR_SIZE*sizeof(CandidateElt<SUMTYPE>), cudaMemcpyHostToDevice);
auto l3 = std::chrono::high_resolution_clock::now();
copy_search_time += (double)std::chrono::duration_cast<std::chrono::seconds>(l3-l2).count();
copy_search_time += ((double)(std::chrono::duration_cast<std::chrono::milliseconds>(l3-l2).count())/1000.0);
}
auto l1 = std::chrono::high_resolution_clock::now();
sortCandidates<T,SUMTYPE,MAX_DIM,NEAR_SIZE,FAR_SIZE,SORT_THREADS><<<NUM_BLOCKS, SORT_THREADS>>>(d_tailPoints, d_headPoints, d_near, d_far, d_nearest, curr_batch_size, metric, 0);
printf("final sort kernel:%d\n", cudaDeviceSynchronize());
auto l2 = std::chrono::high_resolution_clock::now();
sort_time += (double)std::chrono::duration_cast<std::chrono::seconds>(l2-l1).count();
sort_time += ((double)(std::chrono::duration_cast<std::chrono::milliseconds>(l2-l1).count())/1000.0);
compressToRNG<T,SUMTYPE,MAX_DIM,NEAR_SIZE,FAR_SIZE><<<NUM_BLOCKS, NUM_THREADS, NUM_THREADS*resultsPerVector*sizeof(DistPair<SUMTYPE>)>>>(d_tailPoints, d_headPoints, d_near, d_far, d_results, resultsPerVector, curr_batch_size, metric);
printf("compress kernel:%d\n", cudaDeviceSynchronize());
auto l3 = std::chrono::high_resolution_clock::now();
printf("memcpy:%d\n", cudaMemcpy(&results[offset*resultsPerVector], d_results, curr_batch_size*resultsPerVector*sizeof(DistPair<SUMTYPE>), cudaMemcpyDeviceToHost));
printf("copied into offset:%d, size:%d\n", offset*resultsPerVector, curr_batch_size*resultsPerVector*sizeof(DistPair<SUMTYPE>));
compress_time += (double)std::chrono::duration_cast<std::chrono::seconds>(l3-l2).count();
compress_time += ((double)(std::chrono::duration_cast<std::chrono::milliseconds>(l3-l2).count())/1000.0);
}
printf("sort time:%.2lf, search time:%.2lf, compress time:%.2lf\n", sort_time, copy_search_time, compress_time);
auto endt = std::chrono::high_resolution_clock::now();
printf("Total time:%.2lf\n", ((double)std::chrono::duration_cast<std::chrono::seconds>(endt-t1).count() + ((double)(std::chrono::duration_cast<std::chrono::milliseconds>(endt-t1).count()))/1000.0));
}
*/
#endif
|
af8b91de418477d75de5750383094b748827d541
|
58b0a41ccdceb06a237f1d70976bc9a8b3b6b2ce
|
/main.cpp
|
b557edd4e9e392bb73d18cbbc3b0c42e442509f9
|
[
"MIT"
] |
permissive
|
op-hunter/CLAIM
|
ccd78119f3476506e32828c6be5f7a02b5e874c2
|
6adda9c0633635351ad3835b523d158fc97a6f79
|
refs/heads/main
| 2023-06-16T23:39:49.567987
| 2021-07-14T09:12:08
| 2021-07-14T09:12:08
| 369,697,384
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,085
|
cpp
|
main.cpp
|
#include <iostream>
#include <string>
#include <cluster.h>
#include <chrono>
#include <fstream>
#include "kmeans.h"
#include "distance.h"
const int SZ = 0;
void LoadQ(char** pquery, size_t &nq) {
std::string query_file = "/home/zilliz/workspace/data/sift1m_query.bin";
std::ifstream fin(query_file.c_str(), std::ios::binary);
unsigned unq, unqd;
fin.read((char*)&unq, 4);
fin.read((char*)&unqd, 4);
nq = unq;
*pquery = (char*) malloc(nq * unqd * sizeof(float));
fin.read(*pquery, nq * unqd * sizeof(float));
fin.close();
std::cout << "read query done, nq = " << nq << ", dim = " << unqd << std::endl;
}
void Recall(std::vector<std::vector<std::pair<float, size_t>>>& groundtruth,
std::vector<std::vector<float>>& resultset,
size_t topk, size_t nq) {
int tot_cnt = 0;
std::cout << "recall@" << topk << ":" << std::endl;
for (unsigned i = 0; i < nq; i ++) {
int cnt = 0;
// std::cout << "groundtruth[i][k - 1].first = " << groundtruth[i][k - 1].first << std::endl;
for (size_t j = 0; j < topk; j ++) {
if (resultset[i][j] <= groundtruth[i][topk - 1].first)
cnt ++;
}
// std::cout << "cnt = " << cnt << std::endl;
tot_cnt += cnt;
std::cout << "query " << i + 1 << " recall@" << topk << " is: " << ((double)(cnt)) / topk * 100 << "%." << std::endl;
}
std::cout << "avg recall@100 = " << ((double)tot_cnt) / topk / nq * 100 << "%." << std::endl;
}
int main() {
char *pquery = nullptr;
size_t k = 100;
size_t nq;
LoadQ(&pquery, nq);
std::vector<std::vector<std::pair<float, size_t>>> groundtruth;
groundtruth.resize(nq);
size_t sz;
std::ifstream finn("/home/zilliz/workspace/data/sift_ground_truth_100.bin", std::ios::binary);
for (unsigned i = 0; i < nq; i ++) {
finn.read((char*)&sz, 8);
// std::cout << "query " << i + 1 << " has " << sz << " groundtruth ans." << std::endl;
groundtruth[i].resize(sz);
finn.read((char*)groundtruth[i].data(), k * 16);
}
finn.close();
std::cout << "show groundtruth:" << std::endl;
for (auto i = 0; i < nq; i ++) {
std::cout << "top1: (" << groundtruth[i][0].second << ", " << groundtruth[i][0].first
<< "), topk: " << groundtruth[i][k - 1].second << ", " << groundtruth[i][k - 1].first
<< ")" << std::endl;
}
// test kmeans
{
claim::Cluster kmeans(1000000, 128, SZ, 5);
std::string datafile = "/home/zilliz/workspace/data/sift1m.bin";
auto tstart = std::chrono::high_resolution_clock::now();
auto t0 = std::chrono::high_resolution_clock::now();
kmeans.Load(datafile);
auto t1 = std::chrono::high_resolution_clock::now();
std::cout << "kmeans::Load done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
std::cout << "Load Done!" << std::endl;
t0 = std::chrono::high_resolution_clock::now();
kmeans.Kmeans();
t1 = std::chrono::high_resolution_clock::now();
std::cout << "kmeans::Kmeans done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
std::cout << "Kmeans Done!" << std::endl;
// t0 = std::chrono::high_resolution_clock::now();
// kmeans.HealthyCheck();
// t1 = std::chrono::high_resolution_clock::now();
// std::cout << "kmeans::HealthyCheck done in "
// << std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
// << " milliseconds." << std::endl;
// std::cout << "HealthyCheck Done!" << std::endl;
t0 = std::chrono::high_resolution_clock::now();
kmeans.ShowCSHistogram();
t1 = std::chrono::high_resolution_clock::now();
std::cout << "kmeans::ShowCSHistogram done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
std::cout << "ShowCSHistogram Done!" << std::endl;
auto tend = std::chrono::high_resolution_clock::now();
std::cout << "kmeans totally done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( tend - tstart ).count()
<< " milliseconds." << std::endl;
std::vector<std::vector<size_t>> ids;
std::vector<std::vector<float>> dis;
std::cout << "Do Query after kmeans:" << std::endl;
t0 = std::chrono::high_resolution_clock::now();
kmeans.Query((float*)pquery, nq, k, 0, ids, dis);
t1 = std::chrono::high_resolution_clock::now();
std::cout << "kmeans::Query1 done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
std::cout << "show ans of kmeans:" << std::endl;
for (auto i = 0; i < nq; i ++) {
std::cout << "top1: (" << ids[i][0] << ", " << dis[i][0]
<< ") topk: (" << ids[i][k - 1] << ", " << dis[i][k - 1] << ")" << std::endl;
}
Recall(groundtruth, dis, k, nq);
/*
std::cout << "now do split:" << std::endl;
t0 = std::chrono::high_resolution_clock::now();
kmeans.Split(4);
t1 = std::chrono::high_resolution_clock::now();
std::cout << "kmeans::Split done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
kmeans.HealthyCheck();
t0 = std::chrono::high_resolution_clock::now();
kmeans.ShowCSHistogram();
t1 = std::chrono::high_resolution_clock::now();
std::cout << "kmeans::ShowCSHistogram done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
auto tendd = std::chrono::high_resolution_clock::now();
std::cout << "kmeans + split totally done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( tendd - tstart ).count()
<< " milliseconds." << std::endl;
std::cout << "Do Query after re-cluster:" << std::endl;
t0 = std::chrono::high_resolution_clock::now();
kmeans.Query((float*)pquery, nq, k, 0, ids, dis);
t1 = std::chrono::high_resolution_clock::now();
std::cout << "kmeans::Query2 done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
std::cout << "show ans of kmeans.Query:" << std::endl;
for (auto i = 0; i < nq; i ++) {
std::cout << "top1: (" << ids[i][0] << ", " << dis[i][0]
<< ") topk: (" << ids[i][k - 1] << ", " << dis[i][k - 1] << ")" << std::endl;
}
Recall(groundtruth, dis, k, nq);
*/
}
// test claim
/*
{
claim::Cluster cmli(1000000, 128, SZ, 5);
std::string datafile = "/home/zilliz/workspace/data/sift1m.bin";
auto tstart = std::chrono::high_resolution_clock::now();
auto t0 = std::chrono::high_resolution_clock::now();
cmli.Load(datafile);
auto t1 = std::chrono::high_resolution_clock::now();
std::cout << "cmli::Load done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
std::cout << "Load Done!" << std::endl;
t0 = std::chrono::high_resolution_clock::now();
cmli.SizeLimited();
t1 = std::chrono::high_resolution_clock::now();
std::cout << "cmli::Init done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
std::cout << "Init Done!" << std::endl;
t0 = std::chrono::high_resolution_clock::now();
cmli.HealthyCheck();
t1 = std::chrono::high_resolution_clock::now();
std::cout << "cmli::HealthyCheck done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
std::cout << "HealthyCheck Done!" << std::endl;
t0 = std::chrono::high_resolution_clock::now();
cmli.ShowCSHistogram();
t1 = std::chrono::high_resolution_clock::now();
std::cout << "cmli::ShowCSHistogram done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
std::cout << "ShowCSHistogram Done!" << std::endl;
auto tend = std::chrono::high_resolution_clock::now();
std::cout << "cmli totally done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( tend - tstart ).count()
<< " milliseconds." << std::endl;
std::vector<std::vector<size_t>> ids;
std::vector<std::vector<float>> dis;
std::cout << "Do Query after cmli.re-cluster:" << std::endl;
t0 = std::chrono::high_resolution_clock::now();
cmli.Query((float*)pquery, nq, k, 0, ids, dis);
t1 = std::chrono::high_resolution_clock::now();
std::cout << "cmli::Query done in "
<< std::chrono::duration_cast<std::chrono::milliseconds>( t1 - t0 ).count()
<< " milliseconds." << std::endl;
std::cout << "show ans of cmli.Query:" << std::endl;
for (auto i = 0; i < nq; i ++) {
std::cout << "top1: (" << ids[i][0] << ", " << dis[i][0]
<< ") topk: (" << ids[i][k - 1] << ", " << dis[i][k - 1] << ")" << std::endl;
}
Recall(groundtruth, dis, k, nq);
}
*/
free(pquery);
return 0;
}
|
aba09bdbb659673bcc9eacaa72d8198292f526f6
|
34f3488ec4f0755286fbbca18dcbf9d23d45e405
|
/AnimaEngine/AnimaRendererDrawableGeometry.h
|
1064a4bb803282bd2065acc6ec490698620446ed
|
[] |
no_license
|
zillemarco/Anima_Old
|
3b7a558e15f5f11642c515c4b71114f42b98b6b4
|
910dc6c389bd8f34923d6530cd35d14bc7e8f8b1
|
refs/heads/master
| 2020-12-13T19:13:30.230363
| 2016-02-20T13:13:59
| 2016-02-20T13:13:59
| 25,968,811
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,212
|
h
|
AnimaRendererDrawableGeometry.h
|
//
// AnimaRendererDrawableGeometry.h
// Anima
//
// Created by Marco Zille on 26/11/14.
//
//
#ifndef __Anima__AnimaRendererDrawableGeometry__
#define __Anima__AnimaRendererDrawableGeometry__
#include "AnimaEngineCore.h"
#include "AnimaTypes.h"
#include "AnimaEngine.h"
#include "AnimaGeometry.h"
#include "AnimaRendererDrawableGeometryInstances.h"
BEGIN_ANIMA_ENGINE_NAMESPACE
class AnimaRendererDrawableGeometry
{
public:
AnimaRendererDrawableGeometry();
~AnimaRendererDrawableGeometry();
AnimaRendererDrawableGeometry(const AnimaRendererDrawableGeometry& src);
AnimaRendererDrawableGeometry(const AnimaRendererDrawableGeometry&& src);
AnimaRendererDrawableGeometry& operator=(const AnimaRendererDrawableGeometry& src);
AnimaRendererDrawableGeometry& operator=(AnimaRendererDrawableGeometry&& src);
public:
void SetGeometry(AnimaGeometry* geometry);
AnimaGeometry* GetGeometry();
AnimaArray<AnimaRendererDrawableGeometryInstances>* GetDrawableGeometryInstances();
protected:
AnimaArray<AnimaRendererDrawableGeometryInstances> _drawableGeometriesInstances;
AnimaGeometry* _geometry;
};
END_ANIMA_ENGINE_NAMESPACE
#endif /* defined(__Anima__AnimaRendererDrawableGeometry__) */
|
da15173fbf30ef03c12be6f615bc6ecc725fba40
|
b05833df5cd682305be3af97a04e66e74dc58cbe
|
/oops5_convertToNumBasic/main.cpp
|
0fd6efff939eae775a8626e6e016337029fc7357
|
[] |
no_license
|
mittrayash/CPP-Projects
|
7170ff5330b88cc71b0d19ccaee2de36e37a3de3
|
12179251df47231d34a291bd534bc1e4044835d8
|
refs/heads/master
| 2021-07-07T09:53:53.036769
| 2017-10-02T06:44:16
| 2017-10-02T06:44:16
| 105,505,232
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 369
|
cpp
|
main.cpp
|
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char val[50];
cout << "Enter amount in rupees with commas: ";
cin >> (val);
int len = strlen(val);
int i = 0;
cout << "Amount = ";
while(i < len){
if(val[i] != ','){
cout << val[i];
}
i++;
}
cout << endl;
return 0;
}
|
125cc08f9fa9f3727cf1d54dbf0ef769263d6f13
|
a2206795a05877f83ac561e482e7b41772b22da8
|
/Source/PV/build/VTK/Wrapping/Python/vtkTableReaderPython.cxx
|
364391f5288e992776bc4caba4dce17e37960b99
|
[] |
no_license
|
supreethms1809/mpas-insitu
|
5578d465602feb4d6b239a22912c33918c7bb1c3
|
701644bcdae771e6878736cb6f49ccd2eb38b36e
|
refs/heads/master
| 2020-03-25T16:47:29.316814
| 2018-08-08T02:00:13
| 2018-08-08T02:00:13
| 143,947,446
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,640
|
cxx
|
vtkTableReaderPython.cxx
|
// python wrapper for vtkTableReader
//
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include "vtkPythonArgs.h"
#include "vtkPythonOverload.h"
#include "vtkConfigure.h"
#include <vtksys/ios/sstream>
#include "vtkIndent.h"
#include "vtkTableReader.h"
#if defined(VTK_BUILD_SHARED_LIBS)
# define VTK_PYTHON_EXPORT VTK_ABI_EXPORT
# define VTK_PYTHON_IMPORT VTK_ABI_IMPORT
#else
# define VTK_PYTHON_EXPORT VTK_ABI_EXPORT
# define VTK_PYTHON_IMPORT VTK_ABI_EXPORT
#endif
extern "C" { VTK_PYTHON_EXPORT void PyVTKAddFile_vtkTableReader(PyObject *, const char *); }
extern "C" { VTK_PYTHON_EXPORT PyObject *PyVTKClass_vtkTableReaderNew(const char *); }
#ifndef DECLARED_PyVTKClass_vtkDataReaderNew
extern "C" { PyObject *PyVTKClass_vtkDataReaderNew(const char *); }
#define DECLARED_PyVTKClass_vtkDataReaderNew
#endif
static const char **PyvtkTableReader_Doc();
static PyObject *
PyvtkTableReader_GetClassName(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "GetClassName");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkTableReader *op = static_cast<vtkTableReader *>(vp);
PyObject *result = NULL;
if (op && ap.CheckArgCount(0))
{
const char *tempr = (ap.IsBound() ?
op->GetClassName() :
op->vtkTableReader::GetClassName());
if (!ap.ErrorOccurred())
{
result = ap.BuildValue(tempr);
}
}
return result;
}
static PyObject *
PyvtkTableReader_IsA(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "IsA");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkTableReader *op = static_cast<vtkTableReader *>(vp);
char *temp0 = NULL;
PyObject *result = NULL;
if (op && ap.CheckArgCount(1) &&
ap.GetValue(temp0))
{
int tempr = (ap.IsBound() ?
op->IsA(temp0) :
op->vtkTableReader::IsA(temp0));
if (!ap.ErrorOccurred())
{
result = ap.BuildValue(tempr);
}
}
return result;
}
static PyObject *
PyvtkTableReader_NewInstance(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "NewInstance");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkTableReader *op = static_cast<vtkTableReader *>(vp);
PyObject *result = NULL;
if (op && ap.CheckArgCount(0))
{
vtkTableReader *tempr = (ap.IsBound() ?
op->NewInstance() :
op->vtkTableReader::NewInstance());
if (!ap.ErrorOccurred())
{
result = ap.BuildVTKObject(tempr);
if (result && PyVTKObject_Check(result))
{
PyVTKObject_GetObject(result)->UnRegister(0);
PyVTKObject_SetFlag(result, VTK_PYTHON_IGNORE_UNREGISTER, 1);
}
}
}
return result;
}
static PyObject *
PyvtkTableReader_SafeDownCast(PyObject *, PyObject *args)
{
vtkPythonArgs ap(args, "SafeDownCast");
vtkObject *temp0 = NULL;
PyObject *result = NULL;
if (ap.CheckArgCount(1) &&
ap.GetVTKObject(temp0, "vtkObject"))
{
vtkTableReader *tempr = vtkTableReader::SafeDownCast(temp0);
if (!ap.ErrorOccurred())
{
result = ap.BuildVTKObject(tempr);
}
}
return result;
}
static PyObject *
PyvtkTableReader_GetOutput_s1(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "GetOutput");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkTableReader *op = static_cast<vtkTableReader *>(vp);
PyObject *result = NULL;
if (op && ap.CheckArgCount(0))
{
vtkTable *tempr = (ap.IsBound() ?
op->GetOutput() :
op->vtkTableReader::GetOutput());
if (!ap.ErrorOccurred())
{
result = ap.BuildVTKObject(tempr);
}
}
return result;
}
static PyObject *
PyvtkTableReader_GetOutput_s2(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "GetOutput");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkTableReader *op = static_cast<vtkTableReader *>(vp);
int temp0;
PyObject *result = NULL;
if (op && ap.CheckArgCount(1) &&
ap.GetValue(temp0))
{
vtkTable *tempr = (ap.IsBound() ?
op->GetOutput(temp0) :
op->vtkTableReader::GetOutput(temp0));
if (!ap.ErrorOccurred())
{
result = ap.BuildVTKObject(tempr);
}
}
return result;
}
static PyObject *
PyvtkTableReader_GetOutput(PyObject *self, PyObject *args)
{
int nargs = vtkPythonArgs::GetArgCount(self, args);
switch(nargs)
{
case 0:
return PyvtkTableReader_GetOutput_s1(self, args);
case 1:
return PyvtkTableReader_GetOutput_s2(self, args);
}
vtkPythonArgs::ArgCountError(nargs, "GetOutput");
return NULL;
}
static PyObject *
PyvtkTableReader_SetOutput(PyObject *self, PyObject *args)
{
vtkPythonArgs ap(self, args, "SetOutput");
vtkObjectBase *vp = ap.GetSelfPointer(self, args);
vtkTableReader *op = static_cast<vtkTableReader *>(vp);
vtkTable *temp0 = NULL;
PyObject *result = NULL;
if (op && ap.CheckArgCount(1) &&
ap.GetVTKObject(temp0, "vtkTable"))
{
if (ap.IsBound())
{
op->SetOutput(temp0);
}
else
{
op->vtkTableReader::SetOutput(temp0);
}
if (!ap.ErrorOccurred())
{
result = ap.BuildNone();
}
}
return result;
}
static PyMethodDef PyvtkTableReader_Methods[] = {
{(char*)"GetClassName", PyvtkTableReader_GetClassName, METH_VARARGS,
(char*)"V.GetClassName() -> string\nC++: const char *GetClassName()\n\n"},
{(char*)"IsA", PyvtkTableReader_IsA, METH_VARARGS,
(char*)"V.IsA(string) -> int\nC++: int IsA(const char *name)\n\n"},
{(char*)"NewInstance", PyvtkTableReader_NewInstance, METH_VARARGS,
(char*)"V.NewInstance() -> vtkTableReader\nC++: vtkTableReader *NewInstance()\n\n"},
{(char*)"SafeDownCast", PyvtkTableReader_SafeDownCast, METH_VARARGS | METH_STATIC,
(char*)"V.SafeDownCast(vtkObject) -> vtkTableReader\nC++: vtkTableReader *SafeDownCast(vtkObject* o)\n\n"},
{(char*)"GetOutput", PyvtkTableReader_GetOutput, METH_VARARGS,
(char*)"V.GetOutput() -> vtkTable\nC++: vtkTable *GetOutput()\nV.GetOutput(int) -> vtkTable\nC++: vtkTable *GetOutput(int idx)\n\nGet the output of this reader.\n"},
{(char*)"SetOutput", PyvtkTableReader_SetOutput, METH_VARARGS,
(char*)"V.SetOutput(vtkTable)\nC++: void SetOutput(vtkTable *output)\n\nGet the output of this reader.\n"},
{NULL, NULL, 0, NULL}
};
static vtkObjectBase *PyvtkTableReader_StaticNew()
{
return vtkTableReader::New();
}
PyObject *PyVTKClass_vtkTableReaderNew(const char *modulename)
{
PyObject *cls = PyVTKClass_New(&PyvtkTableReader_StaticNew,
PyvtkTableReader_Methods,
"vtkTableReader", modulename,
NULL, NULL,
PyvtkTableReader_Doc(),
PyVTKClass_vtkDataReaderNew(modulename));
return cls;
}
const char **PyvtkTableReader_Doc()
{
static const char *docstring[] = {
"vtkTableReader - read vtkTable data file\n\n",
"Superclass: vtkDataReader\n\n",
"vtkTableReader is a source object that reads ASCII or binary vtkTable\ndata files in vtk format. (see text for format details). The output\nof this reader is a single vtkTable data object. The superclass of\nthis class, vtkDataReader, provides many methods for controlling the\nreading of the data file, see vtkDataReader for more information.\n\nCaveats:\n\nBinary files written on one system may not be rea",
"dable on other\nsystems.\n\nSee Also:\n\nvtkTable vtkDataReader vtkTableWriter\n\n",
NULL
};
return docstring;
}
void PyVTKAddFile_vtkTableReader(
PyObject *dict, const char *modulename)
{
PyObject *o;
o = PyVTKClass_vtkTableReaderNew(modulename);
if (o && PyDict_SetItemString(dict, (char *)"vtkTableReader", o) != 0)
{
Py_DECREF(o);
}
}
|
acc140920b9f5fc3eb97099e448072846b04e86e
|
c5af8ee216759517b981014437a944cc8678b897
|
/State.cpp
|
6fb1d1874ae615409cbbfd213b4e930943d7426b
|
[] |
no_license
|
fesse/timelaps_arduino
|
0c12174d547a02edd87ee23d110ff77f85b24a0e
|
ca42d7540007fa283af13d50eb66946fe6695073
|
refs/heads/master
| 2021-01-10T11:26:40.724986
| 2014-09-29T19:31:58
| 2014-09-29T19:56:50
| 36,109,451
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,079
|
cpp
|
State.cpp
|
/*
* State.cpp
*
* Created on: Jul 1, 2014
* Author: mathias
*/
#include "State.h"
State::State(){
totalNbrOfPhotos = 1000;
exposureWaitTime = 1000;
motorRunTime = 100;
direction = LEFT;
runState = STATE_IDLE;
nbrOfPhotosTaken = 0;
}
void State::setTotalNbrOfPhotos(long nbrOfPhotos) {
totalNbrOfPhotos = nbrOfPhotos;
}
long State::getTotalNbrOfPhotos() {
return totalNbrOfPhotos;
}
void State::setExposureWaitTime(long waitTime) {
exposureWaitTime = waitTime;
}
long State::getExposureWaitTime() {
return exposureWaitTime;
}
void State::setMotorRunTime(long motorRunTime) {
this->motorRunTime = motorRunTime;
}
long State::getMotorRunTime() {
return motorRunTime;
}
void State::setDirection(int newDirection) {
direction = newDirection;
}
int State::getDirection() {
return direction;
}
int State::getRunState() {
return runState;
}
void State::setRunState(int newRunState) {
runState = newRunState;
}
long State::getNbrOfPhotosTaken() {
return nbrOfPhotosTaken;
}
void State::setNbrOfPhotosTaken(int nbr) {
nbrOfPhotosTaken = nbr;
}
|
f991387430107564c65a1f82fe21ba70cc42a515
|
c5fde8abf5b1b07a7b69a18f4b2e5569986d3095
|
/integral/integrate.hpp
|
7b85e6096b229a21c1664c6b70fabfd01148ab5c
|
[] |
no_license
|
svdprima/MIPT_Homework
|
bc6e5b139a6e414a5172cf78c73df158a66c464f
|
3e61cb75177a478fa69af20459bc591780b1b33d
|
refs/heads/master
| 2021-01-18T09:15:28.443071
| 2017-05-03T21:41:52
| 2017-05-03T21:41:52
| 84,310,551
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 157
|
hpp
|
integrate.hpp
|
#ifndef INTEGRATE
#define INTEGRATE
double integrate (double (*f) (double x), const double left, const double right, const unsigned int thread_nu);
#endif
|
73604e2a2a5fd36cf74925ca19f074821fa56af6
|
e56dc7453b16e75510ec7da88cb6759bec7e7443
|
/01 C++/3 专题 通信/2 multiThread_SC/CServerSocket.h
|
553a4ceea00feab3120e355d2f1c1605e3ebb8ca
|
[] |
no_license
|
zw398430866/study_code
|
dbb97257d14bf37119e573c0b806e1a6c179bb1a
|
372d69d974d9b530901ce1e1ac347af8cf3ce074
|
refs/heads/master
| 2020-03-28T08:18:53.518402
| 2018-09-10T17:38:40
| 2018-09-10T17:38:40
| 147,957,529
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 749
|
h
|
CServerSocket.h
|
#ifndef _C_SSERVER_SOCKET_
#define _C_SSERVER_SOCKET_
#include <WinSock2.h>
#include <iostream>
#include <stdio.h>
#include <string>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
#define BUFF_SIZE 128
class CServerSocket{
public:
CServerSocket();
~CServerSocket();
CServerSocket(int port, string addrIp);
void CServerSetPort(int port);
void CServerSetAddrIp(string addrIp);
void CServerSetPortAndIp(int port,string addrIp);
int start(); /* server服务器启动唯一入口 */
private:
int m_Accept();
//DWORD WINAPI CServerSocket::m_thread_Acception(LPVOID pVoid); /* 新起一个accept ClientSocket用于接收 */
int m_Port;
string m_addrIp;
SOCKET m_ServerSocket;
//SOCKET m_ClientSocket;
};
#endif
|
1cf229707001fd41381b88c2d837fd2daee6a874
|
e5174200fe8b6497cfa2467581b3a7dc8f0a0e4b
|
/src/instruments/instrumentFM.cpp
|
972c83aa99ebe4391b68a62cc326a3767f544d79
|
[] |
no_license
|
oscar-agraz/P5
|
bf9bcf53b8a3de24a5c5372f63667ef3e1b9322e
|
c479f8a0dc93c2e1f8e648c661bb024048c3ecae
|
refs/heads/master
| 2020-09-30T00:16:56.195412
| 2020-01-07T21:00:16
| 2020-01-07T21:00:16
| 227,155,019
| 0
| 0
| null | 2019-12-10T15:32:26
| 2019-12-10T15:32:25
| null |
UTF-8
|
C++
| false
| false
| 1,884
|
cpp
|
instrumentFM.cpp
|
#include <iostream>
#include <math.h>
#include "instrumentFM.h"
#include "keyvalue.h"
#include <stdlib.h>
using namespace upc;
using namespace std;
InstrumentFM::InstrumentFM(const std::string ¶m)
: adsr(SamplingRate, param) {
bActive = false;
x.resize(BSIZE);
KeyValue kv(param);
int N;
if (!kv.to_int("N",N))
N = 40;
tbl.resize(N);
float phase=0, step=2*M_PI/(float)N;
index = 0;
for (int i=0; i < N ; ++i) {
tbl[i] = sin(phase);
phase += step;
}
}
void InstrumentFM::command(long cmd, long note, long vel) {
if (cmd == 9) {
bActive = true;
adsr.start();
step = 0;
index = 0;
findex = 0;
accstep = 0;
I=0.5;
N1=100;
N2=20;
//N2=140;
N=100;
f0=440.0*pow(2,(((float)note-69.0)/12.0));
fm=N2*f0/N1;
nota=f0/SamplingRate;
step1=nota*N1;
step2=nota*N2;
A=vel/127.;
}
else if (cmd == 8) { //'Key' released: sustain ends, release begins
adsr.stop();
}
else if (cmd == 0) { //Sound extinguished without waiting for release to end
adsr.end();
}
}
const vector<float> & InstrumentFM::synthesize() {
if (not adsr.active()) {
x.assign(x.size(), 0);
bActive = false;
return x;
}
else if (not bActive)
return x;
for (unsigned int i=0; i < x.size() ; ++i) {
findex += step1;
index2 += step2;
if(findex>=tbl.size()){
findex = findex - tbl.size();
}
if(index2>=tbl.size()){
index2 = index2 - tbl.size();
}
prev = (int)findex;
weight = findex-prev;
if(prev==tbl.size()-1){
next=0;
//findex = findex - tbl.size();
}
else next = prev+1;
//prev2 = (int)index2;
//if(prev2==tbl.size()-1){
// next2=0;
//findex = findex - tbl.size();
//}
//else next2 = prev2+1;
x[i] = weight*A*tbl[prev+I*tbl[index2]]+(1-weight)*A*tbl[next+I*tbl[index2]];
//x[i] = weight*A*tbl[prev+I*tbl[prev2]]+(1-weight)*A*tbl[next+I*tbl[next2]];
}
adsr(x);
return x;
}
|
66465e45710313daed439504dd6d2ebe43ca440b
|
2bb40601196d2c46b81650e6b9d265f7f2e0bcac
|
/TATIANA_ENCALADA-_LCD_MSM-EMBEBIDOS/TATIANA_ENCALADA-_LCD_MSM-EMBEBIDOS.ino
|
c56e11126e2d798c1a6d9717e19b320db7de8e3a
|
[] |
no_license
|
tatiana2004/LCD
|
0ea6b76d3c7e65788ee6f8d276e8f71ca442d49b
|
cb9af95891d54446a4b281e46611b69550710926
|
refs/heads/master
| 2020-06-10T19:37:46.078296
| 2016-12-08T02:29:08
| 2016-12-08T02:29:08
| 75,895,033
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,726
|
ino
|
TATIANA_ENCALADA-_LCD_MSM-EMBEBIDOS.ino
|
#include <LiquidCrystal.h> // libreria para la LCD
char texto; // texto para ingresar
int i=0; // variable i
String palabra=""; // variable palabra
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //inicializar la librería indicando los pins de la interfaz
void setup()
{
lcd.begin(16,2); //configuracion de la lcd en este caso 16 columnas y 2 filas
Serial.begin(9600); //configuración monitor serie
Serial.println("INGRESE TEXTO"); //ingrese el usuario texto
}
void loop()
{
if (Serial.available())
{
texto=Serial.read(); // lee el texto ingresado
palabra+=texto; // Obtenemos el tamaño del texto
if(texto=='-')
{
for( ; i<300 ; i++) // Mostramos entrada texto por la izquierda
{
lcd.setCursor(i, 0);
lcd.print(palabra); // Escribimos el texto
delay(450); // Esperamos
lcd.setCursor(i, 0); //Situamos el cursor
lcd.println("");
}
for(int i=16; i>=0;i--) // Desplazamos el texto hacia la derecha
{
lcd.setCursor(i, 1);
lcd.print(palabra); // Escribimos el texto
delay(450); // Esperamos
lcd.setCursor(i, 1); //Situamos el cursor
lcd.println("");
}
}
}
}
|
6a5f757a0046f972844bc77553afc650dc5a1e5f
|
1bd5111963ed4d1fab5fec0e7d1101df2b78946d
|
/Class_Notes/02_notes_src/default_func_parameters_variant2.cpp
|
dcc83d53b2fd13c735a28c0caffa9a7a83d95f5d
|
[] |
no_license
|
deep-inder/C-codes
|
3544c748fb43d1c152277b389abeba38425883c0
|
4838fdcb0f43d9e24529618dad9ade5c920ae956
|
refs/heads/master
| 2022-10-29T22:36:13.522695
| 2018-11-19T20:35:27
| 2018-11-19T20:35:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 155
|
cpp
|
default_func_parameters_variant2.cpp
|
// default_func_parameters_variant2.cpp
#include <iostream>
extern void showints(int,int) ;
int main() {
showints(1,0);
showints();
return 0 ;
}
|
9c4dd3d79d32359aabc6958a908db1d4642b433c
|
4d04b7b0a8e9418f729ddee54bda43484657d52f
|
/Мої/boal/Unit2.h
|
ee55cb3fbd91bb7834e0c52fed2f28daad81f3e9
|
[] |
no_license
|
BREAK350/myCProgram-old
|
359c021d7bcfa9e44fa831498a417294703a0c1e
|
10bbfdd3cadd8c8d91b078591d6d646da20b48cb
|
refs/heads/master
| 2021-01-10T20:04:20.229647
| 2015-01-28T06:51:00
| 2015-01-28T06:51:00
| 29,954,421
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,324
|
h
|
Unit2.h
|
//---------------------------------------------------------------------------
#ifndef Unit2H
#define Unit2H
#include "Unit1.h"
#include <math.h>
//---------------------------------------------------------------------------
class TDf {
private:
float value;
public:
TDf operator=(float);
float operator+(float);
TDf operator-(float);
TDf operator*(float);
TDf operator/(float);
};
//---------------------------------------------------------------------------
class Alpha {
private:
float alpha;
public:
Alpha operator=(float);
Alpha operator+=(float);
Alpha operator-(float);
void CheckAlpha();
float degree();
};
//---------------------------------------------------------------------------
class V {
private:
float v;
public:
V operator=(float);
V operator+(float);
V operator-(float);
float value();
};
//---------------------------------------------------------------------------
class CBoal {
private:
float x,y;
int r;
public:
CBoal();
~CBoal();
Alpha alpha;
V v;
void DrawBoal(int,int,TForm*);
void ClearBoal(int,int,TForm*);
void Radius(int);
void Move();
};
//---------------------------------------------------------------------------
#endif
|
b3f4a4a61f32a9efbf885acba08c38f6b0fb6fee
|
a348a0d054799c007b2748457ffe99714e1ec515
|
/Classes/base/BaseScene.cpp
|
c4016bfdd8def4bb8b01f5c41076bcbc8cd4a5e3
|
[] |
no_license
|
ysnows/Game-cocos2dx-
|
7d81d6fdf6563eabc24b64785abea8ed5dd2113a
|
915b8a27119f95899037571904f003b580e603f5
|
refs/heads/master
| 2021-01-11T07:02:11.714227
| 2016-12-03T09:53:19
| 2016-12-03T09:53:19
| 71,952,631
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 666
|
cpp
|
BaseScene.cpp
|
//
// BaseScene.cpp
// Game
//
// Created by 咸光金 on 2016/10/26.
//
//
#include "BaseScene.h"
BaseScene::BaseScene(bool bPortrait):_rootLayer(nullptr){
log("BaseScene()");
Scene::init();
director=Director::getInstance();
visibleSize=director->getVisibleSize();
visibleOrigin=director->getVisibleOrigin();
}
BaseScene::~BaseScene(void){
}
void BaseScene::onEnter(){
log("Base OnEnter");
Scene::onEnter();
}
void BaseScene::onExit(){
log("Base OnExit");
if (_rootLayer!=nullptr) {
_rootLayer->removeFromParent();
}
TextureCache::getInstance()->removeAllTextures();
Scene::onExit();
}
|
c698d719ca76a12683066184809895ad05059a7f
|
5e2428bd724dafdeeb781cec54b7cc258331bd76
|
/C:C++/Classes/pcOrdering/Desktop.hpp
|
7dc7513b7c6152c95a1af008c1cb155aaf6bf561
|
[] |
no_license
|
brogan-avery/MyPortfolio-AndExamples
|
60e898742b41f92e46147e92f67fc16357d2b894
|
555a69cf3495183700f463cf7808e0ba65b53a96
|
refs/heads/main
| 2023-05-03T00:31:02.949069
| 2021-05-26T22:09:43
| 2021-05-26T22:09:43
| 360,210,871
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,282
|
hpp
|
Desktop.hpp
|
/*
***************************************************************
* Class Name: Desktop
* Author: Brogan Avery
* Created: 2021-02-12
***************************************************************
*/
#ifndef Desktop_h
#define Desktop_h
#include <stdio.h>
#include <string>
#include "PowerSupply.hpp"
#include "Computer.hpp"
using namespace std;
// class declaration
class Desktop{
private: // objects have a data type of another class
PowerSupply powerSupply;
Computer computer;
double price;
public:
Desktop(); // default constructor
Desktop(PowerSupply, Computer, double);
void setPowerSupply(PowerSupply);
void setComputer(Computer);
void setPrice(double);
PowerSupply getPowerSupply();
Computer getComputer();
double getPrice();
string getTotal();
string toString();
};
// ==== constructors ====
//default
Desktop::Desktop(){
setPowerSupply(PowerSupply());
setComputer(Computer());
setPrice(0);
}
Desktop::Desktop(PowerSupply powerSupply, Computer computer, double price){
setPowerSupply(powerSupply);
setComputer(computer);
setPrice(price);
}
// ==== setters ====
void Desktop::setPowerSupply(PowerSupply powerSupply){
this->powerSupply = powerSupply;
}
void Desktop::setComputer(Computer computer){
this->computer = computer;
}
void Desktop::setPrice(double price){
this->price = price;
}
// ==== getters ====
PowerSupply Desktop:: getPowerSupply(){
return powerSupply;
}
Computer Desktop:: getComputer(){
return computer;
}
double Desktop:: getPrice(){
return price;
}
// added for testing
string Desktop:: getTotal(){
double total = getPrice() + getPowerSupply().getPrice() + getComputer().getPrice() + getComputer().getCpu().getPrice() + getComputer().getMemory().getPrice() + getComputer().getStorage().getPrice();
string totalStr = to_string(total);
totalStr.resize(7);
return totalStr;
}
string Desktop:: toString(){
string price = to_string(getPrice());
price.resize(6);
string str = "Power Supply: " + getPowerSupply().toString() + " | Computer: " + getComputer().toString() + " | Price: " + price;
return str;
}
#endif /* Desktop_h */
|
d4b1063229c9f6066219249193e974472a238ed6
|
a5c3b4d98ddc0d9f919fa5597580cceb39bd5072
|
/week_3/2018202118HYX/src/head.h
|
aba8514e46c217ce61beeb4c5ad6e15ae9cd251f
|
[] |
no_license
|
WhiteCatFly/Turing_Student_Code_2019
|
17f4ed781327706b14b66ef90b0b90478792915b
|
4d744f6a3072dc9184c10c5daad60dee4a83a588
|
refs/heads/master
| 2021-06-15T02:32:07.977336
| 2019-07-05T07:06:32
| 2019-07-05T07:06:32
| 173,031,113
| 8
| 27
| null | 2020-01-09T01:44:23
| 2019-02-28T03:04:38
|
C++
|
UTF-8
|
C++
| false
| false
| 606
|
h
|
head.h
|
#ifndef HEAD_H
#define HEAD_H
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <queue>
#include <regex>
#include <set>
void input_first_url(std::string &url);
class crawl
{
private:
std::queue<std::string> todo;
std::set<std::string> done;
int n;
std::string current;
std::string root;
std::string getcontent();
int adjust(std::string &a_url);
void parse(std::string &content, std::set<std::string> &urls);
public:
crawl()=default;
crawl(std::string root_);
~crawl();
void BFS();
};
#endif
|
7f2afec76e14891a1d04b94657cfc606454df9a1
|
157fd7fe5e541c8ef7559b212078eb7a6dbf51c6
|
/TRiAS/TRiAS/Extensions/Extension BaseClass (MFC)/XTENSNP.CXX
|
c39d501f96216f8354a07139bfc757143f27bbb8
|
[] |
no_license
|
15831944/TRiAS
|
d2bab6fd129a86fc2f06f2103d8bcd08237c49af
|
840946b85dcefb34efc219446240e21f51d2c60d
|
refs/heads/master
| 2020-09-05T05:56:39.624150
| 2012-11-11T02:24:49
| 2012-11-11T02:24:49
| null | 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 132
|
cxx
|
XTENSNP.CXX
|
// Precompiled Header für XTENSN.LIB ------------------------------------------
// File: XTENSNP.CXX
#include "xtensnp.hxx"
|
d19418e7e558db24a10ab9357a5c49769e645f5b
|
be6fc3ca8823fe24ea89a104ca625c0ef34fbe17
|
/include/Flashlight.hpp
|
22867d32142597905daca7c4e56f8e8c24ba996f
|
[
"BSD-2-Clause"
] |
permissive
|
alecwalsh/glfwogltest2
|
09cf01cb9e47ffe892da70b6f8353448e0517947
|
10b9a8dc6e5bfe30973c80a628b85bfe249d420c
|
refs/heads/master
| 2023-01-10T18:27:06.616563
| 2022-12-27T07:57:08
| 2022-12-27T07:57:08
| 119,344,167
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 402
|
hpp
|
Flashlight.hpp
|
#pragma once
#include "SpotLight.hpp"
#include "Camera.hpp"
class Flashlight : public SpotLight {
const GameEngine::Camera& camera;
public:
Flashlight(glm::vec3 direction, glm::vec3 diffuse, glm::vec3 specular, float cutoffAngleCos, const GameEngine::Camera& camera,
bool active = true) noexcept;
void SetUniforms(std::uint32_t program, std::size_t index) override;
};
|
5cffef270893185866c5e2230c8944ebbaa495c5
|
ac0455fd429fcfa34c76fb35da481c7b219a3aba
|
/packet.cpp
|
5e3a4f5ba2d2bdc98a5d26e44c5974427705b46a
|
[] |
no_license
|
jeffreyhxu/cs118-proj2
|
83dbe671b3d5397d7f8fd0cd3d60369fb7ba4bfc
|
d18c4285961d7c0947b2d54cbb67019ef4313042
|
refs/heads/master
| 2021-04-26T21:53:09.613780
| 2018-03-17T05:55:40
| 2018-03-17T05:55:40
| 124,171,429
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,472
|
cpp
|
packet.cpp
|
#include "packet.h"
#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
#include <vector>
Packet::Packet() {
}
Packet::Packet(int ack, int seq, int len, vector<int> flags, char* message) {
m_ack = ack;
m_seq = seq;
m_len = len;
m_flags = flags;
m_message = message;
m_header[0] = (ack & 0xFF00) >> 8;
m_header[1] = (ack & 0x00FF);
m_header[2] = (seq & 0xFF00) >> 8;
m_header[3] = (seq & 0x00FF);
m_header[4] = (len & 0xFF00) >> 8;
m_header[5] = (len & 0x00FF);
m_header[7] = flags[0] + 2*flags[1] + 4*flags[2];
memcpy(m_raw, m_header, 8);
memcpy(m_raw + 8, m_message, 1016);
}
Packet::Packet(char raw[]) {
memcpy(m_raw, raw, 1024);
memcpy(m_header, m_raw, 8);
m_message = (char*)malloc(1016); // This does not get deallocated by a destructor because we need to hold onto it after the Packet
memcpy(m_message, m_raw+8, 1016); // is freed to buffer messages. This means we have to keep track of it and free it elsewhere.
m_ack = 0 | (unsigned char)m_header[0];
m_ack = (m_ack << 8) + ((unsigned char)m_header[1]);
m_seq = 0 | (unsigned char)m_header[2];
m_seq = (m_seq << 8) + ((unsigned char)m_header[3]);
m_len = 0 | (unsigned char)m_header[4];
m_len = (m_len << 8) + ((unsigned char)m_header[5]);
m_flags.resize(8);
m_flags[0] = (m_header[7] & 0x01);
m_flags[1] = (m_header[7] & 0x02) >> 1;
m_flags[2] = (m_header[7] & 0x04) >> 2;
}
|
37960ee41bfc195efbd41e8c96d44cbabbca5dc3
|
d0767f67a74f55b4ecf2002ea0b5eeaadce791a5
|
/RooMySig.cxx
|
c4824c0137fa8fcbbf3f136773b0059f9dce9354
|
[] |
no_license
|
longyf/fit-PHSPf-interference
|
eebac684f77166e20652384e3913ca629a181c41
|
9c843d8422bf2e65ae2e697d8f3469a91a6dfd98
|
refs/heads/master
| 2021-04-26T23:03:01.002426
| 2018-03-06T03:11:42
| 2018-03-06T03:11:42
| 123,922,657
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,670
|
cxx
|
RooMySig.cxx
|
/*****************************************************************************
* Project: RooFit *
* *
* This code was autogenerated by RooClassFactory *
*****************************************************************************/
// Your description goes here...
#include "Riostream.h"
#include "RooMySig.h"
#include "RooAbsReal.h"
#include "RooAbsCategory.h"
#include <math.h>
#include "TMath.h"
ClassImp(RooMySig)
RooMySig::RooMySig(const char *name, const char *title,
RooAbsReal& _m,
RooAbsReal& _mean,
RooAbsReal& _Gamma,
RooAbsReal& _phi,
RooAbsReal& _ratio,
RooAbsReal& _p1,
RooAbsReal& _p2,
RooAbsReal& _p3,
RooAbsReal& _p4,
RooAbsReal& _p5,
RooAbsReal& _p6) :
RooAbsPdf(name,title),
m("m","m",this,_m),
mean("mean","mean",this,_mean),
Gamma("Gamma","Gamma",this,_Gamma),
phi("phi","phi",this,_phi),
ratio("ratio","ratio",this,_ratio),
p1("p1","p1",this,_p1),
p2("p2","p2",this,_p2),
p3("p3","p3",this,_p3),
p4("p4","p4",this,_p4),
p5("p5","p5",this,_p5),
p6("p6","p6",this,_p6)
{
}
RooMySig::RooMySig(const RooMySig& other, const char* name) :
RooAbsPdf(other,name),
m("m",this,other.m),
mean("mean",this,other.mean),
Gamma("Gamma",this,other.Gamma),
phi("phi",this,other.phi),
ratio("ratio",this,other.ratio),
p1("p1",this,other.p1),
p2("p2",this,other.p2),
p3("p3",this,other.p3),
p4("p4",this,other.p4),
p5("p5",this,other.p5),
p6("p6",this,other.p6)
{
}
Double_t RooMySig::evaluate() const
{
// ENTER EXPRESSION IN TERMS OF VARIABLE ARGUMENTS HERE
//The range is for 3-body bkg
Double_t low=1.96;//
Double_t up=2.56;//
//PHSP factors
Double_t m_jpsi=3.097;
Double_t m_phi=1.019;
Double_t m_eta=0.548;
Double_t m_etap=0.958;
Double_t p=0;
if ( (m*m-(m_phi+m_etap)*(m_phi+m_etap))>0. ) {
p=sqrt( (m*m-(m_phi+m_etap)*(m_phi+m_etap))*(m*m-(m_phi-m_etap)*(m_phi-m_etap)) ) / (2*m);
}
if (p<0) p=0;
Double_t q=0;
if ( (m_jpsi*m_jpsi-(m_eta+m)*(m_eta+m))>0. ) {
q=sqrt( (m_jpsi*m_jpsi-(m_eta+m)*(m_eta+m))*(m_jpsi*m_jpsi-(m_eta-m)*(m_eta-m)) ) / (2*m_jpsi);
}
if (q<0) q=0;
//PHSP factor=p^{l1+1/2}*q^{l2+1/2}
//We assume l1=l2=1
Double_t PHSPf=p*sqrt(p)*q*sqrt(q);
//sig: |BW|^2
Double_t sig=(1./( (m*m-mean*mean)*(m*m-mean*mean)+(mean*Gamma)*(mean*Gamma) ))*PHSPf*PHSPf;
//efficiency
Double_t eff=0;
if (m>=1.977&&m<=2.549) eff=2.372-3.572*m+1.741*m*m-0.2684*m*m*m;
//bkg: poly
Double_t bkg=0.;
if ( (m>=low)&&(m<=up) ) {
Double_t X=-1.0+2.0*( (m-low)/(up-low) );
Double_t T0=1.0;
Double_t T1=X;
Double_t T2=2.0*X*X-1.0;
Double_t T3=4.0*X*X*X-3.0*X;
Double_t T4=8.0*X*X*X*X-8.0*X*X+1.0;
Double_t T5=16.0*X*X*X*X*X-20.0*X*X*X+5.0*X;
Double_t T6=32.0*X*X*X*X*X*X-48.0*X*X*X*X+18.0*X*X-1.0;
bkg=(T0+p1*T1+p2*T2+p3*T3+p4*T4+p5*T5+p6*T6)*ratio*ratio;
if (bkg<0.) bkg=0.;
}//end with if ( (m>low)&&(m<up) )
//inter
Double_t inter=2.*( cos(phi)*(m*m-mean*mean)-sin(phi)*mean*Gamma ) / ( (m*m-mean*mean)*(m*m-mean*mean)+(mean*Gamma)*(mean*Gamma) ) *sqrt(bkg) * PHSPf;
return (sig+inter+bkg)*eff;
}
|
9f8d3ced1fa9d4affbecaefc902a186e5bd7f807
|
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
|
/third_party/WebKit/Source/core/css/properties/CSSPropertyFontUtils.cpp
|
4cde177e5950d630a089717a78af53c9756ff2a8
|
[
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-only",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] |
permissive
|
wzyy2/chromium-browser
|
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
|
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
|
refs/heads/master
| 2022-11-23T20:25:08.120045
| 2018-01-16T06:41:26
| 2018-01-16T06:41:26
| 117,618,467
| 3
| 2
|
BSD-3-Clause
| 2022-11-20T22:03:57
| 2018-01-16T02:09:10
| null |
UTF-8
|
C++
| false
| false
| 10,571
|
cpp
|
CSSPropertyFontUtils.cpp
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/css/properties/CSSPropertyFontUtils.h"
#include "core/css/CSSFontFamilyValue.h"
#include "core/css/CSSFontFeatureValue.h"
#include "core/css/CSSFontStyleRangeValue.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSValueList.h"
#include "core/css/CSSValuePair.h"
#include "platform/wtf/text/StringBuilder.h"
namespace blink {
CSSValue* CSSPropertyFontUtils::ConsumeFontSize(
CSSParserTokenRange& range,
CSSParserMode css_parser_mode,
CSSPropertyParserHelpers::UnitlessQuirk unitless) {
if (range.Peek().Id() >= CSSValueXxSmall &&
range.Peek().Id() <= CSSValueLarger)
return CSSPropertyParserHelpers::ConsumeIdent(range);
return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
range, css_parser_mode, kValueRangeNonNegative, unitless);
}
CSSValue* CSSPropertyFontUtils::ConsumeLineHeight(
CSSParserTokenRange& range,
CSSParserMode css_parser_mode) {
if (range.Peek().Id() == CSSValueNormal)
return CSSPropertyParserHelpers::ConsumeIdent(range);
CSSPrimitiveValue* line_height =
CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
if (line_height)
return line_height;
return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
range, css_parser_mode, kValueRangeNonNegative);
}
CSSValueList* CSSPropertyFontUtils::ConsumeFontFamily(
CSSParserTokenRange& range) {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
do {
CSSValue* parsed_value = ConsumeGenericFamily(range);
if (parsed_value) {
list->Append(*parsed_value);
} else {
parsed_value = ConsumeFamilyName(range);
if (parsed_value) {
list->Append(*parsed_value);
} else {
return nullptr;
}
}
} while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
return list;
}
CSSValue* CSSPropertyFontUtils::ConsumeGenericFamily(
CSSParserTokenRange& range) {
return CSSPropertyParserHelpers::ConsumeIdentRange(range, CSSValueSerif,
CSSValueWebkitBody);
}
CSSValue* CSSPropertyFontUtils::ConsumeFamilyName(CSSParserTokenRange& range) {
if (range.Peek().GetType() == kStringToken) {
return CSSFontFamilyValue::Create(
range.ConsumeIncludingWhitespace().Value().ToString());
}
if (range.Peek().GetType() != kIdentToken)
return nullptr;
String family_name = ConcatenateFamilyName(range);
if (family_name.IsNull())
return nullptr;
return CSSFontFamilyValue::Create(family_name);
}
String CSSPropertyFontUtils::ConcatenateFamilyName(CSSParserTokenRange& range) {
StringBuilder builder;
bool added_space = false;
const CSSParserToken& first_token = range.Peek();
while (range.Peek().GetType() == kIdentToken) {
if (!builder.IsEmpty()) {
builder.Append(' ');
added_space = true;
}
builder.Append(range.ConsumeIncludingWhitespace().Value());
}
if (!added_space &&
(CSSPropertyParserHelpers::IsCSSWideKeyword(first_token.Value()) ||
EqualIgnoringASCIICase(first_token.Value(), "default"))) {
return String();
}
return builder.ToString();
}
static CSSValueList* CombineToRangeListOrNull(
const CSSPrimitiveValue* range_start,
const CSSPrimitiveValue* range_end) {
DCHECK(range_start);
DCHECK(range_end);
if (range_end->GetFloatValue() < range_start->GetFloatValue())
return nullptr;
CSSValueList* value_list = CSSValueList::CreateSpaceSeparated();
value_list->Append(*range_start);
value_list->Append(*range_end);
return value_list;
}
static bool IsAngleWithinLimits(CSSPrimitiveValue* angle) {
constexpr float kMaxAngle = 90.0f;
return angle->GetFloatValue() >= -kMaxAngle &&
angle->GetFloatValue() <= kMaxAngle;
}
CSSValue* CSSPropertyFontUtils::ConsumeFontStyle(
CSSParserTokenRange& range,
const CSSParserMode& parser_mode) {
if (range.Peek().Id() == CSSValueNormal ||
range.Peek().Id() == CSSValueItalic)
return CSSPropertyParserHelpers::ConsumeIdent(range);
if (range.Peek().Id() != CSSValueOblique)
return nullptr;
CSSIdentifierValue* oblique_identifier =
CSSPropertyParserHelpers::ConsumeIdent<CSSValueOblique>(range);
CSSPrimitiveValue* start_angle =
CSSPropertyParserHelpers::ConsumeAngle(range, nullptr, WTF::nullopt);
if (!start_angle)
return oblique_identifier;
if (!IsAngleWithinLimits(start_angle))
return nullptr;
if (parser_mode != kCSSFontFaceRuleMode || range.AtEnd()) {
CSSValueList* value_list = CSSValueList::CreateSpaceSeparated();
value_list->Append(*start_angle);
return CSSFontStyleRangeValue::Create(*oblique_identifier, *value_list);
}
CSSPrimitiveValue* end_angle =
CSSPropertyParserHelpers::ConsumeAngle(range, nullptr, WTF::nullopt);
if (!end_angle || !IsAngleWithinLimits(end_angle))
return nullptr;
CSSValueList* range_list = CombineToRangeListOrNull(start_angle, end_angle);
if (!range_list)
return nullptr;
return CSSFontStyleRangeValue::Create(*oblique_identifier, *range_list);
}
CSSIdentifierValue* CSSPropertyFontUtils::ConsumeFontStretchKeywordOnly(
CSSParserTokenRange& range) {
const CSSParserToken& token = range.Peek();
if (token.Id() == CSSValueNormal || (token.Id() >= CSSValueUltraCondensed &&
token.Id() <= CSSValueUltraExpanded))
return CSSPropertyParserHelpers::ConsumeIdent(range);
return nullptr;
}
CSSValue* CSSPropertyFontUtils::ConsumeFontStretch(
CSSParserTokenRange& range,
const CSSParserMode& parser_mode) {
CSSIdentifierValue* parsed_keyword = ConsumeFontStretchKeywordOnly(range);
if (parsed_keyword)
return parsed_keyword;
CSSPrimitiveValue* start_percent =
CSSPropertyParserHelpers::ConsumePercent(range, kValueRangeNonNegative);
if (!start_percent || start_percent->GetFloatValue() <= 0)
return nullptr;
// In a non-font-face context, more than one percentage is not allowed.
if (parser_mode != kCSSFontFaceRuleMode || range.AtEnd())
return start_percent;
CSSPrimitiveValue* end_percent =
CSSPropertyParserHelpers::ConsumePercent(range, kValueRangeNonNegative);
if (!end_percent || end_percent->GetFloatValue() <= 0)
return nullptr;
return CombineToRangeListOrNull(start_percent, end_percent);
}
CSSValue* CSSPropertyFontUtils::ConsumeFontWeight(
CSSParserTokenRange& range,
const CSSParserMode& parser_mode) {
const CSSParserToken& token = range.Peek();
if (token.Id() >= CSSValueNormal && token.Id() <= CSSValueLighter)
return CSSPropertyParserHelpers::ConsumeIdent(range);
// Avoid consuming the first zero of font: 0/0; e.g. in the Acid3 test. In
// font:0/0; the first zero is the font size, the second is the line height.
// In font: 100 0/0; we should parse the first 100 as font-weight, the 0
// before the slash as font size. We need to peek and check the token in order
// to avoid parsing a 0 font size as a font-weight. If we call ConsumeNumber
// straight away without Peek, then the parsing cursor advances too far and we
// parsed font-size as font-weight incorrectly.
if (token.GetType() == kNumberToken &&
(token.NumericValue() < 1 || token.NumericValue() > 1000))
return nullptr;
CSSPrimitiveValue* start_weight =
CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
if (!start_weight || start_weight->GetFloatValue() < 1 ||
start_weight->GetFloatValue() > 1000)
return nullptr;
// In a non-font-face context, more than one number is not allowed. Return
// what we have. If there is trailing garbage, the AtEnd() check in
// CSSPropertyParser::ParseValueStart will catch that.
if (parser_mode != kCSSFontFaceRuleMode || range.AtEnd())
return start_weight;
CSSPrimitiveValue* end_weight =
CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
if (!end_weight || end_weight->GetFloatValue() < 1 ||
end_weight->GetFloatValue() > 1000)
return nullptr;
return CombineToRangeListOrNull(start_weight, end_weight);
}
// TODO(bugsnash): move this to the FontFeatureSettings API when it is no longer
// being used by methods outside of the API
CSSValue* CSSPropertyFontUtils::ConsumeFontFeatureSettings(
CSSParserTokenRange& range) {
if (range.Peek().Id() == CSSValueNormal)
return CSSPropertyParserHelpers::ConsumeIdent(range);
CSSValueList* settings = CSSValueList::CreateCommaSeparated();
do {
CSSFontFeatureValue* font_feature_value =
CSSPropertyFontUtils::ConsumeFontFeatureTag(range);
if (!font_feature_value)
return nullptr;
settings->Append(*font_feature_value);
} while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
return settings;
}
CSSFontFeatureValue* CSSPropertyFontUtils::ConsumeFontFeatureTag(
CSSParserTokenRange& range) {
// Feature tag name consists of 4-letter characters.
static const unsigned kTagNameLength = 4;
const CSSParserToken& token = range.ConsumeIncludingWhitespace();
// Feature tag name comes first
if (token.GetType() != kStringToken)
return nullptr;
if (token.Value().length() != kTagNameLength)
return nullptr;
AtomicString tag = token.Value().ToAtomicString();
for (unsigned i = 0; i < kTagNameLength; ++i) {
// Limits the range of characters to 0x20-0x7E, following the tag name rules
// defined in the OpenType specification.
UChar character = tag[i];
if (character < 0x20 || character > 0x7E)
return nullptr;
}
int tag_value = 1;
// Feature tag values could follow: <integer> | on | off
if (range.Peek().GetType() == kNumberToken &&
range.Peek().GetNumericValueType() == kIntegerValueType &&
range.Peek().NumericValue() >= 0) {
tag_value = clampTo<int>(range.ConsumeIncludingWhitespace().NumericValue());
if (tag_value < 0)
return nullptr;
} else if (range.Peek().Id() == CSSValueOn ||
range.Peek().Id() == CSSValueOff) {
tag_value = range.ConsumeIncludingWhitespace().Id() == CSSValueOn;
}
return CSSFontFeatureValue::Create(tag, tag_value);
}
CSSIdentifierValue* CSSPropertyFontUtils::ConsumeFontVariantCSS21(
CSSParserTokenRange& range) {
return CSSPropertyParserHelpers::ConsumeIdent<CSSValueNormal,
CSSValueSmallCaps>(range);
}
} // namespace blink
|
9fbf011bd6890fd7ac458a4a12ecf7259d945fdc
|
52cfe058dcf70c85eb789a17b3f86e355686743b
|
/Source/Synth/GPNetwork.cpp
|
5419f01d728961226b2b2cc49d05ad91ba246cba
|
[] |
no_license
|
idaohang/gpsynth
|
eeff8bd6322bff2ac89799b578e57d4ad55e60dc
|
aa15c191988bd2a0ec81bf7cea595aa689b07956
|
refs/heads/master
| 2020-12-11T07:46:13.190957
| 2013-10-03T05:59:30
| 2013-10-03T05:59:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,442
|
cpp
|
GPNetwork.cpp
|
/*
==============================================================================
GPNetwork.cpp
Created: 6 Feb 2013 11:05:02am
Author: cdonahue
==============================================================================
*/
#include "GPNetwork.h"
/*
============
CONSTRUCTION
============
*/
GPNetwork::GPNetwork(GPNode* r, std::string o) :
ID(-1), origin(o), height(-1), fitness(-1),
minimum((-1) * std::numeric_limits<float>::infinity()), maximum(std::numeric_limits<float>::infinity()),
traced(false), preparedToRender(false),
renderRoot(new SilenceNode()), root(r), allNodes(0), allMutatableParams(0)
{
}
GPNetwork::GPNetwork(GPRandom* rng, std::string netstring) :
ID(-1), origin("string"), height(-1), fitness(-1),
minimum((-1) * std::numeric_limits<float>::infinity()), maximum(std::numeric_limits<float>::infinity()),
traced(false), preparedToRender(false),
renderRoot(new SilenceNode()), allNodes(0), allMutatableParams(0)
{
root = createNode(netstring, rng);
}
GPNetwork::~GPNetwork() {
if (!preparedToRender) {
delete root;
}
delete renderRoot;
}
GPNetwork* GPNetwork::getCopy(std::string neworigin) {
GPNetwork* copy = new GPNetwork(root->getCopy(), neworigin);
return copy;
}
/*
===========
EXAMINATION
===========
*/
void GPNetwork::evaluateBlockPerformance(unsigned firstFrameNumber, unsigned numSamples, float* sampleTimes, unsigned numConstantVariables, float* constantVariables, float* buffer) {
renderRoot->evaluateBlockPerformance(firstFrameNumber, numSamples, sampleTimes, numConstantVariables, constantVariables, buffer);
}
std::string GPNetwork::toString(unsigned precision) {
std::stringstream ss;
ss.precision(precision);
root->toString(ss);
return ss.str();
}
GPNode* GPNetwork::getRoot() {
return root;
}
bool GPNetwork::equals(GPNetwork* other, unsigned precision) {
return toString(precision).compare(other->toString(precision)) == 0;
}
GPNode* GPNetwork::getRandomNetworkNode(GPRandom* r) {
assert(traced = true);
return allNodes[r->random(allNodes.size())];
}
std::vector<GPMutatableParam*>* GPNetwork::getAllMutatableParams() {
assert(traced = true);
return &allMutatableParams;
}
/*
=======
HELPERS
=======
*/
void GPNetwork::traceNetwork() {
allNodes.clear();
allMutatableParams.clear();
root->trace(&allNodes, &allMutatableParams, NULL, &height, 0);
traced = true;
}
// renderRoot = silence and root = realroot whenever preparedToRender is false
// renderRoot = realroot and root = realroot whenever preparedToRender is true
void GPNetwork::prepareToRender(float sr, unsigned blockSize, unsigned maxNumFrames, float maxTime) {
doneRendering();
if (!preparedToRender) {
delete renderRoot;
}
root->setRenderInfo(sr, blockSize, maxNumFrames, maxTime);
renderRoot = root;
preparedToRender = true;
updateMutatedParams();
}
// only changed the params
void GPNetwork::updateMutatedParams() {
assert(preparedToRender);
root->updateMutatedParams();
minimum = root->minimum;
maximum = root->maximum;
}
void GPNetwork::doneRendering() {
if (preparedToRender) {
root->doneRendering();
minimum = (-1) * std::numeric_limits<float>::infinity();
maximum = std::numeric_limits<float>::infinity();
renderRoot = new SilenceNode();
preparedToRender = false;
}
}
/*
This method replaces the subtree rooted at node old with node new's
*/
void GPNetwork::replaceSubtree(GPNode* old, GPNode* nu) {
// handle root case
if (old == root) {
root = nu;
}
else {
// replace parent-child links
bool replacedLink = false;
for (unsigned i = 0; i < old->parent->arity; i++) {
if (old->parent->descendants[i] == old) {
old->parent->descendants[i] = nu;
replacedLink = true;
}
}
if (!replacedLink)
std::cerr << "Bad parent-child links detected during subtree replacement." << std::endl;
}
/*
// assign nu parent pointer
nu->parent = old->parent;
*/
traced = false;
}
void GPNetwork::ephemeralRandom(GPRandom* r) {
root->ephemeralRandom(r);
}
// method to compare networks by identification
bool compareNetworksByID(GPNetwork* one, GPNetwork* two) {
return one->ID < two->ID;
}
|
81af23850e02d110759e15a332b8dba331113a02
|
b9a6e74c99728874dc9ba7bbb705ad76d01394ea
|
/Castlevania/SecretBrick.h
|
b1b144bd923d08cbefb6ad88bf17c39c60753260
|
[] |
no_license
|
tudautroccuto741/Castlevania
|
ce416f28d9fbf4179afbf4d71e3b473cd9de566f
|
28417f18151ff6cca8376d5784dcdbb968657172
|
refs/heads/master
| 2021-04-10T15:06:07.032534
| 2020-08-07T12:59:22
| 2020-08-07T12:59:22
| 248,913,413
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 467
|
h
|
SecretBrick.h
|
#pragma once
#include "GameObject.h"
#include "Animations.h"
#define SECRET_BRICK_BBOX_WIDTH 32
#define SECRET_BRICK_BBOX_HEIGHT 32
#define CANNOT_BE_HIT_TIME 200
enum class SecretBrickAniID
{
idle = 4011
};
class CSecretBrick : public CGameObject
{
static DWORD cannot_be_hit_start;
public:
void GetBoundingBox(float &left, float &top, float &right, float &bottom) override;
void Destroy() override;
void BeHit(int damage) override;
CSecretBrick();
};
|
cec9f078e4a528e78f0cc6233bac59ce5eed65f3
|
fe2836176ca940977734312801f647c12e32a297
|
/LeetCode/old/PrepForGoogleInterview2018/C++/first/102.cpp
|
ff19703c7c44b14041c304a3ada32e17a2cb8ea0
|
[] |
no_license
|
henrybear327/Sandbox
|
ef26d96bc5cbcdc1ce04bf507e19212ca3ceb064
|
d77627dd713035ab89c755a515da95ecb1b1121b
|
refs/heads/master
| 2022-12-25T16:11:03.363028
| 2022-12-10T21:08:41
| 2022-12-10T21:08:41
| 53,817,848
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,918
|
cpp
|
102.cpp
|
// clang-format -style=LLVM -i *.cpp && astyle --style=linux *.cpp && rm *.orig
// && g++ -Wall -Wextra -std=c++11 ...
#include <bits/stdc++.h>
using namespace std;
static int initialSetup = []()
{
// toggle off cout & cin, instead, use printf & scanf
std::ios::sync_with_stdio(false);
// untie cin & cout
cin.tie(NULL);
return 0;
}
();
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
vector<vector<int>> levelOrder(TreeNode *root)
{
vector<vector<int>> ans;
if (root == NULL)
return ans;
queue<TreeNode *> q;
q.push(root);
vector<int> level;
level.push_back(root->val);
ans.push_back(level);
while (q.size() > 0) {
int level_size = q.size();
level.clear();
for (int i = 0; i < level_size; i++) {
TreeNode *cur = q.front();
q.pop();
if (cur->left) {
q.push(cur->left);
level.push_back(cur->left->val);
}
if (cur->right) {
q.push(cur->right);
level.push_back(cur->right->val);
}
}
if (level.size() > 0)
ans.push_back(level);
}
return ans;
}
};
// class Solution
// {
// public:
// vector<vector<int>> levelOrder(TreeNode *root)
// {
// queue<TreeNode *> q;
// vector<vector<int>> ans;
// unordered_map<TreeNode *, pair<int, int>> level;
// if (root == NULL)
// return ans;
// q.push(root);
// level[root] = make_pair(0, 0);
// int mx = 0;
// int timer = 1;
// while (q.size() > 0) {
// TreeNode *cur = q.front();
// q.pop();
// if (cur->left) {
// level[cur->left] =
// make_pair(level[cur].first + 1, timer++); // level,
// timestamp
// mx = max(mx, level[cur->left].first);
// q.push(cur->left);
// }
// if (cur->right) {
// level[cur->right] = make_pair(level[cur].first + 1, timer++);
// mx = max(mx, level[cur->right].first);
// q.push(cur->right);
// }
// }
// for (int i = 0; i <= mx; i++) {
// vector<int> tmp;
// ans.push_back(tmp);
// }
// map<pair<int, int>, int> levelOrder;
// for (auto i : level) {
// levelOrder[i.second] = i.first->val;
// }
// for (auto i : levelOrder) {
// ans[i.first.first].push_back(i.second);
// }
// return ans;
// }
// };
int main()
{
return 0;
}
|
52e992e6243ba829128bd3f8b08fa32da632e07d
|
db3f82897530b15aa2015c527dcf40700d88be48
|
/Lockon/Src/WorldGeneral/wQuaternion.h
|
553d34d51c433b53f9874f263931e9f46393395a
|
[] |
no_license
|
VahidHeidari/ReverseEngineering
|
2eff32d4d49b560311c29cea06352d28d32c86ca
|
04f915c3009bdd59eddd53793256574c1b0b4d1b
|
refs/heads/master
| 2021-01-11T08:32:53.721706
| 2017-07-18T04:08:10
| 2017-07-18T04:08:10
| 76,719,008
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 576
|
h
|
wQuaternion.h
|
#ifndef WQUATERNION_H_
#define WQUATERNION_H_
class wQuaternion
{
public: __thiscall wQuaternion::wQuaternion(class wQuaternion const &)
public: __thiscall wQuaternion::wQuaternion(void)
public: virtual __thiscall wQuaternion::~wQuaternion(void)
public: class wQuaternion & __thiscall wQuaternion::operator=(class wQuaternion const &)
public: virtual class Quaternion __thiscall wQuaternion::GetValue(double)
const wQuaternion::`vftable'
};
class EagleDynamics::Common::Serializer & __cdecl operator<<(class EagleDynamics::Common::Serializer &,class wQuaternion &)
#endif
|
c44298bdf0d690594e534cc7672a4db85f07b810
|
2efc1d8fbe93a40ee7b1fb6e37230bc5bc2340c8
|
/Coding Question 02 - Finding Primes/Coding Question 02 - Finding Primes/main.cpp
|
5170c90d414b7c9f892d664e5655af2ce6d07142
|
[] |
no_license
|
jameswang27/Challenge-Questions
|
d6901d45fd7e4523d4f5865e0014c1c6da110bbc
|
7c620569826ed979b1c7904cd9b1457eb0c53144
|
refs/heads/master
| 2021-01-10T10:34:09.819645
| 2016-01-24T08:16:16
| 2016-01-24T08:16:16
| 50,227,599
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,656
|
cpp
|
main.cpp
|
//Intuit Coding Question 02
/*
Find the 3rd, 58th and 10,001th prime number.
*/
/*
We will try to solve this problem quickly by taking advantage of some properties of prime numbers.
Note that the answers that the algorithm produces should be, according to Wolfram Alpha:
-3rd: 5
-58th: 271
-10,001th: 104743
Important Observations:
All composite numbers can be prime factorized into prime numbers
Once we test 2 agains the prime, we no longer need to test other even numbers
If n is the number we're checking, we can check up to the floor of the square root of n. This is because it's divisor pair would have appeared
earlier if a number larger than this max is a divisor.
*/
#include <assert.h> //For test cases
#include <iostream> //For cout
#include <math.h> //For sqrt and floor
#include <vector>
using namespace std;
bool isPrime(int num, vector<long>& primes);
int main()
{
vector<long> data;
int count = 1;
//Find up to the 10001th prime number
while(data.size() < 10001) //Have this second number be the prime that you want to find + 1. The nth prime number is in the n-1th spot in the vector.
{
isPrime(count, data);
count++;
}
//Print the prime numbers that we found
cout << "The 3rd prime number is: " << data[2] << endl;
cout << "The 58th prime number is: " << data[57] << endl;
cout << "The 10001st prime number is: " << data[10000] << endl;
cout << "Finished" << endl;
}
/*
Purpose: Find if a number is prime.
Functionality:
Parameters:
-int num: integer to be checked
Return value: a boolean that indicates if the integer checked was a prime or not.
*/
bool isPrime(int num, vector<long>& primes)
{
if (num == 1) return false; //1 is not a prime number
if (num == 2) //2 is the only even prime number
{
primes.push_back(num);
return true;
}
//if (num % 2 == 0) return false; //If the number is divisible by 2 we can immediately return false, 2 is the only prime even number
int last = floor(sqrt(num)); //This is the last int we need to check as a divisor. It should contain the floor of the sqrt of num.
//Begin at 3 because we definitely don't need to check 1, and we've already checked 2
//Because we checked 2, we no longer need to check potential even divisors because those would in turn be divisible by 2
for (size_t i = 0; i < primes.size(); i++)
{
if (primes[i] > last)
{
primes.push_back(num);
return true;
}
if (num % primes[i] == 0) return false;
}
primes.push_back(num);
return true; //If it makes it this far, then there was no proper divisor and the number is indeed prime
}
|
4a890dc7ee1978c7910cea3ea1d51287f356a2e7
|
d6d6893f488941edfc5d244221583c63572d9d5f
|
/test/src/math/test_vecmat.cpp
|
c5baff4ff7b50a7ce91c48f95369239e976afc55
|
[
"Unlicense"
] |
permissive
|
scp-fs2open/fs2open.github.com
|
4170cc58b92577b41308a9e6343dd3fc3fb7a074
|
865f7e725c7a4d9c0b209a49ed0cbd8dc45e8ae7
|
refs/heads/master
| 2023-08-29T11:29:27.822804
| 2023-08-27T20:33:28
| 2023-08-27T20:33:28
| 7,700,081
| 382
| 311
|
NOASSERTION
| 2023-09-14T15:49:22
| 2013-01-19T06:10:53
|
C++
|
UTF-8
|
C++
| false
| false
| 18,330
|
cpp
|
test_vecmat.cpp
|
#include <gtest/gtest.h>
#include <math/vecmat.h>
#include <math/staticrand.h>
#include <utils/Random.h>
#include "util/FSTestFixture.h"
using Random = util::Random;
// "Correct" answers for matrix functions provided by Wolfram Mathematica 11
// Vector function tests oringially made by The_E
const matrix uninvertable = {{{{{{1.0f, 1.0f, 1.0f}}}, {{{1.0f, 1.0f, 1.0f}}}, {{{1.0f, 1.0f, 1.0f}}}}}};
const matrix input1 = {{{{{{4509.0f, 8600.0f, 5523.0f}}}, {{{5276.0f, 668.0f, 462.0f}}}, {{{145.0f, 8490.0f, 5111.0f}}}}}};
const matrix input2 = {{{{{{0.7703f, 0.8180f, 0.8535f}}}, {{{0.6409f, 0.0125f, 0.1777f}}}, {{{0.3785f, 0.0090f, 0.3851f}}}}}};
const matrix input3 = {{{{{{0.5118f, 27.86f, 1.0f}}}, {{{0.0f, 777.2f, 0.0596f}}}, {{{2.5f, 67.95f, 0.0058f}}}}}};
#define EXPECT_MATRIX_NEAR(out,matrix) EXPECT_NEAR(error(&out,matrix), 0.0f, 0.001f);
matrix make_matrix(float a, float b, float c, float d, float e, float f, float g, float h, float i) {
matrix out = { {{{{{a, b, c}}}, {{{d, e, f}}}, {{{g, h, i}}}}} };
return out;
}
float error(matrix* val, matrix target) {
float totalError = 0;
for (int i = 0; i < 9; i++) {
float diff = val->a1d[i] - target.a1d[i];
totalError += diff * diff;
}
return totalError;
}
class VecmatTest : public test::FSTestFixture {
public:
VecmatTest() : test::FSTestFixture() { pushModDir("vecmat"); }
protected:
void SetUp() override
{
test::FSTestFixture::SetUp();
Random::seed(1);
}
void TearDown() override { test::FSTestFixture::TearDown(); }
};
TEST_F(VecmatTest, matrixInvert) {
matrix out;
matrix out2;
// make sure inverts work, of course
EXPECT_TRUE(vm_inverse_matrix(&out, &input2));
EXPECT_MATRIX_NEAR(out, make_matrix(
-0.0223985f, 2.1415f, -0.938528f,
1.25112f, 0.184007f, -2.85778f,
-0.00722484f, -2.1091f, 3.58596f));
//make sure multiplying by the original gives you the identity
vm_matrix_x_matrix(&out2, &out, &input2);
EXPECT_MATRIX_NEAR(out2, vmd_identity_matrix);
// make sure order doesn't matter
vm_matrix_x_matrix(&out2, &input2, &out);
EXPECT_MATRIX_NEAR(out2, vmd_identity_matrix);
//make sure inverting twice gets you back where you started
EXPECT_TRUE(vm_inverse_matrix(&out2, &out));
EXPECT_MATRIX_NEAR(out2, input2);
//make sure uninvertable matrices give you false and a zero matrix
EXPECT_FALSE(vm_inverse_matrix(&out, &uninvertable));
EXPECT_MATRIX_NEAR(out, vmd_zero_matrix);
}
TEST_F(VecmatTest, matrixAdd) {
matrix out;
vm_matrix_add(&out, &input1, &input2);
EXPECT_MATRIX_NEAR(out, make_matrix(
4509.77f, 8600.82f, 5523.85f,
5276.64f, 668.013f, 462.178f,
145.379f, 8490.01f, 5111.39f));
vm_matrix_add(&out, &out, &input3);
EXPECT_MATRIX_NEAR(out, make_matrix(
4510.28f, 8628.68f, 5524.85f,
5276.64f, 1445.21f, 462.237f,
147.879f, 8557.96f, 5111.39f));
vm_matrix_add(&out, &input2, &input3);
EXPECT_MATRIX_NEAR(out, make_matrix(
1.2821f, 28.678f, 1.8535f,
0.6409f, 777.213f, 0.2373f,
2.8785f, 67.959f, 0.3909f));
}
TEST_F(VecmatTest, matrixSub) {
matrix out;
vm_matrix_sub(&out, &input1, &input2);
EXPECT_MATRIX_NEAR(out, make_matrix(
4508.23f, 8599.18f, 5522.15f,
5275.36f, 667.988f, 461.822f,
144.622f, 8489.99f, 5110.61f));
vm_matrix_sub(&out, &out, &input3);
EXPECT_MATRIX_NEAR(out, make_matrix(
4507.72f, 8571.32f, 5521.15f,
5275.36f, -109.213f, 461.763f,
142.122f, 8422.04f, 5110.61f));
vm_matrix_sub(&out, &input2, &input3);
EXPECT_MATRIX_NEAR(out, make_matrix(
0.2585f, -27.042f, -0.1465f,
0.6409f, -777.188f, 0.1181f,
-2.1215f, -67.941f, 0.3793f));
}
TEST_F(VecmatTest, matrixAdd2) {
matrix out;
out = input1;
vm_matrix_add2(&out, &input2);
EXPECT_MATRIX_NEAR(out, make_matrix(
4509.77f, 8600.82f, 5523.85f,
5276.64f, 668.013f, 462.178f,
145.379f, 8490.01f, 5111.39f));
vm_matrix_add2(&out, &input3);
EXPECT_MATRIX_NEAR(out, make_matrix(
4510.28f, 8628.68f, 5524.85f,
5276.64f, 1445.21f, 462.237f,
147.879f, 8557.96f, 5111.39f));
out = input2;
vm_matrix_add2(&out, &input3);
EXPECT_MATRIX_NEAR(out, make_matrix(
1.2821f, 28.678f, 1.8535f,
0.6409f, 777.213f, 0.2373f,
2.8785f, 67.959f, 0.3909f));
}
TEST_F(VecmatTest, matrixSub2) {
matrix out;
out = input1;
vm_matrix_sub2(&out, &input2);
EXPECT_MATRIX_NEAR(out, make_matrix(
4508.23f, 8599.18f, 5522.15f,
5275.36f, 667.988f, 461.822f,
144.622f, 8489.99f, 5110.61f));
vm_matrix_sub2(&out, &input3);
EXPECT_MATRIX_NEAR(out, make_matrix(
4507.72f, 8571.32f, 5521.15f,
5275.36f, -109.213f, 461.763f,
142.122f, 8422.04f, 5110.61f));
out = input2;
vm_matrix_sub2(&out, &input3);
EXPECT_MATRIX_NEAR(out, make_matrix(
0.2585f, -27.042f, -0.1465f,
0.6409f, -777.188f, 0.1181f,
-2.1215f, -67.941f, 0.3793f));
}
TEST_F(VecmatTest, test_vm_vec_add)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v2, v3;
static_randvec_unnormalized(Random::next(), &v1);
static_randvec_unnormalized(Random::next(), &v2);
vm_vec_add(&v3, &v1, &v2);
for (size_t i = 0; i < 3; ++i) {
auto value1 = v1.a1d[i];
auto value2 = v2.a1d[i];
auto value3 = v3.a1d[i];
ASSERT_FLOAT_EQ(value3, value1 + value2);
}
}
}
TEST_F(VecmatTest, test_vm_vec_sub)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v2, v3;
static_randvec_unnormalized(Random::next(), &v1);
static_randvec_unnormalized(Random::next(), &v2);
vm_vec_sub(&v3, &v1, &v2);
for (size_t i = 0; i < 3; ++i) {
auto value1 = v1.a1d[i];
auto value2 = v2.a1d[i];
auto value3 = v3.a1d[i];
ASSERT_FLOAT_EQ(value3, value1 - value2);
}
}
}
TEST_F(VecmatTest, test_vm_vec_add2)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v2, v1backup;
static_randvec_unnormalized(Random::next(), &v1);
static_randvec_unnormalized(Random::next(), &v2);
v1backup.xyz = v1.xyz;
vm_vec_add2(&v1, &v2);
for (size_t i = 0; i < 3; ++i) {
auto value1 = v1.a1d[i];
auto value2 = v2.a1d[i];
auto value3 = v1backup.a1d[i];
ASSERT_FLOAT_EQ(value1, value2 + value3);
}
}
}
TEST_F(VecmatTest, test_vm_vec_sub2)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v2, v1backup;
static_randvec_unnormalized(Random::next(), &v1);
static_randvec_unnormalized(Random::next(), &v2);
v1backup.xyz = v1.xyz;
vm_vec_sub2(&v1, &v2);
for (size_t i = 0; i < 3; ++i) {
auto value1 = v1.a1d[i];
auto value2 = v2.a1d[i];
auto value1Backup = v1backup.a1d[i];
ASSERT_FLOAT_EQ(value1, value1Backup - value2);
}
}
}
TEST_F(VecmatTest, test_vm_vec_avg)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d vArray[2];
vec3d vAvg;
for (size_t i = 0; i < 2; i++) {
static_randvec_unnormalized(Random::next(), &vArray[i]);
}
vm_vec_avg(&vAvg, &vArray[0], &vArray[1]);
float accX = 0.0f, accY = 0.0f, accZ = 0.0f;
for (size_t i = 0; i < 2; ++i) {
accX += vArray[i].xyz.x;
accY += vArray[i].xyz.y;
accZ += vArray[i].xyz.z;
}
accX /= 2;
accY /= 2;
accZ /= 2;
ASSERT_FLOAT_EQ(vAvg.xyz.x, accX);
ASSERT_FLOAT_EQ(vAvg.xyz.y, accY);
ASSERT_FLOAT_EQ(vAvg.xyz.z, accZ);
}
}
TEST_F(VecmatTest, test_vm_vec_avg3)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d vArray[3];
vec3d vAvg;
for (size_t i = 0; i < 3; i++) {
static_randvec_unnormalized(Random::next(), &vArray[i]);
}
vm_vec_avg3(&vAvg, &vArray[0], &vArray[1], &vArray[2]);
float accX = 0.0f, accY = 0.0f, accZ = 0.0f;
for (size_t i = 0; i < 3; ++i) {
accX += vArray[i].xyz.x;
accY += vArray[i].xyz.y;
accZ += vArray[i].xyz.z;
}
accX /= 3;
accY /= 3;
accZ /= 3;
ASSERT_FLOAT_EQ(vAvg.xyz.x, accX);
ASSERT_FLOAT_EQ(vAvg.xyz.y, accY);
ASSERT_FLOAT_EQ(vAvg.xyz.z, accZ);
}
}
TEST_F(VecmatTest, test_vm_vec_avg4)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d vArray[4];
vec3d vAvg;
for (size_t i = 0; i < 4; i++) {
static_randvec_unnormalized(Random::next(), &vArray[i]);
}
vm_vec_avg4(&vAvg, &vArray[0], &vArray[1], &vArray[2], &vArray[3]);
float accX = 0.0f, accY = 0.0f, accZ = 0.0f;
for (size_t i = 0; i < 4; ++i) {
accX += vArray[i].xyz.x;
accY += vArray[i].xyz.y;
accZ += vArray[i].xyz.z;
}
accX /= 4;
accY /= 4;
accZ /= 4;
ASSERT_FLOAT_EQ(vAvg.xyz.x, accX);
ASSERT_FLOAT_EQ(vAvg.xyz.y, accY);
ASSERT_FLOAT_EQ(vAvg.xyz.z, accZ);
}
}
TEST_F(VecmatTest, test_vm_vec_avg_n)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d vArray[1000];
vec3d vAvg;
for (size_t i = 0; i < 1000; i++) {
static_randvec_unnormalized(Random::next(), &vArray[i]);
}
vm_vec_avg_n(&vAvg, 1000, vArray);
float accX = 0.0f, accY = 0.0f, accZ = 0.0f;
for (size_t i = 0; i < 1000; ++i) {
accX += vArray[i].xyz.x;
accY += vArray[i].xyz.y;
accZ += vArray[i].xyz.z;
}
accX /= 1000;
accY /= 1000;
accZ /= 1000;
ASSERT_FLOAT_EQ(vAvg.xyz.x, accX);
ASSERT_FLOAT_EQ(vAvg.xyz.y, accY);
ASSERT_FLOAT_EQ(vAvg.xyz.z, accZ);
}
}
TEST_F(VecmatTest, test_vm_vec_scale)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v1Unscaled;
static_randvec_unnormalized(Random::next(), &v1);
v1Unscaled.xyz = v1.xyz;
auto rand_scale = static_randf(Random::next());
vm_vec_scale(&v1, rand_scale);
ASSERT_FLOAT_EQ(v1.xyz.x, v1Unscaled.xyz.x * rand_scale);
ASSERT_FLOAT_EQ(v1.xyz.y, v1Unscaled.xyz.y * rand_scale);
ASSERT_FLOAT_EQ(v1.xyz.z, v1Unscaled.xyz.z * rand_scale);
}
}
TEST_F(VecmatTest, test_vm_vec4_scale)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec4 v1, v1Unscaled;
for (size_t i = 0; i < 4; ++i) {
v1.a1d[i] = static_randf(Random::next());
v1Unscaled.a1d[i] = v1.a1d[i];
}
auto rand_scale = static_randf(Random::next());
vm_vec_scale(&v1, rand_scale);
ASSERT_FLOAT_EQ(v1.xyzw.x, v1Unscaled.xyzw.x * rand_scale);
ASSERT_FLOAT_EQ(v1.xyzw.y, v1Unscaled.xyzw.y * rand_scale);
ASSERT_FLOAT_EQ(v1.xyzw.z, v1Unscaled.xyzw.z * rand_scale);
ASSERT_FLOAT_EQ(v1.xyzw.w, v1Unscaled.xyzw.w * rand_scale);
}
}
TEST_F(VecmatTest, test_vm_vec_copy_scale)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v1Unscaled, v2;
static_randvec_unnormalized(Random::next(), &v1);
v1Unscaled.xyz = v1.xyz;
auto rand_scale = static_randf(Random::next());
vm_vec_copy_scale(&v2, &v1, rand_scale);
ASSERT_FLOAT_EQ(v2.xyz.x, v1Unscaled.xyz.x * rand_scale);
ASSERT_FLOAT_EQ(v2.xyz.y, v1Unscaled.xyz.y * rand_scale);
ASSERT_FLOAT_EQ(v2.xyz.z, v1Unscaled.xyz.z * rand_scale);
}
}
TEST_F(VecmatTest, test_vm_vec_scale_add)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v2, v3;
static_randvec_unnormalized(Random::next(), &v1);
static_randvec_unnormalized(Random::next(), &v2);
auto rand_scale = static_randf(Random::next());
vm_vec_scale_add(&v3, &v1, &v2, rand_scale);
ASSERT_FLOAT_EQ(v3.xyz.x, v1.xyz.x + (rand_scale * v2.xyz.x));
ASSERT_FLOAT_EQ(v3.xyz.y, v1.xyz.y + (rand_scale * v2.xyz.y));
ASSERT_FLOAT_EQ(v3.xyz.z, v1.xyz.z + (rand_scale * v2.xyz.z));
}
}
TEST_F(VecmatTest, test_vm_vec_scale_sub)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v2, v3;
static_randvec_unnormalized(Random::next(), &v1);
static_randvec_unnormalized(Random::next(), &v2);
auto rand_scale = static_randf(Random::next());
vm_vec_scale_sub(&v3, &v1, &v2, rand_scale);
ASSERT_FLOAT_EQ(v3.xyz.x, v1.xyz.x - (rand_scale * v2.xyz.x));
ASSERT_FLOAT_EQ(v3.xyz.y, v1.xyz.y - (rand_scale * v2.xyz.y));
ASSERT_FLOAT_EQ(v3.xyz.z, v1.xyz.z - (rand_scale * v2.xyz.z));
}
}
TEST_F(VecmatTest, test_vm_vec_scale_add2)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v2, v1Unscaled;
static_randvec_unnormalized(Random::next(), &v1);
static_randvec_unnormalized(Random::next(), &v2);
v1Unscaled.xyz = v1.xyz;
auto rand_scale = static_randf(Random::next());
vm_vec_scale_add2(&v1, &v2, rand_scale);
ASSERT_FLOAT_EQ(v1.xyz.x, v1Unscaled.xyz.x + (rand_scale * v2.xyz.x));
ASSERT_FLOAT_EQ(v1.xyz.y, v1Unscaled.xyz.y + (rand_scale * v2.xyz.y));
ASSERT_FLOAT_EQ(v1.xyz.z, v1Unscaled.xyz.z + (rand_scale * v2.xyz.z));
}
}
TEST_F(VecmatTest, test_vm_vec_scale2)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v1Unscaled;
static_randvec_unnormalized(Random::next(), &v1);
v1Unscaled.xyz = v1.xyz;
auto rand_scale_n = static_randf(Random::next());
auto rand_scale_d = static_randf(Random::next());
vm_vec_scale2(&v1, rand_scale_n, rand_scale_d);
ASSERT_FLOAT_EQ(v1.xyz.x, v1Unscaled.xyz.x * (rand_scale_n / rand_scale_d));
ASSERT_FLOAT_EQ(v1.xyz.y, v1Unscaled.xyz.y * (rand_scale_n / rand_scale_d));
ASSERT_FLOAT_EQ(v1.xyz.z, v1Unscaled.xyz.z * (rand_scale_n / rand_scale_d));
}
}
TEST_F(VecmatTest, test_vm_vec_project_parallel)
{
//tests that vm_vec_project_parallel, correctly projects a
//vector onto the unit vectors
//expect that only the component of the respective unit vector remains
vec3d v1;
static_randvec(Random::next(), &v1);
vec3d unit1 = {};
unit1.xyz.x = 1.0f;
vec3d unit2 = {};
unit2.xyz.y = 1.0f;
vec3d unit3 = {};
unit3.xyz.z = 1.0f;
vec3d resx = {};
float magx = vm_vec_projection_parallel(&resx, &v1, &unit1);
ASSERT_FLOAT_EQ(magx, resx.xyz.x);
ASSERT_FLOAT_EQ(resx.xyz.x, v1.xyz.x);
ASSERT_FLOAT_EQ(resx.xyz.y, 0.0f);
ASSERT_FLOAT_EQ(resx.xyz.z, 0.0f);
vec3d resy = {};
float magy = vm_vec_projection_parallel(&resy, &v1, &unit2);
ASSERT_FLOAT_EQ(magy, resy.xyz.y);
ASSERT_FLOAT_EQ(resy.xyz.x, 0.0f);
ASSERT_FLOAT_EQ(resy.xyz.y, v1.xyz.y);
ASSERT_FLOAT_EQ(resy.xyz.z, 0.0f);
vec3d resz = {};
float magz = vm_vec_projection_parallel(&resz, &v1, &unit3);
ASSERT_FLOAT_EQ(magz, resz.xyz.z);
ASSERT_FLOAT_EQ(resz.xyz.x, 0.0f);
ASSERT_FLOAT_EQ(resz.xyz.y, 0.0f);
ASSERT_FLOAT_EQ(resz.xyz.z, v1.xyz.z);
}
TEST_F(VecmatTest, test_vm_vec_project_plane)
{
vec3d v1;
static_randvec(Random::next(), &v1);
vec3d unit1 = {};
unit1.xyz.x = 1.0f;
vec3d unit2 = {};
unit2.xyz.y = 1.0f;
vec3d unit3 = {};
unit3.xyz.z = 1.0f;
vec3d resx = {};
vm_vec_projection_onto_plane(&resx, &v1, &unit1);
ASSERT_FLOAT_EQ(resx.xyz.x, 0.0f);
ASSERT_FLOAT_EQ(resx.xyz.y, v1.xyz.y);
ASSERT_FLOAT_EQ(resx.xyz.z, v1.xyz.z);
vec3d resy = {};
vm_vec_projection_onto_plane(&resy, &v1, &unit2);
ASSERT_FLOAT_EQ(resy.xyz.x, v1.xyz.x);
ASSERT_FLOAT_EQ(resy.xyz.y, 0.0f);
ASSERT_FLOAT_EQ(resy.xyz.z, v1.xyz.z);
vec3d resz = {};
vm_vec_projection_onto_plane(&resz, &v1, &unit3);
ASSERT_FLOAT_EQ(resz.xyz.x, v1.xyz.x);
ASSERT_FLOAT_EQ(resz.xyz.y, v1.xyz.y);
ASSERT_FLOAT_EQ(resz.xyz.z, 0.0f);
}
TEST_F(VecmatTest, test_vm_vec_mag)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v;
static_randvec_unnormalized(Random::next(), &v);
auto magnitude = fl_sqrt((v.xyz.x * v.xyz.x) + (v.xyz.y * v.xyz.y) + (v.xyz.z * v.xyz.z));
ASSERT_FLOAT_EQ(magnitude, vm_vec_mag(&v));
}
}
TEST_F(VecmatTest, test_vm_vec_mag_squared) {
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v;
static_randvec_unnormalized(Random::next(), &v);
auto magnitude = (v.xyz.x * v.xyz.x) + (v.xyz.y * v.xyz.y) + (v.xyz.z * v.xyz.z);
ASSERT_FLOAT_EQ(magnitude, vm_vec_mag_squared(&v));
}
}
TEST_F(VecmatTest, test_vm_vec_dist) {
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v2, t;
static_randvec_unnormalized(Random::next(), &v1);
static_randvec_unnormalized(Random::next(), &v2);
auto distance = vm_vec_dist(&v1, &v2);
vm_vec_sub(&t, &v1, &v2);
auto test_distance = vm_vec_mag(&t);
ASSERT_FLOAT_EQ(distance, test_distance);
}
}
TEST_F(VecmatTest, test_vm_vec_dist_squared)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v2, t;
static_randvec_unnormalized(Random::next(), &v1);
static_randvec_unnormalized(Random::next(), &v2);
auto distance = vm_vec_dist_squared(&v1, &v2);
vm_vec_sub(&t, &v1, &v2);
auto test_distance = vm_vec_mag_squared(&t);
ASSERT_FLOAT_EQ(distance, test_distance);
}
}
TEST_F(VecmatTest, test_vm_vec_normalize)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v, vBackup;
static_randvec_unnormalized(Random::next(), &v);
vBackup.xyz = v.xyz;
auto magnitude = vm_vec_normalize(&v);
auto test_magnitude = vm_vec_mag(&vBackup);
ASSERT_FLOAT_EQ(magnitude, test_magnitude);
auto inverse_magnitude = 1.0f / test_magnitude;
vm_vec_scale(&vBackup, inverse_magnitude);
ASSERT_FLOAT_EQ(v.xyz.x, vBackup.xyz.x);
ASSERT_FLOAT_EQ(v.xyz.y, vBackup.xyz.y);
ASSERT_FLOAT_EQ(v.xyz.z, vBackup.xyz.z);
}
}
TEST_F(VecmatTest, test_vm_vec_copy_normalize)
{
for (size_t loop = 0; loop < 1000; ++loop) {
vec3d v1, v2, vBackup;
static_randvec_unnormalized(Random::next(), &v1);
vBackup.xyz = v1.xyz;
auto magnitude = vm_vec_copy_normalize(&v2, &v1);
ASSERT_FLOAT_EQ(v1.xyz.x, vBackup.xyz.x);
ASSERT_FLOAT_EQ(v1.xyz.y, vBackup.xyz.y);
ASSERT_FLOAT_EQ(v1.xyz.z, vBackup.xyz.z);
auto test_magnitude = vm_vec_mag(&vBackup);
ASSERT_FLOAT_EQ(magnitude, test_magnitude);
auto inverse_magnitude = 1.0f / test_magnitude;
vm_vec_scale(&vBackup, inverse_magnitude);
ASSERT_FLOAT_EQ(v2.xyz.x, vBackup.xyz.x);
ASSERT_FLOAT_EQ(v2.xyz.y, vBackup.xyz.y);
ASSERT_FLOAT_EQ(v2.xyz.z, vBackup.xyz.z);
}
}
TEST_F(VecmatTest, orthogonalize_matrix) {
// V regression test - old version couldn't handle this V
matrix input_matrix = make_matrix(
0.636235237f, -0.0492025875f, -0.769924462f,
-0.513205945f, -0.419860631f, 0.748556376f,
-0.513205945f, -0.419860631f, 0.748556376f);
for (int i = 0; i < 1000; i++) {
matrix hopefully_orthogonal_matrix = input_matrix;
vm_orthogonalize_matrix(&hopefully_orthogonal_matrix);
// Test that the matrix we got is orthogonal
matrix transpose, hopefully_identity;
vm_copy_transpose(&transpose, &hopefully_orthogonal_matrix);
vm_matrix_x_matrix(&hopefully_identity, &transpose, &hopefully_orthogonal_matrix);
EXPECT_MATRIX_NEAR(vmd_identity_matrix, hopefully_identity);
// Test that old_fvec is (approximately) in the span of {new_fvec}
vec3d diff;
vm_vec_cross(&diff, &hopefully_orthogonal_matrix.vec.fvec, &input_matrix.vec.fvec);
EXPECT_LE(vm_vec_mag(&diff), 1e-7);
// Test that old_uvec is (approximately) in the span of {new_fvec, new_uvec} (which we know has new_rvec as normal vector)
float dot = vm_vec_dot(&input_matrix.vec.uvec, &hopefully_orthogonal_matrix.vec.rvec);
EXPECT_NEAR(dot, 0, 1e-7);
for (int j = 0; j < 9; j++)
input_matrix.a1d[j] = frand() - 0.5f;
}
}
|
681cb8613271662b4a585349c7bab03325fe8563
|
e1ce5c1c8e403df3446ea6736803cec795b47ec5
|
/wei-noise-master/11-DiffSamp/src/code/Library/Coordinate.cpp
|
49f6d03fa3b8a9192e81b18c09b8d5296dae4b08
|
[
"MIT"
] |
permissive
|
HannahJHan/BlueNoiseSampling
|
c33f240221dd91843d0033de144adc4a238f69c7
|
1aec7e67f3e84735054ec79c6b477950095942ca
|
refs/heads/master
| 2022-12-31T16:17:48.937577
| 2020-10-20T10:43:32
| 2020-10-20T10:43:32
| 305,656,275
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 78
|
cpp
|
Coordinate.cpp
|
/*
Coordinate.cpp
Li-Yi Wei
07/07/2007
*/
#include "Coordinate.hpp"
|
efea4d4302965ed52fb41d979b01fa14c1d85ac0
|
549a402538164fb88a2711ae1454f413127630c6
|
/src/OrkaImage.cpp
|
fced4dd1931d3dc39502b56ef152bc3b1597313a
|
[] |
no_license
|
vilhelmo/orka
|
f06c6e9f4c49ec50af2d2c993585ba54b323e83c
|
6ba56cf74742b32ea0913dc1b4edc7e1452cd38a
|
refs/heads/master
| 2016-08-04T01:24:24.839916
| 2014-01-12T08:59:48
| 2014-01-12T08:59:48
| 10,898,266
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,451
|
cpp
|
OrkaImage.cpp
|
/*
* OrkaImage.cpp
*
* Created on: Dec 15, 2013
* Author: vilhelm
*/
#include "OrkaImage.h"
#include <QMutexLocker>
#include <string>
#include <thread>
#include <chrono>
#include "OrkaException.h"
namespace orka {
OrkaImage::OrkaImage(std::string filename) :
pixel_data_(NULL), filename_(filename), loaded_(false), height_(0), width_(
0), channels_(0), image_gamma_(1.0) {
load_mutex_ = new QMutex();
}
OrkaImage::OrkaImage(OpenImageIO::ImageCache * cache, std::string filename) :
pixel_data_(NULL), filename_(filename), loaded_(false) {
load_mutex_ = new QMutex();
OpenImageIO::ImageSpec spec;
bool ok = cache->get_imagespec(OpenImageIO::ustring(filename_), spec);
if (!ok) {
throw OrkaException(
std::string("Unable to open image: ") + filename_ + "\nError: "
+ OpenImageIO::geterror());
}
width_ = spec.width;
height_ = spec.height;
channels_ = spec.nchannels;
format_ = spec.format;
if (format_ == OpenImageIO::TypeDesc::HALF) {
format_ = OpenImageIO::TypeDesc::FLOAT;
}
color_space_ = spec.get_string_attribute("oiio:ColorSpace",
"GammaCorrected");
if (color_space_ == "GammaCorrected") {
image_gamma_ = spec.get_float_attribute("oiio:Gamma", 2.2);
} else {
image_gamma_ = 1.0;
}
pixel_data_ = malloc(width_ * height_ * channels_ * format_.elementsize());
ok = cache->get_pixels(OpenImageIO::ustring(filename_), 0, 0, 0, width_, 0,
height_, 0, 1, format_, pixel_data_);
if (!ok) {
throw OrkaException(
std::string("Unable to read image: ") + filename_ + "\nError: "
+ OpenImageIO::geterror());
}
loaded_ = true;
}
OrkaImage::OrkaImage(int width, int height, int channels) :
loaded_(true), width_(width), height_(height), channels_(channels), image_gamma_(
1.0) {
// Used by VLCMovieProvider. Hard-coded to UCHAR format for now.
load_mutex_ = new QMutex();
format_ = OpenImageIO::TypeDesc::UCHAR;
pixel_data_ = malloc(
width_ * height_ * channels_ * sizeof(format_.elementsize()));
}
OrkaImage::OrkaImage(const OrkaImage & other) {
load_mutex_ = new QMutex();
width_ = other.width_;
height_ = other.height_;
channels_ = other.channels_;
filename_ = other.filename_;
loaded_ = other.loaded_;
image_gamma_ = other.image_gamma_;
if (loaded_) {
pixel_data_ = malloc(
width_ * height_ * channels_ * other.format_.elementsize());
memcpy(pixel_data_, other.pixel_data_,
width_ * height_ * channels_ * other.format_.elementsize());
}
}
OrkaImage::~OrkaImage() {
QMutexLocker locker(load_mutex_);
if (loaded_) {
free(pixel_data_);
}
locker.unlock();
}
void OrkaImage::loadImage() {
QMutexLocker locker(load_mutex_);
if (loaded_) {
// Image already loaded.
locker.unlock();
return;
}
// clock_t start = clock();
OpenImageIO::ImageInput * open_image_ = OpenImageIO::ImageInput::open(
filename_);
if (!open_image_) {
throw OrkaException(
std::string("Unable to open image: ") + filename_ + "\nError: "
+ OpenImageIO::geterror());
}
const OpenImageIO::ImageSpec &spec = open_image_->spec();
width_ = spec.width;
height_ = spec.height;
channels_ = spec.nchannels;
format_ = spec.format;
if (format_ == OpenImageIO::TypeDesc::HALF) {
format_ = OpenImageIO::TypeDesc::FLOAT;
}
color_space_ = spec.get_string_attribute("oiio:ColorSpace",
"GammaCorrected");
if (color_space_ == "GammaCorrected") {
image_gamma_ = spec.get_float_attribute("oiio:Gamma", 2.2);
} else {
image_gamma_ = 1.0;
}
pixel_data_ = malloc(width_ * height_ * channels_ * format_.elementsize());
open_image_->read_image(format_, pixel_data_);
open_image_->close();
delete open_image_;
loaded_ = true;
locker.unlock();
// clock_t end = clock();
// std::cout << "read image in " << ((float) end - start) / CLOCKS_PER_SEC
// << " secs." << std::endl;
}
bool OrkaImage::isLoaded() {
bool loaded;
QMutexLocker locker(load_mutex_);
loaded = loaded_;
locker.unlock();
return loaded;
}
void * OrkaImage::getPixels() {
QMutexLocker locker(load_mutex_);
bool loaded = loaded_;
locker.unlock();
if (loaded) {
return pixel_data_;
} else {
return NULL;
}
}
void OrkaImage::freePixels() {
QMutexLocker locker(load_mutex_);
if (loaded_) {
free(pixel_data_);
loaded_ = false;
}
locker.unlock();
}
unsigned int OrkaImage::width() {
QMutexLocker locker(load_mutex_);
bool loaded = loaded_;
locker.unlock();
if (loaded) {
return width_;
} else {
return 0;
}
}
unsigned int OrkaImage::height() {
QMutexLocker locker(load_mutex_);
bool loaded = loaded_;
locker.unlock();
if (loaded) {
return height_;
} else {
return 0;
}
}
unsigned int OrkaImage::channels() {
QMutexLocker locker(load_mutex_);
bool loaded = loaded_;
locker.unlock();
if (loaded) {
return channels_;
} else {
return 0;
}
}
unsigned int OrkaImage::approxSize() {
QMutexLocker locker(load_mutex_);
bool loaded = loaded_;
locker.unlock();
if (loaded) {
return width_ * height_ * channels_ * format_.elementsize();
} else {
return 0;
}
}
GLenum OrkaImage::glType() {
switch (format_.basetype) {
case OpenImageIO::TypeDesc::UCHAR:
return GL_UNSIGNED_BYTE;
break;
case OpenImageIO::TypeDesc::CHAR:
return GL_BYTE;
break;
case OpenImageIO::TypeDesc::USHORT:
return GL_UNSIGNED_SHORT;
break;
case OpenImageIO::TypeDesc::SHORT:
return GL_SHORT;
break;
case OpenImageIO::TypeDesc::UINT:
return GL_UNSIGNED_INT;
break;
case OpenImageIO::TypeDesc::INT:
return GL_INT;
break;
case OpenImageIO::TypeDesc::FLOAT:
return GL_FLOAT;
break;
default:
throw new OrkaException("Unknown oiio to gl format.");
break;
}
return GL_FLOAT;
}
} /* namespace orka */
|
f8f1b69e5b02ae73bac734f0108f7d03b4d00cb0
|
bf9db376540a7e9a9180aef4cae0afc054f12bf5
|
/src/test_cases/c/src/loop_red.cpp
|
cf30d83fbc7f8f509b271903952617ee25460ac0
|
[
"MIT"
] |
permissive
|
Baltoli/He-2
|
ae815d83a1c9b22a358e980c2e63a9aac88b7a99
|
c3b20da61d8e0d4878e530fe26affa2ec4a4e717
|
refs/heads/master
| 2023-01-19T08:01:27.806898
| 2020-11-17T19:37:34
| 2020-11-17T19:37:34
| 299,584,728
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 116
|
cpp
|
loop_red.cpp
|
#include <stdio.h>
int main(){
int limit = 32;
int a = 0;
for(int i=0; i<limit; i++){
a+=i;
}
}
|
e7e21bfd862ea9f3ec0b9cede77ce65210b5a9ed
|
f7c21624103462928c9816df4d2b0b97f28fb439
|
/mohe-sx-game-server/MJShanxi2/LogicServer/Desk.cpp
|
cfcf538ae7cc464aefe93e283cd4c6727d331042
|
[] |
no_license
|
Pircs/lipengServer
|
17e1fc7595e8e55e5b2b7e5f582be062e7713f40
|
1e7c13338eee6398e5ada73d31845aecd9d920d8
|
refs/heads/master
| 2020-09-18T10:33:08.268173
| 2019-10-07T11:13:00
| 2019-10-07T11:13:00
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 79,335
|
cpp
|
Desk.cpp
|
#include "Desk.h"
#include "Work.h"
#include "LLog.h"
#include "Config.h"
#include "RoomVip.h"
#include "UserManager.h"
#include "LogicToggles.h"
#include "..\mhmessage\mhmsghead.h"
Desk::Desk()
{
_clearData();
}
Desk::~Desk()
{
}
bool Desk::initDesk(int iDeskId, GameType gameType)
{
_clearData();
switch (gameType) {
#define XX(k, v, player_count) case v: m_iPlayerCapacity = player_count; break;
ShanXi_GAME_TYPE_MAP(XX)
#undef XX
default:
LLOG_ERROR("Desk::initDesk -- Game type is wrong. Type = %d", gameType);
return false;
}
m_desk_user_count = m_iPlayerCapacity;
if(!_createRegister(gameType))
{
return false;
}
m_id = iDeskId;
LTime cur;
m_timeDeskCreate = cur.Secs();
MHLOG_DESK("****Create desk id:%d game_type:%d, m_iPlayerCapacity:%d", m_id, gameType, m_iPlayerCapacity);
return true;
}
Lint Desk::GetDeskId()
{
return m_id;
}
Lint Desk::GetPlayerCapacity()
{
return m_iPlayerCapacity;
}
void Desk::Tick(LTime& curr)
{
CheckReset();
CheckAutoPlayCard();
if(m_timeDeskCreate && m_deskState == DESK_WAIT) //如果超过8小时还没有开始过就进行解散
{
if(m_vip == NULL || !m_vip->IsBegin()) //如果没有赋值或者没有开始过
{
LTime cur;
Lint iInterval = cur.Secs() - m_timeDeskCreate;
if(iInterval >= (2 * 60 * 60))
{
if (m_deskCreatedType == 1) {
LMsgL2LMGDeleteUserCreatedDesk deleteDeskInfo;
deleteDeskInfo.m_deskId = m_id;
deleteDeskInfo.m_userid = m_creatUserId;
if (m_feeType == 0)
{
deleteDeskInfo.m_cost = m_cost;
}
deleteDeskInfo.m_delType = 2;
gWork.SendToLogicManager(deleteDeskInfo);
}
LLOG_ERROR("The desk(%d) doesn't begin beyond 8 hours", m_id);
ResetEnd();
}
}
{
boost::mutex::scoped_lock l(m_mutexDeskLookonUser);
auto it = m_desk_Lookon_user.begin();
while (it != m_desk_Lookon_user.end())
{
if ((*it)->IsInRoomFor15Second())
{
break;
}
it++;
}
if (it != m_desk_Lookon_user.end())
{
LMsgC2SUserSelectSeat msg;
for (int i = 0; i < m_iPlayerCapacity; i++)
{
if (NULL == m_seatUser[i])
{
msg.m_pos = i;
LLOG_ERROR("Desk allocate empty pos for user. desk:%d, user:%d, pos:%d", m_id, (*it)->GetUserDataId(), i);
this->HanderSelectSeat((*it), &msg);
break;
}
}
}
}
}
}
void Desk::SetAutoPlay( Lint pos, bool bauto, Lint outtime )
{
m_autoPlay[pos] = bauto;
if ( bauto )
{
LTime cur;
m_autoPlayTime[pos] = cur.Secs();
m_autoOutTime[pos] = outtime;
}
}
void Desk::CheckAutoPlayCard()
{
if(m_deskType != DeskType_Coins)
return;
if(m_deskState == DESK_PLAY )
{
LTime cur;
for(int i = 0; i < m_iPlayerCapacity; ++i)
{
if ( !m_user[i] )
{
continue;
}
Lint outtime = m_autoOutTime[i];
if ( outtime > 0 ) // <=0 不给玩家自动操作
{
if ( !m_user[i]->GetOnline() ) // 玩家不在线倒计时短一些
{
outtime = 1;
}
else
{
outtime += DIFFOPOUTTIME; // 服务器的时间要长一些
}
if ( gConfig.GetDebugModel() && m_user[i]->GetUserDataId() >= 10000001 ) // 机器人倒计时
{
outtime = 2;
}
if ( m_autoPlay[i] && cur.Secs() - m_autoPlayTime[i] > outtime )
{
LLOG_DEBUG("Desk::CheckAutoPlayCard [deskid = %d][pos = %d] auto play card",m_id, i);
m_autoPlay[i] = false;
mGameHandler->ProcessAutoPlay(i,m_user[i]);
}
}
}
}
}
void Desk::SetDeskType( DeskType type )
{
m_deskType = type;
}
DeskType Desk::GetDeskType()
{
return m_deskType;
}
void Desk::SetSelectSeat(bool state)
{
m_selectSeat = state;
}
Lint Desk::GetCreatDeskTime()
{
return m_timeDeskCreate;
}
void Desk::SetCreatType(Lint type)
{
m_deskCreatedType = type;
}
Lint Desk::GetCreatType()
{
return m_deskCreatedType;
}
//申请解算房间
void Desk::HanderResutDesk(User* pUser,LMsgC2SResetDesk* msg)
{
LLOG_DEBUG("Logwyz ...................Desk::HanderResutDesk");
if (pUser==NULL)return;
//重复申请
if (m_resetTime != 0)
{
return;
}
//Lint pos = GetUserPos(pUser);
//if(pos == INVAILD_POS)
//{
// return;
//}
if ( (!MHIsRoomUser(pUser) ) && (pUser != m_creatUser ))
{
LLOG_ERROR("Desk::HanderResutDesk pUser not in room and not m_creatUser, userid=[%d]",pUser->GetUserDataId());
return;
}
//Lint pos1=GetUserSeatPos(pUser);
LLOG_ERROR("Desk::HanderResutDesk pUser userid=[%d],GetUserSeatPos(pUser)=[%d]", pUser->GetUserDataId(), GetUserSeatPos(pUser));
//if(pos == INVAILD_POS)
//{
// LLOG_ERROR("Desk::HanderResutDesk pUser not in seatUser, userid=[%d]", pUser->GetUserDataId());
// return;
//}
if(!m_vip || m_deskState == DESK_FREE)
{
LLOG_ERROR("Desk::HanderResutDesk error desk free");
return;
}
if (m_deskState == DESK_PLAY)
{
Lint seatPos=GetUserSeatPos(pUser);
Lint pos=GetUserPos(pUser);
if (seatPos==INVAILD_POS)
{
//LLOG_ERROR("Desk::HanderResutDesk error m_deskState == DESK_PLAY, userid[%d] pos[%d],SeatPos[%d]", pUser->GetUserDataId,pos, seatPos);
return;
}
//将桌子状态设置为解散房间状态
m_deskbeforeState = m_deskState;
//m_deskState = DESK_RESET_ROOM;
memset(m_reset, RESET_ROOM_TYPE_WAIT, sizeof(m_reset));
m_reset[pos] = RESET_ROOM_TYPE_AGREE;
m_resetTime = gWork.GetCurTime().Secs() + 3 * 60;
m_resetUser = pUser->m_userData.m_nike;
m_resetUserId = pUser->m_userData.m_id;
for(Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if (m_user[i] == NULL)
continue;
LMsgS2CResetDesk send;
send.m_errorCode = 0;
send.m_applay = m_resetUser;
send.m_userId = pUser->m_userData.m_id;
send.m_time = m_resetTime - gWork.GetCurTime().Secs();
send.m_flag = m_reset[i] ? 1 : 0;
send.m_userId = pUser->m_userData.m_id;
for (Lint j = 0; j < m_iPlayerCapacity; ++j)
{
if (m_user[j] == NULL)
continue;
if (m_reset[j] == RESET_ROOM_TYPE_AGREE)
{
send.m_agree.push_back(m_user[j]->m_userData.m_nike);
send.m_agreeHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_agreeUserId.push_back(m_user[j]->m_userData.m_id);
}
else if (m_reset[j] == RESET_ROOM_TYPE_WAIT)
{
send.m_wait.push_back(m_user[j]->m_userData.m_nike);
send.m_waitHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_waitUserId.push_back(m_user[j]->m_userData.m_id);
}
else
{
send.m_refluse = m_user[j]->m_userData.m_nike;
}
}
m_user[i]->Send(send);
}
}
else if (m_deskState == DESK_WAIT)
{
m_dismissUser = true;
if (!m_vip->IsBegin())
{
LLOG_DEBUG("!m_vip->IsBegin()");
//这里为什么要==0 ????
//if(pos == 0)
//{
LMsgS2CResetDesk send;
send.m_errorCode = 1;
send.m_applay = pUser->m_userData.m_nike;
send.m_userId = pUser->m_userData.m_id;
send.m_flag = 1;
MHBoadCastAllDeskUser(send);
//BoadCast(send);
ResetEnd();
//}
}
else
{
LLOG_DEBUG("!m_vip->IsBegin() else ");
Lint pos1=GetUserPos(pUser);
memset(m_reset, RESET_ROOM_TYPE_WAIT, sizeof(m_reset));
//将桌子状态设置为解散房间状态
m_deskbeforeState = m_deskState;
//m_deskState = DESK_RESET_ROOM;
m_reset[pos1] = RESET_ROOM_TYPE_AGREE;
m_resetTime = gWork.GetCurTime().Secs() + 3 * 60;
m_resetUser = pUser->m_userData.m_nike;
m_resetUserId = pUser->m_userData.m_id;
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if (m_user[i] == NULL)
continue;
LMsgS2CResetDesk send;
send.m_errorCode = 0;
send.m_applay = m_resetUser;
send.m_userId = pUser->m_userData.m_id;
send.m_time = m_resetTime - gWork.GetCurTime().Secs();
send.m_flag = m_reset[i] ? 1 : 0;
for (Lint j = 0; j < m_iPlayerCapacity; ++j)
{
if (m_user[j] == NULL)
continue;
if (m_reset[j] == RESET_ROOM_TYPE_AGREE)
{
send.m_agree.push_back(m_user[j]->m_userData.m_nike);
send.m_agreeHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_agreeUserId.push_back(m_user[j]->m_userData.m_id);
}
else if (m_reset[j] == RESET_ROOM_TYPE_WAIT)
{
send.m_wait.push_back(m_user[j]->m_userData.m_nike);
send.m_waitHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_waitUserId.push_back(m_user[j]->m_userData.m_id);
}
else
{
send.m_refluse = m_user[j]->m_userData.m_nike;
}
}
m_user[i]->Send(send);
}
}
}
}
//玩家选择解散操作
void Desk::HanderSelectResutDesk(User* pUser,LMsgC2SSelectResetDesk* msg)
{
LLOG_DEBUG("Logwyz ...................HanderSelectResutDesk");
if(m_resetTime == 0)
return;
Lint pos = GetUserPos(pUser);
if (pos == INVAILD_POS)
{
return;
}
if (msg->m_flag < 1 || msg->m_flag >2)
{
msg->m_flag = 1;
}
m_reset[pos] = msg->m_flag;
Lint agree = 0, refluse = 0;
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if (m_reset[i] == RESET_ROOM_TYPE_AGREE)
agree++;
else if (m_reset[i] == RESET_ROOM_TYPE_REFLUSE)
refluse++;
}
if (refluse >= 1)
{
LLOG_DEBUG("HanderSelectResutDesk333333333333333333333333333");
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if(m_user[i] == NULL)
continue;
LMsgS2CResetDesk send;
send.m_errorCode = 4;
send.m_applay = m_resetUser;
send.m_userId = m_resetUserId;
send.m_time = m_resetTime - gWork.GetCurTime().Secs();
send.m_flag = m_reset[i] ? 1 : 0;
for (Lint j = 0; j < m_iPlayerCapacity; ++j)
{
if(m_user[j] == NULL)
continue;
if (m_reset[j] == RESET_ROOM_TYPE_AGREE)
{
send.m_agree.push_back(m_user[j]->m_userData.m_nike);
send.m_agreeHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_agreeUserId.push_back(m_user[j]->m_userData.m_id);
}
else if (m_reset[j] == RESET_ROOM_TYPE_WAIT)
{
send.m_wait.push_back(m_user[j]->m_userData.m_nike);
send.m_waitHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_waitUserId.push_back(m_user[j]->m_userData.m_id);
}
else
{
send.m_refluse = m_user[j]->m_userData.m_nike;
}
}
m_user[i]->Send(send);
}
LLOG_ERROR(" m_desk[%d],m_deskState=[%d],m_deskbeforeState=[%d]", m_id,m_deskState, m_deskbeforeState);
//m_deskState = m_deskbeforeState;
ResetClear();
//由于网络原因可能某些玩家已经准备但延迟收到解散命令,当有人拒绝的时候应该再次check一下
LLOG_DEBUG("Logwyz .... MHCheckGameStart() 380 ");
MHCheckGameStart();
//CheckGameStart();
}
else if (agree >= (m_desk_user_count))
{
LLOG_DEBUG("HanderSelectResutDesk222222222222222222222222222");
//发送删除信息,删除房主创建的对应的桌子号
LMsgL2LMGDeleteUserCreatedDesk deleteDeskInfo;
deleteDeskInfo.m_deskId = m_id;
deleteDeskInfo.m_userid = m_creatUserId;
if (m_feeType == 0)
{
deleteDeskInfo.m_cost = m_cost;
}
if (m_couFei) {
deleteDeskInfo.m_delType = 0;
}
else {
deleteDeskInfo.m_delType = 2;
}
gWork.SendToLogicManager(deleteDeskInfo);
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if(m_user[i] == NULL)
continue;
LMsgS2CResetDesk send;
send.m_errorCode = 2;
send.m_applay = m_resetUser;
send.m_userId = m_resetUserId;
send.m_time = m_resetTime - gWork.GetCurTime().Secs();
send.m_flag = m_reset[i] ? 1 : 0;
for (Lint j = 0; j < m_iPlayerCapacity; ++j)
{
if(m_user[j] == NULL)
continue;
if (m_reset[j] == RESET_ROOM_TYPE_AGREE)
{
send.m_agree.push_back(m_user[j]->m_userData.m_nike);
send.m_agreeHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_agreeUserId.push_back(m_user[j]->m_userData.m_id);
}
else if (m_reset[j] == RESET_ROOM_TYPE_WAIT)
{
send.m_wait.push_back(m_user[j]->m_userData.m_nike);
send.m_waitHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_waitUserId.push_back(m_user[j]->m_userData.m_id);
}
else
{
send.m_refluse = m_user[j]->m_userData.m_nike;
}
}
m_user[i]->Send(send);
}
ResetEnd();
}
else
{
LLOG_DEBUG("HanderSelectResutDesk111111111111111111111111111111111");
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if(m_user[i] == NULL)
continue;
LMsgS2CResetDesk send;
send.m_errorCode = 0;
send.m_applay = m_resetUser;
send.m_userId = m_resetUserId;
send.m_time = m_resetTime - gWork.GetCurTime().Secs();
send.m_flag = m_reset[i] ? 1 : 0;
send.m_agreeHeadUrl.clear();
for (Lint j = 0; j < m_iPlayerCapacity; ++j)
{
if(m_user[j] == NULL)
continue;
if (m_reset[j] == RESET_ROOM_TYPE_AGREE)
{
send.m_agree.push_back(m_user[j]->m_userData.m_nike);
send.m_agreeHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_agreeUserId.push_back(m_user[j]->m_userData.m_id);
}
else if (m_reset[j] == RESET_ROOM_TYPE_WAIT)
{
send.m_wait.push_back(m_user[j]->m_userData.m_nike);
send.m_waitHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_waitUserId.push_back(m_user[j]->m_userData.m_id);
}
else
{
send.m_refluse = m_user[j]->m_userData.m_nike;
}
}
m_user[i]->Send(send);
}
}
}
void Desk::CheckReset()
{
if (m_resetTime && gWork.GetCurTime().Secs() > m_resetTime)
{
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if(m_user[i] == NULL)
continue;
LMsgS2CResetDesk send;
send.m_errorCode = 3;
send.m_applay = m_resetUser;
send.m_userId = m_resetUserId;
send.m_time = m_resetTime - gWork.GetCurTime().Secs();
send.m_flag = m_reset[i] ? 1 : 0;
for (Lint j = 0; j < m_iPlayerCapacity; ++j)
{
if(m_user[j] == NULL)
continue;
if (m_reset[j] == RESET_ROOM_TYPE_AGREE)
{
//LLOG_DEBUG("HanderResutDesk nike = %s ", m_user[j]->m_userData.m_nike.c_str());
send.m_agree.push_back(m_user[j]->m_userData.m_nike);
//LLOG_DEBUG("HanderResutDesk headImageUrl = %s ", m_user[j]->m_userData.m_headImageUrl.c_str());
send.m_agreeHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_agreeUserId.push_back(m_user[j]->m_userData.m_id);
}
else if (m_reset[j] == RESET_ROOM_TYPE_WAIT)
{
send.m_wait.push_back(m_user[j]->m_userData.m_nike);
send.m_waitHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_waitUserId.push_back(m_user[j]->m_userData.m_id);
}
else
{
send.m_refluse = m_user[j]->m_userData.m_nike;
}
}
m_user[i]->Send(send);
}
ResetEnd();
}
}
void Desk::HanderUserReady(User* pUser,LMsgC2SUserReady* msg)
{
LLOG_ERROR("Logwyz .... Desk::HanderUserReady");
LMsgS2CUserReady ready;
Lint pos = GetUserPos(pUser);
Lint seatID = GetUserSeatPos(pUser);
if(m_deskState != DESK_WAIT/*&&m_deskState !=DESK_COUNT_RESULT*/)
{
LLOG_ERROR("Desk::HanderUserReady state error, userid=%d deskstate=%d", pUser->GetUserDataId(), m_deskState);
return;
}
if(seatID== INVAILD_POS)
{
LLOG_ERROR("Desk::HanderUserReady pos error, userid=%d pos=%d,seatID=%d", pUser->GetUserDataId(), pos, seatID);
return;
}
//日志太多暂时屏蔽
//LLOG_INFO("Desk::HanderUserReady userid=%d pos=%d", pUser->GetUserDataId(), pos);
//ready.m_pos = pos;
//准备的人实际的位置
ready.m_pos=seatID;
if (seatID!= INVAILD_POS)
{
//BoadCast(ready);
//m_readyState[pos] = 1;
MHBoadCastAllDeskUser(ready);
m_readyState[seatID]=1;
}
LLOG_DEBUG("Logwyz .... MHCheckGameStart() 557 ");
MHCheckGameStart();
}
void Desk::HanderSelectSeat(User* pUser, LMsgC2SUserSelectSeat* msg)
{
Lint pos1 = GetUserSeatPos(pUser); //用户在用户队列中的位置
if (pos1!=INVAILD_POS)
{
LLOG_ERROR("Desk::HanderSelectSeat error, userid=%d already has seat [%d]", pUser->GetUserDataId(), pos1);
return;
}
if (m_deskState != DESK_WAIT/*&&m_deskState !=DESK_COUNT_RESULT*/)
{
LLOG_ERROR("Desk::HanderSelectSeat state error, userid=%d deskstate=%d", pUser->GetUserDataId(), m_deskState);
return;
}
//if (pos == INVAILD_POS)
//{
// LLOG_ERROR("Desk::HanderSelectSeat user pos error, userid=%d pos=%d", pUser->GetUserDataId(), pos);
// return;
//}
//用户选择的位置
LLOG_DEBUG("Desk::HanderSelectSeat userid=%d pos=%d", pUser->GetUserDataId(), msg->m_pos);
if (msg->m_pos < 0 || msg->m_pos >=INVAILD_POS)
{
return;
}
for (int i = 0; i < 4; i++) {
if (m_seatUser[i] != NULL && m_seatUser[i] == pUser)
return;
}
if (m_firestUser == NULL) {
m_firestUser = pUser;
}
boost::recursive_mutex::scoped_lock l(m_mutexSeat);
//判断用户选择的位置是否被占用
if(m_seatUser[msg->m_pos] == NULL)
{
LMsgS2CUserSelectSeat selectSeat1;
//m_seatUser[msg->m_pos] = m_user[pos]; //m_seatUser的Index就是座位号
m_seatUser[msg->m_pos]=pUser;
//从lookon用户中退出
m_desk_Lookon_user.remove(pUser);
//m_seat[pos] = msg->m_pos; //用户选择的位置 这个状态在开始游戏以后填写
//用户选座顺序记录
m_user_select_seat_turn.push_back(pUser);
m_readyState[msg->m_pos] = 1;
selectSeat1.m_id = pUser->GetUserDataId();
selectSeat1.m_pos = msg->m_pos;
selectSeat1.m_StartGameButtonPos=INVAILD_POS;
pUser->ClearInRoomTime();
LLOG_DEBUG("Logwyz.......m_Greater2CanStart=[%d],m_StartGameButtonPos=[%d]", m_Greater2CanStart, m_StartGameButtonPos);
//发送manager,
if (m_clubInfo.m_clubId != 0)
{
LLOG_DEBUG("Desk::HanderSelectSeat LMsgL2LMGUserAddClubDesk");
LMsgL2LMGUserAddClubDesk send;
send.m_clubId = m_clubInfo.m_clubId;
send.m_playTypeId = m_clubInfo.m_playTypeId;
send.m_clubDeskId = m_clubInfo.m_clubDeskId;
//send.m_userId = pUser->GetUserDataId();
send.m_strUUID = pUser->m_userData.m_unioid;
//send.m_pos = msg->m_pos;
gWork.SendToLogicManager(send);
}
//>=2可以开局
if (m_Greater2CanStart&&MHGetSeatUserCount()!=m_iPlayerCapacity)
{
if (m_StartGameButtonPos==INVAILD_POS)
{
if (MHCheckGameStart()==1) //可以开始游戏
{
if (m_deskCreatedType==0)
{
if (GetUserSeatPos(m_creatUser)!=INVAILD_POS)
{
//开始游戏,指定开始按钮用户为房主
m_StartGameButtonPos=GetUserSeatPos(m_creatUser);
selectSeat1.m_StartGameButtonPos=m_StartGameButtonPos;
}
}
else
{
//开始游戏,指定开始按钮用户
m_StartGameButtonPos=MHSpecPersonPos();
selectSeat1.m_StartGameButtonPos=m_StartGameButtonPos;
LLOG_DEBUG("Logwyz.......select m_StartGameButtonPos=[%d]", m_StartGameButtonPos);
}
}
}
else
selectSeat1.m_StartGameButtonPos=m_StartGameButtonPos;
//广播用户选择位置
MHBoadCastAllDeskUser(selectSeat1);
}
else //规定人数开局
{
//广播用户选择位置
MHBoadCastAllDeskUser(selectSeat1);
MHCheckGameStart();
}
if (m_Greater2CanStart&&MHGetSeatUserCount() == m_iPlayerCapacity)
{
MHHanderStartGame();
}
//BoadCast(selectSeat1); //广播用户选择位置
//MHBoadCastAllDeskUser(selectSeat1);
LLOG_DEBUG("Desk::HanderSelectSeat after selected userid=%d pos=%d", pUser->GetUserDataId(), msg->m_pos);
// 机器人随机分配到其他座位放在这里?
/*
LLOG_DEBUG("******************Desk::HanderSelectSeat 开始处理机器人位置选择****************");
if (gConfig.GetDebugModel() && gConfig.GetIfAddRobot())
{
std::queue<int> robotPos;
for (int i = 0; i < DESK_USER_COUNT; i++)
{
if (i != msg->m_pos)
{
robotPos.push(i);
}
}
for (int i = 0; i < this->m_desk_user_count; i++)
{
User * pTableUser = this->GetPosUser(i); //队列中用户, i是用户的队列位置
if (pTableUser && (pUser != pTableUser) && (pTableUser->getUserGateID() > 10000)) //机器人
{
// 寻找一个空的位置
int selectPos = robotPos.front();
m_seat[i] = selectPos;
selectSeat.m_id = pTableUser->GetUserDataId();
selectSeat.m_pos = selectPos;
BoadCast(selectSeat);
m_readyState[i] = 1;
m_seatUser[selectPos] = m_user[i];
robotPos.pop(); // 去掉占用的位置
LLOG_DEBUG("*****************Robot UserID: %d, 选择位置 %d, rebotPos.size() = %d****************", pTableUser->GetUserDataId(), selectPos, robotPos.size());
}
}
}
*/
}
else {
LMsgS2CUserSelectSeat selectSeat2;
selectSeat2.m_id = pUser->GetUserDataId();
selectSeat2.m_pos = INVAILD_POS;
LLOG_DEBUG("Desk::HanderSelectSeat after selected userid=%d pos=%d", pUser->GetUserDataId(), selectSeat2.m_pos);
pUser->Send(selectSeat2);
}
}
void Desk::HanderUserOutDesk(User* pUser)
{
LLOG_DEBUG("Logwyz Desk::HanderUserOutDesk");
//Lint pos = GetUserPos(pUser);
//if(pos == INVAILD_POS)
//{
// return;
//}
if (pUser==NULL)return;
if (!MHIsRoomUser(pUser))
{
LLOG_DEBUG("Logwyz Desk::HanderUserOutDesk user[%d] not in room",pUser->GetUserDataId());
return;
}
//谁回来了
LMsgS2CUserOnlineInfo info;
info.m_flag = 0;
//if (m_selectSeat) {
// info.m_pos = m_seat[pos];
//}
//else {
// info.m_pos = pos;
//}
info.m_pos=GetUserSeatPos(pUser);
info.m_userid = pUser->m_userData.m_id;
MHBoadCastAllDeskUserWithOutUser(info, pUser);
}
void Desk::HanderUserEndSelect(User* pUser,LMsgC2SUserEndCardSelect* msg)
{
if(m_deskPlayState != DESK_PLAY_END_CARD)
{
LLOG_DEBUG("Desk::HanderUserEndSelect state error %d:%d:%d",m_deskState,m_deskPlayState,msg->m_flag);
return;
}
if (mGameHandler)
{
mGameHandler->HanderUserEndSelect(pUser, msg);
}
}
void Desk::HanderUserStartHu(User* pUser,LMsgC2SUserStartHuSelect* msg)
{
LLOG_DEBUG("Desk::HanderUserStartHu %d:%d",msg->m_type,msg->m_card.size());
if(m_deskState != DESK_PLAY || m_deskPlayState != DESK_PLAY_START_HU)
{
LLOG_DEBUG("Desk::HanderUserStartHu state error %d:%d:%d",m_deskState,m_deskPlayState,msg->m_type);
return;
}
if (mGameHandler)
{
mGameHandler->HanderUserStartHu(pUser, msg);
}
}
void Desk::HanderUserTangReq( User* pUser,LMsgC2STangCard* msg )
{
if(mGameHandler)
mGameHandler->HanderUserTangReq(pUser,msg);
}
void Desk::HanderUserPlayCard(User* pUser,LMsgC2SUserPlay* msg)
{
if(m_deskState != DESK_PLAY || m_deskPlayState != DESK_PLAY_GET_CARD)
{
//pUser->Send(sendMsg);
LLOG_ERROR("Desk::HanderUserPlayCard state error %s ,m_deskState = %d m_deskPlayState = %d",pUser->m_userData.m_nike.c_str(),m_deskState, m_deskPlayState);
return;
}
if (mGameHandler)
{
mGameHandler->HanderUserPlayCard(pUser, msg);
}
}
void Desk::HanderUserOperCard(User* pUser,LMsgC2SUserOper* msg)
{
if (m_deskState != DESK_PLAY || m_deskPlayState != DESK_PLAY_THINK_CARD)
{
LLOG_DEBUG("Desk::HanderUserOperCard state error %s, m_deskState = %d m_deskPlayState = %d", pUser->m_userData.m_nike.c_str(), m_deskState);
return;
}
if (mGameHandler)
{
mGameHandler->HanderUserOperCard(pUser, msg);
}
}
void Desk::HanderUserSpeak(User* pUser, LMsgC2SUserSpeak* msg)
{
LLOG_DEBUG("Logwyz Desk::HanderUserSpeak ");
if(mGameHandler)
{
mGameHandler->HanderUserSpeak(pUser,msg);
}
//Lint pos = GetUserPos(pUser);
//if (pos == INVAILD_POS)
//{
// return;
//}
if (!MHIsRoomUser(pUser))
{
LLOG_DEBUG("Logwyz Desk::HanderUserSpeak user not in room");
return;
}
if (msg->m_msg == "555666+") {
LMsgS2CUserSpeak speak;
//speak.m_userId = m_user[pos]->GetUserDataId();
//speak.m_pos = pos;
//if (m_selectSeat) {
// speak.m_pos = m_seat[pos];
//}
//speak.m_pos = pos;
//if (speak.m_pos == INVAILD_POS)
// return;
speak.m_userId=pUser->GetUserDataId();
speak.m_pos=GetUserSeatPos(pUser);
if (speak.m_pos==INVAILD_POS)
return;
speak.m_id = msg->m_id;
speak.m_type = msg->m_type;
speak.m_musicUrl = msg->m_musicUrl;
speak.m_msg = __DATE__ " " __TIME__;
pUser->Send(speak);
return;
}
LMsgS2CUserSpeak speak;
//speak.m_userId = m_user[pos]->GetUserDataId();
speak.m_userId=pUser->GetUserDataId();
speak.m_pos = GetUserSeatPos(pUser);
//if (m_selectSeat) {
// speak.m_pos = m_seat[pos];
//}
if (speak.m_pos == INVAILD_POS)
return;
speak.m_id = msg->m_id;
speak.m_type = msg->m_type;
speak.m_musicUrl = msg->m_musicUrl;
speak.m_msg = msg->m_msg;
//BoadCast(speak);
MHBoadCastAllDeskUser(speak);
}
bool Desk::OnUserReconnect(User* pUser)
{
//Lint pos = GetUserPos(pUser);
//if (pos == INVAILD_POS)
//{
// LLOG_ERROR("Desk::OnUserReconnect pos error %d", pUser->GetUserDataId());
// return false;
//}
if (pUser==NULL)return false;
if (!MHIsRoomUser(pUser))
{
LLOG_ERROR("Desk::OnUserReconnect [%d] not in room", pUser->GetUserDataId());
return false;
}
Lint reUserPos=GetUserSeatPos(pUser);
//m_readyState[pos] = 1;
if(m_deskState == DESK_WAIT && reUserPos!=INVAILD_POS) //如果是等待状态回来时需要把准备
{
LMsgS2CUserReady ready;
ready.m_pos =reUserPos;
//if (m_selectSeat) {
// ready.m_pos = m_seat[pos];
//}
//BoadCast(ready);
MHBoadCastAllDeskUser(ready);
m_readyState[reUserPos]=1;
}
//把自己加进来
LMsgS2CIntoDesk send1;
send1.m_deskId=m_id;
//俱乐部
if (m_clubInfo.m_clubId!=0&&m_clubInfo.m_clubDeskId!=0&&m_clubInfo.m_showDeskId!=0)
send1.m_deskId=m_clubInfo.m_showDeskId;
//send1.m_pos = pos;
//if (m_selectSeat) {
// send1.m_pos = m_seat[pos];
//}
//else {
// send1.m_pos = pos;
//}
//send1.m_pos = m_seat[pos];
send1.m_pos=reUserPos;
if(reUserPos!=INVAILD_POS)
send1.m_ready = m_readyState[reUserPos];
else
send1.m_ready=0;
//send1.m_ready=(reUserPos!=INVAILD_POS)?m_readyState[reUserPos]:0;
send1.m_score = m_vip ? m_vip->GetUserScore(pUser) : 0;
send1.m_coins = pUser->GetUserData().m_coins;
send1.m_state = m_state;
send1.m_maxCircle = m_vip ? m_vip->m_maxCircle : 0;
send1.m_playtype = m_playtype;
send1.m_changeOutTime = m_autoChangeOutTime;
send1.m_opOutTime = m_autoPlayOutTime;
send1.m_baseScore = m_baseScore;
send1.m_credits = pUser->m_userData.m_creditValue;
send1.m_cellscore = m_cellscore;
send1.m_flag = m_flag;
send1.m_feeType = m_feeType;
send1.m_cheatAgainst = m_cheatAgainst;
send1.m_deskType = m_deskType;
send1.m_userIp = pUser->m_userData.m_customString1;
send1.m_userGps = pUser->m_userData.m_customString2;
send1.m_createUserId = m_creatUserId;
send1.m_deskCreatedType = m_deskCreatedType;
send1.m_Greater2CanStart=m_Greater2CanStart;
send1.m_StartGameButtonPos=m_StartGameButtonPos;
send1.m_gamePlayerCount=m_desk_user_count;
send1.m_startButtonAppear=m_startButtonAppear;
send1.m_clubId=m_clubInfo.m_clubId;
send1.m_playTypeId=m_clubInfo.m_playTypeId;
LLOG_DEBUG("OnUserReconnect send1.m_deskCreatedType = %d,m_StartGameButtonPos=[%d],m_desk_user_count=[%d],m_startButtonAppear=[%d],m_clubId=[%d],m_playTypeId=[%d]", send1.m_deskCreatedType, m_StartGameButtonPos, m_desk_user_count, m_startButtonAppear, send1.m_clubId, send1.m_playTypeId);
LLOG_DEBUG("OnUserReconnect send1.m_userIp = %s", send1.m_userIp.c_str());
pUser->Send(send1);
/*
//把其他人加进来
for(Lint i = 0 ;i < m_iPlayerCapacity; ++i)
{
if(m_user[i] != NULL && m_user[i] != pUser )
{
LMsgS2CDeskAddUser addmsg2;
addmsg2.m_userId = m_user[i]->GetUserDataId();
addmsg2.m_pos = i;
if (m_selectSeat) {
addmsg2.m_pos = m_seat[i];
}
//addmsg2.m_pos = m_seat[i];
addmsg2.m_nike = m_user[i]->m_userData.m_nike;
addmsg2.m_ready = m_readyState[i];
addmsg2.m_sex = m_user[i]->m_userData.m_sex;
addmsg2.m_face = m_user[i]->m_userData.m_headImageUrl;
addmsg2.m_ip = m_user[i]->m_userData.m_customString1;
addmsg2.m_score = m_vip ? m_vip->GetUserScore(m_user[i]) : 0;
addmsg2.m_online = m_user[i]->GetOnline();
addmsg2.m_coins = m_user[i]->GetUserData().m_coins;
addmsg2.m_credits = m_user[i]->m_userData.m_creditValue;
addmsg2.m_userGps = m_user[i]->m_userData.m_customString2;
addmsg2.m_cheatAgainst = m_cheatAgainst;
addmsg2.m_videoPermission = m_user[i]->m_videoPermission;
pUser->Send(addmsg2);
}
}
*/
//把其他座位人加进来
for (Lint i=0; i < m_iPlayerCapacity; ++i)
{
if (m_seatUser[i]!=NULL && m_seatUser[i]!=pUser)
{
LMsgS2CDeskAddUser addmsg2;
addmsg2.m_userId=m_seatUser[i]->GetUserDataId();
addmsg2.m_pos=i;
//if (m_selectSeat) {
// addmsg2.m_pos=m_seat[i];
//}
//addmsg2.m_pos = m_seat[i];
addmsg2.m_nike=m_seatUser[i]->m_userData.m_nike;
addmsg2.m_ready=m_readyState[i];
addmsg2.m_sex=m_seatUser[i]->m_userData.m_sex;
addmsg2.m_face=m_seatUser[i]->m_userData.m_headImageUrl;
addmsg2.m_ip=m_seatUser[i]->m_userData.m_customString1;
addmsg2.m_score=m_vip?m_vip->GetUserScore(m_seatUser[i]):0;
addmsg2.m_online=m_seatUser[i]->GetOnline();
addmsg2.m_coins=m_seatUser[i]->GetUserData().m_coins;
addmsg2.m_credits=m_seatUser[i]->m_userData.m_creditValue;
addmsg2.m_userGps=m_seatUser[i]->m_userData.m_customString2;
addmsg2.m_cheatAgainst=m_cheatAgainst;
addmsg2.m_videoPermission=m_seatUser[i]->m_videoPermission;
pUser->Send(addmsg2);
}
}
//把Lookon用户加进来
std::list<User*>::iterator userIt;
for (userIt=m_desk_Lookon_user.begin(); userIt!=m_desk_Lookon_user.end(); ++userIt)
{
User* LookonUser=*userIt;
if (LookonUser==NULL ||pUser==LookonUser)continue;
LMsgS2CDeskAddUser addmsg2;
addmsg2.m_userId=LookonUser->GetUserDataId();
addmsg2.m_pos=INVAILD_POS;
addmsg2.m_nike=LookonUser->m_userData.m_nike;
addmsg2.m_ready=0;
addmsg2.m_sex=LookonUser->m_userData.m_sex;
addmsg2.m_face=LookonUser->m_userData.m_headImageUrl;
addmsg2.m_ip=LookonUser->m_userData.m_customString1;
addmsg2.m_score=m_vip?m_vip->GetUserScore(LookonUser):0;
addmsg2.m_online=LookonUser->GetOnline();
addmsg2.m_coins=LookonUser->GetUserData().m_coins;
addmsg2.m_credits=LookonUser->m_userData.m_creditValue;
addmsg2.m_userGps=LookonUser->m_userData.m_customString2;
addmsg2.m_cheatAgainst=m_cheatAgainst;
addmsg2.m_videoPermission=LookonUser->m_videoPermission;
pUser->Send(addmsg2);
}
//谁回来了
LMsgS2CUserOnlineInfo info;
info.m_flag = 1;
//if (m_selectSeat) {
// info.m_pos = m_seat[pos];
//}
//else {
// info.m_pos = pos;
//}
info.m_pos=GetUserSeatPos(pUser);
info.m_userid = pUser->m_userData.m_id;
//info.m_pos = pos;
//BoadCastWithOutUser(info, pUser);
MHBoadCastAllDeskUserWithOutUser(info, pUser);
//不在游戏中,不需要后面的数据
if(m_deskState == DESK_WAIT)
{
LLOG_DEBUG("Logwyz .... MHCheckGameStart() 981 ");
MHCheckGameStart();
//CheckGameStart();
}
else
{
//发送当前圈数信息
if(m_vip)
{
m_vip->SendInfo();
}
if(mGameHandler)
{
mGameHandler->OnUserReconnect(pUser);
}
}
//如果有人申请解散则通知解散信息
if(m_resetTime)
{
// 如果是lookon用户,解散房间不需要他们同意或者拒绝
if (!MHIsLookonUser(pUser))
{
LMsgS2CResetDesk send;
send.m_errorCode=0;
send.m_applay=m_resetUser;
send.m_userId=m_creatUserId;
send.m_time=m_resetTime-gWork.GetCurTime().Secs();
//解散的时候是游戏已经开始,直接用m_user的位置
Lint userPos=GetUserPos(pUser);
send.m_flag=m_reset[userPos]?1:0;
for (Lint j=0; j<m_iPlayerCapacity; ++j)
{
if (m_user[j]==NULL)
continue;
if (m_reset[j]==RESET_ROOM_TYPE_AGREE)
{
//LLOG_DEBUG("OnUserReconnect nike = %s ", m_user[j]->m_userData.m_nike.c_str());
send.m_agree.push_back(m_user[j]->m_userData.m_nike);
//LLOG_DEBUG("OnUserReconnect headImageUrl = %s ", m_user[j]->m_userData.m_headImageUrl.c_str());
send.m_agreeHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_agreeUserId.push_back(m_user[j]->m_userData.m_id);
}
else if (m_reset[j]==RESET_ROOM_TYPE_WAIT)
{
send.m_wait.push_back(m_user[j]->m_userData.m_nike);
send.m_waitHeadUrl.push_back(m_user[j]->m_userData.m_headImageUrl);
send.m_waitUserId.push_back(m_user[j]->m_userData.m_id);
}
else
{
send.m_refluse=m_user[j]->m_userData.m_nike;
}
}
pUser->Send(send);
}
else
{
//解散时候lookon用户需要做什么
}
}
LLOG_ERROR("**************断线重连桌子ID: %d ", m_id);
for (int i = 0; i < m_iPlayerCapacity; i++)
{
if (m_user[i]) {
LLOG_ERROR("********** 用户ID = %d IP = %s", m_user[i]->GetUserData().m_id, m_user[i]->m_userData.m_customString1.c_str());
}
}
return true;
}
// 玩家换牌
void Desk::HanderUserChange(User* pUser, LMsgC2SUserChange* msg)
{
if (mGameHandler)
{
mGameHandler->HanderUserChange(pUser, msg);
}
}
void Desk::SetVip(VipLogItem* vip)
{
m_vip = vip;
if(m_vip)
{
m_state = vip->m_state;
m_playtype = vip->m_playtype;
mGameHandler->SetPlayType(vip->m_playtype);
}
}
VipLogItem* Desk::GetVip()
{
return m_vip;
}
Lint Desk::GetFreePos()
{
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if (m_user[i] == NULL)
return i;
}
return INVAILD_POS;
}
void Desk::OnUserInRoom(User* user)
{
//if (GetUserPos(user) != INVAILD_POS)
//{
// LLOG_ERROR("Desk::OnUserInRoom is in desk %d", user->GetUserDataId());
// return;
//}
if (MHIsRoomUser(user))
{
LLOG_ERROR("Desk::OnUserInRoom is in desk %d", user->GetUserDataId());
return;
}
//关于几个变量说明 by wyz: m_user , m_seatUser,m_desk_Lookon_user 用户进入房间只写入m_desk_all_user,m_desk_Lookon_user 这两个变量;用户选座成功以后用户写入m_seatUser(东南西北实际位置),从m_desk_Lookon_user移除;游戏开始时,写入m_user(位置与实际位置无关,按东南西北依次排),m_switchPos位置记录转换关系 by wyz
//Lint pos = GetFreePos();
//if(pos == INVAILD_POS)
//{
// LLOG_ERROR("Desk::OnUserInRoom INVAILD_POS %d",user->GetUserDataId());
// return;
//}
Lint pos=INVAILD_POS;
m_selectSeat = true;
//m_user[pos] = user;
//没有选座的用户都是lookon用户
//m_desk_all_user.push_back(user);
m_desk_Lookon_user.push_back(user);
user->SetDesk(this);
user->updateInRoomTime();
//m_readyState[pos] = 0;
//Lint realSeat = m_seat[pos];
LMsgS2CIntoDesk send1;
send1.m_deskId = m_id;
//俱乐部
if (m_clubInfo.m_clubId!=0&&m_clubInfo.m_clubDeskId!=0&&m_clubInfo.m_showDeskId!=0)
send1.m_deskId=m_clubInfo.m_showDeskId;
send1.m_pos = pos;
//if (m_selectSeat) {
// send1.m_pos = realSeat;
//}
//send1.m_ready = m_readyState[pos];
send1.m_ready=0;
send1.m_score = m_vip ? m_vip->GetUserScore(user) : 0;
send1.m_coins = user->GetUserData().m_coins;
send1.m_state = m_state;
send1.m_maxCircle = m_vip ? m_vip->m_maxCircle : 0;
send1.m_playtype = m_playtype;
send1.m_changeOutTime = m_autoChangeOutTime;
send1.m_opOutTime = m_autoPlayOutTime;
send1.m_baseScore = m_baseScore;
send1.m_credits = user->m_userData.m_creditValue;
send1.m_createUserId = m_creatUserId;
send1.m_deskCreatedType = m_deskCreatedType;
send1.m_cellscore = m_cellscore;
send1.m_flag = m_flag;
send1.m_feeType = m_feeType;
send1.m_cheatAgainst = m_cheatAgainst;
send1.m_deskType = m_deskType;
send1.m_userIp = user->m_userData.m_customString1;
send1.m_userGps = user->m_userData.m_customString2;
send1.m_Greater2CanStart=m_Greater2CanStart;
send1.m_StartGameButtonPos=m_StartGameButtonPos;
send1.m_gamePlayerCount=m_desk_user_count;
send1.m_startButtonAppear=m_startButtonAppear;
send1.m_clubId=m_clubInfo.m_clubId;
send1.m_playTypeId=m_clubInfo.m_playTypeId;
send1.m_GpsLimit = this->m_Gps_Limit;
LLOG_DEBUG("OnUserReconnect send1.m_deskCreatedType = %d,m_StartGameButtonPos=[%d],m_Greater2CanStart[%d],m_desk_user_count=[%d],m_startButtonAppear=[%d],m_clubId=[%d],m_playTypeId=[%d]", send1.m_deskCreatedType, m_StartGameButtonPos, m_StartGameButtonPos, m_desk_user_count, m_startButtonAppear, send1.m_clubId, send1.m_playTypeId);
LLOG_DEBUG("OnUserReconnect send1.m_userIp = %s, LMsgS2CIntoDesk.m_GpsLimit:%d", send1.m_userIp.c_str(), send1.m_GpsLimit);
user->Send(send1);
LMsgS2CDeskAddUser addmsg1;
addmsg1.m_userId = user->GetUserDataId();
addmsg1.m_score = m_vip ? m_vip->GetUserScore(user) : 0;
addmsg1.m_pos = pos;
//if (m_selectSeat) {
// addmsg1.m_pos = realSeat;
//}
LLOG_DEBUG("*******************用户加入房间的位置 msgid = %d userid = %d pos = %d", addmsg1.m_msgId, addmsg1.m_userId, addmsg1.m_pos);
addmsg1.m_nike = user->m_userData.m_nike;
//addmsg1.m_ready = m_readyState[pos];
addmsg1.m_ready=0;
addmsg1.m_sex = user->m_userData.m_sex;
addmsg1.m_ip = user->m_userData.m_customString1;
addmsg1.m_face = user->m_userData.m_headImageUrl;
addmsg1.m_online = user->GetOnline();
addmsg1.m_coins = user->GetUserData().m_coins;
addmsg1.m_credits = user->m_userData.m_creditValue;
addmsg1.m_userGps = user->m_userData.m_customString2;
addmsg1.m_cheatAgainst = m_cheatAgainst;
addmsg1.m_videoPermission = user->m_videoPermission;
//在座的人
for(Lint i = 0 ;i < m_iPlayerCapacity; ++i)
{
if(m_seatUser[i] != NULL && m_seatUser[i] != user)
{
LMsgS2CDeskAddUser addmsg2;
addmsg2.m_userId =m_seatUser[i]->GetUserDataId();
//Lint realSeat = m_seat[i];
addmsg2.m_pos = i;
//if (m_selectSeat) {
// addmsg2.m_pos = realSeat;
//}
addmsg2.m_nike =m_seatUser[i]->m_userData.m_nike;
addmsg2.m_ready = m_readyState[i];
addmsg2.m_sex =m_seatUser[i]->m_userData.m_sex;
addmsg2.m_face =m_seatUser[i]->m_userData.m_headImageUrl;
addmsg2.m_ip =m_seatUser[i]->GetIp();
addmsg2.m_score = m_vip ? m_vip->GetUserScore(m_seatUser[i]) : 0;
addmsg2.m_online =m_seatUser[i]->GetOnline();
addmsg2.m_coins =m_seatUser[i]->GetUserData().m_coins;
addmsg2.m_credits =m_seatUser[i]->m_userData.m_creditValue;
addmsg2.m_userGps =m_seatUser[i]->m_userData.m_customString2;
addmsg2.m_cheatAgainst = m_cheatAgainst;
addmsg2.m_videoPermission =m_seatUser[i]->m_videoPermission;
user->Send(addmsg2);
m_seatUser[i]->Send(addmsg1);
}
}
//发送Lookon用户的
LLOG_DEBUG("Logwyz-------------m_desk_Lookon_user=[%d]", m_desk_Lookon_user.size());
std::list<User*>::iterator userIt;
for (userIt=m_desk_Lookon_user.begin(); userIt!=m_desk_Lookon_user.end(); ++userIt)
{
User* temp=*userIt;
if (temp==NULL)continue;
if (temp!=user)
{
LMsgS2CDeskAddUser addmsg2;
addmsg2.m_userId=temp->GetUserDataId();
addmsg2.m_pos=INVAILD_POS;
addmsg2.m_nike=temp->m_userData.m_nike;
addmsg2.m_ready=0;
addmsg2.m_sex=temp->m_userData.m_sex;
addmsg2.m_face=temp->m_userData.m_headImageUrl;
addmsg2.m_ip=temp->GetIp();
addmsg2.m_score=m_vip?m_vip->GetUserScore(temp):0;
addmsg2.m_online=temp->GetOnline();
addmsg2.m_coins=temp->GetUserData().m_coins;
addmsg2.m_credits=temp->m_userData.m_creditValue;
addmsg2.m_userGps=temp->m_userData.m_customString2;
addmsg2.m_cheatAgainst=m_cheatAgainst;
addmsg2.m_videoPermission=temp->m_videoPermission;
user->Send(addmsg2);
temp->Send(addmsg1);
}
}
//如果人满,发送manager,更新俱乐部界面
if (m_clubInfo.m_clubId!=0&&MHGetDeskUserCount()==m_desk_user_count)
{
MHNotifyManagerDeskInfo(1);
}
//发送manager, 添加用户
//if (m_clubInfo.m_clubId!=0)
//{
// LLOG_DEBUG("Desk::OnUserInRoom LMsgL2LMGUserAddClubDesk");
// LMsgL2LMGUserAddClubDesk send;
// send.m_clubId=m_clubInfo.m_clubId;
// send.m_playTypeId=m_clubInfo.m_playTypeId;
// send.m_clubDeskId=m_clubInfo.m_clubDeskId;
// send.m_userId=user->GetUserDataId();
// send.m_strUUID=user->m_userData.m_unioid;
//
// gWork.SendToLogicManager(send);
//}
//CheckGameStart();
}
void Desk::OnUserInRoom(User* user[])
{
LLOG_DEBUG("Desk::OnUserInRoom(User* user[])");
for(Lint i = 0; i < DESK_USER_COUNT; ++i)
{
Lint pos = GetFreePos();
if(pos == INVAILD_POS)
{
LLOG_ERROR("Desk::OnUserInRoom INVAILD_POS %d",user[0]->GetUserDataId());
return;
}
m_user[pos] = user[i];
user[i]->SetDesk(this);
m_readyState[pos] = 1;
}
CheckGameStart();
}
void Desk::OnUserOutRoom(User* user)
{
boost::mutex::scoped_lock(m_mutexDeskLookonUser);
if (user==NULL)
return;
LLOG_DEBUG("Desk::OnUserOutRoom, userid=[%d]", user->GetUserDataId());
//Lint pos = GetUserPos(user);
//if(pos == INVAILD_POS)
//{
// LLOG_ERROR("Desk::OnUserOutRoom INVAILD_POS %d",user->GetUserDataId());
// return;
//}
//if(GetUserPos(user)!= INVAILD_POS)
//{
// LLOG_ERROR("Desk::OnUserOutRoom INVAILD_POS %d",user->GetUserDataId());
// return;
//}
if (!MHIsRoomUser(user))
{
LLOG_ERROR("Desk::OnUserOutRoom userid[%d] not in room", user->GetUserDataId());
return;
}
LMsgS2CDeskDelUser del;
if (m_dismissUser) {
del.m_DismissName = m_creatUserNike;
}
del.m_userId = user->m_userData.m_id;
if (MHIsSeatUser(user))
del.m_pos=GetUserSeatPos(user);
else
del.m_pos=INVAILD_POS;
del.m_StartGameButtonPos=m_StartGameButtonPos;
//重新选择第一个选座的人
if (m_firestUser==user)m_firestUser=NULL;
if (MHIsInSeatTurn(user))
{
LLOG_DEBUG("Logwyz ... Desk::OnUserOutRoom user[%d] out , m_user_select_seat_turn.remove ", user->GetUserDataId());
m_user_select_seat_turn.remove(user);
}
LLOG_DEBUG("Logwyz ... Desk::OnUserOutRoom user[%d] out , m_StartGameButtonPos=[%d] ", user->GetUserDataId(),m_StartGameButtonPos);
//开始删除桌子上用户信息
bool userIsLookOnUser=false;
int delUserPos=GetUserPos(user);
if (delUserPos!=INVAILD_POS)
m_user[delUserPos]=NULL;
int delUserSeatPos=GetUserSeatPos(user);
if (delUserSeatPos!=INVAILD_POS) {
m_seatUser[delUserSeatPos]=NULL;
m_readyState[delUserSeatPos]=0;
}
else
{
m_desk_Lookon_user.remove(user);
userIsLookOnUser=true;
}
//退出用户是否是开始按钮用户,如果不是,检查入座人数
if (m_StartGameButtonPos!=INVAILD_POS &&(!userIsLookOnUser) && (delUserSeatPos==m_StartGameButtonPos || MHGetSeatUserCount()<2))
{
LLOG_DEBUG("Logwyz ... Desk::OnUserOutRoom user[%d] out , userPos=[%d],seatCount=[%d],m_StartGameButtonPos=[%d] ", user->GetUserDataId(), GetUserSeatPos(user), MHGetSeatUserCount(),m_StartGameButtonPos);
if (MHGetSeatUserCount()>=2)
{
m_StartGameButtonPos=MHSpecPersonPos();
del.m_StartGameButtonPos=m_StartGameButtonPos;
}
else
{
m_StartGameButtonPos=INVAILD_POS;
del.m_StartGameButtonPos=m_StartGameButtonPos;
}
}
//for(Lint i = 0 ;i < m_iPlayerCapacity; ++i)
//{
// if(m_user[i] != NULL)
// {
// m_user[i]->Send(del);
// }
//}
//向房间所有人广播
MHBoadCastAllDeskUser(del);
user->Send(del);
//修改状态
user->setUserState(LGU_STATE_CENTER);
user->ModifyUserState(true);
//清除状态
user->SetDesk(NULL);
////开始删除用户 ,移到上面
//int delUserPos=GetUserPos(user);
//if (delUserPos!=INVAILD_POS)
// m_user[delUserPos]=NULL;
//
//int delUserSeatPos=GetUserSeatPos(user);
//if (delUserSeatPos!=INVAILD_POS) {
// m_seatUser[delUserSeatPos]=NULL;
// m_readyState[delUserSeatPos]=0;
//}
//else
//{
// m_desk_Lookon_user.remove(user);
//}
//发送manager
if (m_clubInfo.m_clubId!=0)
{
LLOG_DEBUG("Desk::OnUserOutRoom LMsgL2LMGUserLeaveClubDesk");
LMsgL2LMGUserLeaveClubDesk send;
send.m_clubId=m_clubInfo.m_clubId;
send.m_playTypeId=m_clubInfo.m_playTypeId;
send.m_clubDeskId=m_clubInfo.m_clubDeskId;
send.m_userId=user->GetUserDataId();
send.m_strUUID=user->m_userData.m_unioid;
gWork.SendToLogicManager(send);
}
//如果人满,发送manager,更新俱乐部界面
if (m_clubInfo.m_clubId!=0&&MHGetDeskUserCount()==m_desk_user_count-1)
{
MHNotifyManagerDeskInfo(0);
}
//if (m_seat[pos] != INVAILD_POS) {
// m_seatUser[m_seat[pos]] = NULL;
//}
//m_seat[pos] = INVAILD_POS;
//删除玩家 不删除机器人
if (user->getUserGateID() != 65535) //不是机器人删除掉
{
UserManager::Instance().DelUser(user);
delete user;
}
}
Lint Desk::GetNextPos(Lint prev)
{
if(prev < 0 || prev >= m_iPlayerCapacity)
{
return INVAILD_POS;
}
return prev == (m_iPlayerCapacity - 1) ? 0 : (prev + 1);
}
Lint Desk::GetPrevPos(Lint next)
{
if(next < 0 || next >= m_iPlayerCapacity)
{
return INVAILD_POS;
}
return next == 0 ? (m_iPlayerCapacity - 1) : (next - 1);
}
Lint Desk::GetUserPos(User* user)
{
if(user == NULL)
{
return INVAILD_POS;
}
for(Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if(m_user[i] == user)
return i;
}
return INVAILD_POS;
}
Lint Desk::GetUserSeatPos(User* user)
{
if (user == NULL)
{
return INVAILD_POS;
}
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if (m_seatUser[i] == user)
return i;
}
return INVAILD_POS;
}
User* Desk::GetPosUser(Lint pos)
{
if(pos<0 || pos >= INVAILD_POS)
{
return NULL;
}
return m_user[pos];
}
Lint Desk::GetUserCount()
{
Lint cnt = 0;
for(Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if(m_user[i])
{
cnt += 1;
}
}
return cnt;
}
void Desk::SetDeskWait()
{
memset(m_readyState, 0, sizeof(m_readyState));
m_deskState = DESK_WAIT;
}
void Desk::OnDeskWait()
{
}
void Desk::CheckGameStart()
{
MHLOG("*********************************************Desk::CheckGameStart()");
if(m_deskState != DESK_WAIT) //只有桌子为等待状态才继续
{
LLOG_DEBUG("Desk's status is wrong. Desk state = %d.", m_deskState);
return;
}
if(m_resetTime != 0)
{
LLOG_DEBUG("Desk ising reseted");
return;
}
//判断所有的人是否都已经准备
if(GetUserCount() != m_iPlayerCapacity)
{
LLOG_DEBUG("The player num isn't enought");
return;
}
for(int i = 0; i < m_iPlayerCapacity; i++)
{
if(m_user[i] == NULL || !m_readyState[i])
{
LLOG_DEBUG("The player hasn't been ready");
return;
}
}
for (int i = 0; i < m_iPlayerCapacity; i++)
{
if (m_seat[i] == INVAILD_POS)
{
LLOG_DEBUG("The player hasn't been select seat");
return;
}
}
m_selectSeat = false;
for (int i = 0; i < DESK_USER_COUNT; i++)
{
m_user[i] = m_seatUser[i]; //如果都准备好,把m_seatUser所有用户拷贝到m_user,这样m_user的索引号为座位号
}
GetVip()->ResetUser(m_user);
bool bFind = false;
for (int i = 0; i < DESK_USER_COUNT; i++)
{
if (m_user[i]) {
if (m_creatUserId == m_user[i]->GetUserDataId()) {
LLOG_DEBUG("m_zhuangPos = %d", i);
m_zhuangPos = i;
bFind = true;
break;
}
}
}
if (!bFind && m_firestUser) {
for (int i = 0; i < DESK_USER_COUNT; i++)
{
if (m_firestUser == m_user[i]) {
LLOG_DEBUG("m_zhuangPos = %d", i);
m_zhuangPos = i;
bFind = true;
break;
}
}
}
if(mGameHandler)
{
mGameHandler->SetDeskPlay();
}
else
{
LLOG_ERROR("Game handler han't beed created");
}
LLOG_ERROR("**************开始游戏时桌子ID: %d ", m_id);
for (int i = 0; i < m_iPlayerCapacity; i++)
{
if (m_user[i]) {
LLOG_ERROR("********** 用户ID %d IP = %s", m_user[i]->GetUserData().m_id, m_user[i]->m_userData.m_customString1.c_str());
}
}
}
void Desk::SetDeskFree()
{
m_deskState = DESK_FREE;
m_timeDeskCreate = 0;
if(mGameHandler)
{
GameHandlerFactory::getInstance()->destroy((GameType)m_state,mGameHandler);
LLOG_DEBUG("Desk::SetDeskFree mHander");
mGameHandler = NULL;
}
if( m_deskType == DeskType_Coins )
{
// 金币桌子由金币服务器负责回收自己回收
}
else
{
//gWork.RecycleDeskId(m_id);
gWork.RecycleDeskId(m_id, m_clubInfo.m_clubId, m_clubInfo.m_playTypeId, m_clubInfo.m_clubDeskId);
MHLOG_DESK("***Send to logic manager to recycle desk id: %d", m_id);
}
}
void Desk::BoadCast(LMsg& msg)
{
LLOG_DEBUG("BoadCast m_iPlayerCapacity = %d", m_iPlayerCapacity);
for(Lint i = 0 ; i < m_iPlayerCapacity ;++i)
{
if(m_user[i])
m_user[i]->Send(msg);
}
}
void Desk::BoadCastWithOutUser(LMsg& msg, User* user)
{
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if (m_user[i] && m_user[i] != user)
m_user[i]->Send(msg);
}
}
std::vector<std::string> Desk::getAllPlayerName()
{
std::vector<std::string> tempNameList;
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
//if (m_user[i]) {
// std::string name = m_user[i]->GetUserData().m_nike;
if (m_seatUser[i]) {
std::string name =m_seatUser[i]->GetUserData().m_nike;
tempNameList.push_back(name);
}
}
return tempNameList;
}
void Desk::ClearUser()
{
if( m_deskType == DeskType_Common )
{
LLOG_DEBUG("m_iPlayerCapacity = %d", m_iPlayerCapacity);
for (Lint i = 0; i < m_iPlayerCapacity; ++i)
{
//if (m_user[i])
if (m_seatUser[i])
OnUserOutRoom(m_seatUser[i]);
}
}
else
{
for(Lint i = 0 ;i < m_iPlayerCapacity; ++i)
{
if(m_user[i])
{
m_user[i]->setUserState(LGU_STATE_COIN);
m_user[i]->ModifyUserState(true); //修改user状态,通知金币服务器
m_user[i]->SetDesk(NULL);
//删除玩家 不删除机器人
if (m_user[i]->getUserGateID() != 65535) //不是机器人删除掉
{
UserManager::Instance().DelUser(m_user[i]);
delete m_user[i];
m_user[i] = NULL;
}
m_readyState[i] = 0;
}
}
}
}
void Desk::SetAllReady()
{
memset(m_readyState, 1, sizeof(m_readyState));
}
void Desk::ResetClear()
{
m_resetTime = 0;
m_resetUser.clear();
memset(m_reset, 0, sizeof(m_reset));
}
void Desk::ResetEnd()
{
LLOG_DEBUG("Logwyz ...............Desk::ResetEnd()");
if(m_vip)
{
m_vip->m_reset = 1;
if (m_vip->m_curCircle >= 1 && m_deskState == DESK_WAIT) // 局结束,下局未开始点
{
m_vip->InsertDeskWinnerInfo();
m_vip->UpdateDeskTotalScoreToDB();
}
}
if (m_deskState == DESK_PLAY)
{
LLOG_DEBUG("Logwyz ...............Desk::ResetEnd(),m_deskState == DESK_PLAY");
m_bIsDissmissed = true;
if (mGameHandler)
{
mGameHandler->OnGameOver(WIN_NONE, INVAILD_POS, INVAILD_POS, NULL);
}
}
else
{
if (m_deskCreatedType == 1) {
LMsgL2LMGDeleteUserCreatedDesk deleteDeskInfo;
deleteDeskInfo.m_deskId = m_id;
deleteDeskInfo.m_userid = m_creatUserId;
if (m_feeType == 0)
{
deleteDeskInfo.m_cost = m_cost;
}
if (m_couFei) {
deleteDeskInfo.m_delType = 0;
}else {
deleteDeskInfo.m_delType = 2;
}
gWork.SendToLogicManager(deleteDeskInfo);
}
if (m_vip && m_vip->IsBegin())
{
LLOG_DEBUG("Logwyz ...............Desk::ResetEnd(),m_vip->SendEnd()");
m_vip->SendEnd();
}
SetVip(NULL);
ClearUser();
//清空lookon用户
MHClearLookonUser();
ResetClear();
SetDeskFree();
}
}
void Desk::SpecialCardClear()
{
memset(m_specialCard,0,sizeof(m_specialCard));
}
//////////////////////////////////////////////////////////////////////////
Lint Desk::getGameType() const
{
return m_state;
}
const std::vector<Lint>& Desk::getPlayType() const
{
return m_playtype;
}
Lint Desk::getDeskState() const
{
return m_deskState;
}
void Desk::setDeskState(Lint nState)
{
m_deskState = nState;
}
Lint Desk::getDeskPlayState()
{
return m_deskPlayState;
}
void Desk::setDeskPlayState(Lint nDeskPlayState)
{
m_deskPlayState = nDeskPlayState;
}
void Desk::HanderGameOver(Lint result)
{
LLOG_DEBUG("Desk::HanderGameOver");
if (m_vip == NULL)
{
return;
}
if( m_deskType == DeskType_Common )
{
LLOG_DEBUG("Desk::HanderGameOver m_deskType == DeskType_Common");
//检测扣房卡
if (m_vip->m_curCircle == 1 && !m_vip->m_reset)
{
Lint cardType = CARD_TYPE_4;
if (m_vip->m_maxCircle == 8)
cardType = CARD_TYPE_8;
else if (m_vip->m_maxCircle == 16)
cardType = CARD_TYPE_16;
LLOG_ERROR("*****每局结束桌子ID: %d ", m_id);
for (int i = 0; i < m_iPlayerCapacity; i++)
{
if (m_user[i]) {
LLOG_ERROR("**** 用户ID = %d IP = %s", m_user[i]->GetUserData().m_id, m_user[i]->m_userData.m_customString1.c_str());
}
}
//发送删除信息,删除房主创建的对应的桌子号
if (m_deskCreatedType == 1) {
LMsgL2LMGDeleteUserCreatedDesk deleteDeskInfo;
deleteDeskInfo.m_deskId = m_id;
deleteDeskInfo.m_userid = m_creatUserId;
if (m_feeType == 0)
{
deleteDeskInfo.m_cost = m_cost;
}
deleteDeskInfo.m_delType = 1;
gWork.SendToLogicManager(deleteDeskInfo);
}
//扣费标志 重要
m_couFei = true;
//扣费信息
Lint nFree = 0;
Lint nTotalDeskFeeValue = 0;
LTime cur;
Lint curTime = cur.Secs();
//这个是时间,也没有什么用
if (curTime > m_startTime && curTime < m_endTime)
{
nFree = 1;
}
//这个是做活动的,没有什么用
if (m_state != 100010 && m_state != 100008 && m_state != 100009) {
nFree = 0;
}
if (nFree) {
LLOG_ERROR("******DeskId:%d 房主扣费 在免费时间 不需要扣费", m_id);
}
//普通房间扣费
if (m_clubInfo.m_clubId==0&&m_clubInfo.m_clubDeskId==0) //普通桌子
{
if (m_feeType==0) {
LLOG_ERROR("******DeskId:%d 房主扣费 creatUserId = %d cost = %d", m_id, m_creatUserId, m_cost);
if (nFree==0)
{
User* pCreatUser=gUserManager.GetUserbyDataId(m_creatUserId);
if (pCreatUser) {
pCreatUser->DelCardCount(cardType, m_cost, CARDS_OPER_TYPE_CREATE_ROOM, "system", m_feeType); //房主扣费,房主在线
}
else {
HanderDelCardCount(cardType, m_cost, CARDS_OPER_TYPE_CREATE_ROOM, "system", m_feeType, m_creatUserId, m_unioid); //房主不在线
}
m_vip->UpdateDeskTotalFeeValueToDB(m_cost);
}
}
else {
LLOG_ERROR("*****DeskId:%d 分摊房费 平均费用 = %d", m_id, m_even);
if (nFree==0)
{
Lint nTotalDeskFeeValue=0;
for (int i=0; i<m_iPlayerCapacity; i++)
{
if (m_user[i])
{
m_user[i]->DelCardCount(cardType, m_even, CARDS_OPER_TYPE_CREATE_ROOM, "system", m_feeType); //分摊房费
m_vip->UpdateUserFeeValueToDB(m_user[i]->GetUserDataId(), m_even); // 修改数据库
nTotalDeskFeeValue+=m_even;
}
}
m_vip->UpdateDeskTotalFeeValueToDB(nTotalDeskFeeValue);
}
}
}
else //俱乐部桌子扣费
{
if (m_feeType==0) //会长扣费
{
LLOG_ERROR("******clubShowDesk:%d 会长扣费 creatUserId = %d cost = %d", m_clubInfo.m_showDeskId, m_creatUserId, m_cost);
//m_vip->UpdateClubCreatorNumDiamondToDB(m_cost, m_creatUserId);
HanderDelCardCount(cardType, m_cost, CARDS_OPER_TYPE_CLUB_DIAMOND, "system", m_feeType, m_creatUserId, m_unioid); //房主不在线
m_vip->UpdateDeskTotalFeeValueToDB(m_cost);
}
else {
LLOG_ERROR("*****DeskId:%d 分摊房费 平均费用 = %d", m_id, m_even);
if (nFree==0)
{
Lint nTotalDeskFeeValue=0;
for (int i=0; i<m_iPlayerCapacity; i++)
{
if (m_user[i])
{
m_user[i]->DelCardCount(cardType, m_even, CARDS_OPER_TYPE_CREATE_ROOM, "system", m_feeType); //分摊房费
m_vip->UpdateUserFeeValueToDB(m_user[i]->GetUserDataId(), m_even); // 修改数据库
nTotalDeskFeeValue+=m_even;
}
}
m_vip->UpdateDeskTotalFeeValueToDB(nTotalDeskFeeValue);
}
}
}
}
}
if(m_vip->isNormalEnd())
{
LLOG_DEBUG("Desk::HanderGameOver m_vip->isNormalEnd()");
//清空lookon用户
MHClearLookonUser();
if(m_deskType == DeskType_Common)
{
LMsgL2LDBSaveCRELog log;
if(m_user[0]!=NULL)
log.m_strUUID = m_user[0]->m_userData.m_unioid;
log.m_deskID = this->m_id;
log.m_strLogId = m_vip->m_id;
log.m_time = m_vip->m_time;
for(Lint i = 0; i < m_iPlayerCapacity; ++i)
{
if(m_user[i]!=NULL)
log.m_id[i] = m_user[i]->m_userData.m_id;
}
gWork.SendMsgToDb(log);
}
}
if(m_vip->isEnd())
{
LLOG_DEBUG("Desk::HanderGameOver m_vip->isEnd()");
if (m_deskCreatedType == 1) {
LMsgL2LMGDeleteUserCreatedDesk deleteDeskInfo;
deleteDeskInfo.m_deskId = m_id;
deleteDeskInfo.m_userid = m_creatUserId;
if (m_feeType == 0)
{
deleteDeskInfo.m_cost = m_cost;
}
if (m_couFei) {
deleteDeskInfo.m_delType = 0;
}
else {
deleteDeskInfo.m_delType = 2;
}
gWork.SendToLogicManager(deleteDeskInfo);
}
//logic manager
//发送manager
if (m_clubInfo.m_clubId!=0)
{
LLOG_DEBUG("Desk::HanderGameOver LMsgL2LMGUserLeaveClubDesk");
LMsgL2LMGUserLeaveClubDesk send;
send.m_clubId=m_clubInfo.m_clubId;
send.m_playTypeId=m_clubInfo.m_playTypeId;
send.m_clubDeskId=m_clubInfo.m_clubDeskId;
for (int i=0; i<m_iPlayerCapacity; i++)
{
if (m_seatUser[i])
{
send.m_userId=m_seatUser[i]->GetUserDataId();
send.m_strUUID=m_seatUser[i]->m_userData.m_unioid;
gWork.SendToLogicManager(send);
}
}
}
LLOG_DEBUG("Desk::HanderGameOver m_vip->SendEnd()");
m_vip->SendEnd();
m_vip->m_desk = NULL;
ClearUser();
SetDeskFree();
SetVip(NULL);
ResetClear();
}
SpecialCardClear();
}
void Desk::HanderAddCardCount(Lint pos, Lint CardNum, CARDS_OPER_TYPE AddType, Lstring admin)
{
if(pos < 0 || pos >= INVAILD_POS)
{
LLOG_ERROR("Desk::HanderAddCardCount pos = %d error", pos);
return;
}
if(!m_user[pos])
{
LLOG_ERROR("Desk::HanderAddCardCount user = %d is null", pos);
return;
}
if(CardNum <= 0) return;
m_user[pos]->AddCardCount(CARD_TYPE_8, CardNum, AddType, admin);
}
void Desk::HanderDelCardCount(Lint cardType, Lint count, Lint operType, Lstring admin, Lint feeType, Lint userId, Lstring unioid)
{
LLOG_ERROR("*****DeskId:%d 房主建房 Desk::HanderDelCardCount type=%d,count=%d,operType=%d,FORCE_ROOM_CARD_FREE=%d", m_id, cardType, count, operType, FORCE_ROOM_CARD_FREE);
if (FORCE_ROOM_CARD_FREE) {
return;
}
//会长钻石券
if (CARDS_OPER_TYPE_CLUB_DIAMOND==operType)
{
LMsgL2LMGModifyCard msg;
msg.admin=admin;
msg.cardType=cardType;
msg.cardNum=count;
msg.isAddCard=0;
msg.operType=operType;
msg.m_userid=userId;
msg.m_strUUID=unioid;
gWork.SendToLogicManager(msg);
return;
}
/*
int delCount = ::GetCardDelCount(cardType, count);
if (!feeType) {
delCount = delCount * 4;
}*/
User* user = gUserManager.GetUserbyDataId(userId);
if (user) {
if (user->m_userData.m_numOfCard2s - count >= 0)
user->m_userData.m_numOfCard2s = user->m_userData.m_numOfCard2s - count;
else
user->m_userData.m_numOfCard2s = 0;
}
LMsgL2LMGModifyCard msg;
msg.admin = admin;
msg.cardType = cardType;
msg.cardNum = count;
msg.isAddCard = 0;
msg.operType = operType;
msg.m_userid = userId;
msg.m_strUUID = unioid;
gWork.SendToLogicManager(msg);
}
bool Desk::DissmissAllplayer()
{
if (getDeskState() == DESK_WAIT)
{
LLOG_DEBUG("Desk::DissmissAllplayer deskid=%d deskstate=%d", GetDeskId() , getDeskState());
ResetEnd();
return true;
}
return false;
}
Lint Desk::GetFirstZhuangPos()
{
return m_zhuangPos;
}
void Desk::_clearData()
{
m_id = 0;
m_deskbeforeState = DESK_FREE;
m_deskState = DESK_FREE;
m_deskPlayState = -1;
memset(m_user, 0, sizeof(m_user));
m_vip = 0;
for (int i = 0; i < DESK_USER_COUNT; i++) {
m_seat[i] = INVAILD_POS;
}
//memset(m_seat, 0, sizeof(m_seat));
memset(m_readyState, 0, sizeof(m_readyState));
m_state = 0;
m_playtype.clear();
ResetClear();
SpecialCardClear();
m_resetUser = ""; //申请的玩家
m_resetTime = 0; //申请解算的时间
mGameHandler = NULL;
m_iPlayerCapacity = 0;
m_timeDeskCreate = 0;
m_cost = 0;
m_even = 0;
m_free = 0;
m_startTime = 0;
m_endTime = 0;
m_gameStartTime = 0;
memset( m_autoPlay, 0, sizeof(m_autoPlay) );
memset( m_autoPlayTime, 0, sizeof(m_autoPlayTime) );
memset( m_autoOutTime, 0, sizeof(m_autoOutTime) );
m_autoChangeOutTime = 0;
m_autoPlayOutTime = 0;
m_baseScore = 1;
memset( m_coinsResult, 0, sizeof(m_coinsResult) );
m_creatUser = NULL;
m_deskType = DeskType_Common;
m_selectSeat = false; //选座状态 创建房间时为true 选择完座位时为false
m_firestUser = NULL;
for (int i = 0; i < 4; i++)
{
m_seatUser[i] = NULL;
m_videoPermit[i] = 1;
}
m_zhuangPos = 0;
m_dismissUser = false;
m_couFei = false;
//清空
memset(m_switchPos, 0x00, sizeof(m_switchPos));
//m_desk_all_user.clear();
m_desk_Lookon_user.clear();
m_user_select_seat_turn.clear();
m_Greater2CanStart=0;
m_StartGameButtonPos=INVAILD_POS;
m_startButtonAppear=0;
m_clubInfo.reset();
m_bIsDissmissed = false;
m_Gps_Limit = 0;
}
bool Desk::_createRegister(GameType gameType)
{
mGameHandler = GameHandlerFactory::getInstance()->create(gameType);
if (!mGameHandler)
{
LLOG_ERROR("No game handler for game type %d found.", gameType);
return false;
}
mGameHandler->startup(this);
return true;
}
//////////////////////////////////////////////////////////////////////////
//by wyz 20171103 改好,机器人选择不能用,这个函数没有改
void Desk::MHProcessRobotSelectSeat(User * pUser)
{
LLOG_DEBUG("******Desk::MHProcessRebootSelectSea处理机器人位置选择*********");
if (pUser->m_desk != this)
{
LLOG_ERROR("Error, user did not add to desk userid=%d deskid=%d", pUser->GetUserDataId(), this->GetDeskId());
return;
}
if (m_deskState != DESK_WAIT/*&&m_deskState !=DESK_COUNT_RESULT*/)
{
LLOG_ERROR("desk state error, userid=%d deskstate=%d", pUser->GetUserDataId(), m_deskState);
return;
}
if (!m_selectSeat)
{
LLOG_ERROR("desk state error, desk is not in select seat. deskid = %d, selectseat=%d", GetDeskId(), m_selectSeat);
return;
}
Lint pos = GetUserPos(pUser);
if (pos == INVAILD_POS)
{
LLOG_ERROR("error user pos, userid = %d, pos = %d", pUser->GetUserDataId(), pos);
return;
}
Lint pos_user_selected = INVAILD_POS;
User * pActiveUser = 0;
for (int i = 0; i < DESK_USER_COUNT; i++)
{
if (m_user[i] != NULL && m_user[i]->GetUserDataId() < 10000000)
{
pActiveUser = m_user[i];
LLOG_DEBUG("Desk::MHProcessRebootSelectSeat found user, userid = %d", pActiveUser->GetUserDataId());
break;
}
}
if (gConfig.GetDebugModel() && gConfig.GetIfAddRobot())
{
Lint pos_will_selected = INVAILD_POS;
for (int j = 0; j < DESK_USER_COUNT; j++)
{
bool bSelected = false;
for (int i = 0; i < DESK_USER_COUNT; i++)
{
if (j == m_seat[i])
{
bSelected = true;
break;
}
}
if (!bSelected)
{
pos_will_selected = j;
LLOG_DEBUG("Desk::MHProcessRebootSelectSeat 找到未使用的座位号 %d", pos_will_selected);
break;
}
}
if (pos_will_selected != INVAILD_POS)
{
LMsgS2CUserSelectSeat selectSeat;
m_seat[pos] = pos_will_selected; //用户选择的位置
selectSeat.m_id = pUser->GetUserDataId();
selectSeat.m_pos = pos_will_selected;
BoadCast(selectSeat); //广播用户选择位置
m_readyState[pos] = 1;
m_seatUser[pos_will_selected] = m_user[pos]; //m_seatUser的Index就是座位号
}
this->CheckGameStart();
}
}
void Desk::MHPrintDeskStatus()
{
char buf[64];
int user_count = 0;
#ifdef WIN32
LTime time;
time.SetSecs(m_timeDeskCreate);
_snprintf_s(buf, 512, "%04d%02d%02d-%02d:%02d:%02d", time.GetYear(), time.GetMonth(), time.GetMday(), time.GetHour(), time.GetMin(), time.GetSec());
buf[63] = 0;
for (int i = 0; i < DESK_USER_COUNT; i++)
{
if (m_user[i])
{
user_count++;
}
}
MHLOG_DESK("Desk id= %d state= %d usercount=%d cratetime= %s", m_id, m_deskState, user_count, buf);
#endif // WIN32
}
//////////////////////////////
//判断是否Lookon用户
bool Desk::MHIsLookonUser(User* pUser)
{
if (pUser==NULL)return false;
std::list<User*>::iterator finduser=find(m_desk_Lookon_user.begin(), m_desk_Lookon_user.end(), pUser);
if (finduser==m_desk_Lookon_user.end())
return false;
return true;
}
//判断选座用户
bool Desk::MHIsInSeatTurn(User* pUser)
{
if (pUser==NULL)return false;
if (GetUserSeatPos(pUser)==INVAILD_POS)
{
m_user_select_seat_turn.remove(pUser);
return false;
}
std::list<User*>::iterator finduser=find(m_user_select_seat_turn.begin(), m_user_select_seat_turn.end(), pUser);
if (finduser==m_user_select_seat_turn.end())
return false;
return true;
}
bool Desk::MHIsRoomUser(User* pUser)
{
//if (pUser==NULL)return false;
//std::list<User*>::iterator finduser=find(m_desk_all_user.begin(), m_desk_all_user.end(), pUser);
//if (finduser==m_desk_all_user.end())
// return false;
//return true;
return (MHIsLookonUser(pUser)||MHIsSeatUser(pUser));
}
bool Desk::MHIsSeatUser(User* pUser)
{
if (pUser==NULL)return false;
for (Lint i=0; i<m_iPlayerCapacity; ++i)
{
if (m_seatUser[i]==pUser)
return true;
}
return false;
}
//广播桌子所有用户
void Desk::MHBoadCastAllDeskUser(LMsg& msg)
{
LLOG_DEBUG("Logwyz-------------Desk::MHBoadCastAllDeskUser ");
//LLOG_DEBUG("Logwyz-------------Desk::MHBoadCastAllDeskUser size=[%d], msgid=[%d] ",m_desk_all_user.size(),msg.m_msgId);
//std::list<User*>::iterator userIt;
//for (userIt=m_desk_all_user.begin(); userIt!=m_desk_all_user.end(); ++userIt)
//{
// User* temp=*userIt;
// if (temp==NULL)continue;
// temp->Send(msg);
//}
//广播座位用户
MHBoadCastDeskSeatUser(msg);
//广播lookon用户
MHBoadCastDeskLookonUser(msg);
}
//广播桌子所有用户without usr
void Desk::MHBoadCastAllDeskUserWithOutUser(LMsg& msg, User* user)
{
LLOG_DEBUG("Logwyz-------------Desk::MHBoadCastAllDeskUser(LMsg& msg) ");
//std::list<User*>::iterator userIt;
//for (userIt=m_desk_all_user.begin(); userIt!=m_desk_all_user.end(); ++userIt)
//{
// User* temp=*userIt;
// if (temp==NULL||temp!=user)continue;
// temp->Send(msg);
//}
MHBoadCastDeskSeatUserWithOutUser(msg, user);
MHBoadCastDeskLookonUserWithOutUser(msg, user);
}
//广播桌子Lookon用户
void Desk::MHBoadCastDeskLookonUser(LMsg& msg)
{
LLOG_DEBUG("Logwyz-------------Desk::MHBoadCastDeskLookonUser(LMsg& msg) ,size=[%d]", m_desk_Lookon_user.size());
std::list<User*>::iterator userIt;
for (userIt=m_desk_Lookon_user.begin(); userIt!=m_desk_Lookon_user.end(); ++userIt)
{
User* temp=*userIt;
if (temp==NULL)continue;
temp->Send(msg);
}
}
//广播桌子Lookon用户without user
void Desk::MHBoadCastDeskLookonUserWithOutUser(LMsg& msg, User* user)
{
LLOG_DEBUG("Logwyz-------------Desk::MHBoadCastDeskLookonUserWithOutUser");
std::list<User*>::iterator userIt;
for (userIt=m_desk_Lookon_user.begin(); userIt!=m_desk_Lookon_user.end(); ++userIt)
{
User* temp=*userIt;
if (temp==NULL||temp!=user)continue;
temp->Send(msg);
}
}
//广播桌上座位用户
void Desk::MHBoadCastDeskSeatUser(LMsg& msg)
{
LLOG_DEBUG("MHBoadCastDeskSeatUser m_iPlayerCapacity = %d", m_iPlayerCapacity);
for (Lint i=0; i < m_iPlayerCapacity; ++i)
{
if (m_seatUser[i])
m_seatUser[i]->Send(msg);
}
}
//广播桌上座位用户without user
void Desk::MHBoadCastDeskSeatUserWithOutUser(LMsg& msg , User* user)
{
LLOG_DEBUG("MHBoadCastDeskSeatUserWithOutUser m_iPlayerCapacity = %d", m_iPlayerCapacity);
for (Lint i=0; i < m_iPlayerCapacity; ++i)
{
if (m_seatUser[i]&&m_seatUser[i]!=user)
m_seatUser[i]->Send(msg);
}
}
//入座人数 ;GetUserCount() 是游戏人数
Lint Desk::MHGetSeatUserCount()
{
Lint cnt=0;
for (Lint i=0; i < m_iPlayerCapacity; ++i)
{
if (m_seatUser[i])
{
cnt+=1;
}
}
return cnt;
}
Lint Desk::MHGetDeskUserCount()
{
return MHGetSeatUserCount()+m_desk_Lookon_user.size();
}
//判断是否开始游戏
Lint Desk::MHCheckGameStart()
{
LLOG_DEBUG("*********************************************Desk::MHCheckGameStart()");
if (m_deskState!=DESK_WAIT) //只有桌子为等待状态才继续
{
LLOG_DEBUG("Desk's status is wrong. Desk state = %d.", m_deskState);
return 0;
}
if (m_resetTime!=0)
{
LLOG_DEBUG("Desk ising reseted");
return 0;
}
//判断所有的人是否都已经准备
LLOG_DEBUG("Logwyz ..............twoCanStartGame=[%d]", m_Greater2CanStart);
if (m_Greater2CanStart) //>2可以开始
{
if (MHGetSeatUserCount()<2)
{
LLOG_DEBUG("The player num isn't enought");
return 0;
}
}
else
{
if (MHGetSeatUserCount()!=m_iPlayerCapacity)
{
LLOG_DEBUG("The player num isn't enought");
return 0;
}
}
//座位上人数准备状况
for (int i=0; i < m_iPlayerCapacity; i++)
{
if (m_seatUser[i]!=NULL &&m_readyState[i]==0)
{
LLOG_DEBUG("The player[%d] hasn't been ready", m_seatUser[i]->GetUserDataId());
return 0;
}
}
//第一局
if (m_vip->m_curCircle==0&&m_Greater2CanStart==1)
{
LLOG_DEBUG("first dw begin...");
return 1;
}
else
{
LLOG_DEBUG("not first dw begin game...");
MHHanderStartGame();
return 2;
}
//for (int i=0; i < m_iPlayerCapacity; i++)
//{
// if (m_user[i]==NULL||!m_readyState[i])
// {
// LLOG_DEBUG("The player hasn't been ready");
// return;
// }
//}
//
//for (int i=0; i < m_iPlayerCapacity; i++)
//{
// if (m_seat[i]==INVAILD_POS)
// {
// LLOG_DEBUG("The player hasn't been select seat");
// return;
// }
//}
//
//
//
//m_selectSeat=false;
//
//for (int i=0; i < DESK_USER_COUNT; i++)
//{
// m_user[i]=m_seatUser[i]; //如果都准备好,把m_seatUser所有用户拷贝到m_user,这样m_user的索引号为座位号
//}
//
//GetVip()->ResetUser(m_user);
//
//bool bFind=false;
//if (m_creatUser) {
// for (int i=0; i < DESK_USER_COUNT; i++)
// {
// if (m_creatUser==m_user[i]) {
// LLOG_DEBUG("m_zhuangPos = %d", i);
// m_zhuangPos=i;
// bFind=true;
// break;
// }
// }
//}
//
//
//if (!bFind && m_firestUser) {
// for (int i=0; i < DESK_USER_COUNT; i++)
// {
// if (m_firestUser==m_user[i]) {
// LLOG_DEBUG("m_zhuangPos = %d", i);
// m_zhuangPos=i;
// bFind=true;
// break;
// }
// }
//}
//
//if (mGameHandler)
//{
// mGameHandler->SetDeskPlay();
//}
//else
//{
// LLOG_ERROR("Game handler han't beed created");
//}
//LLOG_ERROR("**************桌子ID: %d ", m_id);
//for (int i=0; i < m_iPlayerCapacity; i++)
//{
// if (m_user[i]) {
// LLOG_ERROR("********** %s IP = %s", m_user[i]->GetUserData().m_nike.c_str(), m_user[i]->m_userData.m_customString1.c_str());
// }
//}
}
//开始游戏
void Desk::MHHanderStartGame()
{
LLOG_DEBUG("Logwyz....................MHHanderStartGame()");
//换一个转换方法
int j=0;
memset(m_switchPos, 0x00, sizeof(m_switchPos));
for (int i=0; i<DESK_USER_COUNT; i++)
{
if (m_seatUser[i])
{
m_user[j]=m_seatUser[i];
m_switchPos[j++]=i;
}
}
m_desk_user_count=j;
//位置转换
memcpy(m_seatUser, m_user, sizeof(m_seatUser));
for (int i=0; i<DESK_USER_COUNT; i++)
{
m_switchPos[i]=i;
}
GetVip()->ResetUser(m_user);
////这里首局选庄
//bool bFind=false;
//if (m_creatUser) {
// for (int i=0; i < DESK_USER_COUNT; i++)
// {
// if (m_creatUser==m_user[i]) {
// LLOG_DEBUG("m_zhuangPos = %d", i);
// m_zhuangPos=i;
// bFind=true;
// break;
// }
// }
//}
//
//if (!bFind && m_firestUser) {
// for (int i=0; i < DESK_USER_COUNT; i++)
// {
// if (m_firestUser==m_user[i]) {
// LLOG_DEBUG("m_zhuangPos = %d", i);
// m_zhuangPos=i;
// bFind=true;
// break;
// }
// }
//}
if (m_vip && !m_vip->IsBegin())
{
m_gameStartTime = time(NULL);
}
m_zhuangPos=MHSpecPersonPos();
LLOG_DEBUG("Logwyz MHHanderStartGame m_zhuangPos = %d", m_zhuangPos);
if (mGameHandler)
{
mGameHandler->MHSetDeskPlay(m_desk_user_count);
}
else
{
LLOG_ERROR("Game handler han't beed created");
}
//LLOG_ERROR("**************桌子ID: %d ", m_id);
//for (int i=0; i < m_iPlayerCapacity; i++)
//{
// if (m_user[i]) {
// LLOG_ERROR("********** %s IP = %s", m_user[i]->GetUserData().m_nike.c_str(), m_user[i]->m_userData.m_customString1.c_str());
// }
//}
}
//解散时,清空lookon
void Desk::MHClearLookonUser()
{
LLOG_DEBUG("Logwyz-------------Desk::MHClearLookonUser()");
if (m_deskType==DeskType_Common)
{
LLOG_DEBUG("Desk::MHClearLookonUser(): Lookon User size = %d", m_desk_Lookon_user.size());
//std::list<User*>::iterator userIt;
//for (userIt=m_desk_Lookon_user.begin(); userIt!=m_desk_Lookon_user.end(); ++userIt)
//{
// User* temp=*userIt;
// if (temp==NULL)continue;
// OnUserOutRoom(temp);
//
//}
Lint lookonUserCount=m_desk_Lookon_user.size();
for (int i=0; i<lookonUserCount; ++i)
{
LLOG_DEBUG("Logwyz-------------Desk::MHClearLookonUser() in for begin size=[%d]", m_desk_Lookon_user.size());
if (m_desk_Lookon_user.size()==0)break;
User* temp=m_desk_Lookon_user.back();
if (temp==NULL)continue;
OnUserOutRoom(temp);
LLOG_DEBUG("Logwyz-------------Desk::MHClearLookonUser() in for end size=[%d]", m_desk_Lookon_user.size());
}
LLOG_INFO("Logwyz-------------m_desk_Lookon_user.clear()");
//m_desk_all_user.clear();
m_desk_Lookon_user.clear();
m_user_select_seat_turn.clear();
//for (Lint i=0; i < m_iPlayerCapacity; ++i)
//{
// if (m_user[i])
// OnUserOutRoom(m_user[i]);
//}
}
else
{
// ????? 金币场 是啥,什么时候用
LLOG_DEBUG("else ::: Lookon User size = %d", m_desk_Lookon_user.size());
//for (Lint i=0; i < m_iPlayerCapacity; ++i)
//{
// if (m_user[i])
// {
// m_user[i]->setUserState(LGU_STATE_COIN);
// m_user[i]->ModifyUserState(true); //修改user状态,通知金币服务器
//
// m_user[i]->SetDesk(NULL);
//
// //删除玩家 不删除机器人
// if (m_user[i]->getUserGateID()!=65535) //不是机器人删除掉
// {
// UserManager::Instance().DelUser(m_user[i]);
// delete m_user[i];
// m_user[i]=NULL;
// }
//
// m_readyState[i]=0;
// }
//}
}
}
//客户端发送开始游戏指令
void Desk::MHHanderStartGameButton(User* pUser, LMsgC2SStartGame *msg)
{
LLOG_ERROR("Desk::MHHanderStartGameButton");
if (pUser==NULL||msg==NULL)return;
LMsgC2SStartGame startButton;
Lint seatID=GetUserSeatPos(pUser);
if (m_deskState!=DESK_WAIT/*&&m_deskState !=DESK_COUNT_RESULT*/)
{
LLOG_ERROR("Desk::MHHanderStartGameButton state error, userid=%d deskstate=%d", pUser->GetUserDataId(), m_deskState);
return;
}
if (seatID==INVAILD_POS)
{
LLOG_ERROR("Desk::MHHanderStartGameButton pos error, userid=%d seatID=%d", pUser->GetUserDataId(), seatID);
return;
}
if (seatID!=m_StartGameButtonPos)
{
LLOG_ERROR("Desk::MHHanderStartGameButton pos error, userid=%d seatID=%d,m_StartGameButtonPos=[%d]", pUser->GetUserDataId(), seatID, m_StartGameButtonPos);
return;
}
if(MHGetSeatUserCount()<2)
{
LLOG_ERROR("Desk::MHHanderStartGameButton player not enough, userid=%d seatID=%d,m_StartGameButtonPos=[%d],MHGetSeatUserCount()=[%d]", pUser->GetUserDataId(), seatID, m_StartGameButtonPos, MHGetSeatUserCount());
//这种情况,说明有人退出了,不能开始游戏,把开始按钮收回
m_StartGameButtonPos=INVAILD_POS;
return;
}
//把没有选座的玩家提出房间
LLOG_DEBUG("DeskType_Common::: Lookon User size = %d", m_desk_Lookon_user.size());
std::list<User*>::iterator userIt;
//for (userIt=m_desk_Lookon_user.begin(); userIt!=m_desk_Lookon_user.end(); ++userIt)
//{
// User* temp=*userIt;
// if (temp==NULL)continue;
// OnUserOutRoom(temp);
//
//}
Lint lookonUserCount=m_desk_Lookon_user.size();
for (int i=0; i<lookonUserCount; ++i)
{
LLOG_DEBUG(" in for begin m_desk_Lookon_user.size()=[%d]", m_desk_Lookon_user.size());
if (m_desk_Lookon_user.size()==0)break;
User* temp=m_desk_Lookon_user.back();
if (temp==NULL)continue;
OnUserOutRoom(temp);
LLOG_DEBUG(" in for end m_desk_Lookon_user.size()=[%d]", m_desk_Lookon_user.size());
}
m_desk_Lookon_user.clear();
LLOG_DEBUG("Logwyz .... MHCheckGameStart() 2553 ");
//开始按钮位置为无效
m_StartGameButtonPos=INVAILD_POS;
m_startButtonAppear=1;
MHHanderStartGame();
}
//选择特殊用户的位置位置(规则:如果创建房间的人入座了,返回其位置;如果没有,选择第一个入座的人的位置;如果没有,东南西北依次)
Lint Desk::MHSpecPersonPos()
{
//if (m_creatUser)
//{
// if (GetUserSeatPos(m_creatUser)!=INVAILD_POS)
// return GetUserSeatPos(m_creatUser);
//}
if (MHGetCreatorSeatPos()!=INVAILD_POS)
return MHGetCreatorSeatPos();
//选座时间
std::list<User*>::iterator userIt;
for (userIt=m_user_select_seat_turn.begin(); userIt!=m_user_select_seat_turn.end(); ++userIt)
{
User* temp=*userIt;
if (temp==NULL)continue;
if (GetUserSeatPos(temp)!=INVAILD_POS)
return GetUserSeatPos(temp);
}
//预防措施m_user_select_seat_turn没有人,按东南西北计算
for (Lint i=0; i<m_iPlayerCapacity; ++i)
{
if (m_seatUser[i])return i;
}
return INVAILD_POS;
}
//返回房主在m_seatUser 中的位置,不存在返回INVAILD_POS
Lint Desk::MHGetCreatorSeatPos()
{
for (Lint i=0; i < m_iPlayerCapacity; ++i)
{
if (m_seatUser[i])
{
if (m_seatUser[i]->GetUserDataId()==m_creatUserId)
return i;
}
}
return INVAILD_POS;
}
//返回房主在m_user 中的位置,不存在返回INVAILD_POS
Lint Desk::MHGetCreatorPos()
{
for (Lint i=0; i < m_iPlayerCapacity; ++i)
{
if (m_user[i])
{
if (m_user[i]->GetUserDataId()==m_creatUserId)
return i;
}
}
return INVAILD_POS;
}
Lint Desk::MHGetDeskUser(std::vector<Lstring> &seatPlayerName, std::vector<Lstring> &noSeatPlayerName)
{
//入座
for (int i=0; i<DESK_USER_COUNT; i++)
{
if (m_seatUser[i])
seatPlayerName.push_back(m_seatUser[i]->m_userData.m_nike);
}
//为入座
for (auto ItLookonUser=m_desk_Lookon_user.begin(); ItLookonUser!=m_desk_Lookon_user.end(); ItLookonUser++)
{
noSeatPlayerName.push_back((*ItLookonUser)->m_userData.m_nike);
}
return 0;
}
void Desk::MHNotifyManagerDeskInfo(Lint roomFull, Lint currCircle, Lint totalCircle)
{
LLOG_DEBUG("Desk::MHNotifyManagerDeskInfo roomFull=[%d],currCircle=[%d], totalCircle=[%d]", roomFull, currCircle, totalCircle);
LMsgL2LMGFreshDeskInfo send;
send.m_clubId=m_clubInfo.m_clubId;
send.m_playTypeId=m_clubInfo.m_playTypeId;
send.m_clubDeskId=m_clubInfo.m_clubDeskId;
send.m_showDeskId=m_clubInfo.m_showDeskId;
send.m_roomFull=roomFull;
send.m_currCircle=currCircle;
send.m_totalCircle=totalCircle;
gWork.SendToLogicManager(send);
}
bool Desk::MHCheckUserGPSLimit(User *pUser, Lstring & desk_gps_list)
{
bool bRet = true;
if (NULL == pUser)
{
LLOG_ERROR("Desk::MHCheckUserGPSLimit, param error, empty user, desk:%d, GPSLimit=%d", m_id, m_Gps_Limit);
return false;
}
LLOG_ERROR("Desk::MHCheckUserGPSLimit, desk:%d, user:%d", m_id, pUser->GetUserDataId());
if (m_Gps_Limit == 0)
return bRet;
std::ostringstream ss;
Lstring user_name = string_replace(pUser->m_userData.m_nike, Lstring(","), Lstring(""));
user_name = string_replace(user_name, Lstring("|"), Lstring(""));
ss << user_name << ",";
ss << pUser->m_userData.m_customString2;
{
//进入用户和在座用户
boost::mutex::scoped_lock l(m_mutexDeskLookonUser);
for(auto it = m_desk_Lookon_user.begin(); it != m_desk_Lookon_user.end();it++)
{
if ((*it)->IsInLimitGPSPosition(*pUser))
bRet = false;
if (pUser->GetUserDataId() != (*it)->GetUserDataId())
{
Lstring user_name = string_replace((*it)->m_userData.m_nike, Lstring(","), Lstring(""));
user_name = string_replace(user_name, Lstring("|"), Lstring(""));
ss << "|" << user_name << "," << (*it)->m_userData.m_customString2;
}
}
}
for (int i = 0; i < m_iPlayerCapacity; i++)
{
if (m_seatUser[i])
{
if (m_seatUser[i]->IsInLimitGPSPosition(*pUser))
bRet = false;
if (pUser->GetUserDataId() != m_seatUser[i]->GetUserDataId())
{
Lstring user_name = string_replace(m_seatUser[i]->m_userData.m_nike, Lstring(","), Lstring(""));
user_name = string_replace(user_name, Lstring("|"), Lstring(""));
ss << "|" << user_name << "," << m_seatUser[i]->m_userData.m_customString2;
}
}
}
desk_gps_list = ss.str();
return bRet;
}
bool Desk::MHDismissDeskOnPlay()
{
ResetEnd();
return true;
}
|
00d75327cb336e5bb4028078b389dd5e2426cb40
|
6d4299ea826239093a91ff56c2399f66f76cc72a
|
/Visual Studio 2017/Projects/baekjun/baekjun/4597.cpp
|
1683cd0e85c882efebf03c169e250671f988e9ed
|
[] |
no_license
|
kongyi123/Algorithms
|
3eba88cff7dfb36fb4c7f3dc03800640b685801b
|
302750036b06cd6ead374d034d29a1144f190979
|
refs/heads/master
| 2022-06-18T07:23:35.652041
| 2022-05-29T16:07:56
| 2022-05-29T16:07:56
| 142,523,662
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 650
|
cpp
|
4597.cpp
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <memory.h>
char str[100];
int main(void) {
while (1) {
fscanf(stdin, "%s", &str[1]);
if (str[1] == '#') break;
int len = strlen(&str[1]);
int cnt = 0;
for (int i = 1;i < len;i++) {
if (str[i] == '1') cnt++;
}
char ch = str[len];
str[len] = 0;
if (ch == 'o' && cnt % 2 == 1) fprintf(stdout, "%s0\n", &str[1]);
else if (ch == 'o' && cnt % 2 == 0) fprintf(stdout, "%s1\n", &str[1]);
else if (ch == 'e' && cnt % 2 == 1) fprintf(stdout, "%s1\n", &str[1]);
else if (ch == 'e' && cnt % 2 == 0) fprintf(stdout, "%s0\n", &str[1]);
}
return 0;
}
|
fd76c4dd257f7ca48f32bb9b3967fdad5e76ab71
|
49844c7c88e70d95d5ba498737caedd9dd869866
|
/src/class/include/class/ButtonLoader.hpp
|
20968fbb03b9caabd983d42fa26a14fc73c55bd3
|
[] |
no_license
|
mmmaxou/une-piece
|
42f30285fc78633ae77e7a1fe639f0162e7470ca
|
9ebb89758fa8e98c1c5e1761b9317212066d03e5
|
refs/heads/master
| 2020-04-06T23:25:25.989124
| 2019-02-13T06:35:36
| 2019-02-13T06:35:36
| 157,868,387
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,893
|
hpp
|
ButtonLoader.hpp
|
#ifndef BUTTON_LOADER_UP_HPP__
#define BUTTON_LOADER_UP_HPP__
#pragma once
#include <class/StaticImageLoader.hpp>
#include <glimac/SDLWindowManager.hpp>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace glimac;
namespace UP
{
struct Button : public StaticImage
{
GLuint* _texture_hovered;
GLuint* _texture_clicked;
bool _isHovered;
bool _isClicked;
std::function<void()> _behavior;
Button()
: _isClicked(false), _isHovered(false)
{}
};
/**
* @brief ButtonLoader Object
* @brief Create StaticImages for a button
* @brief Manage the button State ( hover / clicked )
* @brief Manage the button Behavior
*
*/
class ButtonLoader : public StaticImageLoader
{
public:
/// Constructor and destructor
/**
* @brief Destroy the Button Loader:: Button Loader object
*
*/
~ButtonLoader();
/// Methods
/**
* @brief Set enabled to False for all the buttons
*
*/
void disable() const;
/**
* @brief Get the Button object
*
* @param buttonName
* @param file
* @param line
* @param function
* @return Button*
*/
Button* getButton(const std::string &buttonName, const char* file, const unsigned int line, const char* function);
/**
* @brief Get the Button object
*
* @param buttonName
* @param file
* @param line
* @param function
* @return Button*
*/
Button* getButton(const std::string &buttonName, const char* file, const unsigned int line, const char* function) const;
/**
* @brief Set the buttons to the state hovered
*
*/
void mouseHover(const SDL_Event &e) const;
/**
* @brief Set the buttons to the state Clicked
*
*/
void mouseClick() const;
/**
* @brief Disable the state Clicked
*
*/
void mouseUnclick() const;
/**
* @brief Add an image to the Loader. REQUIRE 3 images :
* @brief "<filename>", "<filename>_hovered" and "<filename>_clicked"
*
* @param filename
* @param x
* @param y
* @param scale
*/
void addImage(const std::string &filename, const float &x=0.f, const float &y=0.f, const float &scale=1.0f);
/**
* @brief Setup things for an image :
* @brief - Vertices of the square
* @brief - Matrix corresponding of the shape and ratio of the square
* @brief - IBO
*
* @param filename
* @param x
* @param y
* @param scale
* @param img
*/
void setupImage(const std::string &filename, const float &x, const float &y, const float &scale, Button *img);
/**
* @brief Set the Behavior object
*
* @param imageName
* @param behavior
*/
void setBehavior(const std::string &imageName, const std::function<void()> &behavior) const;
/**
* @brief Display 1 image
*
* @param imageName
*/
void displayImage(const std::string &imageName) const;
// METHODS
};
}
#endif
|
37d4adff8680c303959cbec2f84bfa50f82e1502
|
10587620d1875a32090a9145a9f4cf6ed83d54e2
|
/C++编程/Qt网络编程/基于QT框架,HTTP协议下的一个简单的图片阅读器/build-PhotoShow-Desktop_Qt_5_7_0_MinGW_32bit-Debug/ui_photoshow.h
|
46fb0fdf2710f5cc63366f2be87d66f937ce11d2
|
[] |
no_license
|
zhengzebin525/LINUX-Environmental-programming
|
2eab34cfdcc959e92224b2eda696d20907f68fef
|
18952913a36e73a3352b4af3dcf8494eac83029a
|
refs/heads/master
| 2020-04-16T04:08:35.759680
| 2019-07-07T14:20:00
| 2019-07-07T14:20:00
| 165,257,064
| 4
| 11
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,696
|
h
|
ui_photoshow.h
|
/********************************************************************************
** Form generated from reading UI file 'photoshow.ui'
**
** Created by: Qt User Interface Compiler version 5.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_PHOTOSHOW_H
#define UI_PHOTOSHOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QListWidget>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_PhotoShow
{
public:
QAction *actionClear;
QAction *actionUpdata;
QWidget *centralWidget;
QListWidget *Photolist;
QLabel *photolabel;
QMenuBar *menuBar;
QMenu *menu;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *PhotoShow)
{
if (PhotoShow->objectName().isEmpty())
PhotoShow->setObjectName(QStringLiteral("PhotoShow"));
PhotoShow->resize(432, 379);
actionClear = new QAction(PhotoShow);
actionClear->setObjectName(QStringLiteral("actionClear"));
actionUpdata = new QAction(PhotoShow);
actionUpdata->setObjectName(QStringLiteral("actionUpdata"));
centralWidget = new QWidget(PhotoShow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
Photolist = new QListWidget(centralWidget);
Photolist->setObjectName(QStringLiteral("Photolist"));
Photolist->setGeometry(QRect(0, 0, 151, 271));
photolabel = new QLabel(centralWidget);
photolabel->setObjectName(QStringLiteral("photolabel"));
photolabel->setGeometry(QRect(170, 0, 221, 311));
photolabel->setLayoutDirection(Qt::LeftToRight);
PhotoShow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(PhotoShow);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 432, 23));
menu = new QMenu(menuBar);
menu->setObjectName(QStringLiteral("menu"));
PhotoShow->setMenuBar(menuBar);
mainToolBar = new QToolBar(PhotoShow);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
PhotoShow->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(PhotoShow);
statusBar->setObjectName(QStringLiteral("statusBar"));
PhotoShow->setStatusBar(statusBar);
menuBar->addAction(menu->menuAction());
menu->addAction(actionClear);
menu->addAction(actionUpdata);
retranslateUi(PhotoShow);
QMetaObject::connectSlotsByName(PhotoShow);
} // setupUi
void retranslateUi(QMainWindow *PhotoShow)
{
PhotoShow->setWindowTitle(QApplication::translate("PhotoShow", "PhotoShow", 0));
actionClear->setText(QApplication::translate("PhotoShow", "clear", 0));
actionUpdata->setText(QApplication::translate("PhotoShow", "update", 0));
photolabel->setText(QApplication::translate("PhotoShow", "\345\233\276\347\211\207\346\230\276\347\244\272", 0));
menu->setTitle(QApplication::translate("PhotoShow", "\350\217\234\345\215\225", 0));
} // retranslateUi
};
namespace Ui {
class PhotoShow: public Ui_PhotoShow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_PHOTOSHOW_H
|
6a442b619fd0b1747683613f1f89c5766d3ff137
|
d7d6678b2c73f46ffe657f37169f8e17e2899984
|
/controllers/ros/include/services/motor_get_acceleration.h
|
50b0fa5a5e6c8e644078f521ba3e7e35597a3c5e
|
[] |
no_license
|
rggasoto/AdvRobotNav
|
ad8245618e1cc65aaf9a0d659c4bb1588f035f18
|
d562ba4fba896dc23ea917bc2ca2d3c9e839b037
|
refs/heads/master
| 2021-05-31T12:00:12.452249
| 2016-04-15T14:02:05
| 2016-04-15T14:02:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,328
|
h
|
motor_get_acceleration.h
|
#ifndef WEBOTS_ROS_MESSAGE_MOTOR_GET_ACCELERATION_H
#define WEBOTS_ROS_MESSAGE_MOTOR_GET_ACCELERATION_H
#include "ros/service_traits.h"
#include "motor_get_accelerationRequest.h"
#include "motor_get_accelerationResponse.h"
namespace webots_ros
{
struct motor_get_acceleration
{
typedef motor_get_accelerationRequest Request;
typedef motor_get_accelerationResponse Response;
Request request;
Response response;
typedef Request RequestType;
typedef Response ResponseType;
};
} // namespace webots_ros
namespace ros
{
namespace service_traits
{
template<>
struct MD5Sum< ::webots_ros::motor_get_acceleration > {
static const char* value()
{
return "57794db3a45a41ef77957ee422483467";
}
static const char* value(const ::webots_ros::motor_get_acceleration&) { return value(); }
};
template<>
struct DataType< ::webots_ros::motor_get_acceleration > {
static const char* value()
{
return "webots_ros/motor_get_acceleration";
}
static const char* value(const ::webots_ros::motor_get_acceleration&) { return value(); }
};
template<>
struct MD5Sum< ::webots_ros::motor_get_accelerationRequest>
{
static const char* value()
{
return MD5Sum< ::webots_ros::motor_get_acceleration >::value();
}
static const char* value(const ::webots_ros::motor_get_accelerationRequest&)
{
return value();
}
};
template<>
struct DataType< ::webots_ros::motor_get_accelerationRequest>
{
static const char* value()
{
return DataType< ::webots_ros::motor_get_acceleration >::value();
}
static const char* value(const ::webots_ros::motor_get_accelerationRequest&)
{
return value();
}
};
template<>
struct MD5Sum< ::webots_ros::motor_get_accelerationResponse>
{
static const char* value()
{
return MD5Sum< ::webots_ros::motor_get_acceleration >::value();
}
static const char* value(const ::webots_ros::motor_get_accelerationResponse&)
{
return value();
}
};
template<>
struct DataType< ::webots_ros::motor_get_accelerationResponse>
{
static const char* value()
{
return DataType< ::webots_ros::motor_get_acceleration >::value();
}
static const char* value(const ::webots_ros::motor_get_accelerationResponse&)
{
return value();
}
};
} // namespace service_traits
} // namespace ros
#endif // WEBOTS_ROS_MESSAGE_MOTOR_GET_ACCELERATION_H
|
9e558286d85712568c46cd55a38e7d4b92a95768
|
0eb64d1b0f893be0c715c89d995a687fb0dfb426
|
/Server/Multiplayer/PlayerManager.h
|
022d41c10ce5551d397a1c9b2064b859d2cf52f1
|
[] |
no_license
|
Dekryptor/Gothic3-Online
|
cd8439ad9309fcf0ba5b226158ac4be00e7cdc2c
|
50f2cb7e083ebd59051f26b95e04f80f7c8fbe20
|
refs/heads/master
| 2021-06-21T21:57:14.093925
| 2017-11-27T12:46:35
| 2017-11-27T12:46:35
| 124,277,237
| 2
| 0
| null | 2021-01-10T19:39:10
| 2018-03-07T18:27:02
|
PHP
|
UTF-8
|
C++
| false
| false
| 917
|
h
|
PlayerManager.h
|
#ifndef _PLAYERMANAGER_H
#define _PLAYERMANAGER_H
#define pM PlayerManager::GetInstance()
#define playerListIter map<SystemAddress, Player*>::iterator
class PlayerManager
{
private:
PlayerManager();
PlayerManager( const PlayerManager & ) {};
~PlayerManager();
void DestroyPlayerForAll(Player* player);
void CreatePlayerForPlayer(Player* p1, Player* p2);
public:
static PlayerManager& GetInstance()
{
static PlayerManager singletone;
return singletone;
}
map<SystemAddress, Player*> playerList;
Player* CreatePlayer(SystemAddress sa, int id);
bool DestroyPlayer(Player* player);
bool DestroyPlayer(SystemAddress address);
void CreatePlayerForAll(Player* player);
void CreateAllForPlayer(Player* player);
Player* Get(SystemAddress sa);
Player* Get(int id);
bool IsExist(SystemAddress sa);
bool IsNameExist(RakString name);
size_t GetPlayersCount() { return this->playerList.size();};
};
#endif
|
3f2a48002200cb90ef5d726ae21d46ebac3e1cee
|
80ce9bb29ec86854146c2a5462885c159cd59024
|
/include/ContourDescript.h
|
df28565d1cb3e680b08b14d37cc614af9b1dce8b
|
[] |
no_license
|
TomasStachera/Eli
|
30d692b579bbd41224f4f0029e5b9f468d0bcd3b
|
60a51b263588a5d88f7663d900613606fee26ce3
|
refs/heads/master
| 2021-06-26T16:42:15.349758
| 2020-12-25T14:56:56
| 2020-12-25T14:56:56
| 168,968,684
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,454
|
h
|
ContourDescript.h
|
#ifndef CONTOURDESCRIPT_H
#define CONTOURDESCRIPT_H
//(*Headers(ContourDescript)
#include <wx/sizer.h>
#include <wx/textctrl.h>
#include <wx/checklst.h>
#include <wx/toolbar.h>
#include <wx/panel.h>
#include <wx/button.h>
#include <wx/frame.h>
#include <wx/statusbr.h>
#include <wx/choice.h>
//*)
#include <wx/evtloop.h>
#include <wx/stattext.h>
//#include <wx/app.h>
#include "commands_main.h"
#include "ContourDescript3.h"
using namespace std;
/*
Class for displayed panel for editing
Input parameters:
- parent: parent window
- id: window id
- pos: position of window
- size : size of window
- pd: PDAT structure
- obprg : ObjectPrograms structure with opened object programs
- numbobj : Object block number ( It can be from range 1-20)
*/
class ContourDescript: public wxFrame
{
public:
ContourDescript(wxWindow* parent,wxWindowID id=wxID_ANY,const wxPoint& pos=wxDefaultPosition,const wxSize& size=wxDefaultSize,PDAT *pd=NULL,ObjectPrograms *obprg=NULL,int numbobj=0);
virtual ~ContourDescript();
//(*Declarations(ContourDescript)
wxToolBarToolBase* ToolBarItem4;
wxToolBar* ToolBar1;
wxToolBarToolBase* ToolBarItem9;
wxToolBarToolBase* ToolBarItem3;
wxToolBarToolBase* ToolBarItem12;
wxToolBarToolBase* ToolBarItem11;
wxButton* Button1;
wxToolBarToolBase* ToolBarItem10;
wxPanel* Panel1;
wxButton* Button2;
wxToolBarToolBase* ToolBarItem6;
wxToolBarToolBase* ToolBarItem13;
wxToolBarToolBase* ToolBarItem1;
wxTextCtrl* ContourInfo;
wxToolBarToolBase* ToolBarItem5;
wxToolBarToolBase* ToolBarItem8;
wxToolBarToolBase* ToolBarItem2;
wxCheckListBox* ContourList;
wxToolBarToolBase* ToolBarItem7;
wxTextCtrl* StatTextX;
//*)
wxButton* ButtonExp;
// Function for show this frame as a modal dialog
int ShowModal()
{
Show();
m_evtLoop = new wxModalEventLoop(this);
m_evtLoop->Run();
delete m_evtLoop;
m_evtLoop = NULL;
Hide();
return m_retCode;
}
void EndModal(int retCode)
{
m_retCode = retCode;
m_evtLoop->Exit();
}
protected:
//(*Identifiers(ContourDescript)
static const long ID_PANEL1;
static const long ID_CHECKLISTBOX1;
static const long ID_BUTTON1;
static const long ID_BUTTON2;
static const long ID_TEXTCTRL1;
static const long idQuit;
static const long idSave;
static const long idRead;
static const long idFilter;
static const long idRunFilter;
static const long idFilterClear;
static const long idObjectMod;
static const long idRunObject;
static const long ListObject;
static const long idVariablesDispl;
static const long idClearDispObj;
static const long idSetupObj;
static const long idHelp;
static const long ID_TOOLBAR1;
static const long ID_TEXTCTRL2;
//*)
static const long ID_BUTTON3;
wxModalEventLoop *m_evtLoop;
int m_retCode;
ContourCalculation *cont_calc;
private:
//(*Handlers(ContourDescript)
void QuitClick(wxCommandEvent& event);
void OnPanel1Paint(wxPaintEvent& event);
void OnToolBarRead(wxCommandEvent& event);
void Button_SelectAll(wxCommandEvent& event);
void Button_SelectNone(wxCommandEvent& event);
void OnListBoxSelect(wxCommandEvent& event);
void OnToolBarFilterDisplay(wxCommandEvent& event);
void OnToolBarRunFilter(wxCommandEvent& event);
void OnObjectModuleClicked(wxCommandEvent& event);
void OnToolRunObjectModuleClicked(wxCommandEvent& event);
void OnToolBarItem7Clicked(wxCommandEvent& event);
void OnToolBarItem8Clicked(wxCommandEvent& event);
void OnToolBarItem9Clicked(wxCommandEvent& event);
void OnToolBarSaveClicked(wxCommandEvent& event);
void OnToolBarClearFIlterClicked(wxCommandEvent& event);
void OnToolBarItemDisplVariablesClicked(wxCommandEvent& event);
void OnToolBarItemHelpClicked(wxCommandEvent& event);
//*)
void Button_Export(wxCommandEvent& event);
void OnMouseEvent(wxMouseEvent &event);
void DrawBitmatPic(void);
int GenerateDisplPicture(Mat img);
int ReturnContourRectPos(int x,int y,int *val);
int MeasureAllValues(void);
Mat displayed_Image; //Image is display in result window
Mat mainImage;
Mat mainImage2; //template image
vector<vector<Point> > contx; // contours sequence
vector<Vec4i> hierarch;
int total_contours;// numbers of all contours
float x_ratio,y_ratio; //ration between width(height) of image and panel dimension
int x_size,y_size;
int contour_list_number; // how many contours are in the contour list box
float syst_variable[100];
bool isDisplayedImage;
OBJECTFOUND *obj_found;
int all_found_objects;
struct CONTOUR_LIST{
int list_box_pos; //actual list box position
Rect bounding_rect; //Bounding rect of selected contour
double perimeter; // Perimeter (lenght) of contour
double contour_area; // Area of contours
RotatedRect min_area_rec; //MInimal rectangle that will bound contour
Point2f min_enclosing_circle_center; // Minimal contours enclosing circle center
float min_enclosing_circle_radius; // MInimal contour enclosing circle radius
RotatedRect fit_elipse; //best fitting elipsoid
Moments moments; //moments structure
};
CONTOUR_LIST *cont_list;
DECLARE_EVENT_TABLE()
};
#endif
|
6ce6bcc7678b08d74a0a995838dd84939b5be89b
|
9a4054fc65510acc51672c6355962b8d19503af7
|
/Source/Application/BinStream.hpp
|
1697fe184ee575a0bce6bdb03ce3b864a7f544f3
|
[] |
no_license
|
fpawel/hromat900
|
fdeb3832a1256e07795d9b0be4bde5606a53293b
|
81802843340ee0f445e06f5067e6f5f69908665e
|
refs/heads/master
| 2020-03-25T23:32:14.132685
| 2018-10-31T13:50:25
| 2018-10-31T13:50:25
| 144,279,577
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 2,597
|
hpp
|
BinStream.hpp
|
#ifndef MY_BIN_STREAM_HLPR
#define MY_BIN_STREAM_HLPR
#define VCL_IOSTREAM
#include "MyIostream.h"
#include "MyExcpt.hpp"
#include "crc16.h"
DECLARATE_AND_DEFINE_MY_EXCEPTION_CLASS_(CantReadIStream, Exception );
DECLARATE_AND_DEFINE_MY_EXCEPTION_CLASS_(CantWriteOStream, Exception );
class MyBinaryIStreamHlpr : public CalcCRC16Hlpr
{
public:
typedef void (__closure *OnReadMthd)(const char*, unsigned);
explicit MyBinaryIStreamHlpr( std::istream& strm, bool enableThrow = true,
unsigned short crc16 = 0xFFFF ) : CalcCRC16Hlpr( crc16 ),
strm_(strm), enableThrow_(enableThrow)
{}
template<class T> void operator>>(T& t ) const
{
DoRead<T*>( &t, sizeof(t) );
}
template<class T> T Get() const
{
T t;
DoRead<T*>( &t, sizeof(T) );
return t;
}
template<class T> void ReadArray(T* p, unsigned size ) const
{
DoRead<T*>( p, size*sizeof(T) );
}
bool CheckCRC16() const
{
this->Get<unsigned char>();
this->Get<unsigned char>();
return this->GetCRC16()==0;
}
private:
mutable std::istream& strm_;
const bool enableThrow_;
template<class T> void DoRead( T t, unsigned sz ) const
{
char* p = reinterpret_cast<char*>( t );
strm_.read( p, sz );
if( strm_.fail() && enableThrow_ )
MY_THROW_CLASS_(MyCantReadIStreamException, "Ошибка чтения файла.");
UpdateCRC16( (unsigned char*) p, sz );
}
};
class MyBinaryOStreamHlpr : public CalcCRC16Hlpr
{
public:
explicit MyBinaryOStreamHlpr( std::ostream& strm,
unsigned short crc16 = 0xFFFF ) :
CalcCRC16Hlpr( crc16 ), strm_(strm)
{}
template<class T> void operator<<(const T& t ) const
{
DoWrite<const T*>( &t, sizeof(t) );
}
template<class T> void WriteArray(const T* p, unsigned size ) const
{
DoWrite<const T*>( p, size*sizeof(T) );
}
void FixCRC16() const
{
const unsigned short
crc16 = this->GetCRC16();
const unsigned char ch[2] = {crc16 >> 8, crc16 };
WriteArray<unsigned char>(ch,2);
assert( this->GetCRC16()==0 );
}
private:
mutable std::ostream& strm_;
template<class T> void DoWrite( T t, unsigned sz ) const
{
const char* p = reinterpret_cast<const char*>( t );
strm_.write( p, sz );
if( strm_.fail() ) MY_THROW_CLASS_(MyCantWriteOStreamException,
"Ошибка записи файла");
UpdateCRC16( (unsigned char*) p, sz );
}
};
#endif
|
7886f3e963af47d9c3e76bd02bddb5cbe9e45758
|
a30a8b60e07ba5b3db7455c7901b3aa464db97d8
|
/code/Ad-Hoc/p-level-5/2330.cpp
|
e3d215beb5b4a7d20c3e34fd8617eb7c2f349faf
|
[
"Unlicense"
] |
permissive
|
RenanTashiro/URI
|
a0cb7fca4eb4cca563efe41c7978514902f2b005
|
85c4d3079211d4b4415798649af8c6ce3be541b8
|
refs/heads/master
| 2021-01-22T19:55:02.241244
| 2018-05-25T19:38:46
| 2018-05-25T19:38:46
| 85,258,612
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 769
|
cpp
|
2330.cpp
|
/*
Nome: Telemarketing
ID: 2330
Resposta: Accepted
Linguagem: C++ (g++ 4.8.5, -std=c++11 -O2 -lm) [+0s]
Tempo: 0.188s
Tamanho: 581 Bytes
Submissao: 07/02/18 17:11:50
*/
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> ii;
int main()
{
int n, l;
scanf("%d%d", &n, &l);
priority_queue<ii, vector<ii>, greater<ii>> next;
vector<int> time(n, 0), count(n, 0);
int t;
for(int i = 0; i < n; i++)
next.push({0, i});
for(int i = 0; i < l; i++)
{
scanf("%d", &t);
ii seller = next.top();
next.pop();
count[seller.second]++;
time[seller.second] += t;
next.push({time[seller.second], seller.second});
}
for(int i = 0; i < n; i++)
printf("%d %d\n", i+1, count[i]);
}
|
95f366fca36a3e7e49d03b6d017d156e0e69738c
|
af8f027cac42a7e332224ca664dd8b1565f0fee9
|
/source/Bezier.cpp
|
7f4141a3b5a9d178544e4d2b7c022dcb688a21e3
|
[] |
no_license
|
MasterMoritz/ComputerGraphics
|
1deca04226075b6300ab404c9a87899518febdc0
|
7f71a2f886db1ad77ba8a5c0949418d8cd33f204
|
refs/heads/master
| 2021-03-30T16:57:20.555174
| 2015-06-25T02:48:23
| 2015-06-25T02:48:23
| 32,816,159
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 882
|
cpp
|
Bezier.cpp
|
/******************************************************************
*
* Bezier.c
*
* Description: Helper routine for bezier curve computations.
*
*
* Computer Graphics Proseminar SS 2015
*
* Interactive Graphics and Simulation Group
* Institute of Computer Science
* University of Innsbruck
*
* Andreas Moritz, Philipp Wirtenberger, Martin Agreiter
*******************************************************************/
/* Standard includes */
#include <math.h>
/******************************************************************
*
* ComputeBezierPoint
*
*******************************************************************/
void ComputeBezierPoint(const float points[4][3], float t, float result[3]) {
int i = 0;
for(i = 0; i < 3; i++) {
result[i] = pow(1-t, 3)*points[0][i] + 3*t*pow(1-t, 2)*points[1][i] + 3*t*t*(1-t)*points[2][i] + t*t*t*points[3][i];
}
}
|
d53dad857368f93eb33e61cecc753bbfdfa4dac1
|
b8376621d63394958a7e9535fc7741ac8b5c3bdc
|
/common/Server/GameServer/PokerServer/PokerServer/PB_Server/include/GBuf.h
|
e38c26d88d3088cd6a182124ca606f31c7b38a2d
|
[] |
no_license
|
15831944/job_mobile
|
4f1b9dad21cb7866a35a86d2d86e79b080fb8102
|
ebdf33d006025a682e9f2dbb670b23d5e3acb285
|
refs/heads/master
| 2021-12-02T10:58:20.932641
| 2013-01-09T05:20:33
| 2013-01-09T05:20:33
| null | 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 3,243
|
h
|
GBuf.h
|
//
// GBuf.h
//
#ifndef GBUF_H
#define GBUF_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
///////////////////////////////////////////////////////////////////////////////
// GXBuf
typedef SelfPtrT<IXBuf> GXBuf;
///////////////////////////////////////////////////////////////////////////////
// GBuf
class GBuf
{
protected:
LPXBUF m_pXBuf;
public:
GBuf() { m_pXBuf = ::XbufCreate(); }
GBuf(const GBuf& buf) { m_pXBuf = ::XbufCreate(buf.m_pXBuf); }
GBuf(LPXBUF pXBuf, BOOL bCopy) { m_pXBuf = (bCopy ? ::XbufCreate(pXBuf) : pXBuf); }
GBuf(void* p, DWORD dwLen) { m_pXBuf = ::XbufCreate(); m_pXBuf->AddRight(p, dwLen); }
~GBuf() { if(m_pXBuf) m_pXBuf->Delete(); }
public:
void Attach(LPXBUF pXBuf) { if(m_pXBuf) m_pXBuf->Delete(); m_pXBuf = pXBuf; }
LPXBUF Detach() { LPXBUF pXBuf = m_pXBuf; m_pXBuf = NULL; return pXBuf; }
public:
inline LPXBUF GetXBuf() const { return m_pXBuf; }
inline LPXBUF operator->() const { return m_pXBuf; }
inline operator LPXBUF() const { return m_pXBuf; }
GBuf& operator=(const GBuf& buf) { m_pXBuf->Copy(buf.m_pXBuf); return(*this); }
public:
LPCBYTE GetData() const { return m_pXBuf->GetData(); }
DWORD GetLength() const { return m_pXBuf->GetLength(); }
void SetLength(DWORD dwLen) { m_pXBuf->SetLength(dwLen); }
void Reserve(DWORD dwLen) { m_pXBuf->Reserve(dwLen); }
void AddRight(LPVOID p, DWORD dwLen) { m_pXBuf->AddRight(p, dwLen); }
void RemoveLeft(DWORD dwSize) { m_pXBuf->RemoveLeft(dwSize); }
void Clear() { m_pXBuf->RemoveLeft( m_pXBuf->GetLength() ); }
public:
// Buffer의 멤버인 XMEM의 시작점과 길이를 변경(실제 Data resize는 일어나지 않음에 유의)
void SetPosLength(const DWORD dwPos, const DWORD dwLen) { m_pXBuf->SetPosLength(dwPos, dwLen); }
DWORD GetPos() const { return m_pXBuf->GetPos(); }
};
///////////////////////////////////////////////////////////////////////////////
// GBufQ
class GBufQ : public std::list<GBuf>
{
public:
typedef std::list<GBuf> TBase;
public:
GBufQ() {};
GBufQ(const GBuf& ro) { push_back(ro); }
GBufQ(const GBufQ& rb) : TBase(rb) { }
DWORD Count() const { return (DWORD)size(); };
BOOL IsEmpty() const { return(size() == 0); };
void Clear() { clear(); };
GBuf& Top() { return front(); };
GBuf Pop() { ASSERT(!IsEmpty()); GBuf ro = front(); pop_front(); return ro; }
BOOL Pop(GBuf& ro) { if(IsEmpty()) return FALSE; ro = front(); pop_front(); return TRUE; }
void Push(const GBuf& ro) { push_back(ro); }
void Push(const GBufQ& rb) { insert(end(), rb.begin(), rb.end()); }
GBufQ& operator+=(const GBuf& r) { Push(r); return *this; }
GBufQ& operator+=(const GBufQ& r) { Push(r); return *this; }
GBufQ operator+(const GBuf& r) { GBufQ rb(*this); rb.Push(r); return rb; }
GBufQ operator+(const GBufQ& r) { GBufQ rb(*this); rb.Push(r); return rb; }
};
///////////////////////////////////////////////////////////////////////////////
class GSafeBufQ
{
IMPLEMENT_TISAFE(GSafeBufQ)
public:
void Push(const GBuf& buf) {
TLock lo(this);
mRcvBufQ.Push(buf);
}
BOOL Pop(GBuf& buf) {
TLock lo(this);
if(mRcvBufQ.IsEmpty()) return FALSE;
mRcvBufQ.Pop(buf);
return TRUE;
}
void Clear()
{
TLock lo(this);
mRcvBufQ.Clear();
}
protected:
GBufQ mRcvBufQ;
};
#endif //!GBUF_H
|
4c8391ac53d188f13f18cb9184f050fa4f6af5d7
|
c350d938ce94f7526d5d243fec0b2269e63b961a
|
/include/GridAccel.h
|
3943e5b7662528dba0f95c7555fe6416a1b84c7f
|
[] |
no_license
|
Vancroth/FormFactor
|
daa08c29c1d20929ec319a69fc84b3fdbce2d77d
|
6500b7b5aff7e46961919a10f51276f2c6e76cac
|
refs/heads/master
| 2023-07-14T03:29:04.650417
| 2010-03-11T23:50:55
| 2010-03-11T23:50:55
| 552,028
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 865
|
h
|
GridAccel.h
|
/*
* Implementation for a axis aligned grid.
*
* The gid is used for the acceleration of
* collisions and for visibility checks, i.e.
* hidden surface removal and proximity to character.
*/
#pragma once
#include <vector>
#include "Primitive.h"
#include "BoundingBox.h"
namespace FormFactor {
/*
* Used to track whether a primitive has already been checked
* in another voxel.
*/
struct Mailbox {
Mailbox() {}
Mailbox(const Reference<Primitive> &p) {
prim = p;
lastId = -1;
}
Reference<Primitive> prim;
int lastId;
};
class GridAccel : public Primitive {
public:
GridAccel(const std::vector<Reference<Primitive> > &prims, bool refineImmediately);
private:
std::vector<Reference<Primitive> > prims;
BoundingBox bounds; // global boundary
Mailbox *mailboxes;
unsigned int nMailboxes;
};
} // end FormFactor
|
3091c3b3d4e954ca9f0bc8d454319033538aca9e
|
4b32612e77cfbb45d8ae26fa0b6dacb767833f22
|
/main.cpp
|
bf25a8ad02ae120292dd9f03ecc514da61113081
|
[] |
no_license
|
Pvnisher/Domande
|
099286068664865484d9b05f256454bd4839e0c6
|
2ce50ad2df3aea6aa8b705af1d137c5807bde799
|
refs/heads/main
| 2023-06-06T07:03:57.822312
| 2021-06-26T12:01:51
| 2021-06-26T12:01:51
| 377,540,947
| 3
| 1
| null | 2021-06-26T12:01:51
| 2021-06-16T15:20:52
|
C++
|
UTF-8
|
C++
| false
| false
| 6,700
|
cpp
|
main.cpp
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void write_headers(const string& output_file, const string& = "headers.html");
int main(int argc, char **argv) {
string file_domande;
string file_output;
string header = "headers.html";
string aus;
bool flags[]{false, false, false};
char aus2;
if (argc > 1) {
int i;
for (i = 0; i < argc; i++) {
string s1(argv[i]);
if (s1[0] == '-' && s1.length() > 1) {
if ((s1[1] == 'h' || s1 == "--help")){
cout << argv[0] << " Simple application to automate the generation of html files starting from file.txt of questions - answers for training exams.\n";
cout << "Options : \n";
cout << "\t-h\t--help\tShow this help\n";
cout << "\t-f\t--file\tFollowed by the path set the path to the txt file to convert\n";
cout << "\t-o\t--output\tFollowed by the path set the path to output file (specify .html in the name)\n";
cout << "\t-t\t--template\tFollowed by the path set the path to the template files containing headers to be printed before the contents\n";
cout << "\n You can also use the interactive mode running " << argv[0] << " whitout arguments\n";
cout << "\n Example usage:" << argv[0] << " -t headers.html -f file.txt -o out.html\n";
return 0;
}
if(i+1 < argc){
string s2(argv[i+1]);
if ((s1[1] == 'f' || s1 == "--file") && s2.length() > 0) {
flags[0] = true;
file_domande = s2;
}
if ((s1[1] == 't' || s1 == "--template") && s2.length() > 0) {
flags[1] = true;
header = s2;
}
if ((s1[1] == 'o' || s1 == "--output") && s2.length() > 0) {
flags[2] = true;
file_output = s2;
}
}
}
}
}
if(file_domande.empty())
{
cout << "Inserire il nome del file \n";
cin >> file_domande;
}
if (file_output.empty())
{
file_output = file_domande;
file_output.append(".html");
}
fstream stream_input;
fstream stream_output;
stream_input.open(file_domande, ios::in);
write_headers(file_output, header);
stream_output.open(file_output, std::ios_base::app);
int id = 1;
int risposta = 0;
int domanda = 0;
int block = 0;
while (!stream_input.eof())
{
stream_input >> aus2;
if (aus2 == '@')
{
if (risposta == 1) {
stream_output <<"</div></div>";
risposta = 0;
if (block == 1) {
block = 0;
stream_output << "</div>";
}
}
stream_output << "<div id='" << id++ << "' class='sdrogo'><div class='domanda'>";
getline(stream_input, aus, '\n');
stream_output << aus << "<br>\n";
domanda = 1;
block = 1;
}
if (aus2 == '!')
{
if(domanda == 1) {
stream_output << "</div>";
domanda = 0;
}
stream_output << "<div class='container'><div class='risposta'>";
getline(stream_input, aus, '\n');
stream_output << aus << "<br>\n";
risposta = 1;
}
if (aus2 != '@' && aus2 != '!')
{
stream_output << aus2;
getline(stream_input, aus, '\n');
stream_output << aus << "<br>\n";
}
}
stream_output << "</div></div></div></div></body></html>";
cout << "FILE READY";
stream_input.close();
stream_output.close();
return 0;
}
void write_headers(const string& output_file, const string& headers_file)
{
fstream file;
fstream input;
file.open(output_file, std::ios_base::out);
if (file.is_open()){
input.open(headers_file, ios::in);
if (input.is_open()) {
string str;
while (input >> str)
file << str << " ";
input.close();
}
else
{
//inizio e script w3school
file << "<html><head><script src='https://www.w3schools.com/lib/w3.js'></script>";
//mio script
file << "<script>var x;var num;\nfunction cambia(t){\nif(t=='a' && x<document.querySelectorAll('.sdrogo').length){\ndocument.getElementById(x).style=\"display:none;\"\n";
file << "if(rand==true)\nx=Math.floor((Math.random() * num) + 1);\nelse\nx++;\ndocument.getElementById(x).style=\"display:inline-block;\"}\nif(t=='i' && x>1){\ndocument.getElementById(x).style=\"display:none;\"\n";
file << "if(rand==true)\nx=Math.floor((Math.random() * num) + 1);\nelse\nx--;\ndocument.getElementById(x).style=\"display:inline-block;\"}}\nfunction start(){\n";
file << "x=1;num=document.querySelectorAll('.sdrogo').length;\ndocument.getElementById(1).style=\"display:inline-block;\";\nw3.toggleShow('.risposta');}\n";
file << "function toggleRand(){\nif(rand==true){\ndocument.getElementById('rand').value=\"rand disattivo\";\nrand=false;}\n";
file << "else{\ndocument.getElementById('rand').value=\"rand attivo\";\nrand=true;}}\n</script>\n";
//css e chiudo head
file << "<style>.container {height:85%; max-height:85%; display: inline-block; overflow: scroll; width: 100%;}.domanda{font-weight: bold;}.sdrogo{width: 100%; display:none;}</style></head>";
//bottoni
file << "<body onload='start()'><button id='bottone' style='position:fixed; margin-left: 80%' onclick=\"w3.toggleShow('.risposta')\">Mostra/nascondi riposte</button>";
file << "<input type=button id='nascondimostra' style='position:fixed; margin-left: 80%' onclick=\"w3.toggleShow('.risposta')\" value='Mostra/nascondi riposte'>";
file << "<input type=button id='next' style='position:fixed; margin-left: 80%; margin-top: 10%;' onclick=\"cambia('a')\" value='Prossimo'>";
file << "<input type=button id='back' style='position:fixed; margin-left: 80%; margin-top: 12%;' onclick=\"cambia('i')\" value='Indietro'>";
file << "<input type=button id='rand' style='position:fixed; margin-left: 80%; margin-top: 5%;' onclick='toggleRand()' value='rand disattivo'>";
}
file.close();
}
}
|
0e1a6658d007e2b37ca394eebc74a1ec492eb392
|
49321258cb94dc4320f8487dca6c6f2ec8047e98
|
/SuplaWebServer.cpp
|
dd038c9db426dfa7bd3b45c0c31b00193c9c5c5f
|
[] |
no_license
|
shimano73/Supla_waga_Generic_GUI
|
a70098e778714355d710581d7974df2db8d88cd6
|
9495d6253dd865719b7f4f5f965db1ebb8ca7512
|
refs/heads/main
| 2023-07-14T05:04:57.594553
| 2021-08-29T11:16:56
| 2021-08-29T11:16:56
| 401,010,199
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,744
|
cpp
|
SuplaWebServer.cpp
|
/*
Copyright (C) krycha88
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "SuplaWebServer.h"
#include "SuplaDeviceGUI.h"
#include "SuplaWebPageConfig.h"
#include "SuplaWebPageControl.h"
#include "SuplaWebPageRelay.h"
#include "SuplaWebPageSensor.h"
#include "SuplaCommonPROGMEM.h"
#include <supla/sensor/H711.h>
SuplaWebServer::SuplaWebServer() {
}
void SuplaWebServer::begin() {
this->createWebServer();
strcpy(this->www_username, ConfigManager->get(KEY_LOGIN)->getValue());
strcpy(this->www_password, ConfigManager->get(KEY_LOGIN_PASS)->getValue());
httpUpdater.setup(&httpServer, UPDATE_PATH, www_username, www_password);
httpServer.begin();
}
void SuplaWebServer::iterateAlways() {
httpServer.handleClient();
}
void SuplaWebServer::createWebServer() {
String path = PATH_START;
httpServer.on(path, HTTP_GET, std::bind(&SuplaWebServer::handle, this));
path = PATH_START;
httpServer.on(path, std::bind(&SuplaWebServer::handleSave, this));
path = PATH_START;
path += PATH_UPDATE;
httpServer.on(path, std::bind(&SuplaWebServer::handleFirmwareUp, this));
path = PATH_START;
path += PATH_REBOT;
httpServer.on(path, std::bind(&SuplaWebServer::supla_webpage_reboot, this));
path = PATH_START;
path += PATH_DEVICE_SETTINGS;
httpServer.on(path, std::bind(&SuplaWebServer::handleDeviceSettings, this));
#if defined(SUPLA_RELAY) || defined(SUPLA_ROLLERSHUTTER)
WebPageRelay->createWebPageRelay();
#endif
#if defined(SUPLA_BUTTON) || defined(SUPLA_LIMIT_SWITCH)
WebPageControl->createWebPageControl();
#endif
#if defined(SUPLA_DS18B20) || defined(SUPLA_DHT11) || defined(SUPLA_DHT22) || defined(SUPLA_BME280) || defined(SUPLA_HC_SR04)
WebPageSensor->createWebPageSensor();
#endif
#ifdef SUPLA_CONFIG
WebPageConfig->createWebPageConfig();
#endif
}
void SuplaWebServer::handle() {
// Serial.println(F("HTTP_GET - metoda handle"));
if (ConfigESP->configModeESP == NORMAL_MODE) {
if (!httpServer.authenticate(this->www_username, this->www_password))
return httpServer.requestAuthentication();
}
this->sendContent(supla_webpage_start(0));
}
void SuplaWebServer::handleSave() {
// Serial.println(F("HTTP_POST - metoda handleSave"));
if (ConfigESP->configModeESP == NORMAL_MODE) {
if (!httpServer.authenticate(this->www_username, this->www_password))
return httpServer.requestAuthentication();
}
if (strcmp(httpServer.arg(PATH_REBOT).c_str(), "1") == 0) {
this->rebootESP();
return;
}
ConfigManager->set(KEY_WIFI_SSID, httpServer.arg(INPUT_WIFI_SSID).c_str());
ConfigManager->set(KEY_WIFI_PASS, httpServer.arg(INPUT_WIFI_PASS).c_str());
ConfigManager->set(KEY_SUPLA_SERVER, httpServer.arg(INPUT_SERVER).c_str());
ConfigManager->set(KEY_SUPLA_EMAIL, httpServer.arg(INPUT_EMAIL).c_str());
ConfigManager->set(KEY_HOST_NAME, httpServer.arg(INPUT_HOSTNAME).c_str());
ConfigManager->set(KEY_LOGIN, httpServer.arg(INPUT_MODUL_LOGIN).c_str());
ConfigManager->set(KEY_LOGIN_PASS, httpServer.arg(INPUT_MODUL_PASS).c_str());
ConfigManager->set(KEY_LPG_CALIBRATIONS, httpServer.arg(INPUT_LPG_CALIBRATIONS).c_str());
ConfigManager->set(KEY_LPG_EMPTY, httpServer.arg(INPUT_LPG_EMPTY).c_str());
ConfigManager->set(KEY_LPG_FULL, httpServer.arg(INPUT_LPG_FULL).c_str());
#ifdef SUPLA_ROLLERSHUTTER
ConfigManager->set(KEY_MAX_ROLLERSHUTTER, httpServer.arg(INPUT_ROLLERSHUTTER).c_str());
#endif
switch (ConfigManager->save()) {
case E_CONFIG_OK:
// Serial.println(F("E_CONFIG_OK: Dane zapisane"));
if (ConfigESP->configModeESP == NORMAL_MODE) {
this->sendContent(supla_webpage_start(5));
this->rebootESP();
}
else {
this->sendContent(supla_webpage_start(7));
}
break;
case E_CONFIG_FILE_OPEN:
// Serial.println(F("E_CONFIG_FILE_OPEN: Couldn't open file"));
this->sendContent(supla_webpage_start(4));
break;
}
}
void SuplaWebServer::handleFirmwareUp() {
if (ConfigESP->configModeESP == NORMAL_MODE) {
if (!httpServer.authenticate(www_username, www_password))
return httpServer.requestAuthentication();
}
this->sendContent(supla_webpage_upddate());
}
void SuplaWebServer::handleDeviceSettings() {
if (ConfigESP->configModeESP == NORMAL_MODE) {
if (!httpServer.authenticate(www_username, www_password))
return httpServer.requestAuthentication();
}
this->sendContent(deviceSettings());
}
String SuplaWebServer::supla_webpage_start(int save) {
String content = F("");
content += SuplaSaveResult(save);
content += SuplaJavaScript();
content += F("<form method='post'>");
content += F("<div class='w'>");
content += F("<h3>Ustawienia WIFI</h3>");
content += F("<i><input name='");
content += INPUT_WIFI_SSID;
content += F("' value='");
content += String(ConfigManager->get(KEY_WIFI_SSID)->getValue());
content += F("' length=");
content += MAX_SSID;
content += F(" required><label>Nazwa sieci</label></i>");
content += F("<i><input name='");
content += INPUT_WIFI_PASS;
if (ConfigESP->configModeESP != NORMAL_MODE) {
content += F("' type='password' ");
}
content += F("' value='");
content += String(ConfigManager->get(KEY_WIFI_PASS)->getValue());
content += F("'");
if (ConfigManager->get(KEY_WIFI_PASS)->getValue() != 0) {
content += F("required>");
}
else {
content += F("'minlength='");
content += MIN_PASSWORD;
content += F("' length=");
content += MAX_PASSWORD;
content += F(" required>");
}
content += F("<label>Hasło</label></i>");
content += F("<i><input name='");
content += INPUT_HOSTNAME;
content += F("' value='");
content += ConfigManager->get(KEY_HOST_NAME)->getValue();
content += F("' length=");
content += MAX_HOSTNAME;
content += F(" required><label>Nazwa modułu</label></i>");
content += F("</div>");
content += F("<div class='w'>");
content += F("<h3>Ustawienia SUPLA</h3>");
content += F("<i><input name='");
content += INPUT_SERVER;
content += F("' length=");
content += MAX_SUPLA_SERVER;
String def = DEFAULT_SERVER;
String def_2 = String(ConfigManager->get(KEY_SUPLA_SERVER)->getValue());
if (def == def_2) {
content += F(" placeholder='");
}
else {
content += F(" value='");
}
content += def_2;
content += F("' required><label>Adres serwera</label></i>");
content += F("<i><input name='");
content += INPUT_EMAIL;
content += F("' length=");
content += MAX_EMAIL;
def = DEFAULT_EMAIL;
def_2 = String(ConfigManager->get(KEY_SUPLA_EMAIL)->getValue());
if (def == def_2) {
content += F(" placeholder='");
}
else {
content += F(" value='");
}
content += def_2;
content += F("' required><label>Email</label></i>");
content += F("</div>");
content += F("<div class='w'>");
content += F("<h3>Ustawienia administratora</h3>");
content += F("<i><input name='");
content += INPUT_MODUL_LOGIN;
content += F("' value='");
content += String(ConfigManager->get(KEY_LOGIN)->getValue());
content += F("' length=");
content += MAX_MLOGIN;
content += F("><label>Login</label></i>");
content += F("<i><input name='");
content += INPUT_MODUL_PASS;
if (ConfigESP->configModeESP != NORMAL_MODE) {
content += F("' type='password' ");
}
content += F("' value='");
content += String(ConfigManager->get(KEY_LOGIN_PASS)->getValue());
content += F("'");
content += F("'minlength='");
content += MIN_PASSWORD;
content += F("' length=");
content += MAX_MPASSWORD;
content += F(" required>");
content += F("<label>Hasło</label></i>");
content += F("</div>");
//Ustawienia wagi
content += F("<div class='w'>");
content += F("<h3>Ustawienia wagi </h3>");
content += F("<i><input name='");
content += INPUT_LPG_CALIBRATIONS;
content += F("' value='");
content += String(ConfigManager->get(KEY_LPG_CALIBRATIONS)->getValue());
content += F("' length=");
content += MAX_LPG_CALIBRATIONS;
content += F("><label>Wartość kalibracyjna</label></i>");
content += F("<i><input name='");
content += INPUT_LPG_EMPTY;
content += F("' value='");
content += String(ConfigManager->get(KEY_LPG_EMPTY)->getValue());
content += F("' length=");
content += MAX_LPG_EMPTY;
content += F("><label>Waga pustej butli</label></i>");
content += F("<i><input name='");
content += INPUT_LPG_FULL;
content += F("' value='");
content += String(ConfigManager->get(KEY_LPG_FULL)->getValue());
content += F("' length=");
content += MAX_LPG_FULL;
content += F("><label>Waga pełnej butli</label></i>");
// LPG_Actual = waga.getActual();
content += F("<i><input ");
content += F(" value='");
content += String("19.9");
content += F("'><label>Waga aktualna butli</label></i>");
content += F("</div>");
#ifdef SUPLA_ROLLERSHUTTER
uint8_t maxrollershutter = ConfigManager->get(KEY_MAX_RELAY)->getValueInt();
if (maxrollershutter >= 2) {
content += F("<div class='w'>");
content += F("<h3>Rolety</h3>");
content += F("<i><label>Ilość</label><input name='");
content += INPUT_ROLLERSHUTTER;
content += F("' type='number' placeholder='1' step='1' min='0' max='");
content += maxrollershutter / 2;
content += F("' value='");
content += String(ConfigManager->get(KEY_MAX_ROLLERSHUTTER)->getValue());
content += F("'></i>");
content += F("</div>");
}
#endif
#ifdef SUPLA_DS18B20
WebPageSensor->showDS18B20(content, true);
#endif
content += F("<button type='submit'>Zapisz</button></form>");
content += F("<br>");
content += F("<a href='");
content += PATH_START;
content += PATH_DEVICE_SETTINGS;
content += F("'><button>Ustawienia urządzenia</button></a>");
content += F("<br><br>");
content += F("<a href='");
content += PATH_START;
content += PATH_UPDATE;
content += F("'><button>Aktualizacja</button></a>");
content += F("<br><br>");
content += F("<form method='post' action='");
content += PATH_REBOT;
content += F("'>");
content += F("<button type='submit'>Restart</button></form></div>");
return content;
}
String SuplaWebServer::supla_webpage_upddate() {
String content = "";
content += F("<div class='w'>");
content += F("<h3>Aktualizacja oprogramowania</h3>");
content += F("<br>");
content += F("<center>");
content += F("<iframe src=");
content += UPDATE_PATH;
content +=
F(">Twoja przeglądarka nie akceptuje ramek! width='200' height='100' "
"frameborder='100'></iframe>");
content += F("</center>");
content += F("</div>");
content += F("<a href='/'><button>Powrót</button></a></div>");
return content;
}
void SuplaWebServer::supla_webpage_reboot() {
if (ConfigESP->configModeESP == NORMAL_MODE) {
if (!httpServer.authenticate(www_username, www_password))
return httpServer.requestAuthentication();
}
this->sendContent(supla_webpage_start(2));
this->rebootESP();
}
String SuplaWebServer::deviceSettings() {
String content = "";
content += F("<div class='w'>");
content += F("<h3>Ustawienia urządzenia</h3>");
content += F("<br>");
content += F("<center>");
#if defined(SUPLA_RELAY) || defined(SUPLA_ROLLERSHUTTER)
content += F("<a href='");
content += PATH_START;
content += PATH_RELAY;
content += F("'><button>PRZEKAŹNIKI</button></a>");
content += F("<br><br>");
#endif
#ifdef SUPLA_BUTTON
content += F("<a href='");
content += PATH_START;
content += PATH_CONTROL;
content += F("'><button>PRZYCISKI</button></a>");
content += F("<br><br>");
#endif
#if defined(SUPLA_DS18B20) || defined(SUPLA_DHT11) || defined(SUPLA_DHT22) || defined(SUPLA_SI7021_SONOFF)
content += F("<a href='");
content += PATH_START;
content += PATH_1WIRE;
content += F("'><button>SENSORY 1Wire</button></a>");
content += F("<br><br>");
#endif
#if defined(SUPLA_BME280) || defined(SUPLA_HC_SR04) || defined(SUPLA_SHT30) || defined(SUPLA_SI7021)
content += F("<a href='");
content += PATH_START;
content += PATH_I2C;
content += F("'><button>SENSORY i2c</button></a>");
content += F("<br><br>");
#endif
#if defined(SUPLA_MAX6675)
content += F("<a href='");
content += PATH_START;
content += PATH_SPI;
content += F("'><button>SENSORY SPI</button></a>");
content += F("<br><br>");
#endif
#ifdef SUPLA_CONFIG
content += F("<a href='");
content += PATH_START;
content += PATH_CONFIG;
content += F("'><button>LED, BUTTON CONFIG</button></a>");
content += F("<br><br>");
#endif
content += F("</div>");
content += F("</center>");
content += F("<a href='/'><button>Powrót</button></a></div>");
return content;
}
String SuplaWebServer::selectGPIO(const char* input, uint8_t function, uint8_t nr) {
String page = "";
page += F("<select name='");
page += input;
if (nr != 0) {
page += nr;
}
else {
nr = 1;
}
page += F("'>");
uint8_t selected = ConfigESP->getGpio(nr, function);
for (uint8_t suported = 0; suported < 18; suported++) {
if (ConfigESP->checkBusyGpio(suported, function) == false || selected == suported) {
page += F("<option value='");
page += suported;
if (selected == suported) {
page += F("' selected>");
}
else {
page += F("'>");
}
page += GIPOString(suported);
}
}
page += F("</select>");
return page;
}
const String SuplaWebServer::SuplaFavicon() {
// return F("<link rel='icon'
// href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAB3RJTUUH5AUUCCQbIwTFfgAAAAlwSFlzAAALEgAACxIB0t1+/AAAAARnQU1BAACxjwv8YQUAAAAwUExURf7nNZuNIOvWMci2KWRbFJGEHnRpFy8rCdrGLSAdBgwLAod6G7inJkI8DVJLEKeYIg6cTsoAAAGUSURBVHjaY2CAAFUGNLCF4QAyl4mhmP8BB4LPcWtdAe+BEBiX9QD77Kzl24GKHCAC/OVZH5hkVyUCFQlCRJhnKjAwLVlVb8lQDOY/ZFrG8FDVQbVqbU8BWODc3BX8dbMMGJhfrUyAaOla+/dAP8jyncsbgJTKgVP/b+pOAUudegAkGMsrGZhE1EFyDGwLwNaucmZyl1TgKTdg4JvAwMBzn3txeKWrMwP7wQcMWiAtf2c9YDjUfYBJapsDw66bm4AiUesOnJty0/O9iwLDPI5EhhCD6/q3Chk4dgCleJYpAEOmfCkDB+sbsK1886YBRfgWMTBwbi896wR04YZuAyAH6OmzDCbr3RgYsj6A1HEBPXCfgWHONgaG6eUBII0LFTiA7jn+iIF/MbMTyEu3lphtAJtpvl4BTLPNWgVSySA+y28aWIDdyGtVBgNH5psshVawwHGGO+arLr7MYFoJjZr/zBPYj85a1sC4ulwAIsIdcJzh2qt1WReYBWBR48gxgd1ziQIi6hTYEsxR45pZwRU9+oWgNAB1F3c/H6bYqgAAAABJRU5ErkJggg=='
// type='image/x-png' />\n");
return F("");
}
const String SuplaWebServer::SuplaIconEdit() {
return F(
"<img "
"src='data:image/"
"png;base64,"
"iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAQAAAD8fJRsAAAAB3RJTUUH5AYHChEfgNCVHgAAAAlwSFlzAAAuIwAALiMB"
"eKU/dgAAAARnQU1BAACxjwv8YQUAAABBSURBVHjaY1BiwA4xhWqU/"
"gMxAzZhEGRAF2ZQmoGpA6R6BlSaAV34P0QYIYEmDJPAEIZJQFxSg+"
"kPDGFsHiQkAQDjTS5MMLyE4wAAAABJRU5ErkJggg=='>");
}
const String SuplaWebServer::SuplaJavaScript(String java_return) {
String java_script =
F("<script type='text/javascript'>setTimeout(function(){var "
"element=document.getElementById('msg');if( element != "
"null){element.style.visibility='hidden';location.href='");
java_script += java_return;
java_script += F("';}},1600);</script>\n");
return java_script;
}
const String SuplaWebServer::SuplaSaveResult(int save) {
if (save == 0)
return F("");
String saveresult = "";
saveresult += F("<div id=\"msg\" class=\"c\">");
if (save == 1) {
saveresult += F("Dane zapisane");
}
else if (save == 2) {
saveresult += F("Restart modułu");
}
else if (save == 3) {
saveresult += F("Dane wymazane - należy zrobić restart urządzenia");
}
else if (save == 4) {
saveresult += F("Błąd zapisu - nie można odczytać pliku - brak partycji FS.");
}
else if (save == 5) {
saveresult += F("Dane zapisane - restart modułu.");
}
else if (save == 6) {
saveresult += F("Błąd zapisu - złe dane.");
}
else if (save == 7) {
saveresult += F("data saved");
}
saveresult += F("</div>");
return saveresult;
}
void SuplaWebServer::rebootESP() {
wdt_reset();
ESP.restart();
while (1) wdt_reset();
}
void SuplaWebServer::sendContent(const String content) {
// httpServer.send(200, "text/html", "");
const int bufferSize = 1000;
String _buffer;
int bufferCounter = 0;
int fileSize = content.length();
#ifdef DEBUG_MODE
Serial.print("Content size: ");
Serial.println(fileSize);
#endif
httpServer.setContentLength(fileSize);
httpServer.chunkedResponseModeStart(200, "text/html");
httpServer.sendContent_P(HTTP_META);
httpServer.sendContent_P(HTTP_STYLE);
httpServer.sendContent_P(HTTP_LOGO);
String summary = FPSTR(HTTP_SUMMARY);
summary.replace("{h}", ConfigManager->get(KEY_HOST_NAME)->getValue());
summary.replace("{s}", ConfigESP->getLastStatusSupla());
summary.replace("{v}", Supla::Channel::reg_dev.SoftVer);
summary.replace("{g}", ConfigManager->get(KEY_SUPLA_GUID)->getValueHex(SUPLA_GUID_SIZE));
summary.replace("{m}", ConfigESP->getMacAddress(true));
httpServer.sendContent(summary);
// httpServer.send(200, "text/html", "");
for (int i = 0; i < fileSize; i++) {
_buffer += content[i];
bufferCounter++;
if (bufferCounter >= bufferSize) {
httpServer.sendContent(_buffer);
yield();
bufferCounter = 0;
_buffer = "";
}
}
if (bufferCounter > 0) {
httpServer.sendContent(_buffer);
yield();
bufferCounter = 0;
_buffer = "";
}
httpServer.sendContent_P(HTTP_COPYRIGHT);
httpServer.chunkedResponseFinalize();
}
void SuplaWebServer::redirectToIndex() {
httpServer.sendHeader("Location", "/", true);
httpServer.send(302, "text/plain", "");
httpServer.client().stop();
}
|
2c2da48713ad0eed76828c5e88e81574f87591be
|
34074c4ed049a56c4eaf2e22f46a6f5016cb6143
|
/Operation.cpp
|
d646f5075f58a2f0ea4c09bcc6ef1f57a0718b9c
|
[] |
no_license
|
fivelike/ChessGame
|
03e4679413ab80431ec4a886a579b180fa252b74
|
d8560de74c0a78b64c8b34ae88f9743f3d5ebba2
|
refs/heads/master
| 2020-03-17T07:03:25.303509
| 2018-05-18T16:24:56
| 2018-05-18T16:24:56
| 133,381,162
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 492
|
cpp
|
Operation.cpp
|
// Operation.cpp : 实现文件
//
#include "stdafx.h"
#include "ChessGame.h"
#include "Operation.h"
#include "afxdialogex.h"
// Operation 对话框
IMPLEMENT_DYNAMIC(Operation, CDialogEx)
Operation::Operation(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_DIALOG2, pParent)
{
}
Operation::~Operation()
{
}
void Operation::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(Operation, CDialogEx)
END_MESSAGE_MAP()
// Operation 消息处理程序
|
e586ac668c5faa583b5adfa50752f63ac20e6a39
|
247ac5362ee5094801a519124e6b8e61bce27ba0
|
/DirectXBase/DirectXBase/DescriptionSceneBG.h
|
a1fdf10980cb79f8e137b3272462fef52371348e
|
[] |
no_license
|
SasakiMizuki/MizukiRepository
|
12e7fba06038200fbff42923720d2ff03f12c30e
|
854211a26525ef3b12ee1430ed313ccf57119f74
|
refs/heads/master
| 2020-05-29T15:14:11.031839
| 2017-10-24T16:19:03
| 2017-10-24T16:19:03
| 61,768,941
| 0
| 0
| null | 2017-07-11T05:56:28
| 2016-06-23T03:03:21
|
Logos
|
UTF-8
|
C++
| false
| false
| 365
|
h
|
DescriptionSceneBG.h
|
#pragma once
#include "C2DObj.h"
#define DESCRIPTION_BG_NAME _T("../data/image/description_bg.png")
class CDescriptionSceneBG :
public C2DObj
{
private:
static bool m_bLoad;
public:
CDescriptionSceneBG(CSceneBase* pScene);
virtual ~CDescriptionSceneBG();
virtual void Init();
virtual void Update();
virtual void Fin();
virtual void MakeVertexPolygon();
};
|
cc3894e1945f321705f0504af0172c7017595b16
|
20eb8da7098d4f15620a37893dd6153dd1f5ed6d
|
/SuMa_Code/test/core/lie_test.cpp
|
abee704af8790332cc952f99d71106e55fbe113f
|
[
"MIT"
] |
permissive
|
qiaozhijian/SuMa
|
97cbeeed14a2dfa67607f6db575ef75f82e91670
|
73ca28b76513e4f83cc1a31f7160e1b7139ee53b
|
refs/heads/master
| 2020-12-03T14:59:53.902167
| 2020-01-02T10:53:48
| 2020-01-02T10:53:48
| 231,362,571
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 386
|
cpp
|
lie_test.cpp
|
#include <gtest/gtest.h>
#include <core/lie_algebra.h>
namespace {
TEST(LieTest, testLogExpSE3) {
// simple sanity test, x = exp(log(x)) and x = log(exp(x))
Eigen::VectorXd x(6);
x << -0.7, 0.1, 0.1, 0.1, -0.5, 0.33;
Eigen::VectorXd x_logexp = SE3::log(SE3::exp(x));
for (uint32_t i = 0; i < 6; ++i) {
ASSERT_NEAR(x[i], x_logexp[i], 0.0001);
}
}
}
|
1aa99309eae3dfa4d765bec0c68c24d10804d6a1
|
12efddb38fd5bd1c2b2b3bb1b672714b694d5602
|
/common/minibson.h
|
3271148d9620dd70a0bb0042be9f645eec0f6154
|
[] |
no_license
|
chenxp-github/SmallToolsV2
|
884d61200f556379551477030aa06c64593ce9d4
|
1a8aa863d0bc3744d376284ace85c7503b871f45
|
refs/heads/master
| 2022-06-01T05:19:25.417439
| 2022-04-30T05:31:53
| 2022-04-30T05:31:53
| 210,530,450
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,118
|
h
|
minibson.h
|
#ifndef __MINIBSON_H
#define __MINIBSON_H
#include "mem.h"
#include "closure.h"
CLOSURE_COMMON_OBJECT_OPS_DEFINE_H(CMiniBson,bson)
#define LOCAL_BSON(bson,size) char __##bson[size];\
CMiniBson bson;\
bson.Init();\
bson.SetRawBuf(__##bson,size);\
#define BSON_CHECK(f) do{if(!(f)){\
__LOG("check fail \"%s\" at file=%s line=%d"),#f,__FILE__,__LINE__);\
return 0;\
}}while(0)\
class CMiniBson{
public:
enum{
BSON_TYPE_DOUBLE=0x01,
BSON_TYPE_STRING=0x02,
BSON_TYPE_DOCUMENT=0x03,
BSON_TYPE_ARRAY=0x04,
BSON_TYPE_BINARY=0x05,
BSON_TYPE_BOOLEAN=0x08,
BSON_TYPE_INT32=0x10,
BSON_TYPE_INT64=0x12,
};
enum{
EVENT_BEGIN_DOCUMENT = 1,
EVENT_END_DOCUMENT,
EVENT_SINGLE_VALUE,
};
enum{
INDEX_EVENT = 0,
INDEX_TYPE = 1,
INDEX_NAME = 2,
INDEX_VALUE = 3,
INDEX_IS_ARRAY = 4,
INDEX_ARRAY_LEN = 5,
INDEX_IS_IN_ARRAY = 6,
INDEX_LEVEL = 7,
INDEX_PATH = 8,
//keep last
INDEX_MAX,
};
WEAK_REF_DEFINE();
public:
CMem *mData;
public:
status_t LoadRawBuf(const void *buf, int_ptr_t size);
status_t LoadRawBuf(CMem *buf);
status_t PeekNext(int *type, CMem *name);
CMiniBson();
virtual ~CMiniBson();
status_t InitBasic();
status_t Init();
status_t Destroy();
status_t Copy(CMiniBson *p);
int Comp(CMiniBson *p);
status_t Print(CFileBase *_buf);
status_t EndDocument();
status_t StartDocument();
status_t WriteFile(CFileBase *file);
status_t Write(const void *buf, int_ptr_t size);
status_t LoadBson(CFileBase *data);
status_t LoadBson(const char *fn);
status_t LoadBson();
int32_t ReadInt32();
bool IsEnd();
status_t GetDocument(const char *name, CMiniBson *doc);
status_t StartDocument(CMem *name,fsize_t *offset);
status_t StartDocument(const char *name,fsize_t *offset);
status_t EndDocument(fsize_t offset);
status_t ResetPointer();
status_t GetBinary(const char *name, CMem *bin);
status_t GetString(const char *name, CMem *str);
status_t GetBoolean(const char *name, bool *b);
bool CheckName(const char *name);
status_t SkipString();
status_t GetDouble(const char *name, double *d);
status_t GetInt64(const char *name, int64_t *pInt);
status_t ToJson(CFileBase *json,bool bracket);
status_t GetInt32(const char *name, int32_t *pInt);
status_t GetUInt32(const char *name, uint32_t *pInt);
status_t GetInt16(const char *name, int16_t *pInt);
status_t GetUInt16(const char *name, uint16_t *pInt);
status_t GetInt8(const char *name, int8_t *pInt);
status_t GetUInt8(const char *name, uint8_t *pInt);
status_t PutDouble(const char *name, double d);
status_t PutDouble(CMem *name, double d);
status_t ReadString(CMem *str);
int8_t ReadByte();
status_t PutBoolean(CMem *name,bool b);
status_t PutBoolean(const char *name, bool b);
status_t PutDocument(const char *name, CMiniBson *bson);
int32_t GetDocumentSize();
status_t PutDocument(CMem *name, CMiniBson *bson);
status_t WriteInt64(int64_t i);
status_t PutInt64(CMem *name,int64_t i);
status_t PutInt64(const char *name, int64_t i);
status_t PutBinary(const char *name, CFileBase *bin);
status_t PutBinary(CMem *name, CFileBase *bin);
status_t PutBinary(const char *name, const void *bin, int_ptr_t size);
status_t PutBinary(CMem *name, const void *bin, int_ptr_t size);
status_t PutString(const char *name, const char *str);
status_t PutString(const char *name, CMem *str);
status_t PutString(CMem *name, CMem *str);
status_t PutInt32(const char *name, int32_t i);
status_t PutUInt32(const char *name, uint32_t i);
status_t PutInt16(const char *name,int16_t i);
status_t PutUInt16(const char *name,uint16_t i);
status_t PutInt8(const char *name,int8_t i);
status_t PutUInt8(const char *name,uint8_t i);
status_t WriteByte(int8_t b);
status_t PutInt32(CMem *name,int32_t i);
status_t PutUInt32(CMem *name,uint32_t i);
status_t UpdateDocumentSize();
status_t UpdateDocumentSize(fsize_t offset,fsize_t size);
status_t WriteInt32(int32_t i);
status_t WriteCString(const char *str);
status_t WriteCString(CMem *str);
status_t SetRawBuf(void *buf, int_ptr_t size);
status_t SetRawBuf(CMem *buf);
status_t AllocBuf(int_ptr_t size);
CMem * GetRawData();
status_t Traverse(bool recursive,int level,CClosure *closure);
fsize_t GetPointerPos(void);
status_t SetPointerPos(fsize_t pos);
status_t UpdateArraySize(fsize_t offset,fsize_t size,int32_t array_length);
status_t StartArray(CMem *name,fsize_t *offset);
status_t StartArray(const char *name,fsize_t *offset);
status_t EndArray(fsize_t offset,int32_t array_len);
status_t GetArray(const char *name, CMiniBson *doc,int32_t *array_length);
};
#endif
|
57567236d986bac723764e12a3bda5bb642a15ca
|
9764c92be4c7dff3c26368506aa9f07b1f6f1220
|
/code/core/OS/Net/NetEventManager.cpp
|
b0a30af2ecc977d5c9b1256eb3c92361b5d02cfb
|
[] |
no_license
|
chc/openspy-core-v2
|
b3f115084215f9777a1df7d51706b8359a547f69
|
6846cd42863ba3f4b4e2bfdccd2989d65829efcc
|
refs/heads/master
| 2023-09-04T04:34:13.320093
| 2023-08-30T21:58:42
| 2023-08-30T21:58:42
| 123,511,717
| 89
| 17
| null | 2022-12-27T02:35:52
| 2018-03-02T01:07:39
|
C++
|
UTF-8
|
C++
| false
| false
| 210
|
cpp
|
NetEventManager.cpp
|
#include "NetEventManager.h"
INetEventManager::INetEventManager() {
}
INetEventManager::~INetEventManager() {
}
void INetEventManager::addNetworkDriver(INetDriver *driver) {
m_net_drivers.push_back(driver);
}
|
47d06b7d7d48a616b95e7a3e4472f719aee9edc0
|
5c87f1207a28f69237e772f1d71d591661a22d7e
|
/eeprom-writer.ino
|
aab8bb4e965d20ddd73eab0bc2ee09b2868133fc
|
[] |
no_license
|
JDat/eeprom-writer
|
e017add9363b7b3e2154e6a56d328759cb0122cc
|
f1a7e72ffa6d06b025f530f98c2cbed0a340a713
|
refs/heads/master
| 2020-05-02T15:22:01.334590
| 2019-04-08T13:05:40
| 2019-04-08T13:05:40
| 178,038,997
| 0
| 0
| null | 2019-03-27T17:00:57
| 2019-03-27T17:00:56
| null |
UTF-8
|
C++
| false
| false
| 14,737
|
ino
|
eeprom-writer.ino
|
/*
// EEPROM Programmer with I2C I/O expanders
//
//
// Base and core Written by K Adcock.
// http://danceswithferrets.org/geekblog/?page_id=903
//
// I2C modifications by JDat
// Support for 32 pin (up to 512k * 8 ) Flash
//
// This software presents a 115200-8N1 serial port.
//
// R[hex address] - reads 16 bytes of data from the EEPROM
// W[hex address]:[data in two-char hex] - writes up to 16 bytes of data to the EEPROM
// P - set write-protection bit (Atmels only, AFAIK)
// U - clear write-protection bit (ditto)
// V - prints the version string
// E - Erase all chip contents to 0xFF
//
// Any data read from the EEPROM will have a CRC checksum appended to it (separated by a comma).
// If a string of data is sent with an optional checksum, then this will be checked
// before anything is written.
//
*/
//#include <avr/pgmspace.h>
//#include <Wire.h>
#include "pindefine.h"
#include "Adafruit_MCP23017.h"
const char hex[] =
{
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
const char version_string[] = {"EEPROM Version=0.02"};
static const int kPin_WaitingForInput = LED_BUILTIN;
byte g_cmd[80]; // strings received from the controller will go in here
static const int kMaxBufferSize = 16;
byte buffer[kMaxBufferSize];
uint16_t ic1out=0;
uint16_t ic2out=0;
Adafruit_MCP23017 mcp1;
Adafruit_MCP23017 mcp2;
void setAddrOut(){
for (uint8_t i=0;i<=18;i++){
if (addrRoute[i]==IC1){
mcp1.pinMode(addrArray[i],OUTPUT);
} else if (addrRoute[i]==IC2){
mcp2.pinMode(addrArray[i],OUTPUT);
}
}
}
void setup()
{
Serial.begin(115200);
//Wire.setClock(400000);
Wire.setClock(1000000);
//Wire.setClock(3400000);
//Wire.begin();
mcp1.begin(IC1);
mcp2.begin(IC2);
pinMode(kPin_WaitingForInput, OUTPUT); digitalWrite(kPin_WaitingForInput, HIGH);
// address lines are ALWAYS outputs
setAddrOut();
// control lines are ALWAYS outputs
//pinMode(kPin_nCE, OUTPUT); digitalWrite(kPin_nCE, LOW); // might as well keep the chip enabled ALL the time
mcp1.pinMode(cepin,OUTPUT); bitClear(ic1out,cepin);
mcp1.writeGPIOAB(ic1out);
//pinMode(kPin_nOE, OUTPUT); digitalWrite(kPin_nOE, HIGH);
mcp1.pinMode(oepin,OUTPUT); bitSet(ic1out,oepin);
mcp1.writeGPIOAB(ic1out);
//pinMode(kPin_nWE, OUTPUT); digitalWrite(kPin_nWE, HIGH); // not writing
mcp1.pinMode(wepin,OUTPUT); bitSet(ic1out,wepin);
mcp1.writeGPIOAB(ic1out);
SetDataLinesAsInputs();
SetAddress(0);
//Serial.println("chip Erase start");
//void EraseChip();
//delay(300);
//Serial.println("Erase complete");
// while (-1){
//
// }
}
void loop()
{
digitalWrite(kPin_WaitingForInput, HIGH);
ReadString();
digitalWrite(kPin_WaitingForInput, LOW);
switch (g_cmd[0])
{
case 'V': Serial.println(version_string); break;
case 'P': SetSDPState(true); break;
case 'U': SetSDPState(false); break;
case 'R': ReadEEPROM(); break;
case 'W': WriteEEPROM(); break;
case 'E': eraseChip(); break;
case 0: break; // empty string. Don't mind ignoring this.
default: Serial.println("ERR Unrecognised command"); break;
}
}
void ReadEEPROM() // R<address> - read kMaxBufferSize bytes from EEPROM, beginning at <address> (in hex)
{
if (g_cmd[1] == 0)
{
Serial.println("ERR");
return;
}
// decode ASCII representation of address (in hex) into an actual value
long addr = 0;
int x = 1;
while (x < 6 && g_cmd[x] != 0)
{
addr = addr << 4;
addr |= HexToVal(g_cmd[x++]);
}
//Serial.println("Read addr: " + String(addr,HEX) );
//digitalWrite(kPin_nWE, HIGH); // disables write
bitSet(ic1out,wepin); mcp1.writeGPIOAB(ic1out);
SetDataLinesAsInputs();
//digitalWrite(kPin_nOE, LOW); // makes the EEPROM output the byte
bitClear(ic1out,oepin); mcp1.writeGPIOAB(ic1out);
ReadEEPROMIntoBuffer(addr, kMaxBufferSize);
// now print the results, starting with the address as hex ...
Serial.print(hex[ (addr & 0xF0000) >> 16 ]);
Serial.print(hex[ (addr & 0x0F000) >> 12 ]);
Serial.print(hex[ (addr & 0x00F00) >> 8 ]);
Serial.print(hex[ (addr & 0x000F0) >> 4 ]);
Serial.print(hex[ (addr & 0x0000F) ]);
Serial.print(":");
PrintBuffer(kMaxBufferSize);
Serial.println("OK");
//digitalWrite(kPin_nOE, HIGH); // stops the EEPROM outputting the byte
bitSet(ic1out,oepin); mcp1.writeGPIOAB(ic1out);
}
void WriteEEPROM() // W<four byte hex address>:<data in hex, two characters per byte, max of 16 bytes per line>
{
if (g_cmd[1] == 0)
{
Serial.println("ERR");
return;
}
long addr = 0;
int x = 1;
while (g_cmd[x] != ':' && g_cmd[x] != 0)
{
addr = addr << 4;
addr |= HexToVal(g_cmd[x]);
++x;
}
// g_cmd[x] should now be a :
if (g_cmd[x] != ':')
{
Serial.println("ERR");
return;
}
x++; // now points to beginning of data
uint8_t iBufferUsed = 0;
while (g_cmd[x] && g_cmd[x+1] && iBufferUsed < kMaxBufferSize && g_cmd[x] != ',')
{
uint8_t c = (HexToVal(g_cmd[x]) << 4) | HexToVal(g_cmd[x+1]);
buffer[iBufferUsed++] = c;
x += 2;
}
// if we're pointing to a comma, then the optional checksum has been provided!
if (g_cmd[x] == ',' && g_cmd[x+1] && g_cmd[x+2])
{
byte checksum = (HexToVal(g_cmd[x+1]) << 4) | HexToVal(g_cmd[x+2]);
byte our_checksum = CalcBufferChecksum(iBufferUsed);
if (our_checksum != checksum)
{
// checksum fail!
iBufferUsed = -1;
Serial.print("ERR ");
Serial.print(checksum, HEX);
Serial.print(" ");
Serial.print(our_checksum, HEX);
Serial.println("");
return;
}
}
// buffer should now contains some data
if (iBufferUsed > 0)
{
WriteBufferToEEPROM(addr, iBufferUsed);
}
if (iBufferUsed > -1)
{
Serial.println("OK");
}
}
void eraseChip()
{
//digitalWrite(kPin_LED_Red, HIGH);
//digitalWrite(kPin_nWE, HIGH); // disables write
bitSet(ic1out,wepin); mcp1.writeGPIOAB(ic1out);
//digitalWrite(kPin_nOE, LOW); // makes the EEPROM output the byte
bitClear(ic1out,oepin); mcp1.writeGPIOAB(ic1out);
//SetDataLinesAsInputs();
//byte bytezero = ReadByteFrom(0);
//digitalWrite(kPin_nOE, HIGH); // stop EEPROM from outputting byte
bitSet(ic1out,oepin); mcp1.writeGPIOAB(ic1out);
//digitalWrite(kPin_nCE, HIGH);
bitClear(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
SetDataLinesAsOutputs();
WriteByteTo(0x5555, 0xAA);
WriteByteTo(0x2AAA, 0x55);
WriteByteTo(0x5555, 0x80);
WriteByteTo(0x5555, 0xAA);
WriteByteTo(0x2AAA, 0x55);
WriteByteTo(0x5555, 0x10);
//WriteByteTo(0x0000, bytezero); // this "dummy" write is required so that the EEPROM will flush its buffer of commands.
//digitalWrite(kPin_nCE, LOW); // return to on by default for the rest of the code
//bitClear(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
bitSet(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
delay(300);
Serial.println("OK");
}
// Important note: the EEPROM needs to have data written to it immediately after sending the "unprotect" command, so that the buffer is flushed.
// So we read byte 0 from the EEPROM first, then use that as the dummy write afterwards.
// It wouldn't matter if this facility was used immediately before writing an EEPROM anyway ... but it DOES matter if you use this option
// in isolation (unprotecting the EEPROM but not changing it).
void SetSDPState(bool bWriteProtect)
{
//digitalWrite(kPin_LED_Red, HIGH);
//digitalWrite(kPin_nWE, HIGH); // disables write
bitSet(ic1out,wepin); mcp1.writeGPIOAB(ic1out);
//digitalWrite(kPin_nOE, LOW); // makes the EEPROM output the byte
bitClear(ic1out,oepin); mcp1.writeGPIOAB(ic1out);
SetDataLinesAsInputs();
byte bytezero = ReadByteFrom(0);
//digitalWrite(kPin_nOE, HIGH); // stop EEPROM from outputting byte
bitSet(ic1out,oepin); mcp1.writeGPIOAB(ic1out);
//digitalWrite(kPin_nCE, HIGH);
bitSet(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
SetDataLinesAsOutputs();
// This is for the AT28C256
if (bWriteProtect)
{
WriteByteTo(0x5555, 0xAA);
WriteByteTo(0x2AAA, 0x55);
WriteByteTo(0x5555, 0xA0);
}
else
{
WriteByteTo(0x5555, 0xAA);
WriteByteTo(0x2AAA, 0x55);
WriteByteTo(0x5555, 0x80);
WriteByteTo(0x5555, 0xAA);
WriteByteTo(0x2AAA, 0x55);
WriteByteTo(0x5555, 0x20);
//WriteByteTo(0x5555, 0xAA);
//WriteByteTo(0x2AAA, 0x55);
//WriteByteTo(0x5555, 0xA0);
//WriteByteTo(0x5555, 0xAA);
//WriteByteTo(0x2AAA, 0x55);
//WriteByteTo(0x5555, 0x20);
}
//WriteByteTo(0x0000, bytezero); // this "dummy" write is required so that the EEPROM will flush its buffer of commands.
//digitalWrite(kPin_nCE, LOW); // return to on by default for the rest of the code
//bitClear(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
//bitSet(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
//Serial.print("OK SDP ");
//if (bWriteProtect)
//{
//Serial.println("enabled");
//}
//else
//{
//Serial.println("disabled");
//}
}
// ----------------------------------------------------------------------------------------
void ReadEEPROMIntoBuffer(long addr, int size)
{
//digitalWrite(kPin_nWE, HIGH);
bitSet(ic1out,wepin); mcp1.writeGPIOAB(ic1out);
SetDataLinesAsInputs();
//digitalWrite(kPin_nOE, LOW);
bitClear(ic1out,oepin); mcp1.writeGPIOAB(ic1out);
for (int x = 0; x < size; ++x)
{
buffer[x] = ReadByteFrom(addr + x);
}
//digitalWrite(kPin_nOE, HIGH);
bitSet(ic1out,oepin); mcp1.writeGPIOAB(ic1out);
}
void WriteBufferToEEPROM(long addr, int size)
{
//bitSet(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
//digitalWrite(kPin_nOE, HIGH); // stop EEPROM from outputting byte
bitSet(ic1out,oepin); mcp1.writeGPIOAB(ic1out);
//digitalWrite(kPin_nWE, HIGH); // disables write
bitSet(ic1out,wepin); mcp1.writeGPIOAB(ic1out);
SetDataLinesAsOutputs();
bitClear(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
for (uint8_t x = 0; x < size; ++x)
{
//SetSDPState(true);
WriteByteTo(0x5555, 0xAA);
WriteByteTo(0x2AAA, 0x55);
WriteByteTo(0x5555, 0xA0);
WriteByteTo(addr + x, buffer[x]);
for (uint8_t i=0;i<=2;i++){
//WriteByteTo(addr + x, buffer[x]);
bitClear(ic1out,wepin); mcp1.writeGPIOAB(ic1out);
// bitClear(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
bitSet(ic1out,wepin); mcp1.writeGPIOAB(ic1out);
// bitSet(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
}
}
bitSet(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
}
//W00000:112233445566778899AABBCCDDEEFF00
// ----------------------------------------------------------------------------------------
// this function assumes that data lines have already been set as INPUTS, and that
// nOE is set LOW.
byte ReadByteFrom(long addr)
{
SetAddress(addr);
//digitalWrite(kPin_nCE, LOW);
bitClear(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
byte b = ReadData();
//digitalWrite(kPin_nCE, HIGH);
bitSet(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
return b;
}
// this function assumes that data lines have already been set as OUTPUTS, and that
// nOE is set HIGH.
void WriteByteTo(long addr, byte b)
{
SetAddress(addr);
SetData(b);
//digitalWrite(kPin_nCE, LOW);
//bitClear(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
//digitalWrite(kPin_nWE, LOW); // enable write
bitClear(ic1out,wepin); mcp1.writeGPIOAB(ic1out);
//digitalWrite(kPin_nWE, HIGH); // disable write
bitSet(ic1out,wepin); mcp1.writeGPIOAB(ic1out);
//digitalWrite(kPin_nCE, HIGH);
//bitSet(ic1out,cepin); mcp1.writeGPIOAB(ic1out);
}
// ----------------------------------------------------------------------------------------
void SetDataLinesAsInputs()
{
for (uint8_t i=0;i<=7;i++){
if (dataRoute[i]==IC1){
mcp1.pinMode(dataArray[i],INPUT);
} else if (dataRoute[i]==IC2){
mcp2.pinMode(dataArray[i],INPUT);
}
}
}
void SetDataLinesAsOutputs()
{
for (uint8_t i=0;i<=7;i++){
if (dataRoute[i]==IC1){
mcp1.pinMode(dataArray[i],OUTPUT);
} else if (dataRoute[i]==IC2){
mcp2.pinMode(dataArray[i],OUTPUT);
}
}
}
void SetAddress(long a)
{
for (uint8_t i=0;i<=18;i++){
if (addrRoute[i]==IC1){
if ( a & long(round(pow(2,i))) ){
bitSet(ic1out,addrArray[i]);
} else {
bitClear(ic1out,addrArray[i]);
}
} else if (addrRoute[i]==IC2){
if ( a & long(round(pow(2,i))) ) {
bitSet(ic2out,addrArray[i]);
} else {
bitClear(ic2out,addrArray[i]);
}
}
}
mcp1.writeGPIOAB(ic1out);
mcp2.writeGPIOAB(ic2out);
}
// this function assumes that data lines have already been set as OUTPUTS.
void SetData(byte b)
{
for (uint8_t i=0;i<=7;i++){
if (dataRoute[i]==IC1){
if ( b & (1 << i) ){
bitSet(ic1out,dataArray[i]);
} else {
bitClear(ic1out,dataArray[i]);
}
} else if (dataRoute[i]==IC2){
if ( b & (1 << i) ) {
bitSet(ic2out,dataArray[i]);
} else {
bitClear(ic2out,dataArray[i]);
}
}
}
mcp1.writeGPIOAB(ic1out);
mcp2.writeGPIOAB(ic2out);
}
// this function assumes that data lines have already been set as INPUTS.
byte ReadData()
{
byte b = 0;
for (uint8_t i=0;i<=7;i++) {
if (dataRoute[i]==IC1){
if ( mcp1.digitalRead(dataArray[i]) ) {
bitSet(b,i);
}
} else if (dataRoute[i]==IC2){
if ( mcp2.digitalRead(dataArray[i]) ) {
bitSet(b,i);
}
}
}
return(b);
}
// ----------------------------------------------------------------------------------------
void PrintBuffer(int size)
{
uint8_t chk = 0;
for (uint8_t x = 0; x < size; ++x)
{
Serial.print(hex[ (buffer[x] & 0xF0) >> 4 ]);
Serial.print(hex[ (buffer[x] & 0x0F) ]);
chk = chk ^ buffer[x];
}
Serial.print(",");
Serial.print(hex[ (chk & 0xF0) >> 4 ]);
Serial.print(hex[ (chk & 0x0F) ]);
Serial.println("");
}
void ReadString()
{
int i = 0;
byte c;
g_cmd[0] = 0;
do
{
if (Serial.available())
{
c = Serial.read();
if (c > 31)
{
g_cmd[i++] = c;
g_cmd[i] = 0;
}
}
}
while (c != 10);
}
uint8_t CalcBufferChecksum(uint8_t size)
{
uint8_t chk = 0;
for (uint8_t x = 0; x < size; ++x)
{
chk = chk ^ buffer[x];
}
return(chk);
}
// converts one character of a HEX value into its absolute value (nibble)
byte HexToVal(byte b)
{
if (b >= '0' && b <= '9') return(b - '0');
if (b >= 'A' && b <= 'F') return((b - 'A') + 10);
if (b >= 'a' && b <= 'f') return((b - 'a') + 10);
return(0);
}
|
d8c40141d3d9eb474ad6e37b5d57dc41c4089e19
|
e49d828d909b194aa4c625843879a6be0cc12f62
|
/Dimension/src/Engine/Core/Aplication.cpp
|
7c7447165e42d6eaf6c48331a690e672bb713353
|
[] |
no_license
|
lauriscx/Dimension
|
2b15e5dfc07665116d57fb021e429d89e16cade3
|
d081ff91f1daa60d67db05230ae6777e8d8276f5
|
refs/heads/master
| 2023-02-18T21:16:49.876831
| 2020-11-22T17:06:41
| 2020-11-22T17:06:41
| 280,666,793
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,662
|
cpp
|
Aplication.cpp
|
#include "imgui.h"
#include "GUI/imgui_impl_glfw.h"
#include "GUI/imgui_impl_opengl3.h"
#include "GLAD/glad.h"
#include "Aplication.h"
#include <iostream>
#include "Input/Input.h"
#include "GLFW/glfw3.h"
#include <functional>
#include "Layers/Layer.h"
#include "Temporary/Logger.h"
#include "Input/Events/Error.h"
#include <string>
#include "Render/RenderData/Texture.h"
#include "glm/gtc/matrix_transform.hpp"
#include "FileReader.h"
#include "Render/Render2D.h"
#include <fstream>
Dimension::Aplication* Dimension::Aplication::app;
static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f);
Dimension::Aplication::Aplication(const char* title, int width, int height) : Running(true) {
Dimension::Aplication::app = this;
window = Window::Create(title, width, height);
events.OnEvent(std::bind(&LayerStack::OnEvent, &m_Layers, std::placeholders::_1));
window->EventsHandler(&events);
if (gladLoadGL() == 0) {
DERROR("Failed to load glad");
}
}
void RenderUI();
void Dimension::Aplication::Run() {
Layer * layer = new Layer("Test");
m_Layers.PushLayer(layer);
IMGUI_CHECKVERSION(); // Setup Dear ImGui context
ImGui::CreateContext();
ImGuiIO &io = ImGui::GetIO();
ImGui_ImplGlfw_InitForOpenGL((GLFWwindow*)window->Context(), true); // Setup Platform/Renderer bindings
const char* glsl_version = "#version 330";
ImGui_ImplOpenGL3_Init(glsl_version);
ImGui::StyleColorsDark(); // Setup Dear ImGui style
FileReader reader;
Shader shader;
shader.addVertexCode("/res/Vertex.glsl", reader.ReadFile("../res/Vertex.glsl"));
shader.addFragmentCode("/res/Fragment.glsl", reader.ReadFile("../res/Fragment.glsl"));
shader.compile();
Texture texture;
texture.Bind()->LoadPNG("../res/texture.png")->LoadData()->SetParameters();
GraphicObject sprite;
sprite.GetMaterial()->SetColor({ 0, 1, 1, 1 })->AddTexture(texture, "diffuseMap");
sprite.GetMesh()->GenRectangle(0.1f, 0.1f);
glm::mat4 test(1.0f);
/*test = glm::translate(test, glm::vec3(0, 0.5f, 0));
test = glm::rotate(test, 45.0f, glm::vec3(0, 0, 1.0f));
test = glm::scale(test, glm::vec3(2, 2, 1));*/
sprite.SetTransformation(test);
objectsToRender.push_back(sprite);
GraphicObject triangle;
triangle.GetMaterial()->SetColor({ 1, 0, 0, 1 })->AddTexture(texture, "diffuseMap");
triangle.GetMesh()->GenTriangle(0.5f, 0.5f);
glm::mat4 test2(1.0f);
test2 = glm::translate(test2, glm::vec3(0, -0.5f, 0));
test2 = glm::rotate(test2, -45.0f, glm::vec3(0, 0, 1.0f));
test2 = glm::scale(test2, glm::vec3(2, 2, 1));
triangle.SetTransformation(test2);
//objectsToRender.push_back(triangle);
Render2D render;
auto t_end = std::chrono::high_resolution_clock::now();
auto t_start = std::chrono::high_resolution_clock::now();
double delta_time = 0;
while (Running) {
render.SetClearColor({ color.x, color.y, color.z, color.w });
t_start = std::chrono::high_resolution_clock::now();
/* Render here */
int display_w, display_h;
glfwGetFramebufferSize((GLFWwindow*)window->Context(), &display_w, &display_h);
render.SetWindowSize({ display_w, display_h });
render.PrepareScene();
m_Layers.Update();
/*if (Input::IsKeyPressed(GLFW_KEY_D)) {
objectsToRender.clear();
glm::mat4 moveMatrix = sprite.GetTransformation();
moveMatrix = glm::translate(moveMatrix, glm::vec3(1.0f * delta_time, 0.0f, 0.0f));
sprite.SetTransformation(moveMatrix);
objectsToRender.push_back(sprite);
}
if (Input::IsKeyPressed(GLFW_KEY_A)) {
objectsToRender.clear();
glm::mat4 moveMatrix = sprite.GetTransformation();
moveMatrix = glm::translate(moveMatrix, glm::vec3(-1.0f * delta_time, 0.0f, 0.0f));
sprite.SetTransformation(moveMatrix);
objectsToRender.push_back(sprite);
}
if (Input::IsKeyPressed(GLFW_KEY_S)) {
objectsToRender.clear();
glm::mat4 moveMatrix = sprite.GetTransformation();
moveMatrix = glm::translate(moveMatrix, glm::vec3(0.0f, -1.0f * delta_time, 0.0f));
sprite.SetTransformation(moveMatrix);
objectsToRender.push_back(sprite);
}
if (Input::IsKeyPressed(GLFW_KEY_W)) {
objectsToRender.clear();
glm::mat4 moveMatrix = sprite.GetTransformation();
moveMatrix = glm::translate(moveMatrix, glm::vec3(0.0f, 1.0f * delta_time, 0.0f));
sprite.SetTransformation(moveMatrix);
objectsToRender.push_back(sprite);
}*/
for (GraphicObject grpObj : objectsToRender) {
//render.draw(&grpObj, shader);
render.PackObject(&grpObj);
}
render.flush(&sprite, shader);
RenderUI();
window->Update();
Close();
t_end = std::chrono::high_resolution_clock::now();
delta_time = (std::chrono::duration<double, std::milli>(t_end - t_start).count()) / 1000;
}
}
static void HelpMarker(const char* desc)
{
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(desc);
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
void RenderUI() {
// feed inputs to dear imgui, start new frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// render your GUI
ImGui::Begin("Demo langas");
ImGui::Button("Sveiki!");
ImGui::End();
bool showDemo = true;
ImGui::ShowDemoWindow(&showDemo);
static bool alpha_preview = true;
static bool alpha_half_preview = false;
static bool drag_and_drop = true;
static bool options_menu = true;
static bool hdr = false;
ImGui::Checkbox("With Alpha Preview", &alpha_preview);
ImGui::Checkbox("With Half Alpha Preview", &alpha_half_preview);
ImGui::Checkbox("With Drag and Drop", &drag_and_drop);
ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options.");
ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets.");
ImGuiColorEditFlags misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions);
ImGui::Text("Color widget:");
ImGui::SameLine(); HelpMarker(
"Click on the colored square to open a color picker.\n"
"CTRL+click on individual component to input value.\n");
ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags);
ImGui::Text("Color widget HSV with Alpha:");
ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | misc_flags);
ImGui::Text("Color widget with Float Display:");
ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags);
ImGui::Text("Color button with Picker:");
ImGui::SameLine(); HelpMarker(
"With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n"
"With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only "
"be used for the tooltip and picker popup.");
ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags);
ImGui::Text("Color button with Custom Picker Popup:");
// Generate a default palette. The palette will persist and can be edited.
static bool saved_palette_init = true;
static ImVec4 saved_palette[32] = {};
if (saved_palette_init)
{
for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)
{
ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f,
saved_palette[n].x, saved_palette[n].y, saved_palette[n].z);
saved_palette[n].w = 1.0f; // Alpha
}
saved_palette_init = false;
}
static ImVec4 backup_color;
bool open_popup = ImGui::ColorButton("MyColor##3b", color, misc_flags);
ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x);
open_popup |= ImGui::Button("Palette");
if (open_popup)
{
ImGui::OpenPopup("mypicker");
backup_color = color;
}
if (ImGui::BeginPopup("mypicker"))
{
ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!");
ImGui::Separator();
ImGui::ColorPicker4("##picker", (float*)&color, misc_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview);
ImGui::SameLine();
ImGui::BeginGroup(); // Lock X position
ImGui::Text("Current");
ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40));
ImGui::Text("Previous");
if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)))
color = backup_color;
ImGui::Separator();
ImGui::Text("Palette");
for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)
{
ImGui::PushID(n);
if ((n % 8) != 0)
ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y);
ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip;
if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20)))
color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha!
// Allow user to drop colors into each palette entry. Note that ColorButton() is already a
// drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag.
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3);
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4);
ImGui::EndDragDropTarget();
}
ImGui::PopID();
}
ImGui::EndGroup();
ImGui::EndPopup();
}
// Render dear imgui into screen
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
Dimension::Aplication::~Aplication() {
}
void Dimension::Aplication::Close() {
if (events.Dispacth<WindowCloseEvent>([](WindowCloseEvent* e) {return true;})) {
std::cout << "Close" << std::endl;
Running = false;
}
events.Dispacth<Error>([](Error* e) {
//std::string er = e.GetErrorReport();
std::cout << e->GetErrorReport() << std::endl;
return true;
});
events.Dispacth<WindowResizeEvent>([](WindowResizeEvent* e) {
//std::string er = e.GetErrorReport();
std::cout << "Window width: " << e->GetWidth() << std::endl;
return true;
});
events.Dispacth<KeyPressedEvent>([](KeyPressedEvent* e) {
//std::string er = e.GetErrorReport();
//std::cout << "key: " << e->GetKey() << std::endl;
return true;
});
}
|
6c7fb516eb51ac27d4d84b065bbd610e338885a0
|
6ff5b16946834456b8f22c2b607b577d460f8acf
|
/Debugger/debugger.cpp
|
8a4d30c9919a1a584ee7373b3e95e7077ec89299
|
[
"Unlicense"
] |
permissive
|
stpr18/debugger
|
7da7dc741455479878ef2d743c974d696cf3a2d5
|
40afd258d39ec9c9387d8c6e9d272b8a0f3051d5
|
refs/heads/master
| 2021-01-09T20:23:25.440132
| 2016-06-24T03:54:03
| 2016-06-24T03:54:03
| 61,855,319
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 2,959
|
cpp
|
debugger.cpp
|
#include <vector>
#include <iostream>
#include "debugger.h"
Debugger::Debugger()
{
}
Debugger::~Debugger()
{
DetachAll();
}
void Debugger::RunAndAttach(const char *path)
{
debugger_.RunAndAttach(path);
}
void Debugger::RunAndAttach(const wchar_t *path)
{
debugger_.RunAndAttach(path);
}
void Debugger::Attach(native::ProcessId process_id)
{
debugger_.Attach(process_id);
}
void Debugger::DetachAll()
{
return debugger_.DetachAll();
}
void Debugger::MainLoop()
{
bool first = false;
while (!debugger_.IsExited()) {
native::DebugInfo& event_info = *debugger_.WaitDebugger();
bool exception_handled = true;
switch (event_info.code) {
using EventCode = native::DebugInfo::EventCode;
case EventCode::kCreateProcess:
std::cout << "- プロセス作成:" << event_info.debuggee->GetThreadId() << std::endl;
event_info.debuggee->SetSingleStep(true);
break;
case EventCode::kCreateThread:
std::cout << "- スレッド作成:" << event_info.debuggee->GetThreadId() << std::endl;
//event_info.debuggee->SetSingleStep(true);
break;
case EventCode::kExitProcess:
std::cout << "- プロセス終了:" << event_info.debuggee->GetThreadId() << std::endl;
std::cout << "-- 終了コード:" << event_info.info.exit_process.exit_code << std::endl;
break;
case EventCode::kExitThread:
std::cout << "- スレッド終了:" << event_info.debuggee->GetThreadId() << std::endl;
std::cout << "-- 終了コード:" << event_info.info.exit_thread.exit_code << std::endl;
break;
case EventCode::kLoadLib:
std::cout << "- ライブラリのロード:" << event_info.debuggee->GetThreadId() << std::endl;
break;
case EventCode::kUnloadLib:
std::cout << "- ライブラリのアンロード:" << event_info.debuggee->GetThreadId() << std::endl;
break;
case EventCode::kOutputString:
std::cout << "- デバッグ文字列:" << event_info.debuggee->GetThreadId() << std::endl;
{
std::string str;
event_info.debuggee->ReadMemoryString(&event_info.info.output_string.str, &str);
std::cout << "-- 文字列:" << str << std::endl;
}
break;
case EventCode::kException:
std::cout << "- 例外発生:" << event_info.debuggee->GetThreadId() << std::endl;
exception_handled = false;
break;
case EventCode::kSingleStep:
//std::cout << "- シングルステップ・ブレークポイント:" << event_info.debuggee->GetThreadId() << std::endl;
break;
case EventCode::kBreakPoint:
std::cout << "- ブレークポイント:" << event_info.debuggee->GetThreadId() << std::endl;
break;
case EventCode::kUnknown:
std::cout << "- 不明なデバッグイベント:" << event_info.debuggee->GetThreadId() << std::endl;
break;
default:
std::cout << "- 予期しないイベント" << event_info.debuggee->GetThreadId() << std::endl;
break;
}
std::cout << std::flush;
debugger_.ContinueDebugger(exception_handled);
}
}
|
b9cd06da51f18eeb1d807a5bd6deb647ec9522d6
|
58158c18390549157070514f34c56e85188327af
|
/[Luogu P1280] 尼克的任务.cpp
|
6f54ba1e60a5f8aca57a66c9e32fd76bd87afbd8
|
[] |
no_license
|
TosakaUCW/Solution_Source_Code
|
8c24e3732570bb813d5d713987a99fea17618e1f
|
8469cc7a177ed17e013a5fb17482983d8e61911e
|
refs/heads/master
| 2021-11-26T21:23:50.423916
| 2021-11-19T02:34:01
| 2021-11-19T02:34:01
| 149,946,420
| 7
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 649
|
cpp
|
[Luogu P1280] 尼克的任务.cpp
|
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
const int N = 1e4 + 5;
int n, m, f[N];
std::vector<int> a[N];
int main()
{
memset(f, -0x3f, sizeof f);
f[1] = 0;
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++)
{
int x, y;
scanf("%d%d", &x, &y);
a[x].push_back(y);
}
for (int i = 1; i <= n; i++)
{
if (a[i].size() == 0)
f[i + 1] = std::max(f[i] + 1, f[i + 1]);
else
for (int j = 0; j < a[i].size(); j++)
f[i + a[i][j]] = std::max(f[i + a[i][j]], f[i]);
}
printf("%d", f[n + 1]);
return 0;
}
|
caf6781caf0760971dc88f320d4f861c9641bcbe
|
1e17cf70e2f058afb4d80cf8f43bd288c0669cc1
|
/MainFrm.h
|
9fc9027b7f8e76f99535d847e715f5c683826244
|
[] |
no_license
|
CostasAtomizer/scrsaver_win
|
bda1d69b1a571253e7c166a825214ae1dcc4e2ce
|
97a4717ac68adf50f9db5d558a271299417e5d84
|
refs/heads/master
| 2022-11-29T03:21:48.379453
| 2022-11-05T17:35:47
| 2022-11-05T17:35:47
| 48,375,577
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 2,734
|
h
|
MainFrm.h
|
// MainFrm.h : interface of the CMainFrame class
//
#pragma once
#include "TwRand.h"
#include "TypeOfTheShowDialog.h"
#include <atlimage.h>
#include "math.h"
class CMainFrame : public CFrameWndEx
{
public:
CMainFrame();
protected:
DECLARE_DYNAMIC(CMainFrame)
// Overrides
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo);
// Фигуры рисуются по сообщениям от таймера
afx_msg void OnTimer(UINT id);
// Обработчик сообщения WM_ERASEBKGND. Обычно по этому сообщению
// стирается фон окна. Наш же обработчик ничего не делает, так как
// в окнах с виртуальным окном перерисовывать фон не нужно.
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint();
afx_msg void OnDestroy();
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
CStatusBar m_wndStatusBar;
CToolBar m_wndToolBar;
//CChildView m_wndView;
// Generated message map functions
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSetFocus(CWnd *pOldWnd);
DECLARE_MESSAGE_MAP()
private:
CWinAppEx *pApp;
CDC m_memDC;
CBitmap m_bmp;
CBrush m_bkbrush;
int maxX, maxY;
COLORREF m_textColor;
int NCOLORS;
CTwRand xRnd, yRnd;
CImage* image_0;
CImage* image_1;
DWORD** meta_indexes;
DWORD** meta_indexes_back;
COLORREF* palette;
TypeOfTheShowDialog xOptions;
typedef UINT (*pf)(void*);
pf ArrayOfTheFunctions[5];
public:
afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnStartEnd();
afx_msg void OnStartStart();
afx_msg void OnViewFullscreen();
afx_msg void OnStartOptionsDlg();
protected:
void InitFrame(int ww, int hh);
static UINT DrawThread(void* param);
static UINT DrawThread2(void* param);
static UINT DrawThread3(void* param);
static UINT DrawThread4(void* param);
static UINT DrawColors(void* param);
inline void N_Test(byte* lp_image, int x, int y, int ip, int bpp);
inline void N_Test2(byte* lp_image1, int hh, int ww, int ip, int bpp);
inline void N_Test3(byte* lp_image, int x, int y, int ip, int bpp);
void ClearImage(byte* lp_image, int ip, int bpp, int ww, int hh);
void CopyImage(byte* lp_image_s, byte* lp_image_d, int ip, int bpp, int ww, int hh);
void Palette_Init();
void Shifting_By_Palette(byte* lp_image, int ip, int bpp, int ww, int hh);
bool m_isthread;
};
|
8474b10e58f71daf50c862c992b1e5a0531ac46e
|
9d6db8e0771409158e3c19a79208591041925120
|
/IF20.cpp
|
2c92d7c55fa98940461a763a046c68370965b76b
|
[] |
no_license
|
SmetanaAlex/Menu
|
70a8f4fdb0c85aed435497daac8df10ca82fb297
|
eda158898e8a98a3562770f7921cc3f1d93521c2
|
refs/heads/master
| 2020-07-30T22:18:05.929501
| 2019-09-23T14:40:30
| 2019-09-23T14:40:30
| 210,378,933
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 1,014
|
cpp
|
IF20.cpp
|
#include "iostream"
#include "ifr.h"
using namespace std;
int z20if()
{
setlocale(LC_ALL, "Russian");
cout << "If20. На числовой оси расположены три точки: A, B, C. Определить, какая издвух последних точек(B или C) расположена ближе к A " << endl;
cout << "вывести эту точку и ее расстояние от точки A." << endl;
int a, b, c;
cout << "Введите А" << endl;
cin >> a;
cout << "Введите В" << endl;
cin >> b;
cout << "Введите С" << endl;
cin >> c;
int rr = abs(a - b);
int rk = abs(a - c);
if (rr < rk) {
cout << "точка B расположена ближе к A" << endl;
cout << " Расстояние от точки A до т В- " << rr << endl;
}
else {
cout << "точка C расположена ближе к A" << endl;
cout << "Расстояние от точки A до т С- " << rk << endl;
}
system("pause");
return 0;
}
|
66b0a18ce8195a8da7cfacba5e04739ef4018403
|
400ff661684148cbb6aa99f4ebbc82bc551356d9
|
/c++/aria2/52634627bc/base64/Base64.h
|
367c926daa67b4ff5efac857a456e04d9876fed9
|
[] |
no_license
|
csw201710/demo
|
32d71f333dc7f78fab0e2ab53f6a7e051847eea3
|
386a56961e8099b632115015cbeec599765ead01
|
refs/heads/master
| 2021-08-26T08:03:49.055496
| 2021-08-18T11:22:45
| 2021-08-18T11:22:45
| 171,476,054
| 7
| 11
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 373
|
h
|
Base64.h
|
#ifndef _BASE64_H_
#define _BASE64_H_
#include <string>
using namespace std;
class Base64
{
private:
static string part_encode(const string& subplain);
static string part_decode(const string& subCrypted);
static char getValue(char ch);
public:
static string encode(string plain);
static string decode(string crypted);
};
#endif // _BASE64_H_
|
6776e3264354abfaef4578cfe3f5aa0f4a6c7c0b
|
de7c4a2b70415f0389c54440e9c6bf2cd5cd42f7
|
/StraightGUI/PlayerStatusView.cc
|
3e78f567085e1e78b4390106753fe81a60df4dfd
|
[] |
no_license
|
ZiyiZhao/Straight_GUI
|
a075ae945537c5db12f1a0c0cf998d7cf8967b7e
|
1f21ea7185a930f63f7886499d56ad318bde1818
|
refs/heads/master
| 2021-01-19T05:48:31.664394
| 2014-07-20T16:01:32
| 2014-07-20T16:01:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,573
|
cc
|
PlayerStatusView.cc
|
//
// PlayerStatusView.cc
// Straights
//
// Created by Jack,Errin on 2014-06-14.
// Copyright (c) 2014 Jack,Errin. All rights reserved.
//
/*
* Player class - holds the information to display for the viewer class
*
*/
#include "PlayerStatusView.h"
#include <iostream>
#include <gtkmm/label.h>
#include <sstream>
PlayerStatusView::PlayerStatusView(Model *model, Gtk::Frame *frame){
frame_ = frame;
model_ = model;
// Create one frame for each player and add it to HBox
// Create one label for each player and add it to frame
for(int i = 0; i < 4; i++) {
// create a frame using player type and status
playerStatus_[i] = new Gtk::Frame(model_->getPlayerType()[i]);
Gtk::Label *playerLabelStatus = new Gtk::Label(model_->getPlayerStatus()[i], 0, 0, false);
playerStatus_[i]->add(*playerLabelStatus);
playerStatusHBox_.add(*playerStatus_[i]);
}
// add the contents to window
frame_->add(playerStatusHBox_);
model_->subscribe(this);
}
//desctructor
PlayerStatusView::~PlayerStatusView(){
delete frame_;
for(int i = 0; i < 4; i++){
delete playerStatus_[i];
}
}
// updates
void PlayerStatusView::update(){
// Remove any widget
for(int i = 0; i < 4; i++) {
// for each of the 4 player status frames, remove any widgets and constructs new labels with current information
playerStatus_[i]->remove();
playerStatus_[i]->set_label(model_->getPlayerType()[i]);
Gtk::Label *playerLabelStatus = new Gtk::Label(model_->getPlayerStatus()[i], 0, 0, false);
playerStatus_[i]->add(*playerLabelStatus);
}
}
|
2709c4067ba3cff7aeb8f1890030ccc1e9850721
|
dbcae57ecc5f8d1f7ad2552465834da2784edd3f
|
/ECNU/ecnu_1878.cpp
|
25ef34f4d39dbcec174fbcf9260e007890a3f106
|
[] |
no_license
|
AmazingCaddy/acm-codelab
|
13ccb2daa249f8df695fac5b7890e3f17bb40bf5
|
e22d732d468b748ff12885aed623ea3538058c68
|
refs/heads/master
| 2021-01-23T02:53:50.313479
| 2014-09-29T14:11:12
| 2014-09-29T14:11:12
| 14,780,683
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,342
|
cpp
|
ecnu_1878.cpp
|
//二分搜索
#include<iostream>
#include<algorithm>
#define MAXN 100002
using namespace std;
const int INF=~(1<<31);
int a[MAXN],n;
int bin_search1( int k )
{
int l=0,r=n-1,mid;
while( l<=r )
{
mid=(l+r)>>1;
if( a[mid]>=k ) r=mid-1; //尽量往前移动,取到相同数的第一个数
else l=mid+1;
}
return l;
}
int bin_search2( int k )
{
int l=0,r=n-1,mid;
while( l<=r )
{
mid=(l+r)>>1;
if( a[mid]<=k )l=mid+1; //尽量往后移动,取到相同数的最后一个数
else r=mid-1;
}
return r;
}
int main( )
{
int m,h,i,level,ans;
while( scanf("%d",&n) != EOF )
{
for( i=0; i<n; i++ )
scanf("%d",&a[i]);
sort( a, a+n );
scanf("%d",&m);
for( i=0; i<m; i++ )
{
scanf("%d%d",&h,&level);
switch( level )
{
case 1: ans=bin_search2( 100-h )-bin_search1( 0-h )+1;break;
case 2: ans=bin_search2( 500-h )-bin_search1( 101-h )+1;break;
case 3: ans=bin_search2( 2000-h )-bin_search1( 501-h )+1;break;
case 4: ans=bin_search2( 10000-h )-bin_search1( 2001-h )+1;break;
case 5: ans=bin_search2( 50000-h )-bin_search1( 10001-h )+1;break;
case 6: ans=bin_search2( 200000-h )-bin_search1( 50001-h )+1;break;
case 7: ans=bin_search2( INF-h )-bin_search1( 200001-h )+1;break;
}
printf("%d\n",ans);
}
}
return 0;
}
|
9d9f7e8dbe50ad580909557109345dca98babc89
|
b63a6de87d4dbf3383fc2d95e2f80292321c1a0d
|
/Midterm/problem3.cpp
|
a993593a61b143bd16e284790b466c36481eec20
|
[] |
no_license
|
produdez/C-Fundamental-182
|
bd23d628f484347d7e152ddad3694d486203a731
|
d06bc64f56a71d7bd4448cf9294e3ce81dd8fbce
|
refs/heads/master
| 2023-01-12T10:42:55.760652
| 2020-11-17T03:18:41
| 2020-11-17T03:18:41
| 313,491,316
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 443
|
cpp
|
problem3.cpp
|
#include <iostream>
#include<iomanip>
#include<string>
using namespace std;
main()
{
int N;
cout<<"How big?\n";
cin>>N;
for (int i=0; i<N;i++)
{
cout<<setfill(' ')<<setw(N-i)<<'*';
if(i==0)
{
//DO NOTHING
} else if (i==(N/2))
{
cout<<setfill('*')<<setw(2*i+1);
} else
{
cout<<setfill(' ')<<setw(2*i)<<'*';
}
cout<<'\n';
}
}
|
6985c7ad3480e17717952d233e5f042ac82fd552
|
9445b5c08be0b6c5e874814d08f3d49207aca1d5
|
/main.cpp
|
b3c69b674b386ab50d517e9bb0953a79f6e221da
|
[] |
no_license
|
vient/Brewery
|
05919441c33062f6e3a8ef25eb04ac68877cf4f9
|
03a71f9eca5d59d73d92e0556eafcb24899974a1
|
refs/heads/master
| 2021-01-10T02:00:35.156893
| 2016-04-07T14:39:33
| 2016-04-07T14:39:33
| 55,300,732
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 459
|
cpp
|
main.cpp
|
#include <iostream>
#include <sal.h>
// stupid throw()... Nobody really need them
#pragma warning( disable : 4290 )
#include "Brewery.h"
_Success_(return == EXIT_SUCCESS)
int main(
_In_ int argc,
_In_ char **argv,
_In_ char **envp)
{
auto& brewery = Brewery::Brewery::Instance();
try
{
brewery.interact();
}
catch (const std::exception& exc)
{
std::cerr << exc.what();
}
return EXIT_SUCCESS;
}
|
e5fee323bb6854c348b65c00765c3fe992624291
|
d9ef3a8b94d2e4bc44b1412e673ef78697082e75
|
/OnlineJudge/CodeForces/102001/L.cpp
|
8c413908bbdb5fb142353e448c95c7c69073cb08
|
[] |
no_license
|
tanhtm/Competitive-Programming
|
ee475c898d47041ea5d136227b5af37e2d61cb40
|
9d959be095e35c2a030b5a7196085cdeef396454
|
refs/heads/master
| 2021-06-11T02:31:10.174618
| 2021-03-25T15:18:58
| 2021-03-25T15:18:58
| 162,153,635
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 738
|
cpp
|
L.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
string s,k_;
string ok(long long int k) {
string r = "";
while(k != 0){
r+= k%2 + '0';
k/=2;
}
reverse(r.begin(), r.end());
return r;
}
int main(){
ll k;
string s,s_;
cin>>k>>s;
s_ = s;
sort(s.begin(),s.end());
if(s[0] != '1'){
s[0] = '1';
s.pop_back();
s.insert(s.begin()+1,'0');
}
k_ = ok(k);
int ans = 0;
while(s.size() > k_.size()){
s.pop_back();
ans++;
}
while(s.size() != k_.size()){
s.insert(s.begin(),'0');
}
if(s_.size() == k_.size()){
if(s_ > k_) cout<<1<<endl;
else cout<<0<<endl;
return 0;
}
//cout<<s<<" "<<k_<<endl;
if(k_ >= s) cout<<ans<<endl;
else{
cout<<ans+1<<endl;
}
//cout<<S<<endl;
return 0;
}
|
1edd9ee469f6ddb0d1ee8c02d399a2fb09eac9b7
|
b91a6e4aed84ce4d5a10ee07cd2124008b9260d9
|
/flat/page.h
|
26c4c6ad2dc553f9cd00473f08420c6ec30965ea
|
[] |
no_license
|
lczm/flat
|
e021ea035993511ce024148c8e8f125c788a79ba
|
0763c99f88bfa4cfc381182a71e54545a8642e05
|
refs/heads/master
| 2023-03-28T02:48:50.472931
| 2021-03-22T06:47:23
| 2021-03-22T06:47:23
| 350,236,737
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 493
|
h
|
page.h
|
#pragma once
#define WIN32_LEAN_AND_MEAN
#include "constants.h"
#include "graphics.h"
#include "input.h"
class Page
{
protected:
Graphics* graphics;
Input* input;
public:
Page();
virtual ~Page();
virtual void initialize(Graphics* graphics, Input* input);
virtual void start();
virtual void releaseAll();
virtual void resetAll();
virtual PageType update(float frameTime);
virtual void render();
Graphics* getGraphics() { return graphics; }
Input* getInput() { return input; }
};
|
7a51a254dc1f9e8af8e1bc3351e9b05836b236e9
|
c15d99db59d76496b58d7209cb01b8214a82532b
|
/operating_system/hm/hm1.cpp
|
cafe9f3d5ec5a9fc0bb30838c265d48d2588abeb
|
[] |
no_license
|
ShiinaOrez/C-CPP_IN_CCNU_CS
|
7d490a61e88ccd381e55b719eb52c375b745f8df
|
fbfc8c0262596af917730f19bac95850088c5fc5
|
refs/heads/master
| 2020-04-12T09:54:53.590349
| 2019-12-01T16:10:14
| 2019-12-01T16:10:14
| 162,412,824
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,215
|
cpp
|
hm1.cpp
|
// copyright: 2019-09-23 ShiinaOrez
#include <cstdio>
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
#include <algorithm>
#define max_works 1005
using namespace std;
struct MyTime {
int hour;
int mins;
bool operator < (const MyTime &right_time) const {
return hour < right_time.hour ? true : hour > right_time.hour ? false : mins < right_time.mins ? true : false;
}
bool operator == (const MyTime &right_time) const {
return hour == right_time.hour && mins == right_time.mins;
}
void operator - (const MyTime &right_time) {
int sub_hour = hour - right_time.hour;
int sub_mins = mins - right_time.mins;
if (sub_mins < 0) {
sub_mins += 60;
sub_hour -= 1;
} else if (sub_mins >= 60) {
sub_hour += (sub_mins/60);
sub_mins %= 60;
}
hour = sub_hour;
mins = sub_mins;
return;
}
};
struct Work {
int id;
MyTime entry_time;
int cost;
bool operator < (const Work &right_work) const {
return cost < right_work.cost;
}
};
struct WorkWithRatio {
Work work;
double ratio;
};
struct Info {
Work work;
MyTime start_time;
MyTime end_time;
};
struct MyTime resolve_string_to_time(char* from) {
int length = strlen(from);
int hour=0, mins=0, re=1;
mins += ((from[length-1]-'0') + (from[length-2]-'0')*10);
for (int i=0; i<=length-3; i++) {
hour += re * (from[i]-'0');
re *= 10;
}
return MyTime{
hour,
mins
};
}
void pre_print() {
cout << "[info]|Now please choose the type you want:" << endl;
cout << " |1. First Come First Serve." << endl;
cout << " |2. Shortest Job First." << endl;
cout << " |3. Highest Response Ratio Next." << endl;
cout << " |4. All Above." << endl;
return;
}
void print_excel(vector<Info> infos) {
cout << " ╭─────┬───────────┬──────┬───────────┬─────────┬─────────┬────────────────────────╮" << endl;
cout << " │ JOB │ EntryTime │ Cost │ StartTime │ EndTime │ RunTime │ TakesPowerTurnoverTime │" << endl;
// cout << " ╰─────┴───────────┴──────┴───────────┴─────────┴─────────┴────────────────────────╯" << endl;
float tot_runtime = 0, tot_wi_time = 0;
for (auto iter=infos.begin(); iter!=infos.end(); iter++) {
Info info = (*iter);
MyTime sub_time = info.end_time;
sub_time - info.work.entry_time;
tot_runtime += (sub_time.hour*60+sub_time.mins);
tot_wi_time += (float(sub_time.hour*60+sub_time.mins) / float(info.work.cost));
printf(" ├─────┼───────────┼──────┼───────────┼─────────┼─────────┼────────────────────────┤\n");
printf(" │ %3d │ [%02d:%02d] │ %4d │ [%02d:%02d] │ [%02d:%02d] │ %5d │ %8.4f │\n", \
info.work.id, \
info.work.entry_time.hour, info.work.entry_time.mins, \
info.work.cost, \
info.start_time.hour, info.start_time.mins, \
info.end_time.hour, info.end_time.mins, \
sub_time.hour*60+sub_time.mins, \
float(sub_time.hour*60+sub_time.mins) / float(info.work.cost));
}
printf(" ├─────┴───────────┴──────┴───────────┴─────────┼─────────┼────────────────────────┤\n");
printf(" │ T = %8.4f mins │ │ │\n", tot_runtime/infos.size());
printf(" │ W = %8.4f │ %5d │ %8.4f │\n", tot_wi_time/infos.size(), int(tot_runtime), tot_wi_time);
printf(" ╰──────────────────────────────────────────────┴─────────┴────────────────────────╯\n");
}
bool comp(const Work &w1, const Work &w2) {
return w1.cost < w2.cost;
}
bool compRatio(const WorkWithRatio &w1, const WorkWithRatio &w2) {
return w1.ratio > w2.ratio;
}
vector<Info> fcfs(queue<Work> works, MyTime start_time) {
MyTime mytime=start_time;
int run_time=0;
vector<Info> infos;
while(!works.empty()) {
Work work_now = works.front();
if (mytime < work_now.entry_time) {
mytime = work_now.entry_time;
}
printf("[time]| [%02d:%02d] Start new work: %d.\n", mytime.hour, mytime.mins, work_now.id);
Info info;
info.work = work_now;
info.start_time = mytime;
mytime.mins += work_now.cost;
mytime.hour += (mytime.mins/60);
mytime.mins %= 60;
info.end_time = mytime;
infos.push_back(info);
MyTime sub_time=mytime;
sub_time - work_now.entry_time;
run_time += (sub_time.hour*60 + sub_time.mins);
works.pop();
cout << "[log] | ..Done. Start next work." << endl;
}
cout << "[log] | ...Finished! ";
mytime - start_time;
printf("Running Cost: [%02d:%02d].\n", run_time/60, run_time%60);
return infos;
}
vector<Info> sjf(queue<Work> works, MyTime start_time) {
MyTime mytime=start_time;
vector<Work> work_cache;
int length = works.size(), run_time=0;
vector<Info> infos;
for (int i=0; i<length; i++) {
// load works
while(!works.empty() && (works.front().entry_time < mytime || works.front().entry_time == mytime)) {
work_cache.push_back(works.front());
works.pop();
}
if (work_cache.size() == 0 && !works.empty()) {
mytime = works.front().entry_time;
work_cache.push_back(works.front());
works.pop();
}
sort(work_cache.begin(), work_cache.end(), comp);
Work work_now = work_cache[0];
Info info;
info.work = work_now;
info.start_time = mytime;
printf("[time]| [%02d:%02d] Start new work: %d.\n", mytime.hour, mytime.mins, work_now.id);
mytime.mins += work_now.cost;
mytime.hour += (mytime.mins/60);
mytime.mins %= 60;
info.end_time = mytime;
infos.push_back(info);
MyTime sub_time=mytime;
sub_time - work_now.entry_time;
run_time += (sub_time.hour*60 + sub_time.mins);
work_cache.erase(work_cache.begin());
cout << "[log] | ..Done. Start next work." << endl;
}
cout << "[log] | ...Finished! ";
mytime - start_time;
printf("Running Cost: [%02d:%02d].\n", run_time/60, run_time%60);
return infos;
}
vector<Info> hrrn(queue<Work> works, MyTime start_time) {
MyTime mytime=start_time;
vector<Info> infos;
vector<WorkWithRatio> work_cache;
while(!works.empty()) {
work_cache.push_back(WorkWithRatio{works.front(), 1.0});
works.pop();
}
int length = work_cache.size(), run_time=0;
for (int i=0; i<length; i++) {
// fixed time
if (work_cache.size() == 0) {
mytime = works.front().entry_time;
}
// load works
while(!works.empty() && (works.front().entry_time < mytime || works.front().entry_time == mytime)) {
work_cache.push_back(WorkWithRatio{works.front(), 1.0});
works.pop();
}
for (auto iter=work_cache.begin(); iter!=work_cache.end(); iter++) {
MyTime copy_time=mytime;
copy_time - (*iter).work.entry_time;
(*iter).ratio = 1 + ((copy_time.hour*60 + copy_time.mins) / (*iter).work.cost);
}
sort(work_cache.begin(), work_cache.end(), compRatio);
Work work_now = work_cache[0].work;
Info info;
info.work = work_now;
info.start_time = mytime;
printf("[time]| [%02d:%02d] Start new work: %d.\n", mytime.hour, mytime.mins, work_now.id);
mytime.mins += work_now.cost;
mytime.hour += (mytime.mins/60);
mytime.mins %= 60;
info.end_time = mytime;
infos.push_back(info);
MyTime sub_time=mytime;
sub_time - work_now.entry_time;
run_time += (sub_time.hour*60 + sub_time.mins);
work_cache.erase(work_cache.begin());
cout << "[log] | ..Done. Start next work." << endl;
}
cout << "[log] | ...Finished! ";
mytime - start_time;
printf("Running Cost: [%02d:%02d].\n", run_time/60, run_time%60);
return infos;
}
int main() {
queue<Work> works;
int id_cache, cost_cache;
char entry_time_cache[5];
cout << "[****]|Welcome to my OS homework-1!" << endl;
cout << "[info]|Please input the meta data:" << endl;
cout << " |[work-id] [entry-time] [cost-time]" << endl;
// input the meta data to `works` as vector's element
while(1) {
cin >> id_cache;
if (id_cache == -1) {
cout << "[log] |Input Over." << endl;
break;
} else {
cin >> entry_time_cache >> cost_cache;
works.push(Work{
id_cache,
resolve_string_to_time(entry_time_cache),
cost_cache
});
}
}
pre_print();
int choice=0;
while(choice <= 0 || choice >= 5) {
cout << "[info]|Please Input: ";
cin >> choice;
}
cout << "[log] | ...OK, your choice is " << choice << endl;
vector<Info> result;
switch(choice) {
case 1: {
cout << "[log] |Frist Come First Serve Algorithm: Start." << endl;
result = fcfs(works, works.front().entry_time);
print_excel(result);
break;
}
case 2: {
cout << "[log] |Shortest Job First Algorithm: Start." << endl;
result = sjf(works, works.front().entry_time);
print_excel(result);
break;
}
case 3: {
cout << "[log] |Highest Response Ratio Next Algorithm: Start." << endl;
result = hrrn(works, works.front().entry_time);
print_excel(result);
break;
}
case 4: {
cout << "[log] |Frist Come First Serve Algorithm: Start." << endl;
result = fcfs(works, works.front().entry_time);
print_excel(result);
cout << "[log] |Shortest Job First Algorithm: Start." << endl;
result = sjf(works, works.front().entry_time);
print_excel(result);
cout << "[log] |Highest Response Ratio Next Algorithm: Start." << endl;
result = hrrn(works, works.front().entry_time);
print_excel(result);
}
}
cout << "[log] | ...Over, bye~" << endl;
return 0;
}
|
d410f951e3ff2b33b3cfe53e353c0582241a82d7
|
1bf6be8624fa8231c20b809154482647641328fe
|
/idbbondserver-midware/databusgateway/src/msg_bus_queue_callback.cpp
|
cdac91d99a7991e48a811b43bf1aab0fdbab81ff
|
[] |
no_license
|
iamtcby5188/work
|
d2bcf4d12f3d26eb9f92859ce9e6619651320d39
|
445e49977cf2b2739395f857466662d843a343ef
|
refs/heads/master
| 2020-03-11T06:16:49.339312
| 2018-04-18T06:31:42
| 2018-04-18T06:31:42
| 129,826,310
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,586
|
cpp
|
msg_bus_queue_callback.cpp
|
#include <log.h>
#include <msgbus/util.hpp>
#include <sdbus/util.hpp>
#include "databus_gateway_helper.h"
#include "msg_bus_queue_callback.h"
msg_bus_queue_callback::msg_bus_queue_callback (const std::string& name)
{
name_ = name;
type_ = msgbus::DeliverDirect;
}
msg_bus_queue_callback::~msg_bus_queue_callback ()
{
LOG4_INFO ("destruct msgbus queue callback.");
}
void msg_bus_queue_callback::messages (const msgbus::Message* msgs, int count)
{
for (int i = 0; i < count; ++i)
{
LOG4_TRACE ("received a direct message from msgbus(%s):\n%s.",
name_.c_str (),
msgbus::util::to_string (msgs[i]).c_str ());
send (msgs[i]);
}
}
/* MessageID's format: orignal ReplyTo + _DATABUS_ADDRESS_GATEWAY_ + original MessageID */
void msg_bus_queue_callback::send (msgbus::Message msg)
{
std::string address, message_id, replyto;
helper::retrieve_original_from_message_id (address, message_id,
replyto, msg.GetMessageID());
msg.SetMessageID (message_id);
msg.SetReplyTo (replyto);
sdbus::Message sdmsg;
helper::to_sdbus_message (sdmsg, msg);
sdbus::Connection* pcon = helper::get_sdbus_connection (address);
if (pcon != NULL)
{
if (pcon->Send (replyto, sdmsg))
{
LOG4_TRACE ("sent a direct message to sdbus (%s):\n%s.",
replyto.c_str (),
sdbus::util::to_string (sdmsg).c_str ());
}else
{
LOG4_WARN ("failed to sent a direct message to sdbus (%s).",
replyto.c_str ());
}
}else
{
LOG4_WARN ("can't find connection by %s and discard a sdbus message!",
address.c_str ());
}
}
|
f72bf4a448a80ca8af3cecf3c12e81ff77ce0eac
|
7bc185a9db78d453f4bcc637cb26465d8ad7f9e2
|
/src/raytracer.cpp
|
c43debefba3cad4f23abae044d1af34bf5b91a36
|
[] |
no_license
|
zhaoyan1117/RayTracer_PhotonMapping
|
6353b4277e0b9e5d45b61541ea4e4db614e57124
|
25da221816c8da6146b1806143c40fac3e93a89a
|
refs/heads/master
| 2021-01-01T03:40:48.184860
| 2016-04-18T03:23:57
| 2016-04-18T03:23:57
| 56,473,857
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 59,562
|
cpp
|
raytracer.cpp
|
#include <sstream>
#include <stdio.h>
#include <string>
#include <omp.h>
#include "RTtools.h"
#include "Photon.h"
#include "FreeImage.h"
using namespace std;
class Sampler {
public:
Point LU, LD, RU, RD;
Sample cur;
Point base;
float widthP, heightP;
Vector stepH, stepV;
Vector microStepH, microStepV;
float SPP; //Samples Per Pixel.
float step;
Sampler() {
if (debug) cout << "Zero-parameter constructor of Sampler is called." << endl;
}
float sampleNum(){
return widthP*heightP;
}
Sampler(Point lu, Point ld, Point ru, Point rd, float w, float h, float spp) {
LU = lu;
LD = ld;
RU = ru; RD = rd;
widthP = w;
heightP = h;
SPP = spp;
step = sqrt(SPP);
stepH = Vector::multiVS(Point::minusPoint(RU, LU), 1/widthP); //from left to right.
stepV = Vector::multiVS(Point::minusPoint(LU, LD), 1/heightP); //from down to up.
microStepH = Vector::multiVS(stepH, 1/(2*step));
microStepV = Vector::multiVS(stepV, 1/(2*step));
base = LD;
cur = Sample(0, 0);
}
bool getSample(Sample* sample, std::vector<Point> *points) {
if (cur.y == heightP) {
return false;
}
sample->x = cur.x; sample->y = cur.y;
Point start = Point::addVector(base,
Vector::addVector(
Vector::multiVS(stepH, cur.x),
Vector::multiVS(stepV, cur.y)
)
);
Point curPoint;
for (int i = 1; i < 2*step; i++) {
for (int j = 1; j < 2*step; j++) {
if (((i%2) != 0) and ((j%2) != 0)) {
curPoint = Point::addVector(start,
Vector::addVector(
Vector::multiVS(microStepH, (float) i/2),
Vector::multiVS(microStepV, (float) j/2)
)
);
// If SPP is not 1, jittering in both s and t directions.
if (SPP != 1) {
curPoint = Point::addVector(curPoint,
Vector::addVector(
Vector::multiVS(microStepH, generatRandom()),
Vector::multiVS(microStepV, generatRandom())
)
);
}
points->push_back(curPoint);
}
}
}
if (cur.x < widthP-1) {
++cur.x;
} else {
cur.x = 0;
++cur.y;
}
return true;
}
// Generate peudo-random numbers in [-1.0, 1.0].
float generatRandom() {
float r = (-0.2) + 0.4*(float)rand()/((float)RAND_MAX);
return r;
}
};
class Camera {
public:
Point pos;
float clip;
bool DOF;
Vector upD;
Vector viewD;
Vector diskD;
Camera() {
if (debug) cout << "Zero-parameter constructor of Camera is called." << endl;
}
Camera(Point p, float c, Vector upd, Vector viewd, Vector diskd, bool dof) {
pos = p; clip = c;
upD = upd; viewD = viewd; diskD = diskd;
DOF = dof;
}
void generateRay(Point& pixel, std::vector<Ray> *rays) {
if (not DOF) {
Ray result = Ray(pos, Point::minusPoint(pixel, pos), clip, std::numeric_limits<float>::infinity());
rays->push_back(result);
} else {
Ray results;
Point rp = randomPoint();
for (int i = 0; i < 16; i++) {
results = Ray(rp, Point::minusPoint(pixel, rp), clip, std::numeric_limits<float>::infinity());
rays->push_back(results);
}
}
}
// Use sqrt(r) so uniformly sample on a disk.
Point randomPoint() {
float randomRroot = sqrt(randomRadius());
float randomAng = randomAngle();
float x = pos.x + randomRroot*cos(randomAng)*upD.x + randomRroot*sin(randomAng)*diskD.x;
float y = pos.y + randomRroot*cos(randomAng)*upD.y + randomRroot*sin(randomAng)*diskD.y;
float z = pos.z + randomRroot*cos(randomAng)*upD.z + randomRroot*sin(randomAng)*diskD.z;
return Point(x, y, z);
}
float randomAngle() {
float a = 2.0*PI*(float)rand()/((float)RAND_MAX);
return a;
}
float randomRadius() {
float r = 0.1*(float)rand()/((float)RAND_MAX);
return r;
}
};
class Raytracer {
public:
Primitive* primitives;
std::vector<Light*> *lights;
Color *globalAm;
float (*attenuations)[3];
PhotonMap* pm;
PhotonMap* cm;
bool di;
bool ci;
bool ii;
Raytracer() {
if (debug) cout << "Zero-parameter constructor of Raytracer is called." << endl;
}
Raytracer(Primitive* p, std::vector<Light*> *l, Color* am) {
primitives = p; lights = l; globalAm = am; di = false; ci = false; ii = false;
}
//emit photon for each light source
void emitLightPhoton(){
float lightPower = 6000.0f;
float total = 200000;
pm = new PhotonMap(total);
cm = new PhotonMap(0.1*total);
WPhoton p;
float aver = total/(lights->size());
for (std::vector<Light*>::size_type i = 0; i != lights->size(); i++) {
#pragma omp parallel
{
while(pm->get_stored_photons() < aver){
p = lights->at(i)->emitPhoton();
firstPhotonTrace(p, 5);
}
}
}
pm->scale_photon_power(lightPower/total);
pm->balance();
cm->scale_photon_power(lightPower/total);
cm->balance();
}
//first trace of photon that determines whether the photon should be stored in caustic map
void firstPhotonTrace(WPhoton& p, int depth){
if (depth <= 0) {
return;
}
float tHit;
Intersection in;
BRDF brdf;
Ray ray = Ray(p.pos, p.dir, 0.00001, std::numeric_limits<float>::infinity());
if (!primitives->intersect(ray, &tHit, &in)) {
return;
}
in.primitive->getBRDF(in.lg, &brdf);
if (Vector::dotMul(p.dir, in.lg.normal) > 0 && !(brdf.kt>0)){
in.lg.normal = Vector::negate(in.lg.normal);
}
//refraction
if (brdf.kt > 0) {
LocalGeo local = in.lg;
Vector rayDir = Vector::normalizeV(ray.dir);
float n;
float cosI = -1*Vector::dotMul(rayDir, local.normal);
if (cosI > 0){
n = AIR/brdf.rf;
float cosT = sqrt(1 - sqr(n)*(1-sqr(cosI)));
if (cosT >= 0.0){
Vector refractDir = Vector::addVector(Vector::multiVS(rayDir, n), Vector::multiVS(local.normal, (n*cosI - cosT)));
WPhoton np = WPhoton();
np.color = Color::multiplyC(p.color, brdf.kt);
np.pos = in.lg.pos;
np.dir = refractDir;
photonTrace(np, depth, true);
}
}else{
n = brdf.rf/AIR;
float cosT = sqrt(1 - sqr(n)*(1-sqr(cosI)));
if (cosT >= 0.0){
Vector refractDir = Vector::addVector(Vector::multiVS(rayDir, n), Vector::multiVS(Vector::negate(local.normal), (-n*cosI - cosT)));
WPhoton np = WPhoton();
np.color = Color::multiplyC(p.color, brdf.kt);
np.pos = in.lg.pos;
np.dir = refractDir;
photonTrace(np, depth, true);
}
}
}else{
float pr = max(max(brdf.kd.r + brdf.kr.r, brdf.kd.g + brdf.kr.g), brdf.kd.b + brdf.kr.b);
float pd = pr*(brdf.kd.r + brdf.kd.g + brdf.kd.b)/(brdf.kd.r + brdf.kd.g + brdf.kd.b + brdf.kr.r + brdf.kr.g + brdf.kr.b);
float ran = ((float)rand()/(RAND_MAX));
//diffuse
if (ran < pd){
float Power[3]; Power[0] = p.color.r; Power[1] = p.color.g; Power[2] = p.color.b;
float Pos[3]; Pos[0] = in.lg.pos.x; Pos[1] = in.lg.pos.y; Pos[2] = in.lg.pos.z;
float Dir[3]; Dir[0] = p.dir.x; Dir[1] = p.dir.y; Dir[2] = p.dir.z;
#pragma omp critical
{
pm->store(Power, Pos, Dir);
}
Vector nextDir;
do{
nextDir.setValues(((float)rand()/(RAND_MAX))-0.5, ((float)rand()/(RAND_MAX))-0.5, ((float)rand()/(RAND_MAX))-0.5);
nextDir.normalize();
} while(((float)rand()/(RAND_MAX)) >= Vector::dotMul(nextDir, in.lg.normal));
WPhoton np = WPhoton(in.lg.pos, nextDir, Color::multiplyS(Color::multiplyC(p.color, brdf.kd), 1.0/pd));
photonTrace(np, depth-1, false);
//specular
}else if (ran < pr){
WPhoton np = WPhoton();
np.color = Color::multiplyS(Color::multiplyC(p.color, brdf.kr), 1.0/(pr-pd));
np.pos = in.lg.pos;
Ray reflectRay = createReflectRay(in.lg, ray);
np.dir = reflectRay.dir;
photonTrace(np, depth-1, false);
}else {
return;
}
}
}
void photonTrace(WPhoton& p, int depth, bool caustic){
if (depth <= 0) {
return;
}
float tHit;
Intersection in;
BRDF brdf;
Ray ray = Ray(p.pos, p.dir, 0.00001, std::numeric_limits<float>::infinity());
if (!primitives->intersect(ray, &tHit, &in)) {
return;
}
in.primitive->getBRDF(in.lg, &brdf);
if (Vector::dotMul(p.dir, in.lg.normal) > 0 && !(brdf.kt>0)){
in.lg.normal = Vector::negate(in.lg.normal);
}
if (brdf.kt > 0) {
LocalGeo local = in.lg;
Vector rayDir = Vector::normalizeV(ray.dir);
float n;
float cosI = -1*Vector::dotMul(rayDir, local.normal);
if (cosI > 0){
n = AIR/brdf.rf;
float cosT = sqrt(1 - sqr(n)*(1-sqr(cosI)));
if (cosT >= 0.0){
Vector refractDir = Vector::addVector(Vector::multiVS(rayDir, n), Vector::multiVS(local.normal, (n*cosI - cosT)));
WPhoton np = WPhoton();
np.color = Color::multiplyC(p.color, brdf.kt);
np.pos = in.lg.pos;
np.dir = refractDir;
photonTrace(np, depth, caustic);
}
}else{
n = brdf.rf/AIR;
float cosT = sqrt(1 - sqr(n)*(1-sqr(cosI)));
if (cosT >= 0.0){
Vector refractDir = Vector::addVector(Vector::multiVS(rayDir, n), Vector::multiVS(Vector::negate(local.normal), (-n*cosI - cosT)));
WPhoton np = WPhoton();
np.color = Color::multiplyC(p.color, brdf.kt);
np.pos = in.lg.pos;
np.dir = refractDir;
photonTrace(np, depth, caustic);
}
}
}else{
float pr = max(max(brdf.kd.r + brdf.kr.r, brdf.kd.g + brdf.kr.g), brdf.kd.b + brdf.kr.b);
float pd = pr*(brdf.kd.r + brdf.kd.g + brdf.kd.b)/(brdf.kd.r + brdf.kd.g + brdf.kd.b + brdf.kr.r + brdf.kr.g + brdf.kr.b);
float ran = ((float)rand()/(RAND_MAX));
if (ran < pd){
float Power[3]; Power[0] = p.color.r; Power[1] = p.color.g; Power[2] = p.color.b;
float Pos[3]; Pos[0] = in.lg.pos.x; Pos[1] = in.lg.pos.y; Pos[2] = in.lg.pos.z;
float Dir[3]; Dir[0] = p.dir.x; Dir[1] = p.dir.y; Dir[2] = p.dir.z;
#pragma omp critical
{
pm->store(Power, Pos, Dir);
}
if (caustic){
cm->store(Power, Pos, Dir);
}
Vector nextDir;
do{
nextDir.setValues(((float)rand()/(RAND_MAX))-0.5, ((float)rand()/(RAND_MAX))-0.5, ((float)rand()/(RAND_MAX))-0.5);
nextDir.normalize();
} while(((float)rand()/(RAND_MAX)) >= Vector::dotMul(nextDir, in.lg.normal));
WPhoton np = WPhoton(in.lg.pos, nextDir, Color::multiplyS(Color::multiplyC(p.color, brdf.kd), 1.0/pd));
photonTrace(np, depth-1, false);
}else if (ran < pr){
WPhoton np = WPhoton();
np.color = Color::multiplyS(Color::multiplyC(p.color, brdf.kr), 1.0/(pr-pd));
np.pos = in.lg.pos;
Ray reflectRay = createReflectRay(in.lg, ray);
np.dir = reflectRay.dir;
photonTrace(np, depth-1, false);
}else {
return;
}
}
}
//find the irradiance estimate of the surface hit by the ray
Color irradianceTrace(Ray& ray, bool first){
float tH;
Intersection is;
BRDF brdf;
if (primitives->intersect(ray, &tH, &is)) {
is.primitive->getBRDF(is.lg, &brdf);
if (Vector::dotMul(ray.dir, is.lg.normal) > 0 && !(brdf.kt>0)){
is.lg.normal = Vector::negate(is.lg.normal);
}
if (tH<0.1&&first){
Vector tDir = Vector();
Ray r;
Color irColor = Color();
int numFinalGather = 50;
float totalWeight = 0;
float weight = 0;
for(int z=0; z<numFinalGather; z++){
do {
tDir.setValues(((float)rand()/(RAND_MAX))-0.5, ((float)rand()/(RAND_MAX))-0.5, ((float)rand()/(RAND_MAX))-0.5);
tDir.normalize();
} while(0 >= Vector::dotMul(is.lg.normal, tDir));
r = Ray(is.lg.pos, tDir, 0.01, std::numeric_limits<float>::infinity());
weight = Vector::dotMul(is.lg.normal, tDir);
irColor = Color::add(irColor, Color::multiplyS(irradianceTrace(r, false), weight));
totalWeight += weight;
}
return Color::multiplyC(brdf.kd, Color::multiplyS(irColor, 1.0/totalWeight));
}else {
if (brdf.kr>0.9) {
Ray reflectRay = createReflectRay(is.lg, ray);
return irradianceTrace(reflectRay, first);
} else if (brdf.kt > 0) {
LocalGeo local = is.lg;
Vector rayDir = Vector::normalizeV(ray.dir);
float n;
float cosI = -1*Vector::dotMul(rayDir, local.normal);
if (cosI > 0){
n = AIR/brdf.rf;
float cosT = sqrt(1 - sqr(n)*(1-sqr(cosI)));
if (cosT >= 0.0){
Vector refractDir = Vector::addVector(Vector::multiVS(rayDir, n), Vector::multiVS(local.normal, (n*cosI - cosT)));
Ray refractRay = Ray(local.pos, refractDir, 0.00001, std::numeric_limits<float>::infinity());
return irradianceTrace(refractRay, first);
}
}else{
n = brdf.rf/AIR;
float cosT = sqrt(1 - sqr(n)*(1-sqr(cosI)));
if (cosT >= 0.0){
Vector refractDir = Vector::addVector(Vector::multiVS(rayDir, n), Vector::multiVS(Vector::negate(local.normal), (-n*cosI - cosT)));
Ray refractRay = Ray(local.pos, refractDir, 0.00001, std::numeric_limits<float>::infinity());
return irradianceTrace(refractRay, first);
}
}
} else {
float irad[3];
float pos[3];
float normal[3];
pos[0] = is.lg.pos.x; pos[1] = is.lg.pos.y; pos[2] = is.lg.pos.z;
normal[0] = is.lg.normal.x; normal[1] = is.lg.normal.y; normal[2] = is.lg.normal.z;
pm->irradiance_estimate(irad, pos, normal, 0.5, 300);
return Color::multiplyC(Color(irad[0], irad[1], irad[2]), brdf.kd);
}
}
} else{
return Color();
}
}
void trace(Ray& ray, int depth, Color* color) {
if (debug) cout << "trace is called with depth: " << depth << endl;
float tHit;
Intersection in;
BRDF brdf;
if (depth < 0) {
color->setValues(0.0, 0.0, 0.0);
return;
}
if (!primitives->intersect(ray, &tHit, &in)) {
if (debug) cout << "In trace, not intersect!" << endl;
color->setValues(0.0, 0.0, 0.0);
return;
}
// Calculate self color including self-emission.
Color selfColor;
in.primitive->getBRDF(in.lg, &brdf);
if (Vector::dotMul(ray.dir, in.lg.normal) > 0 && !(brdf.kt>0)){
in.lg.normal = Vector::negate(in.lg.normal);
}
selfColor = Color::add(*globalAm, brdf.em);
if (debug) cout << "In trace, globalAm is: " << globalAm->r << " " << globalAm->g << " " << globalAm->b << endl;
if (debug) cout << "In trace, selfColor before lights is: " << selfColor.r << " " << selfColor.g << " " << selfColor.b << endl;
*color = brdf.em;
// Calculate color from light.
Ray lray;
float irad[3];
float pos[3]; // surface position
float normal[3]; // surface normal at pos
float max_dist; // max distance to look for photons
int nphotons; // number of photons to use
if (ci){
pos[0] = in.lg.pos.x; pos[1] = in.lg.pos.y; pos[2] = in.lg.pos.z;
normal[0] = in.lg.normal.x; normal[1] = in.lg.normal.y; normal[2] = in.lg.normal.z;
max_dist=1;
nphotons=200;
cm->irradiance_estimate(irad, pos, normal, max_dist, nphotons);
*color = Color::add(*color, Color::multiplyC(Color(irad[0], irad[1], irad[2]), brdf.kd));
}
if (ii){
Vector tDir = Vector();
Ray r;
Color irColor = Color();
int numFinalGather = 50;
float totalWeight = 0;
float weight = 0;
Ray reflectR = createReflectRay(in.lg, ray);
for(int z=0; z<numFinalGather; z++){
do {
tDir.setValues(((float)rand()/(RAND_MAX))-0.5, ((float)rand()/(RAND_MAX))-0.5, ((float)rand()/(RAND_MAX))-0.5);
tDir.normalize();
} while(0 >= Vector::dotMul(in.lg.normal, tDir));
r = Ray(in.lg.pos, tDir, 0.01, std::numeric_limits<float>::infinity());
weight = Vector::dotMul(in.lg.normal, tDir);
irColor = Color::add(irColor, Color::multiplyS(irradianceTrace(r, true), weight));
totalWeight += weight;
}
*color = Color::add(*color, Color::multiplyC(brdf.kd, Color::multiplyS(irColor, 1.0/totalWeight)));
}
if (di){
int shadowSamples = 50;
Color lcolor;
float dist;
float falloff;
for (std::vector<Light*>::size_type i = 0; i != lights->size(); i++) {
if (lights->at(i)->type() == 2){
Color tempColor = Color();
int count = 0;
while(count < shadowSamples){
lights->at(i)->generateLightRay(in.lg, lray, lcolor);
if (!primitives->intersectP(lray)) {
dist = lray.dir.length();
// falloff = 1/((*attenuations)[0] + (*attenuations)[1]*dist + (*attenuations)[2]*sqr(dist));
tempColor = Color::add(tempColor, Color::multiplyS(shading(in.lg, brdf, lray, lcolor,\
ray.pos), 1));
// tempColor = Color::add(tempColor, shading(in.lg, brdf, lray, lcolor, ray.pos));
}
count++;
}
selfColor = Color::add(selfColor, Color::multiplyS(tempColor, 1.0/shadowSamples));
}else{
lights->at(i)->generateLightRay(in.lg, lray, lcolor);
if (!primitives->intersectP(lray)) {
if (lights->at(i)->type() == 1) {
selfColor = Color::add(selfColor, shading(in.lg, brdf, lray, lcolor, ray.pos));
} else {
Point lsource = lights->at(i)->getSource();
dist = Point::minusPoint(in.lg.pos, lsource).length();
Color shade = shading(in.lg, brdf, lray, lcolor, ray.pos);
falloff = 1/((*attenuations)[0] + (*attenuations)[1]*dist + (*attenuations)[2]*sqr(dist));
selfColor = Color::add(selfColor, Color::multiplyS(shade, falloff));
}
}
}
}
*color = Color::add(*color, Color::multiplyC(selfColor, Color(1.0-brdf.kt.r, 1.0-brdf.kt.g, 1.0-brdf.kt.b)));
}
// // Handle mirror reflection.
if (brdf.kr > 0) {
if (brdf.glossy == 0){
if (debug) cout << "Start handling mirror reflection." << endl;
Color tempColor;
Ray reflectRay = createReflectRay(in.lg, ray);
// Make a recursive call to trace the reflected ray.
if (debug) cout << "Reflected ray is created, point to: " << reflectRay.dir.x << " " << reflectRay.dir.y << " " << reflectRay.dir.z << endl;
trace(reflectRay, depth-1, &tempColor);
if (debug) cout << "Reflection color is: " << tempColor.r << " " << tempColor.g << " " << tempColor.b << endl;
*color = Color::add(*color, Color::multiplyC(tempColor, brdf.kr));
} else{
int sam = 5;
float di = (sam-1)/2.0;
float sc = 2.0*brdf.glossy/sam;
Ray reflectRay = createReflectRay(in.lg, ray);
Vector vecX = Vector::multiVS(Vector::normalizeV(Vector::crossMul(ray.dir, reflectRay.dir)), sc*reflectRay.dir.length());
Vector vecY = Vector::multiVS(Vector::normalizeV(Vector::crossMul(vecX, reflectRay.dir)), sc*reflectRay.dir.length());
Vector v;
Ray r;
Color tempColor;
Color stepColor;
for (int x = 0; x < sam; x++){
for (int y = 0; y < sam; y++){
v = Vector::addVector(reflectRay.dir, Vector::multiVS(vecX, x-di));
v = Vector::addVector(v, Vector::multiVS(vecY, y-di));
r = Ray(in.lg.pos, v, 0.00001, std::numeric_limits<float>::infinity());
trace(r, depth-1, &stepColor);
tempColor = Color::add(tempColor, stepColor);
}
}
tempColor = Color::multiplyS(tempColor, 1.0/(sam*sam));
*color = Color::add(*color, Color::multiplyC(tempColor, brdf.kr));
}
}
// Handle refraction.
if (brdf.kt > 0) {
LocalGeo local = in.lg;
Color refractColor;
Vector rayDir = Vector::normalizeV(ray.dir);
float n;
float cosI = -1*Vector::dotMul(rayDir, local.normal);
if (cosI > 0){
n = AIR/brdf.rf;
float cosT = sqrt(1 - sqr(n)*(1-sqr(cosI)));
if (cosT >= 0.0){
Vector refractDir = Vector::addVector(Vector::multiVS(rayDir, n), Vector::multiVS(local.normal, (n*cosI - cosT)));
Ray refractRay = Ray(local.pos, refractDir, 0.00001, std::numeric_limits<float>::infinity());
trace(refractRay, depth-1, &refractColor);
*color = Color::add(*color, Color::multiplyC(refractColor, brdf.kt));
}
}else{
n = brdf.rf/AIR;
float cosT = sqrt(1 - sqr(n)*(1-sqr(cosI)));
if (cosT >= 0.0){
Vector refractDir = Vector::addVector(Vector::multiVS(rayDir, n), Vector::multiVS(Vector::negate(local.normal), (-n*cosI - cosT)));
Ray refractRay = Ray(local.pos, refractDir, 0.00001, std::numeric_limits<float>::infinity());
trace(refractRay, depth-1, &refractColor);
*color = Color::add(*color, Color::multiplyC(refractColor, brdf.kt));
}
}
}
}
Color shading (LocalGeo& lg, BRDF& brdf, Ray& lray, Color& lcolor, Point& eye) {
return Color::add(calDiffuse(brdf.kd, lcolor, lg.normal, lray.dir),
calSpecular(brdf.ks, lcolor, brdf.shininess, lg, lray.dir, eye));
}
Color calDiffuse (Color& kd, Color& lcolor, Vector& normal, Vector& ldir) {
float c = Vector::dotMul(Vector::normalizeV(ldir), normal);
if (debug) cout << "In calDiffuse, c is: " << c << endl;
if (c < 0){
return Color();
}
else{
return Color::multiplyS( Color::multiplyC(kd, lcolor), c );
}
}
Color calSpecular (Color& ks, Color& lcolor, float& s, LocalGeo& lg, Vector& ldir, Point& eye) {
Vector norLdir = Vector::normalizeV(ldir);
Vector reflect = Vector::addVector( Vector::negate(norLdir), Vector::multiVS( lg.normal , 2.0 * Vector::dotMul(norLdir, lg.normal) ) );
Vector view = Vector::normalizeV(Point::minusPoint( eye, lg.pos ));
float c = Vector::dotMul (reflect, view);
if (debug) cout << "In calSpecular, c is: " << c << endl;
if (c < 0){
return Color();
}
else{
return Color::multiplyS( Color::multiplyC (ks, lcolor), pow(c, s) );
}
}
Ray createReflectRay (LocalGeo& local, Ray& originRay) {
Vector norLdir = Vector::normalizeV(originRay.dir);
Vector reflect = Vector::addVector( norLdir, Vector::multiVS( local.normal , 2.0 * Vector::dotMul(Vector::negate(norLdir), local.normal) ) );
return Ray(local.pos, reflect, 0.00001, std::numeric_limits<float>::infinity());
}
Ray createGlossyRay (LocalGeo& local, Ray& originRay, float gl) {
Vector norLdir = Vector::normalizeV(originRay.dir);
Vector reflect = Vector::addVector( norLdir, Vector::multiVS( local.normal , 2.0 * Vector::dotMul(Vector::negate(norLdir), local.normal) ) );
reflect = Vector::normalizeV(reflect);
reflect = Vector::addVector(Vector::normalizeV(reflect), Vector::multiVS(Vector(((float)rand()/(RAND_MAX))-0.5,\
((float)rand()/(RAND_MAX))-0.5, ((float)rand()/(RAND_MAX))-0.5), 2*gl));
return Ray(local.pos, reflect, 0.00001, std::numeric_limits<float>::infinity());
}
};
class Film {
public:
int widthP, heightP;
std::string imageName;
Color** map;
Film() {
if (debug) cout << "Zero-parameter constructor of Film is called!" << endl;
}
Film(int w, int h, std::string name) {
widthP = w;
heightP = h;
map = new Color*[widthP];
for (int i = 0; i < widthP; ++i){
map[i] = new Color[heightP];
}
imageName = name;
}
void commit(Sample& sample, Color& color) {
map[sample.x][sample.y].setValues(color.r, color.g, color.b);
if (debug) {
cout << "In commit, color: " << color.r << " " << color.g << " " << color.b << endl;
}
}
void writeImage() {
FreeImage_Initialise ();
FIBITMAP* bitmap = FreeImage_Allocate(widthP, heightP, 24);
RGBQUAD color;
if (!bitmap){
cout << "Cannot allocate images!" << endl;
exit(1);
}
//Draws a gradient from blue to green:
for (int i=0; i<widthP; i++) {
for (int j=0; j<heightP; j++) {
#ifdef OSX
(map[i][j].r <= 1.0) ? (color.rgbBlue = map[i][j].r*255) : (color.rgbBlue = 255);
(map[i][j].g <= 1.0) ? (color.rgbGreen = map[i][j].g*255) : (color.rgbGreen = 255);
(map[i][j].b <= 1.0) ? (color.rgbRed = map[i][j].b*255) : (color.rgbRed = 255);
#else
(map[i][j].r <= 1.0) ? (color.rgbRed = map[i][j].r*255) : (color.rgbRed = 255);
(map[i][j].g <= 1.0) ? (color.rgbGreen = map[i][j].g*255) : (color.rgbGreen = 255);
(map[i][j].b <= 1.0) ? (color.rgbBlue = map[i][j].b*255) : (color.rgbBlue = 255);
#endif
FreeImage_SetPixelColor(bitmap,i,j,&color);
}
}
const char* name = imageName.c_str();
if (FreeImage_Save(FIF_PNG, bitmap, name, 0)) {
cout << "Image successfully saved!" << endl;
}
FreeImage_DeInitialise (); //Cleanup!
}
};
class Scene {
public:
// Image information.
Point LU, LD, RU, RD;
float widthP, heightP;
// Camera information.
Camera camera;
// Sampler.
Sampler sampler;
// Film.
Film film;
// Scene name.
std::string sceneName;
// Raytracer.
Raytracer raytracer;
int depth;
int numofPoints;
Scene(){
if (debug) cout << "Zero-parameter constructor of Scene is called." << endl;
}
Scene(std::string name) {
sceneName = name;
}
void render() {
Sample sample;
std::vector<Point> points;
Color color;
Color stepColor;
std::vector<Ray> rays;
int total = widthP * heightP;
int percent = total/100;
int cur = 0;
int per = 0;
// Build AABB tree.
cout << "Start building AABB trees." << endl;
raytracer.primitives->setAABB();
cout << "AABB tree has been constructed. Start rendering now." << endl;
if (raytracer.ci||raytracer.ii){
raytracer.emitLightPhoton();
cout << "pm: " << raytracer.pm->get_stored_photons() << "\n";
cout << "cm: " << raytracer.cm->get_stored_photons() << "\n";
}
int numofRays;
std::vector<Point>::size_type i;
std::vector<Ray>::size_type j;
int sn = sampler.sampleNum();
cout << "Maximum thread number is " << omp_get_max_threads() << endl;
// For some weird reason, adding this pragma will cause compile error on mac.
#ifndef OSX
#pragma omp parallel for private(i, j, stepColor, color, rays, numofRays, points, sample)
#endif
for (int x = 0; x < sn; x++){
#pragma omp critical
{
sampler.getSample(&sample, &points);
}
for(i = 0; i != points.size(); i++) {
camera.generateRay(points[i], &rays);
for(j = 0; j != rays.size(); j++) {
raytracer.trace(rays[j], depth, &stepColor);
color = Color::add(color, stepColor);
}
numofRays = rays.size();
rays.clear();
}
// Average all the samples.
color = Color::multiplyS(color, 1.0/(numofPoints*numofRays));
#pragma omp critical
{
film.commit(sample, color);
}
// Reset color to 0 for next sample and clear points buffer and ray buffer.
color.setValues(0.0, 0.0, 0.0);
points.clear();
if (debug) cout << "~~~~~~~~~~~~~~~~~~~~~~~DONE~~~~~~~~~~~~~~~~~~~~~~" << endl;
#pragma omp critical
{
cur++;
if (cur > percent) {
// cout << omp_get_thread_num() << endl;
per++;
cur = 0;
cout << per << " percentage done......." << endl;
}
}
}
cout << "100 percentage done......." << endl;
film.writeImage();
}
};
void runScene(std::string file, std::vector<std::string> objFiles) {
//store variables and set stuff at the end.
Scene scene = Scene("output.png");
scene.depth = 5;
int width, height;
float samplesPP = 1; // Default value of samples per pixel.
float clip = 0.0; // Default clipping plane.
float focalDist = 1.0; // Default focal distance.
std::vector<Primitive*> p;
Primitive* prims = new AggregatePrimitive(&p);
std::vector<Light*> li;
Color* globalAm = new Color();
float att[3] = {1, 0, 0};
scene.raytracer = Raytracer(prims, &li, globalAm);
scene.raytracer.attenuations = &att;
scene.raytracer.di = true;
int vI = 0, vnI = 0;
Vector *vertices, *vertexNorm;
std::vector<Matrix*> matrixStack;
Material* m = new Material();
std::ifstream inpfile(file.c_str());
if(!inpfile.is_open()) {
std::cout << "Unable to open file" << std::endl;
exit(0);
} else {
std::string line;
while(inpfile.good()) {
std::vector<std::string> splitline;
std::string buf;
std::getline(inpfile,line);
std::stringstream ss(line);
while (ss >> buf) {
splitline.push_back(buf);
}
//Ignore blank lines
if(splitline.size() == 0) {
continue;
}
//Ignore comments
if(splitline[0][0] == '#') {
continue;
}
//Valid commands:
//size width height
// must be first command of file, controls image size
else if(!splitline[0].compare("size")) {
width = atoi(splitline[1].c_str());
height = atoi(splitline[2].c_str());
scene.widthP = width;
scene.heightP = height;
}
//maxdepth depth
// max # of bounces for ray (default 5)
else if(!splitline[0].compare("maxdepth")) {
scene.depth = atoi(splitline[1].c_str());
}
//output filename
// output file to write image to
else if(!splitline[0].compare("output")) {
scene.sceneName = splitline[1];
scene.film.imageName = scene.sceneName;
}
//Set samples per pixel vale.
else if(!splitline[0].compare("SPP")) {
samplesPP = atof(splitline[1].c_str());
scene.numofPoints = samplesPP;
scene.sampler.SPP = samplesPP;
scene.sampler.step = sqrt(scene.sampler.SPP);
if (samplesPP != 1) cout << "Using DRT with samples per pixel of " << samplesPP << "." << endl;
}
//camera lookfromx lookfromy lookfromz lookatx lookaty lookatz upx upy upz fov
// specifies the camera in the standard way, as in homework 2.
else if(!splitline[0].compare("camera")) {
Point eye = Point(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
Point lookat = Point(atof(splitline[4].c_str()), atof(splitline[5].c_str()), atof(splitline[6].c_str()));
Vector upDir = Vector::normalizeV(Vector(atof(splitline[7].c_str()), atof(splitline[8].c_str()), atof(splitline[9].c_str())));
Vector viewDir = Point::minusPoint(lookat, eye);
if (splitline.size() > 11) focalDist = atof(splitline[11].c_str());
if (splitline.size() > 12) clip = atof(splitline[12].c_str());
bool dof = false;
if (focalDist != 1.0) {
dof = true;
cout << "Initiating depth of field with focal distance " << focalDist << "." << endl;
}
if (clip != 0.0) {
cout << "Settign clipping plane to " << clip << "." << endl;
}
Point center = Point::addVector(eye, Vector::multiVS(Vector::normalizeV(viewDir), focalDist));
float fov = atof(splitline[10].c_str());
float vertL = focalDist * tan(toRadian(fov/2));
float horiL = vertL*width/height;
Vector hod = Vector::normalizeV(Vector::crossMul(viewDir, upDir));
Vector hV = Vector::multiVS(hod, horiL);
Vector upd = Vector::normalizeV(Vector::crossMul(hV, viewDir));
Vector vV = Vector::multiVS(upd, vertL);
scene.LU = Point::addVector(center, Vector::addVector(vV, Vector::negate(hV)));
scene.LD = Point::addVector(center, Vector::addVector(Vector::negate(vV), Vector::negate(hV)));
scene.RU = Point::addVector(center, Vector::addVector(vV, hV));
scene.RD = Point::addVector(center, Vector::addVector(Vector::negate(vV), hV));
//Camera(Point p, float c, Vector upd, Vector viewd, Vector diskd);
scene.camera = Camera(eye, clip, upd, Vector::normalizeV(viewDir), hod, dof);
scene.sampler = Sampler(scene.LU, scene.LD, scene.RU, scene.RD, scene.widthP, scene.heightP, samplesPP);
scene.numofPoints = samplesPP;
scene.film = Film(scene.widthP, scene.heightP, scene.sceneName);
}
//sphere x y z radius
// Defines a sphere with a given position and radius.
else if(!splitline[0].compare("sphere")) {
Matrix mat = Matrix(Matrix::IDENTITY);
Vector ori = Vector(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
Shape* s = new Sphere(ori, atof(splitline[4].c_str()));
for (std::vector<Matrix*>::size_type i = 0; i != matrixStack.size(); i++) {
mat = Matrix::multiply(mat, (*matrixStack[i]));
}
Primitive* sph = new GeometricPrimitive(Transformation(mat), Transformation(Matrix::invert(mat)), s, *m);
p.push_back (sph);
}
else if(!splitline[0].compare("di")) {
scene.raytracer.di = (strcmp (splitline[1].c_str(), "true") == 0);
}
else if(!splitline[0].compare("ci")) {
scene.raytracer.ci = (strcmp (splitline[1].c_str(), "true") == 0);
}
else if(!splitline[0].compare("ii")) {
scene.raytracer.ii = (strcmp (splitline[1].c_str(), "true") == 0);
}
//maxverts number
// Defines a maximum number of vertices for later triangle specifications.
// It must be set before vertices are defined.
else if(!splitline[0].compare("maxverts")) {
vertices = new Vector[atoi(splitline[1].c_str())];
}
//maxvertnorms number
// Defines a maximum number of vertices with normals for later specifications.
// It must be set before vertices with normals are defined.
else if(!splitline[0].compare("maxvertnorms")) {
vertexNorm = new Vector[2*atoi(splitline[1].c_str())];
}
//vertex x y z
// Defines a vertex at the given location.
// The vertex is put into a pile, starting to be numbered at 0.
else if(!splitline[0].compare("vertex")) {
vertices[vI] = Vector(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
vI++;
}
//vertexnormal x y z nx ny nz
// Similar to the above, but define a surface normal with each vertex.
// The vertex and vertexnormal set of vertices are completely independent
// (as are maxverts and maxvertnorms).
else if(!splitline[0].compare("vertexnormal")) {
vertexNorm[vnI] = Vector(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
vertexNorm[vnI+1] = Vector(atof(splitline[4].c_str()), atof(splitline[5].c_str()), atof(splitline[6].c_str()));
vnI += 2;
}
//tri v1 v2 v3
// Create a triangle out of the vertices involved (which have previously been specified with
// the vertex command). The vertices are assumed to be specified in counter-clockwise order. Your code
// should internally compute a face normal for this triangle.
else if(!splitline[0].compare("tri")) {
Matrix mat = Matrix(Matrix::IDENTITY);
Shape* t = new Triangle(vertices[atoi(splitline[1].c_str())], vertices[atoi(splitline[2].c_str())], vertices[atoi(splitline[3].c_str())]);
for (std::vector<Matrix*>::size_type i = 0; i != matrixStack.size(); i++) {
mat = Matrix::multiply(mat, (*matrixStack[i]));
}
Primitive* tri = new GeometricPrimitive(Transformation(mat), Transformation(Matrix::invert(mat)), t, *m);
p.push_back (tri);
}
//trinormal v1 v2 v3
// Same as above but for vertices specified with normals.
// In this case, each vertex has an associated normal,
// and when doing shading, you should interpolate the normals
// for intermediate points on the triangle.
else if(!splitline[0].compare("trinormal")) {
Matrix mat = Matrix(Matrix::IDENTITY);
int i1 = atoi(splitline[1].c_str()), i2 = atoi(splitline[2].c_str()), i3 = atoi(splitline[3].c_str());
Shape* t = new NormalTriangle(vertexNorm[2*i1], vertexNorm[2*i2], vertexNorm[2*i3], vertexNorm[2*i1+1],\
vertexNorm[2*i2+1], vertexNorm[2*i3+1]);
for (std::vector<Matrix*>::size_type i = 0; i != matrixStack.size(); i++) {
mat = Matrix::multiply(mat, (*matrixStack[i]));
}
Primitive* tri = new GeometricPrimitive(Transformation(mat), Transformation(Matrix::invert(mat)), t, *m);
p.push_back (tri);
}
//translate x y z
// A translation 3-vector
else if(!splitline[0].compare("translate")) {
Matrix thisM = Matrix(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()), Matrix::TRANSLATION);
*matrixStack.back() = Matrix::multiply(*matrixStack.back(), thisM);
}
//rotate x y z angle
// Rotate by angle (in degrees) about the given axis as in OpenGL.
else if(!splitline[0].compare("rotate")) {
Vector axis = Vector(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
axis.normalize();
Matrix thisM = Matrix(axis.x, axis.y, axis.z, toRadian(atof(splitline[4].c_str())), Matrix::ROTATION);
*matrixStack.back() = Matrix::multiply(*matrixStack.back(), thisM);
}
//scale x y z
// Scale by the corresponding amount in each axis (a non-uniform scaling).
else if(!splitline[0].compare("scale")) {
Matrix thisM = Matrix(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()), Matrix::SCALING);
*matrixStack.back() = Matrix::multiply(*matrixStack.back(), thisM);
}
//pushTransform
// Push the current modeling transform on the stack as in OpenGL.
// You might want to do pushTransform immediately after setting
// the camera to preserve the “identity” transformation.
else if(!splitline[0].compare("pushTransform")) {
matrixStack.push_back(new Matrix(Matrix::IDENTITY));
}
//popTransform
// Pop the current transform from the stack as in OpenGL.
// The sequence of popTransform and pushTransform can be used if
// desired before every primitive to reset the transformation
// (assuming the initial camera transformation is on the stack as
// discussed above).
else if(!splitline[0].compare("popTransform")) {
matrixStack.pop_back();
}
//directional x y z r g b
// The direction to the light source, and the color, as in OpenGL.
else if(!splitline[0].compare("directional")) {
Vector vec = Vector(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
Color col = Color(atof(splitline[4].c_str()), atof(splitline[5].c_str()), atof(splitline[6].c_str()));
Light* l = new DirectionalLight(vec, col);
li.push_back(l);
}
//point x y z r g b
// The location of a point source and the color, as in OpenGL.
else if(!splitline[0].compare("point")) {
Point poi = Point(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
Color col = Color(atof(splitline[4].c_str()), atof(splitline[5].c_str()), atof(splitline[6].c_str()));
Light* l = new PointLight(poi, col);
li.push_back(l);
}
else if(!splitline[0].compare("square")) {
Point poi1 = Point(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
Point poi2 = Point(atof(splitline[4].c_str()), atof(splitline[5].c_str()), atof(splitline[6].c_str()));
Point poi3 = Point(atof(splitline[7].c_str()), atof(splitline[8].c_str()), atof(splitline[9].c_str()));
Vector vec = Vector(atof(splitline[10].c_str()), atof(splitline[11].c_str()), atof(splitline[12].c_str()));
Color col = Color(atof(splitline[13].c_str()), atof(splitline[14].c_str()), atof(splitline[15].c_str()));
Light* l = new SquareLight(poi1, poi2, poi3, vec, col);
li.push_back(l);
}
//attenuation const linear quadratic
// Sets the constant, linear and quadratic attenuations
// (default 1,0,0) as in OpenGL.
else if(!splitline[0].compare("attenuation")) {
att[0] = atof(splitline[1].c_str());
att[1] = atof(splitline[2].c_str());
att[2] = atof(splitline[3].c_str());
}
//ambient r g b
// The global ambient color to be added for each object
// (default is .2,.2,.2)
else if(!splitline[0].compare("ambient")) {
globalAm->setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
}
//diffuse r g b
// specifies the diffuse color of the surface.
else if(!splitline[0].compare("diffuse")) {
m->constantBRDF.kd.setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
}
//specular r g b
// specifies the specular color of the surface.
else if(!splitline[0].compare("specular")) {
m->constantBRDF.ks.setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
m->constantBRDF.kr.setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
}
//shininess s
// specifies the shininess of the surface.
else if(!splitline[0].compare("shininess")) {
m->constantBRDF.shininess = atof(splitline[1].c_str());
}
else if(!splitline[0].compare("glossy")) {
m->constantBRDF.glossy = atof(splitline[1].c_str());
}
//emission r g b
// gives the emissive color of the surface.
else if(!splitline[0].compare("emission")) {
m->constantBRDF.em.setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
}
else if(!splitline[0].compare("refraction")) {
m->constantBRDF.rf = atof(splitline[1].c_str());
}
else if(!splitline[0].compare("transparency")) {
m->constantBRDF.kt.setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
}
else {
std::cerr << "Unknown command: " << splitline[0] << std::endl;
}
}
inpfile.close();
}
//parse obj files
std::vector<Matrix*> mStack;
const char Seperators[] = "/";
for (int i = 0; i < objFiles.size(); i++){
vI = 1; vnI = 1;
Vector *v = new Vector[10000], *vn = new Vector[10000];
m = new Material();
mStack.clear();
file = objFiles[i];
std::ifstream inpfilee(file.c_str());
scene.sceneName = file.c_str() + std::string(".png");
scene.film.imageName = scene.sceneName;
if(!inpfilee.is_open()) {
std::cout << "Unable to open file" << std::endl;
exit(0);
} else {
std::string line;
while(inpfilee.good()) {
std::vector<std::string> splitline;
std::string buf;
std::getline(inpfilee,line);
std::stringstream ss(line);
while (ss >> buf) {
splitline.push_back(buf);
}
//Ignore blank lines
if(splitline.size() == 0) {
continue;
}
//Ignore comments
if(splitline[0][0] == '#') {
continue;
}
//sphere x y z radius
// Defines a sphere with a given position and radius.
else if(!splitline[0].compare("sphere")) {
Matrix mat = Matrix(Matrix::IDENTITY);
Vector ori = Vector(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
Shape* s = new Sphere(ori, atof(splitline[4].c_str()));
for (std::vector<Matrix*>::size_type i = 0; i != mStack.size(); i++) {
mat = Matrix::multiply(mat, (*mStack[i]));
}
Primitive* sph = new GeometricPrimitive(Transformation(mat), Transformation(Matrix::invert(mat)), s, *m);
p.push_back (sph);
}
else if(!splitline[0].compare("v")) {
v[vI] = Vector(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
vI++;
}
else if(!splitline[0].compare("vn")) {
vn[vnI] = Vector(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
vnI ++;
}
else if(!splitline[0].compare("f")) {
std::vector<std::string> vvn;
std::string word;
stringstream st;
Matrix mat = Matrix(Matrix::IDENTITY);
for (std::vector<Matrix*>::size_type i = 0; i != mStack.size(); i++) {
mat = Matrix::multiply(mat, (*mStack[i]));
}
if (splitline.size() == 4){
st << (splitline[1].c_str()) << "/" << (splitline[2].c_str()) << "/" << (splitline[3].c_str()) << "/";
while(getline(st, word, '/')){
if (word != ""){
vvn.push_back(word);
}
}
Shape* t = new NormalTriangle(v[atoi(vvn[0].c_str())], v[atoi(vvn[2].c_str())], v[atoi(vvn[4].c_str())],\
vn[atoi(vvn[1].c_str())], vn[atoi(vvn[3].c_str())], vn[atoi(vvn[5].c_str())]);
Primitive* tri = new GeometricPrimitive(Transformation(mat), Transformation(Matrix::invert(mat)), t, *m);
p.push_back (tri);
} else{
st << (splitline[1].c_str()) << "/" << (splitline[2].c_str()) << "/" << (splitline[3].c_str()) << "/" << (splitline[4].c_str()) << "/";
while(getline(st, word, '/')){
if (word != ""){
vvn.push_back(word);
}
}
Shape* t1 = new NormalTriangle(v[atoi(vvn[0].c_str())], v[atoi(vvn[2].c_str())], v[atoi(vvn[4].c_str())],\
vn[atoi(vvn[1].c_str())], vn[atoi(vvn[3].c_str())], vn[atoi(vvn[5].c_str())]);
Shape* t2 = new NormalTriangle(v[atoi(vvn[0].c_str())], v[atoi(vvn[4].c_str())], v[atoi(vvn[6].c_str())],\
vn[atoi(vvn[1].c_str())], vn[atoi(vvn[5].c_str())], vn[atoi(vvn[7].c_str())]);
Primitive* tri1 = new GeometricPrimitive(Transformation(mat), Transformation(Matrix::invert(mat)), t1, *m);
Primitive* tri2 = new GeometricPrimitive(Transformation(mat), Transformation(Matrix::invert(mat)), t2, *m);
p.push_back (tri1);
p.push_back (tri2);
}
}
//translate x y z
// A translation 3-vector
else if(!splitline[0].compare("translate")) {
Matrix thisM = Matrix(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()), Matrix::TRANSLATION);
*mStack.back() = Matrix::multiply(*mStack.back(), thisM);
}
//rotate x y z angle
// Rotate by angle (in degrees) about the given axis as in OpenGL.
else if(!splitline[0].compare("rotate")) {
Vector axis = Vector(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
axis.normalize();
Matrix thisM = Matrix(axis.x, axis.y, axis.z, toRadian(atof(splitline[4].c_str())), Matrix::ROTATION);
*mStack.back() = Matrix::multiply(*mStack.back(), thisM);
}
//scale x y z
// Scale by the corresponding amount in each axis (a non-uniform scaling).
else if(!splitline[0].compare("scale")) {
Matrix thisM = Matrix(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()), Matrix::SCALING);
*mStack.back() = Matrix::multiply(*mStack.back(), thisM);
}
//pushTransform
// Push the current modeling transform on the stack as in OpenGL.
// You might want to do pushTransform immediately after setting
// the camera to preserve the “identity” transformation.
else if(!splitline[0].compare("pushTransform")) {
mStack.push_back(new Matrix(Matrix::IDENTITY));
}
//popTransform
// Pop the current transform from the stack as in OpenGL.
// The sequence of popTransform and pushTransform can be used if
// desired before every primitive to reset the transformation
// (assuming the initial camera transformation is on the stack as
// discussed above).
else if(!splitline[0].compare("popTransform")) {
mStack.pop_back();
}
//diffuse r g b
// specifies the diffuse color of the surface.
else if(!splitline[0].compare("diffuse")) {
m->constantBRDF.kd.setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
}
//specular r g b
// specifies the specular color of the surface.
else if(!splitline[0].compare("specular")) {
m->constantBRDF.ks.setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
m->constantBRDF.kr.setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
}
//shininess s
// specifies the shininess of the surface.
else if(!splitline[0].compare("shininess")) {
m->constantBRDF.shininess = atof(splitline[1].c_str());
}
else if(!splitline[0].compare("glossy")) {
m->constantBRDF.glossy = atof(splitline[1].c_str());
}
//emission r g b
// gives the emissive color of the surface.
else if(!splitline[0].compare("emission")) {
m->constantBRDF.em.setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
}
else if(!splitline[0].compare("refraction")) {
m->constantBRDF.rf = atof(splitline[1].c_str());
}
else if(!splitline[0].compare("transparency")) {
m->constantBRDF.kt.setValues(atof(splitline[1].c_str()), atof(splitline[2].c_str()), atof(splitline[3].c_str()));
}
else {
std::cerr << "Unknown command: " << splitline[0] << std::endl;
}
}
inpfilee.close();
}
}
// Initialize a random number generator.
srand((unsigned)time(0));
cout << "di: " << scene.raytracer.di << endl;
cout << "ci: " << scene.raytracer.ci << endl;
cout << "ii: " << scene.raytracer.ii << endl;
scene.render();
}
int main(int argc, char *argv[]) {
if (argc == 1) {
cout << "No input file specified!" << endl;
exit(0);
}
std::string file = argv[1];
std::vector<std::string> objFiles;
if (argc >= 3){
for (int i =2; i<argc; i++){
objFiles.push_back(argv[i]);
}
}
runScene(file, objFiles);
return 0;
};
|
842117a486a8e859dda3e8a92b885a0096680c14
|
9fad4848e43f4487730185e4f50e05a044f865ab
|
/src/chrome/browser/media/router/media_router_base.cc
|
cea5fcdada94f67de9be3a5480ca7828986b3ccc
|
[
"BSD-3-Clause"
] |
permissive
|
dummas2008/chromium
|
d1b30da64f0630823cb97f58ec82825998dbb93e
|
82d2e84ce3ed8a00dc26c948219192c3229dfdaa
|
refs/heads/master
| 2020-12-31T07:18:45.026190
| 2016-04-14T03:17:45
| 2016-04-14T03:17:45
| 56,194,439
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,611
|
cc
|
media_router_base.cc
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/router/media_router_base.h"
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/stl_util.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/profiles/profile.h"
namespace media_router {
MediaRouterBase::MediaRouterBase() = default;
MediaRouterBase::~MediaRouterBase() = default;
std::unique_ptr<PresentationConnectionStateSubscription>
MediaRouterBase::AddPresentationConnectionStateChangedCallback(
const MediaRoute::Id& route_id,
const content::PresentationConnectionStateChangedCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
auto* callbacks = presentation_connection_state_callbacks_.get(route_id);
if (!callbacks) {
callbacks = new PresentationConnectionStateChangedCallbacks;
callbacks->set_removal_callback(base::Bind(
&MediaRouterBase::OnPresentationConnectionStateCallbackRemoved,
base::Unretained(this), route_id));
presentation_connection_state_callbacks_.add(route_id,
base::WrapUnique(callbacks));
}
return callbacks->Add(callback);
}
void MediaRouterBase::OnOffTheRecordProfileShutdown() {
// TODO(mfoltz): There is a race condition where off-the-record routes created
// by pending CreateRoute requests won't be terminated. Fixing this would
// extra bookeeping of route requests in progress, and a way to cancel them
// in-flight.
for (auto route_ids_it = off_the_record_route_ids_.begin();
route_ids_it != off_the_record_route_ids_.end();
/* no-op */) {
// TerminateRoute will erase |route_id| from |off_the_record_route_ids_|,
// make a copy as the iterator will be invalidated.
const MediaRoute::Id route_id = *route_ids_it++;
TerminateRoute(route_id);
}
}
void MediaRouterBase::NotifyPresentationConnectionStateChange(
const MediaRoute::Id& route_id,
content::PresentationConnectionState state) {
if (state == content::PRESENTATION_CONNECTION_STATE_TERMINATED)
OnRouteTerminated(route_id);
auto* callbacks = presentation_connection_state_callbacks_.get(route_id);
if (!callbacks)
return;
callbacks->Notify(content::PresentationConnectionStateChangeInfo(state));
}
void MediaRouterBase::NotifyPresentationConnectionClose(
const MediaRoute::Id& route_id,
content::PresentationConnectionCloseReason reason,
const std::string& message) {
auto* callbacks = presentation_connection_state_callbacks_.get(route_id);
if (!callbacks)
return;
content::PresentationConnectionStateChangeInfo info(
content::PRESENTATION_CONNECTION_STATE_CLOSED);
info.close_reason = reason;
info.message = message;
callbacks->Notify(info);
}
void MediaRouterBase::OnOffTheRecordRouteCreated(
const MediaRoute::Id& route_id) {
DCHECK(!ContainsKey(off_the_record_route_ids_, route_id));
off_the_record_route_ids_.insert(route_id);
}
void MediaRouterBase::OnRouteTerminated(const MediaRoute::Id& route_id) {
// NOTE: This is called for all routes (off the record or not).
off_the_record_route_ids_.erase(route_id);
}
void MediaRouterBase::OnPresentationConnectionStateCallbackRemoved(
const MediaRoute::Id& route_id) {
auto* callbacks = presentation_connection_state_callbacks_.get(route_id);
if (callbacks && callbacks->empty())
presentation_connection_state_callbacks_.erase(route_id);
}
} // namespace media_router
|
6571075ca02ad0b9013a05ac0efe140a03af10de
|
58304dc51601bcdec337120184f9806497a47e44
|
/chapter11/ex18.cpp
|
a2edf1deb4e7acf6a490cef9394dcd53aad9d052
|
[] |
no_license
|
jwbecalm/thinking-in-cpp-forked-
|
3cc0af0c4f1d7497330873f19561604c6d97d3a4
|
4cf9a78692d6e687956622d32e99b0a6e27cf8ee
|
refs/heads/master
| 2020-03-30T01:51:12.826613
| 2013-07-21T16:57:21
| 2013-07-21T16:57:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 285
|
cpp
|
ex18.cpp
|
#include <iostream>
using namespace std;
class argcon
{
public:
argcon(){};
argcon(const argcon& a, int b = 10){ cout << "default: " << b << endl; };
virtual ~argcon(){};
};
void f(argcon c){};
int main(int argc, char *argv[])
{
argcon t;
f(t);
return 0;
}
|
bd59bd824cd59d8f36db6d57ce5424de7222d74b
|
39702a12098cd2e67c6572756c43ffb6d7e8417c
|
/DateCell.h
|
f46a8686e540518f49e7366b3ee00c7f383f9270
|
[] |
no_license
|
zhinian1992/Calendar
|
2a4f3b204993c1286b966907ca564f5012626ec1
|
7e9c2c588f716b8768b9bf061831ace8f1d7912d
|
refs/heads/master
| 2020-04-30T21:19:57.373016
| 2019-03-29T03:54:41
| 2019-03-29T03:54:41
| 177,090,710
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 622
|
h
|
DateCell.h
|
#ifndef DATECELL_H
#define DATECELL_H
#include <QWidget>
#include "DetailWnd.h"
namespace Ui {
class DateCell;
}
class DateCell : public QWidget
{
Q_OBJECT
public:
explicit DateCell(int iNO,QWidget *parent = 0);
~DateCell();
void setCellText(QDate qDate,QString qsTask = "");
void setCellStyle(bool bCurrentDay,bool bCurrentMonth);
private:
void enterEvent(QEvent *event)Q_DECL_OVERRIDE;
void leaveEvent(QEvent *event)Q_DECL_OVERRIDE;
private:
Ui::DateCell *ui;
DetailWnd *m_DetailWnd;
int m_CellNO;
bool m_IsCurrentDay;
bool m_IsCurrentMonth;
};
#endif // DATECELL_H
|
1049cfa3fc8a7a2e8f764e1866626cb800346f9e
|
11a246743073e9d2cb550f9144f59b95afebf195
|
/codeforces/gym/101528/ichthyo.cpp
|
ecbb80b575423d196e265d9b4d511bfb2a9ff871
|
[] |
no_license
|
ankitpriyarup/online-judge
|
b5b779c26439369cedc05c045af5511cbc3c980f
|
8a00ec141142c129bfa13a68dbf704091eae9588
|
refs/heads/master
| 2020-09-05T02:46:56.377213
| 2019-10-27T20:12:25
| 2019-10-27T20:12:25
| 219,959,932
| 0
| 1
| null | 2019-11-06T09:30:58
| 2019-11-06T09:30:57
| null |
UTF-8
|
C++
| false
| false
| 1,291
|
cpp
|
ichthyo.cpp
|
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <utility>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <complex>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
constexpr int MAXN = 52;
int n;
int a[MAXN];
int f(int x) {
return max(1000 - x, 1);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
freopen("ichthyo.in", "r", stdin);
freopen("ichthyo.out", "w", stdout);
scanf("%d", &n);
multiset<pii> ms;
for (int i = 0; i < n; ++i) {
scanf("%d", a + i);
ms.insert({f(a[i]), i});
}
int time = 0;
int pos = 0;
while (true) {
pii cur = *ms.begin();
ms.erase(ms.begin());
// printf("%d %d\n", cur.first, cur.second);
if (cur.first - time < abs(pos - cur.second)) {
printf("%d\n", cur.first);
return 0;
}
time = cur.first;
pos = cur.second;
++a[pos];
ms.insert({time + f(a[pos]), pos});
}
return 0;
}
|
a0bbb2ecb18c3ea5784178a6cf4282f275e35979
|
46ba25e5bed4613884b7b74445d5adae6a09c096
|
/plugin/protocols/include/ProtocolAds.h
|
31d4427e3bf40a9187f70953e4a168f4372a4a5d
|
[
"MIT"
] |
permissive
|
coolengineer/cocos2d-x
|
af7fec2833ada79e553f872f3a1a10c80ea2b653
|
d099698e11cab0aad2e4e13313a828b8e01758b5
|
refs/heads/master
| 2021-01-18T01:58:31.387306
| 2013-04-27T01:58:36
| 2013-04-27T01:58:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,626
|
h
|
ProtocolAds.h
|
#ifndef __CCX_PROTOCOL_ADS_H__
#define __CCX_PROTOCOL_ADS_H__
#include "PluginProtocol.h"
#include <map>
#include <string>
namespace cocos2d { namespace plugin {
typedef std::map<std::string, std::string> TAppInfo;
class AdListener
{
public:
typedef enum
{
eUnknownError = 0,
eNetworkError,
} EAdErrorCode;
virtual void onReceiveAd() {}
virtual void onPresentScreen() {}
virtual void onFailedToReceiveAd(EAdErrorCode code, const char* msg) {}
virtual void onDismissScreen() {}
};
class ProtocolAds : public PluginProtocol
{
public:
typedef enum {
ePosTop = 0,
ePosTopLeft,
ePosTopRight,
ePosBottom,
ePosBottomLeft,
ePosBottomRight,
} EBannerPos;
/**
@brief plugin initialization
*/
virtual bool init();
/**
@brief initialize the application info
@param appInfo This parameter is the info of aplication,
different plugin have different format
@warning Must invoke this interface before other interfaces.
And invoked only once.
*/
virtual void initAppInfo(TAppInfo appInfo);
/**
@brief show banner ads at specified position
@param pos The position where the banner view be shown
@param sizeEnum The size of the banner view.
In different plugin, it's have different mean.
Pay attention to the subclass definition
*/
virtual void showBannerAd(EBannerPos pos, int sizeEnum);
/**
@brief hide the banner ads view
*/
virtual void hideBannerAd();
/**
@brief Set whether needs to output logs to console.
@param debug If true debug mode enabled, or debug mode disabled.
*/
virtual void setDebugMode(bool debug);
/**
@brief set the Ads listener
*/
static void setAdListener(AdListener* pListener)
{
m_pListener = pListener;
}
// For the callbak methods
static void receiveAd();
static void presentScreen();
static void failedToReceiveAd(AdListener::EAdErrorCode code, const char* msg);
static void dismissScreen();
virtual const char* getPluginVersion() { return "ProtocolAds, v0.1.01 , subclass should override this interface!"; };
virtual const char* getSDKVersion();
virtual const char* getPluginName() = 0;
protected:
ProtocolAds();
public:
virtual ~ProtocolAds();
protected:
static AdListener* m_pListener;
};
}} // namespace cocos2d { namespace plugin {
#endif /* __CCX_PROTOCOL_ADS_H__ */
|
eada93cbba9c9e53f44b020bed280cf252d6c81f
|
8510632c7d7725a9133ec5b86172b6458d999f67
|
/datastruct/BinarySortTree.cpp
|
652c2745238c0151bbde525104ba421740669454
|
[] |
no_license
|
JarvisChu/algorithm
|
dab33ef2c86fdd2afe00d27ff1e3e4cee6d4a4ad
|
edb95c68c2af5940fbb073fc973e374b6bcaf24d
|
refs/heads/master
| 2023-06-21T19:41:59.388634
| 2023-06-11T15:25:46
| 2023-06-11T15:25:46
| 181,333,418
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,440
|
cpp
|
BinarySortTree.cpp
|
/*
* 二叉排序树 Binary Sort Tree
* 左子树小于根, 右子树都大于根
* 用于动态查找
*
* 中序遍历就可以得到一个有序的序列
*
* 插入
* 很简单,中序遍历的过程
*
* 删除
* - 叶子直接删:如果被删节点是叶子节点,直接删除即可
* - 单孩直接代:如果被删节点只有一个孩子,直接使用其孩子替代其位置即可
* - 中序前驱代:指被删节点有两个孩子,此时有两种处理方式,
* 假设: p 是要删除的结点,f 是p的父结点
* (1) p的左孩子作为f的左孩子, f->lchild = p->lchild;
* p的右孩子作为 其中序遍历前驱的右孩子
* (2) 用p的中序遍历直接前驱代替p, 然后再删除其直接前驱(递归)
*/
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType; //元素类型
typedef struct Node{
ElemType data;
Node* lchild;
Node* rchild;
}Node;
typedef struct BinarySortTree{
Node* root;
}BinarySortTree;
void Display(Node* root){
if(root == NULL) return;
Display(root->lchild);
printf("%d ", root->data);
Display(root->rchild);
}
// 插入 - 中序遍历
Node* Insert(Node* root, ElemType data){
if(root == NULL){
root = (Node*)malloc(sizeof(Node));
root->data = data;
root->lchild = root->rchild = NULL;
return root;
}
// 相等,已经存在,不用插入
if(data == root->data){
}
// 小于,插入到左子树
else if(data < root->data){
root->lchild = Insert(root->lchild,data);
return root;
}
// 大于,插入到右子树
else if(data > root->data){
root->rchild = Insert(root->rchild,data);
}
return root;
}
// 查找,找到返回p, 否则返回NULL
Node* Search(Node* root, ElemType data){
return NULL;
}
// 删除 root 结点
Node* Delete(Node* root, ElemType data){
if(root == NULL) return NULL;
// 没有左孩子
if(root->lchild == NULL){
// 直接用右孩子替代
Node* p = root;
root = root->rchild; // 将root直接指向右孩子
free(p);
}
// 没有右孩子
else if(root->rchild == NULL){
// 直接用左孩子替代
Node* p = root;
root = root->lchild; // 将root直接指向左孩子
free(p);
}
// 有两个孩子
else{
// 找到中序遍历的前驱(在左孩子的树中)
Node* parent = root; // 指向 pre的parent
Node* pre = root->lchild; // 指向 root的前驱
while(pre->rchild != NULL) { // root的前驱,肯定是最后一个右孩子,不断遍历找
parent = pre;
pre = pre->rchild;
}
// 找到,pre就是前驱,parent 就是前驱的父结点
// 用前驱覆盖root
root->data = pre->data;
// 删除前驱
if(root == parent){ // 前驱就是 左孩子, 直接 root的左孩子 指向前驱的左孩子即可
parent->lchild = pre->lchild; //
}else{ // 前驱在 左孩子的右子树中,前驱结点是父结点parent的右孩子,且前驱本身必然没有右孩子,直接将parent的右孩子 指向 前驱的左孩子即可
parent->rchild = pre->lchild;
}
free(pre);
}
return root;
}
// DeleteBST
Node* DeleteBST(Node* root, ElemType data){
if(root == NULL) return NULL;
if (root->data == data) {
printf("find delete\n");
root = Delete(root, data); // 删除结点root
}
else if(data < root->data){
root->lchild = DeleteBST(root->lchild, data); // 递归,从左子树中删除
}
else if(data > root->data){
root->rchild = DeleteBST(root->rchild, data); // 递归,从右子树中删除
}
return root;
}
int main()
{
BinarySortTree tree;
tree.root = NULL;
tree.root = Insert(tree.root, 45);
tree.root = Insert(tree.root, 24);
tree.root = Insert(tree.root, 53);
tree.root = Insert(tree.root, 12);
tree.root = Insert(tree.root, 24);
tree.root = Insert(tree.root, 90);
tree.root = Insert(tree.root, 90);
tree.root = Insert(tree.root, 25);
Display(tree.root);
tree.root = DeleteBST(tree.root, 24);
printf("\nafter delete 24: ");
Display(tree.root);
return 0;
}
|
e68a15417e99b42baa0ebcd0ffc78aad66b22949
|
878ca47b232081d27390e7bd9d02826b41bc070c
|
/Lab_4_4/Lab/Isosceles.h
|
3bd8614ad2b9c34957adbe9997db468120f3475e
|
[] |
no_license
|
laurashcherbak/cpp_oop
|
6efd8b68156a79f4e27ba1d70b51946bfec2c887
|
a693421f1cfb83fb2db93d4c1fb88ac38cd6f34d
|
refs/heads/master
| 2023-04-25T03:16:19.012303
| 2021-05-19T07:38:43
| 2021-05-19T07:38:43
| 343,200,561
| 0
| 0
| null | 2021-04-19T17:56:04
| 2021-02-28T19:54:18
|
C++
|
UTF-8
|
C++
| false
| false
| 364
|
h
|
Isosceles.h
|
// Isosceles.h
#pragma once
#include "Triangle.h"
class Isosceles :
public Triangle
{
public:
Isosceles(void);
Isosceles(int ab, int bc, int angle);
~Isosceles(void);
virtual void Print();
virtual void Input();
virtual double Square();
virtual double Perimeter();
virtual ostream& Print(ostream& out) const;
virtual istream& Input(istream& in);
};
|
d0d1387381f07d0dae46a178845a73ad671a3bf1
|
4a0ea369c33e0d21f5ef671ba9d82a0e3c4ff6f8
|
/dhash/dhblock_keyhash.h
|
d380e8c77abea351d7bf6cd3ebc1c89126482880
|
[
"MIT"
] |
permissive
|
weidezhang/dht
|
ee37de39a74bc975d37b8245469873bfc2e31c5f
|
2ce617cb6f02b5ebdb599487f0fef5720f688fd5
|
refs/heads/master
| 2021-01-18T07:51:50.113147
| 2013-06-10T09:05:31
| 2013-06-10T09:05:31
| 10,290,178
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,092
|
h
|
dhblock_keyhash.h
|
#include "dhblock.h"
#include "dhblock_replicated.h"
class sfs_pubkey2;
class sfs_sig2;
class sfspriv;
// The salt datatype is an arbitary sequence of sizeof(salt_t) bytes
// provided by the user of dhash. Its purpose is to multiplex one public
// key over any number (not any number but 2^{sizeof(salt_t)*8}) of blocks.
// As long as the signature supplied by the user includes the salt, the
// blocks are still self-certifying. The chordid = hash(pubkey,salt).
// Change the salt, and you get another self-certifying block.
typedef char salt_t [20];
// The purpose of this class is to abstract for users of dhash the payload
// of the actual dhash block. So if, for example, you've stored your data
// in dhash and you want to get it out, you'll need to get the dhash block,
// decode() it using this class, and then ask this class for your data via
// the buf() method.
class keyhash_payload
{
private:
salt_t _salt;
long _version;
str _buf;
public:
keyhash_payload ();
keyhash_payload (salt_t s);
keyhash_payload (long version, str buf);
keyhash_payload (salt_t s, long version, str buf);
~keyhash_payload () {}
const char* salt () const { return _salt; }
long version () const { return _version; }
const str& buf () const { return _buf; }
size_t payload_len () const {
return _buf.len () + sizeof (long) + sizeof (salt_t);
}
chordID id (sfs_pubkey2 pk) const;
bool verify (sfs_pubkey2 pk, sfs_sig2 sig) const;
void sign (ptr<sfspriv> key, sfs_pubkey2& pk, sfs_sig2& sig) const;
int encode (xdrsuio &x) const;
static ptr<keyhash_payload> decode (xdrmem &x, long payloadlen);
static ptr<keyhash_payload> decode (ptr<dhash_block> b);
};
struct dhblock_keyhash : public dhblock_replicated {
dhblock_keyhash () : dhblock_replicated () {};
str produce_fragment (ptr<dhash_block> block, int n);
static bool verify (chordID key, str data);
static long version (const char *value, unsigned int len);
static vec<str> get_payload (str data);
static str marshal_block (sfs_pubkey2 key, sfs_sig2 sig,
keyhash_payload &p);
};
|
5bcf76d62bc7535f44e092fd136a9308f6d66404
|
9247cc17fbcf5ce96960e1b180d463339f45378d
|
/.SPOJ/NKSEQ/NKSEQ/NKSEQ.cpp
|
7ddd9376c77de535b86f9eb897f13df2e05d6186
|
[
"MIT"
] |
permissive
|
sxweetlollipop2912/MaCode
|
dbc63da9400e729ce1fb8fdabe18508047d810ef
|
b8da22d6d9dc4bf82ca016896bf64497ac95febc
|
refs/heads/master
| 2022-07-28T03:42:14.703506
| 2021-12-16T15:44:04
| 2021-12-16T15:44:04
| 294,735,840
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 841
|
cpp
|
NKSEQ.cpp
|
// AC SPOJ
#include "pch.h"
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#define maxN 200002
#define N (2*n)
typedef long maxn, maxa;
maxn n, res;
maxa a[maxN], sum[maxN];
void Prepare() {
std::cin >> n;
for (maxn i = 1; i <= n; i++) std::cin >> a[i], a[i + n] = a[i];
for (maxn i = 1; i <= N; i++) sum[i] = a[i] + sum[i - 1];
}
class cmp {
public:
bool operator() (const maxn x, const maxn y) {
return sum[x] > sum[y];
}
};
std::priority_queue <maxn, std::vector <maxn>, cmp> pq;
void Process() {
for (maxn i = 1; i < n; i++) pq.push(i);
for (maxn i = 1; i <= n; i++) {
pq.push(i + n - 1);
while (pq.top() < i) pq.pop();
if (sum[pq.top()] - sum[i - 1] > 0) ++res;
}
std::cout << res;
}
int main() {
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
Prepare();
Process();
}
|
cfd06eabd0a2bb46c956a88c239ae02e764394ac
|
75a1ce195fa1556e79c0b12e6ec600a0942e91a7
|
/include/jmsg/jmsg_rcver.hpp
|
af9be52a9d81d1c6172b2c9c17eff35eef685d18
|
[
"Apache-2.0"
] |
permissive
|
lineCode/jmsg
|
44ad1d3405d00a8b9f9a20c255edcb4dbc394407
|
d3d3462d76dfdbf8f01f64ba4354f63b56805ceb
|
refs/heads/master
| 2021-01-01T06:09:37.659428
| 2016-11-16T13:57:16
| 2016-11-16T13:57:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,894
|
hpp
|
jmsg_rcver.hpp
|
/**
* generated based on idl, please don't modify it.
*/
#pragma once
#include <map>
#include <string>
#include <functional>
#include "jmsg_id.hpp"
/// @class rcver : used to receive messages
class rcver final {
public:
rcver();
~rcver();
public:
void fill_from(std::function<size_t (void *, size_t)> f);
template<mid_t mid, template<mid_t> class T>
void register_callback(std::function<void(T<mid> &)> cb)
{
m_cbs[__mid_to_str(mid)] = [this, cb](void) -> void {
T<mid> tmp;
__unpack((typename msg_helper<mid>::value_type &)tmp);
cb(tmp);
};
}
template<mid_t mid>
void register_callback(std::function<void(typename msg_helper<mid>::value_type &)> cb)
{
m_cbs[__mid_to_str(mid)] = [this, cb](void) -> void {
typename msg_helper<mid>::value_type msg;
__unpack(msg);
cb(msg);
};
}
private:
const char * __mid_to_str(mid_t mid);
void __unpack(struct fs_state & dst);
void __unpack(struct heat_state & dst);
void __unpack(struct simple_msg & dst);
void __unpack(struct record_offset & dst);
void __unpack(struct tense_test_result & dst);
void __unpack(struct loss_estimating_result & dst);
void __unpack(struct defect_detect_result & dst);
void __unpack(struct fiber_reco_result & dst);
void __unpack(struct manual_discharge_counts & dst);
void __unpack(struct fusion_splice_result & dst);
void __unpack(struct arc_revise & dst);
void __unpack(struct fs_da_cfg & dst);
void __unpack(struct discharge_adjust_result & dst);
void __unpack(struct discharge & dst);
void __unpack(struct discharge_count & dst);
void __unpack(struct set_fs_display_mode_ext & dst);
void __unpack(struct set_fs_display_zoom_ext & dst);
void __unpack(struct set_fs_display_mode & dst);
void __unpack(struct dust_check_result & dst);
void __unpack(struct heat_start & dst);
void __unpack(struct heat_result & dst);
void __unpack(struct image_move & dst);
void __unpack(struct set_window & dst);
void __unpack(struct fs_cover_state & dst);
void __unpack(struct set_lcd_brightness & dst);
void __unpack(struct set_led & dst);
void __unpack(struct motor_start & dst);
void __unpack(struct motor_stop & dst);
void __unpack(struct fs_mt_cfg & dst);
void __unpack(struct motor_test_result & dst);
void __unpack(struct process_progress & dst);
void __unpack(struct fs_rr_cfg & dst);
void __unpack(struct realtime_revise_result & dst);
void __unpack(struct regular_test_result & dst);
void __unpack(struct fs_se_cfg & dst);
void __unpack(struct stabilize_electrode_result & dst);
void __unpack(struct report_dev_state & dst);
void __unpack(struct report_wave_form & dst);
void __unpack(struct fs_ft_cfg & dst);
void __unpack(struct fiber_train_result & dst);
private:
void __reset();
private:
uint8_t m_buf[65536];
std::size_t m_size;
const uint8_t * const m_pend;
void * m_doc;
std::map<std::string, std::function<void(void)>> m_cbs;
};
|
f614ee3fd72b7ec2f46b3d854f3ca809eb255df5
|
31fb4ae9f6f6241b580c23015b1b6b4816520edd
|
/磁盘调度算法.cpp
|
cb33a00c62879a7ba13cf43fd96d275a0815faf1
|
[] |
no_license
|
spiritedboy/gzhu
|
048a8f7d77c3fadff409f6133c038e53186c7bab
|
af0409aae520ce1e31988695eb08ac8fcf786086
|
refs/heads/master
| 2022-03-28T01:53:53.028130
| 2020-01-28T06:17:46
| 2020-01-28T06:17:46
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,524
|
cpp
|
磁盘调度算法.cpp
|
#include<stdlib.h>
#include<iostream>
#include<time.h>
#include<cmath>
#include<cstring>
#define max 50
using namespace std;
int arr[max], copyarr[max], finished[max]; //arr数组用来存请求服务队列,copyarr为辅助数组,值和arr相同
int num; //队列元素个数 //finished数组用来存已排好序的队列(SSTF和电梯法需要用到)
int n1 = 0; //递归计数
int start; //磁头起始位置
/*赋随机值*/void SetValue()
{
int i;
srand(int(time(0)));
for (i = 0; i < num; i++)
{
arr[i] = rand() % 200;
copyarr[i] = arr[i];
}
}
/*输入*/void input()
{
int i;
cout << "请输入请求磁盘服务的队列元素个数:" << endl;
cin >> num;
SetValue(); //调用赋值函数
cout << "请求磁盘服务序列为:";
for (i = 0; i < num; i++)
cout << arr[i] << " ";
cout << endl;
cout << "请输入磁头起始位置:";
cin >> start;
cout << endl;
}
/*升序排序法*/void sort(int a[], int m)
{
//对a数组的前m个元素进行升序排序,即小的在前,大的在后
int i, j, k, temp;
for (i = 0; i < m - 1; i++)
{
k = i;
for (j = i + 1; j < m; j++)
{
if (a[j] < a[k])
k = j;
}
if (k != i)
{
temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
}
/*计算总磁道数*/void sum(int a[])
{
//计算从磁头起始位置遍历完a数组所走的磁道数
int i;
int total = 0;
total = total + abs(start - a[0]); //起始位置与第一个元素a[0]的位置差值的绝对值
for (i = 0; i < num - 1; i++)
{
total = total + abs(a[i] - a[i + 1]); //绝对值进行累加
}
cout << "磁头总移动的磁道数为:" << total << endl;
cout << "磁头移动顺序为:";
cout << start;
for (i = 0; i < num; i++)
cout << "->" << a[i]; //输出从磁头起始位置遍历完a数组的磁头轨迹
cout << endl;
cout << endl;
}
/*先来先服务法*/void FCFS()
{
cout << "先来先服务法:" << endl;
sum(arr); //先来先服务法不需要进行排序,直接调用sum函数,参数是arr数组。
}
/*最短寻道时间优先法*/void SSTF(int x, int y)
{
//x为元素个数,y为磁头起始位置
if (x == 0) //退出递归的条件
{
cout << "最短寻道时间优先法:" << endl;
sum(finished); //最后调用sum函数,参数为finished数组
return;
}
int i, t, temp[max];
int flag=0; //标记
int newstart; //新的起始位置
for (i = 0; i < x; i++)
temp[i] = abs(y - copyarr[i]); //计算起始位置y与copyarr数组前x个元素的差值的绝对值,放进temp数组
sort(temp, x); //对temp数字进行升序排序,排序完成后temp[0]为最小值
for (i = 0; i < x; i++)
{
//判断起始位置y与temp[0]所对应的元素大小
if (y + temp[0] == copyarr[i])
{
flag = 1; //copyarr[i]比y大
break;
}
if (y - temp[0] == copyarr[i])
{
flag = 2; //copyarr[i]比y小
break;
}
}
switch (flag)
{
case 1:newstart = y + temp[0]; break; //copyarr[i]比y大,新的起始位置为y+temp[0]
case 2:newstart = y - temp[0]; break; //copyarr[i]比y小,新的起始位置为y-temp[0]
}
for (i = 0; i < x; i++)
{
if (copyarr[i] == newstart) //在辅助数组copyarr里找到newstart的位置
break;
}
t = copyarr[i];
copyarr[i] = copyarr[x - 1];
copyarr[x - 1] = t; //把最后一个元素和newstart调换位置
finished[n1++] = newstart; //把newstart存进finished数组
SSTF(x - 1, newstart); //递归调用,元素个数减1,新的起始位置
}
/*电梯法*/void dianti()
{
int i, j, k;
int temp[max];
memcpy(temp, arr, sizeof(temp)); //把arr数组复制给temp
temp[num] = start; //把磁头起始位置start放进temp数组,不留空位
sort(temp, num + 1); //对temp数组进行排序
for (i = 0; i < num + 1; i++)
{
if (temp[i] == start) //找到start的位置
break;
}
cout << "电梯法:" << endl;
cout << "先往左再往右:" << endl;
k = 0;
for (j = i - 1; j >= 0; j--)
finished[k++] = temp[j]; //比start小的元素降序放进finished数组
for (j = i + 1; j <= num; j++)
finished[k++] = temp[j]; //比start大的元素升序放进finished数组
sum(finished); //最后调用sum函数,参数为finished数组
cout << "电梯法:" << endl;
cout << "先往右再往左:" << endl;
k = 0;
for (j = i + 1; j <= num; j++)
finished[k++] = temp[j];
for (j = i - 1; j >= 0; j--)
finished[k++] = temp[j];
sum(finished);
}
int main()
{
input();
FCFS();
SSTF(num, start);
dianti();
}
|
842857af4fc49ec0bd845088f01452d11d015f67
|
e8dbde825066192e6d171f98bb5d04d0991944c5
|
/tests/BatchEncoder.Core.UnitTests/worker/LuaOutputParserTests.cpp
|
9ba6ea937d46f7dac3b6589b58741b2e039f2468
|
[
"MIT"
] |
permissive
|
AlbertFFC/BatchEncoder
|
ee896e63aa8d1ee2ead100ab1818c2fc93d5c51e
|
8a19bb4ebb683f99bda30c33854e46e28bac1ec9
|
refs/heads/master
| 2023-05-01T21:05:19.578801
| 2021-05-19T05:38:23
| 2021-05-19T05:38:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 547
|
cpp
|
LuaOutputParserTests.cpp
|
#include "stdafx.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace BatchEncoderCoreUnitTests
{
TEST_CLASS(CLuaOutputParser_Tests)
{
public:
TEST_METHOD(CLuaOutputParser_Constructor)
{
#pragma warning(push)
#pragma warning(disable:4101)
worker::CLuaOutputParser m_Parser;
#pragma warning(pop)
}
TEST_METHOD(CLuaOutputParser_Open)
{
}
TEST_METHOD(CLuaOutputParser_Parse)
{
}
};
}
|
91584c06e4135affb58f5b63c2f1e854a75cac53
|
051a4db48a1c18ed4ac5262a9b91cb9445e39776
|
/VHDL_L2_Cache/My_Cache/LAB5/Utility_Gen/mux_gen.cc
|
c8317ff9a0e4cde0290fc21ca223563e184ec0c7
|
[] |
no_license
|
wh1pch81n/code_projects_portfolio
|
cd45f5bc67952f94c3bb14551cf39e9e8d0e8082
|
a7789b8b4931980ba3a4d27209c4d080f8868126
|
refs/heads/master
| 2021-01-15T19:28:15.150278
| 2013-09-14T00:37:01
| 2013-09-14T00:37:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,806
|
cc
|
mux_gen.cc
|
#include <iostream>
#include <fstream>
using namespace std;
int bitvectorsize(int size){
int numbits(0);
while(size != 1){ size /= 2; numbits++;}
return numbits;
}
string binary( unsigned long n, int length )
{
char result[ (sizeof( unsigned long ) * 8) + 1 ];
unsigned index = sizeof( unsigned long ) * 8;
result[ index ] = '\0';
do result[ --index ] = '0' + (n & 1);
while (n >>= 1);
string pad = result + index;
while(pad.size()< length )
pad = "0" + pad;
return pad;
}
int main() {
string muxsize;
string fname;
int muxt;
ofstream outfile;
cout << "Enter the size of the mux: ";
cin >> muxsize;
cout << endl;
muxt = atoi(muxsize.c_str());
fname = "mux_"+muxsize+"_1.vhd";
outfile.open(fname.c_str());
if(!outfile){
cerr << "File was not created correctly";
exit(-1);
}
outfile << "library IEEE;" << endl << "use IEEE.std_logic_1164.all;"
<< endl << endl
<< "entity mux" << muxsize << "v1 is" << endl
<< "port(" << endl;
for( unsigned int i = 0; i < muxt; i++ )
outfile << '\t' << "d" << i << ": in std_logic;" << endl;
outfile << '\t' << "y : out std_logic;" << endl << '\t'
<< "s : in std_logic_vector( " << bitvectorsize(muxt) - 1
<< " downto 0 )" << endl << ");"
<< endl << "end mux" << muxsize << "v1;" << endl << endl;
outfile << "architecture bhv of mux" << muxsize << "v1 is" << endl
<< "begin" << endl << endl;
outfile << "with s select" << endl << endl
<< "y <= ";
int bitsize = bitvectorsize(muxt);
for( unsigned int i = 0; i < muxt; i++ ){
outfile << "d" << i << " when " << "\""
<< binary(i,bitsize) << "\"," << endl << '\t';
}
outfile << "'0' when others;" << endl << endl
<< "end bhv;";
outfile.close();
return 0;
}
|
b64fcdbb988cf6b9fea6027f4c101c30fe577b29
|
220c3562253663a71db0003a2dda822e39c9efae
|
/Fizz Buzz/Fizz Buzz.cc
|
d14be55bdcaa94218236ac5491da2bd6c3f80e82
|
[] |
no_license
|
rishabhgupta1322/InterviewBit
|
f0fe8f2ffe28e708587d0413ae2ae3e8409e338b
|
730e1241ac8c51d6d44c36d29e41619f2e90348d
|
refs/heads/master
| 2020-03-30T06:18:40.363482
| 2019-04-29T10:17:54
| 2019-04-29T10:17:54
| 150,851,492
| 1
| 1
| null | 2019-05-04T03:00:34
| 2018-09-29T10:02:58
|
C++
|
UTF-8
|
C++
| false
| false
| 507
|
cc
|
Fizz Buzz.cc
|
vector<string> Solution::fizzBuzz(int A) {
vector<string> res;
string s; int t; char ch;
for(int i=1;i<=A;i++){
if(i%15 == 0) res.push_back("FizzBuzz");
else if(i%3 == 0) res.push_back("Fizz");
else if(i%5 == 0) res.push_back("Buzz");
else{
s = "";
t = i;
while(t){
ch = t%10 +'0';
s = ch + s;
t/=10;
}
res.push_back(s);
}
}
return res;
}
|
b18bb3763b37803b2ba0c5b25a292f0abcaba24b
|
d84f21fe7aeaac657f7a4f97f4cd104f24c236e5
|
/Subsets II .cpp
|
41b3dc5e66521e5db8cdf68539f962c2cc280c76
|
[] |
no_license
|
brucelevis/leetcode
|
4b7273dcf8cfce4ac260fa3e6190659fcc396759
|
d300462c12a2a7a97264f405ba95a4031f7b68ba
|
refs/heads/master
| 2020-03-30T01:53:16.337811
| 2016-03-29T03:17:36
| 2016-03-29T03:17:36
| null | 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 2,045
|
cpp
|
Subsets II .cpp
|
/*
±àÒë»·¾³CFree 5.0
²©¿ÍµØÖ·£ºhttp://blog.csdn.net/Snowwolf_Yang
*/
#include <iostream>
#include <vector>
using namespace std;
#if 0
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int> > ret;
vector<int> tmp;
sort(S.begin(),S.end());
subsetsWithDupCore(ret,0,S,tmp);
return ret;
}
void subsetsWithDupCore(vector<vector<int> > &ret,int index,vector<int> &S,vector<int> &tmp)
{
if(index == S.size())
{
if(find(ret.begin(),ret.end(),tmp) == ret.end())
ret.push_back(tmp);
return;
}
subsetsWithDupCore(ret,index+1,S,tmp);
tmp.push_back(S[index]);
subsetsWithDupCore(ret,index+1,S,tmp);
tmp.pop_back();
}
};
#elif 1
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int> > ret;
vector<int> tmp;
sort(S.begin(),S.end());
subsetsWithDupCore(ret,0,S,tmp);
return ret;
}
void subsetsWithDupCore(vector<vector<int> > &ret,int index,vector<int> &S,vector<int> &tmp)
{
if(index == S.size())
{
ret.push_back(tmp);
return;
}
for(int i = index;i<S.size();i++)
{
if(i!=index && S[i] == S[i-1])
continue;
tmp.push_back(S[i]);
subsetsWithDupCore(ret,i+1,S,tmp);
tmp.pop_back();
}
ret.push_back(tmp);
}
};
#endif
void printvec(vector<int > A)
{
for(int i = 0;i<A.size();i++)
{
printf("%d,",A[i]);
}
printf("\n");
}
void printvecvec(vector<vector<int > > A, char *name)
{
printf("%s\n",name);
for(int i = 0;i<A.size();i++)
{
printf("%3d:",i);
printvec(A[i]);
}
printf("\n");
}
void test0()
{
int A[] = {1,2,2};
vector<int > num(A,A+sizeof(A)/sizeof(int));
Solution so;
vector<vector<int> > ret = so.subsetsWithDup(num);
printvecvec(ret,"ret");
if(1)
printf("------------------------failed\n");
else
printf("------------------------passed\n");
}
int main()
{
test0();
return 0;
}
|
35a358965dd5e2382501ca8a276020b09e2461f5
|
c69f1e444089965449899108a927823f9182f940
|
/test/logic_tests/Variable_Tests.cpp
|
9438cbe601936adef33ca3b6a39ac67b43d5c88f
|
[] |
no_license
|
MasonWilie/SAT_Solver
|
a78eded5ca8e1955d2381060432360210d48e6b1
|
4930979cdf2617fece0529eec7fda38c24a8125d
|
refs/heads/master
| 2022-04-20T16:14:57.263099
| 2020-04-23T04:10:00
| 2020-04-23T04:10:00
| 240,777,353
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,003
|
cpp
|
Variable_Tests.cpp
|
#include "gtest/gtest.h"
#include "Variable.h"
TEST(Variable_tests, Constructor)
{
const int name_1{1};
const int name_2{2};
const int name_3{3};
const int name_4{4};
Variable a(name_1);
Variable b(name_2);
Variable c(name_3);
Variable d(name_4);
EXPECT_EQ(name_1, a.GetName());
EXPECT_EQ(false, a.IsSet());
EXPECT_EQ(name_2, b.GetName());
EXPECT_EQ(false, b.IsSet());
EXPECT_EQ(name_3, c.GetName());
EXPECT_EQ(false, c.IsSet());
EXPECT_EQ(name_4, d.GetName());
EXPECT_EQ(false, d.IsSet());
}
TEST(Variable_tests, Setting)
{
const int name_1{1};
const int name_2{2};
Variable a(name_1);
Variable b(name_2);
EXPECT_EQ(name_1, a.GetName());
EXPECT_EQ(false, a.IsSet());
EXPECT_EQ(name_2, b.GetName());
EXPECT_EQ(false, b.IsSet());
a.Set(true);
EXPECT_EQ(true, a.IsSet());
EXPECT_EQ(true, a.IsTrue());
b.Set(false);
EXPECT_EQ(true, b.IsSet());
EXPECT_EQ(false, b.IsTrue());
}
|
1ade4bbf27779e1e249b3abfdf5d9418029eaede
|
23568ef2f0a1fdbc1b64a1dfae73d53bd79dd5f0
|
/2/4/4.1.cpp
|
357541979a8c90f32824b526ce9ee9ddadd16d7a
|
[] |
no_license
|
makisto/prog
|
b9accb2a0d3f680cac4557df276503164d78e64b
|
3d5b164774155cda3c59753b2b884c3cbe9fab18
|
refs/heads/master
| 2022-04-18T12:22:57.681497
| 2020-04-10T17:02:39
| 2020-04-10T17:02:39
| 254,687,281
| 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 923
|
cpp
|
4.1.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include <conio.h>
#include <iostream>
using namespace std;
const int n=5;
typedef int rown[n];
int main()
{
setlocale(LC_ALL, "Russian");
srand(time(NULL));
int i,j,m,max;
rown *B,*C;
cout<<"Ñòîëáöû:";
cin>>m;
B=new rown[m];
C=new rown[m-1];
for (i=0; i<m; i++)
{
for (j=0; j<n; j++)
{
B[i][j]=rand()%100;
cout<<B[i][j]<<"\t";
}
cout<<"\n";
}
cout<<"\n";
max=B[0][0];
int x=0,y=0;
for (i=0; i<m; i++)
{
for (j=0; j<n; j++)
{
if (B[i][j]>=max)
{
max=B[i][j];
x=i;
y=j;
}
}
}
cout<<"\n";
cout<<max;
cout<<"\n";
int q=0,w=0;
for (i=0; i<m; i++)
{
if (i==x) i++;
for (j=0; j<n; j++)
{
if (j==y) j++;
C[q][w]=B[i][j];
w++;
}
q++;
w=0;
}
for (i=0; i<m-1; i++)
{
for (j=0; j<n-1; j++)
{
cout<<C[i][j]<<"\t";
}
cout<<"\n";
}
delete B;
delete C;
getch();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.