text
stringlengths 8
6.88M
|
|---|
#include <sys/types.h>
#include <sys/socket.h>
#include <ctime>
const int g_port = 3123;
struct Message
{
int64_t request;
int64_t response;
} __attribute__((__packed__));
static_assert(sizeof(Message) == 16, "Message size should be 16 bytes");
int64_t now()
{
struct timeval tv = {0, 0};
gettimeofday(&tv, NULL);
return tv.tv_sec * int64_t(100000) + tv.usec;
}
void runServer()
{
}
|
/**
* @file OgreApplication.h
* @brief 用于定义OgreApplication类的头文件
*/
#ifndef OGREAPPLICATION_H
#define OGREAPPLICATION_H
#include <OgreRoot.h>
#if OGRE_VERSION >= 0x00010900
#include <OgreOverlaySystem.h>
#endif
#include <QApplication>
/**
* @class OgreApplication
* @brief 继承自QApplication类.
* 在任何Qt的窗口系统部件被使用之前,要先创建QApplication.
*/
class OgreApplication : public QApplication {
Q_OBJECT
public:
OgreApplication(int argc, char *argv[]); ///<构造函数
void Initialize(); ///<初始化函数
#if OGRE_VERSION >= 0x00010900
Ogre::OverlaySystem *GetOverlaySystem() {
return overlaysystem_;
}
private:
Ogre::OverlaySystem *overlaysystem_;
#endif
};
#endif
|
#ifndef TOMATO_H
#define TOMATO_H
#include <map>
#include <vector>
#include "task.h"
class Tomato
{
public:
Tomato( void );
~Tomato( void );
void load( void );
int addTask( Task task );
Task getTask( int id );
std::map<int,Task>::const_iterator beginForTask() {
return tasks.begin();
}
std::map<int,Task>::const_iterator endForTask() {
return tasks.end();
}
std::vector<TaskData>::const_iterator beginForTaskData( void ) {
return taskDatas.begin();
}
std::vector<TaskData>::const_iterator endForTaskData( void ) {
return taskDatas.end();
}
void flushTaskData( int dayOffset = 7 );
void flushTask( void );
void chooseTask( int id, bool status );
void finishTask( int id, bool status );
void start( int woringTime, int restingTime );
void end( void );
private:
bool isIncludeDays( tm* old, tm* now, int dayOffset, TaskData* result );
std::map<int, Task> tasks;
std::vector<TaskData> taskDatas;
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2005 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "modules/widgets/ColouredMultiEdit.h"
#ifdef COLOURED_MULTIEDIT_SUPPORT
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// DivideHTMLTagFragment is used by GetNextTextFragment in layout/box.cpp to add in the extra breaking up
// of text fragments so we can make sure that fragments break on the < and >, and it also updates the in_tag so
// that it reflects the current tag being processed.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int DivideHTMLTagFragment(int *in_tag, const uni_char *wstart, const uni_char **wend, int *length, BOOL *has_baseline, BOOL next_has_baseline)
{
if (in_tag)
{
if (**wend == '<' && (*in_tag == HTT_NONE || *in_tag == HTT_STYLE_OPEN_START || *in_tag == HTT_SCRIPT_OPEN_START || *in_tag == HTT_COMMENT_START)) {
// If we are not at the start then just hop out
if (*wend != wstart)
return DIVIDETAG_DONE;
// Is this a html comment tag?
if (*in_tag != HTT_STYLE_OPEN_START && *in_tag != HTT_SCRIPT_OPEN_START && !uni_strnicmp(*wend, UNI_L("<!--"), 4))
*in_tag = HTT_COMMENT_START; // Start html comment tag
// Is this a style tag?
if (*in_tag != HTT_SCRIPT_OPEN_START && *in_tag != HTT_COMMENT_START && !uni_strnicmp(*wend, UNI_L("<style"), 6))
*in_tag = HTT_STYLE_OPEN_START; // Start style tag
if (*in_tag != HTT_SCRIPT_OPEN_START && *in_tag != HTT_COMMENT_START && !uni_strnicmp(*wend, UNI_L("</style"), 7))
*in_tag = HTT_STYLE_CLOSE_START; // End style tag
// Is this a script tag?
if (*in_tag != HTT_STYLE_OPEN_START && *in_tag != HTT_COMMENT_START && !uni_strnicmp(*wend, UNI_L("<script"), 7))
*in_tag = HTT_SCRIPT_OPEN_START; // Start script tag
if (*in_tag != HTT_STYLE_OPEN_START && *in_tag != HTT_COMMENT_START && !uni_strnicmp(*wend, UNI_L("</script"), 8))
*in_tag = HTT_SCRIPT_CLOSE_START; // End script tag
// Only set the tag to 1 if it's not already running something else
if (!*in_tag)
*in_tag = HTT_TAG_START;
*has_baseline = next_has_baseline;
(*wend)++;
(*length)--;
return DIVIDETAG_AGAIN;
}
else if (**wend == '>' && *in_tag != HTT_STYLE_OPEN_START && *in_tag != HTT_SCRIPT_OPEN_START)
{
// Is a html comment tag currently running?
if (*in_tag == HTT_COMMENT_START)
{
// Are the previous 2 char's dashes? i.e. a html comment closing tag -->
if (*(*wend - 1) != '-' && *(*wend - 2) != '-')
{
// something else so go around again!
*has_baseline = next_has_baseline;
(*wend)++;
(*length)--;
return DIVIDETAG_AGAIN;
}
}
*has_baseline = next_has_baseline;
(*wend)++;
(*length)--;
if (*in_tag)
(*in_tag) += HTT_TAG_SWITCH;
return DIVIDETAG_DONE;
}
else if (*in_tag)
{
*has_baseline = next_has_baseline;
(*wend)++;
(*length)--;
return DIVIDETAG_AGAIN;
}
}
return DIVIDETAG_NOTHING;
}
#endif // COLOURED_MULTIEDIT_SUPPORT
|
//format : by using make_pair();
#include<iostream>
#include<utility>
#include<string>
using namespace std;
class student
{
string name;
int i;
public:
void set()
{
name="madhav";
i=16;
}
void show()
{
cout<<"\nname of student: "<<name;
cout<<"\nage of student : "<<i;
}
};
int main()
{
student s1,s2;
s1.set();
pair <string,int> p1;
pair <string,string> p2;
pair <string,float> p3;
pair <int,student> p4;
p1=make_pair("rojee",11);
p2=make_pair("madhab","mahanty");
p3=make_pair("over",15.6);
p4=make_pair(1,s1);
cout<<"\np1: ";
cout<<p1.first <<" "<<p1.second ;
cout<<"\np2: ";
cout<<p2.first <<" "<<p2.second ;
cout<<"\np3: ";
cout<<p3.first <<" "<<p3.second ;
cout<<"\np4: ";
cout<<p4.first <<" ";
s2=p4.second;
s2.show();
return 0;
}
|
#ifndef TIMEPOINT_HPP
#define TIMEPOINT_HPP
class TimePoint
{
public:
TimePoint();
TimePoint(const std::string &_time);
TimePoint(const int &_val);
TimePoint operator-(const TimePoint &rhs) const;
TimePoint operator+(const TimePoint &rhs) const;
double operator/(const TimePoint &rhs) const;
void add(const int &_ss);
void subtract(const int &_ss);
bool operator>(TimePoint const &rhs) const;
bool operator==(TimePoint const &rhs) const;
bool operator<(TimePoint const &rhs) const;
int toMins() const;
int toSecs() const;
std::string getTime() const;
void display() const;
private:
std::string time;
int hh, mm, ss, val;
};
TimePoint::TimePoint() : hh(0), mm(0), ss(-1), val(-1) {}
TimePoint::TimePoint(const std::string &_time)
{
sscanf(_time.c_str(), "%d:%d:%d", &hh, &mm, &ss);
val = hh * 60 * 60 + mm * 60 + ss;
char tmp[9];
snprintf(tmp, 10, "%02d:%02d:%02d", hh, mm, ss);
time = tmp;
}
void renew(std::string &time, int &hh, int &mm, int &ss, int &val, const int &_val) {
val = _val;
hh = val / 60 / 60, val -= hh * 60 * 60;
mm = val / 60, val -= mm * 60;
ss = val;
val = _val;
char tmp[9];
snprintf(tmp, 10, "%02d:%02d:%02d", hh, mm, ss);
time = tmp;
}
TimePoint::TimePoint(const int &_val) {
renew(time, hh, mm, ss, val, _val);
}
TimePoint TimePoint::operator-(const TimePoint &rhs) const {
return TimePoint(abs(val - rhs.val));
}
TimePoint TimePoint::operator+(const TimePoint &rhs) const {
return TimePoint(val + rhs.val);
}
double TimePoint::operator/(const TimePoint &rhs) const {
return 1.0 * val / rhs.val;
}
void TimePoint::add(const int &_ss) {
renew(time, hh, mm, ss, val, val + _ss);
}
void TimePoint::subtract(const int &_ss) {
renew(time, hh, mm, ss, val, val - _ss);
}
bool TimePoint::operator>(TimePoint const &rhs) const {
return val > rhs.val;
}
bool TimePoint::operator==(TimePoint const &rhs) const {
return val == rhs.val;
}
bool TimePoint::operator<(TimePoint const &rhs) const {
return val < rhs.val;
}
int TimePoint::toSecs() const {
return val;
}
std::string fromSecs(const int &ss) {
return TimePoint(ss).getTime();
}
int TimePoint::toMins() const {
return val / 60;
}
std::string fromMins(const int &mm) {
return TimePoint(mm * 60).getTime();
}
void TimePoint::display() const {
std::cout << time;
}
std::string TimePoint::getTime() const {
return time;
}
#endif
|
/*
* @lc app=leetcode.cn id=14 lang=cpp
*
* [14] 最长公共前缀
*/
// @lc code=start
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size()==0)return "";
if(strs.size()==1)return strs[0];
int cnt = 0;
int flag = 0;
while(flag == 0){
for(int i=0;i<strs.size();i++){
if(cnt>=strs[0].size()){
flag = 1;
break;
}
if(strs[i][cnt]!=strs[0][cnt]){
flag = 1;
break;
}
}
cnt++;
}
//cout<<cnt-1<<endl;
return strs[0].substr(0,cnt-1);
}
};
// @lc code=end
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
*/
#ifndef MDE_OPPAINTER_H
#define MDE_OPPAINTER_H
#include "modules/pi/OpPainter.h"
#if !defined(MDE_PLATFORM_IMPLEMENTS_OPPAINTER) && !defined(VEGA_OPPAINTER_SUPPORT)
#include "modules/libgogi/mde.h"
class MDE_OpPainter : public OpPainter
{
public:
MDE_OpPainter();
virtual ~MDE_OpPainter();
void SetPreAlpha(UINT8 alpha) { m_pre_alpha = alpha; }
UINT8 GetPreAlpha() { return m_pre_alpha; }
virtual void SetColor(UINT8 red, UINT8 green, UINT8 blue, UINT8 alpha = 255);
virtual void SetFont(OpFont *font);
virtual OP_STATUS SetClipRect(const OpRect &rect);
virtual void RemoveClipRect();
virtual void GetClipRect(OpRect* rect);
virtual void DrawRect(const OpRect &rect, UINT32 width = 1);
virtual void FillRect(const OpRect &rect);
virtual void ClearRect(const OpRect &rect);
virtual void DrawEllipse(const OpRect &rect, UINT32 width = 1);
virtual void FillEllipse(const OpRect &rect);
virtual void DrawLine(const OpPoint &from, UINT32 length, BOOL horizontal, UINT32 width = 1);
virtual void DrawLine(const OpPoint &from, const OpPoint &to, UINT32 width = 1);
virtual void DrawString(const OpPoint &pos, const uni_char* text, UINT32 len, INT32 extra_char_spacing = 0, short word_width = -1);
virtual void DrawPolygon(const OpPoint* point_array, int points, UINT32 width = 1);
virtual void InvertRect(const OpRect &rect);
virtual void InvertBorderRect(const OpRect &rect, int border);
virtual void InvertBorderEllipse(const OpRect &rect, int border);
virtual void InvertBorderPolygon(const OpPoint* point_array, int points, int border);
virtual void DrawBitmapClipped(const OpBitmap* bitmap, const OpRect &source, OpPoint p);
// [OPTIONAL FUNCTIONS]
// Should be used only if they are supported. Otherwise they will be done internal. If you get an OP_ASSERT here, then you need to either change your Supports method or implement the asserted method.
virtual void DrawBitmapClippedTransparent(const OpBitmap* bitmap, const OpRect& source, OpPoint p);
virtual void DrawBitmapClippedAlpha(const OpBitmap* bitmap, const OpRect& source, OpPoint p);
virtual BOOL DrawBitmapClippedOpacity(const OpBitmap* bitmap, const OpRect &source, OpPoint p, int opacity);
virtual void DrawBitmapScaled(const OpBitmap* bitmap, const OpRect& source, const OpRect& dest);
virtual void DrawBitmapScaledTransparent(const OpBitmap* bitmap, const OpRect& source, const OpRect& dest);
virtual void DrawBitmapScaledAlpha(const OpBitmap* bitmap, const OpRect& source, const OpRect& dest);
virtual OP_STATUS DrawBitmapTiled(const OpBitmap* bitmap, const OpPoint& offset, const OpRect& dest, INT32 scale) { OP_ASSERT(FALSE); return OpStatus::ERR; };
/** Creates a bitmap from a rectangle on screen. */
virtual OpBitmap* CreateBitmapFromBackground(const OpRect& rect);
/** It is painting on a OpBitmap wich we may get bitspointer access to */
virtual BOOL IsUsingOffscreenbitmap() { return FALSE; };
/** Returns the offscreenbitmap */
virtual OpBitmap* GetOffscreenBitmap() { return NULL; };
/**
Returns the rect to where the offscreenbuffer is located. If f.eks. a paintevent
repaints a part i the middle of the document, the painting to the offscreenbitmap must
be moved to match that offset.
*/
virtual void GetOffscreenBitmapRect(OpRect* rect) {};
inline void DrawBitmap (OpBitmap* bitmap, OpPoint p) { DrawBitmapClipped(bitmap,
OpRect(0, 0, bitmap->Width(), bitmap->Height()), p); }
inline void DrawBitmapTransparent (OpBitmap* bitmap, OpPoint p) { DrawBitmapClippedTransparent(bitmap,
OpRect(0, 0, bitmap->Width(), bitmap->Height()), p); }
inline void DrawBitmapAlpha (OpBitmap* bitmap, OpPoint p) { DrawBitmapClippedAlpha(bitmap,
OpRect(0, 0, bitmap->Width(), bitmap->Height()), p); }
/**
Finds out what the painter supports.
@return FALSE if it not has the feature.
*/
virtual BOOL Supports(SUPPORTS supports);
/**
Sets the color. Takes an UINT32 instead of separate parameters for red, green, blue.
Format should be 0xRRGGBB
*/
#ifdef OPERA_BIG_ENDIAN
inline void SetColor(UINT32 col) { SetColor(((UINT8*)&col)[3], ((UINT8*)&col)[2], ((UINT8*)&col)[1]); };
#else
inline void SetColor(UINT32 col) { SetColor(((UINT8*)&col)[0], ((UINT8*)&col)[1], ((UINT8*)&col)[2]); };
#endif
UINT32 GetColor();
virtual OP_STATUS BeginOpacity(const OpRect& rect, UINT8 opacity) { return OpStatus::ERR; }
virtual void EndOpacity() {}
void beginPaint(MDE_BUFFER *s);
void endPaint();
MDE_BUFFER* GetScreen() { return screen; }
private:
void DrawBitmapClippedInternal(MDE_BUFFER* buf, const OpRect &source, OpPoint p);
void DrawBitmapScaledInternal(MDE_BUFFER* buf, const OpRect &source, const OpRect& dest);
void DrawBitmapClippedTransparentInternal(MDE_BUFFER* buf, const OpRect& source, OpPoint p);
void DrawBitmapClippedAlphaInternal(MDE_BUFFER* buf, const OpRect& source, OpPoint p);
void DrawBitmapScaledTransparentInternal(MDE_BUFFER* buf, const OpRect& source, const OpRect& dest);
void DrawBitmapScaledAlphaInternal(MDE_BUFFER* buf, const OpRect& source, const OpRect& dest);
MDE_BUFFER *screen;
int paint_count;
struct MdeOpClipRect {
MDE_RECT rect;
struct MdeOpClipRect *prev;
};
MdeOpClipRect *cliprect_stack;
UINT8 m_pre_alpha;
};
#endif // !MDE_PLATFORM_IMPLEMENTS_OPPAINTER && !VEGA_OPPAINTER_SUPPORT
#endif // MDE_OPPAINTER_H
|
// Q. Dynamic Array
// https://www.hackerrank.com/challenges/dynamic-array/problem
#include<iostream>
#include<vector>
using namespace std;
vector<int> dynamicArray(int n, vector<vector<int>> queries) {
int lastAnswer=0;
vector< vector<int> > arr;
vector<int> answerArray;
arr.resize(n);
for(int i=0; i<queries.size(); i++) {
if(queries[i][0]==1) {
arr[(queries[i][1]^lastAnswer)%n].push_back(queries[i][2]);
}
else if(queries[i][0]==2) {
lastAnswer=arr[(queries[i][1]^lastAnswer)%n][queries[i][2]%arr[(queries[i][1]^lastAnswer)%n].size()];
answerArray.push_back(lastAnswer);
}
}
return answerArray;
}
int main() {
vector< vector<int> > arr;
vector<int> arr2;
unsigned int n, q, i, j, k;
int num;
cin>>n>>q;
for(i=0; i<q; i++) {
vector<int> temp;
for(j=0; j<3; j++) {
cin>>num;
temp.push_back(num);
}
arr.push_back(temp);
}
arr2=dynamicArray(n, arr);
for(i=0; i<arr2.size(); i++)
cout<<arr2[i]<<" ";
cout<<endl;
return 0;
}
|
// SPDX-FileCopyrightText: 2021 Samuel Cabrero <samuel@orica.es>
//
// SPDX-License-Identifier: MIT
#ifndef __STATE_ALARM_H__
#define __STATE_ALARM_H__
#include "state.h"
class TAlarm : public TState {
public:
TAlarm();
virtual const char *name() const;
virtual void enter();
virtual void loop();
virtual void exit();
};
#endif /* __STATE_ALARM_H__ */
|
// FileClientCmd.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <fstream>
#include <iostream>
#include "../Common.h"
#include "../CBlockingSocket.h"
#include "../UdpSocket.h"
#include "../Message.h"
#include <string>
#include <process.h>
#include <windows.h>
BOOL multi_thread = false;
unsigned __stdcall downloadFile(LPVOID pArguments) {
CBlockingSocket *cs = (CBlockingSocket *)pArguments;
CBlockingSocket ConnectSocket = *cs;
struct sockaddr_in c;
socklen_t cLen = sizeof(c);
getsockname(ConnectSocket.m_socket, (struct sockaddr*) &c, &cLen);
struct sockaddr_in s;
socklen_t sLen = sizeof(s);
getpeername(ConnectSocket.m_socket, (struct sockaddr*) &s, &sLen);
// recv by udp
UdpSocket udpSock;
udpSock.Open();
int client_tcp_port = htons(c.sin_port);
int client_udp_port = client_tcp_port + 1;
int server_tcp_port = htons(s.sin_port);
int server_udp_port = server_tcp_port - 1;
udpSock.Bind(NULL, client_udp_port);
// set udp_server_addr
sockaddr_in udp_server_addr;
udp_server_addr.sin_family = AF_INET;
udp_server_addr.sin_port = htons(server_udp_port);
udp_server_addr.sin_addr.S_un.S_addr = s.sin_addr.S_un.S_addr;
char filename[MAX_COMMAND_SIZE] = { 0 };
char savepath[MAX_COMMAND_SIZE] = { 0 };
cout << " Input file path: ";
cin >> filename;
cout << " Input save path: ";
cin >> savepath;
// send file name & get file size
Message msg;
char buffer[MAX_COMMAND_SIZE] = { 0 };
msg.setType(COMMAND_DOWNLOAD);
msg.setSize(strlen(filename));
msg.setData(filename);
msg.write(buffer);
ConnectSocket.Send(buffer, MSG_HEADER_LENGTH + strlen(filename));
Message size_msg;
ConnectSocket.Recv(buffer, MSG_HEADER_LENGTH);
size_msg.read(buffer);
int filelen = -1;
if (size_msg.getType() == FILE_DATA_SIZE) {
filelen = size_msg.getSize();
}
if (filelen == -1) {
cout << " File " << filename << " is not existed." << endl;
}
else {
fstream fs;
fs.open(savepath, ios::out | ios::binary);
fs.close();
fs.open(savepath, ios::app | ios::binary);
int percent = 0;
int block = filelen / MAX_DATA_SIZE + 1;
char recvBuf[MAX_BUF_SIZE] = { 0 };
unsigned long lastSeq = 0;
int filerecv = 0;
cout << " Receiving file: " << filename << " (" << filelen << " B)" << endl;
while (1)
{
int sLen = sizeof(sockaddr);
filerecv = recvfrom(udpSock.m_socket, recvBuf, MAX_BUF_SIZE, 0, (sockaddr*)&udp_server_addr, &sLen);
if (filerecv == -1) {
break;
}
// check
Message file_msg;
file_msg.read(recvBuf);
if (file_msg.getChecksum() != Common::CalculateCheckSum(file_msg.getData(), file_msg.getSize())) {
cout << " Checksum is wrong, drop it." << endl;
continue;
}
// send ack
Message data_ack_msg;
data_ack_msg.setType(FILE_DATA_ACK);
char bufAck[MSG_HEADER_LENGTH] = { 0 };
data_ack_msg.write(bufAck);
// get it before drop it
if (lastSeq == file_msg.getSeq()) {
//cout << " Got it before, drop it." << endl;
//cout << " Send ack back to the server." << endl;
sendto(udpSock.m_socket, bufAck, MSG_HEADER_LENGTH, 0, (sockaddr*)&udp_server_addr, sizeof(sockaddr));
continue;
}
fs.write(file_msg.getData(), file_msg.getSize());
lastSeq = file_msg.getSeq();
//cout << " Send ack back to the server." << endl;
sendto(udpSock.m_socket, bufAck, MSG_HEADER_LENGTH, 0, (sockaddr*)&udp_server_addr, sizeof(sockaddr));
//cout << " UDP: Received " << filerecv << " B, data: " << file_msg.getSize() << " B." << endl;
if (!multi_thread) {
// set console color
HANDLE hStdOutHandle;
WORD wOldColorAttrs;
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
hStdOutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdOutHandle, &csbiInfo);
wOldColorAttrs = csbiInfo.wAttributes;
// print progress bar
percent = 100 * file_msg.getSeq() / block;
if (percent == 100) {
SetConsoleTextAttribute(hStdOutHandle, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
Common::progress_bar(percent);
SetConsoleTextAttribute(hStdOutHandle, wOldColorAttrs);
}
else {
Common::progress_bar(percent);
}
}
// over
if (file_msg.getType() == FILE_DATA_END) {
cout << " Download file " << filename << " completed." << endl;
break;
}
}
fs.close();
}
udpSock.Close();
return 0;
}
int main(int argc, char *argv[])
{
//argc = 2;
//argv[1] = (char*)"10.64.132.147";
char *ip = argv[1];
if (argc != 2)
{
cout << "Please input like this: FileClientCmd 10.64.132.147" << endl;
return -1;
}
CBlockingSocket::Initialize();
// init socket
CBlockingSocket ConnectSocket(argv[1], TCP_SRV_PORT);
ConnectSocket.Open();
ConnectSocket.setSendRecvBuffer(MAX_BUF_SIZE);
if (!ConnectSocket.Connect()) {
cout << "Connect failed" << endl;
return -1;
}
cout << "Connection established to remote Server at " << argv[1] << ":" << TCP_SRV_PORT << endl;
while (TRUE) {
cout << "-------------------------------------------------------------" << endl;
cout << "Please input command(dir/download/exit): ";
string command;
cin >> command;
if (command == "dir") {
// get file list by command in tcp
Message msg(COMMAND_DIR, MSG_HEADER_LENGTH, 0, 0, NULL);
char buffer[MSG_HEADER_LENGTH + MAX_COMMAND_SIZE] = { 0 };
msg.write(buffer);
ConnectSocket.Send(buffer, MSG_HEADER_LENGTH);
// get file list
char bufList[MAX_DATA_SIZE] = { 0 };
ConnectSocket.Recv(bufList, MAX_DATA_SIZE);
cout << bufList << endl;
}
else if (command == "open-md") {
multi_thread = true;
cout << "Multi-thread is opened." << endl;
}
else if (command == "close-md") {
multi_thread = false;
cout << "Multi-thread is closed." << endl;
}
else if (command == "download") {
if (multi_thread) {
HANDLE hThread;
unsigned threadID;
hThread = (HANDLE)_beginthreadex(NULL, 0, &downloadFile, &ConnectSocket, 0, &threadID);
}
else {
downloadFile(&ConnectSocket);
}
}
else if (command == "exit") {
Message msg(COMMAND_EXIT, MSG_HEADER_LENGTH, 0, 0, NULL);
char buffer[MSG_HEADER_LENGTH + MAX_COMMAND_SIZE] = { 0 };
msg.write(buffer);
ConnectSocket.Send(buffer, MSG_HEADER_LENGTH);
ConnectSocket.Close();
CBlockingSocket::Cleanup();
return 0;
}
}
ConnectSocket.Close();
CBlockingSocket::Cleanup();
return 0;
}
|
#include <iostream>
struct Player
{
int m_Health;
void other(int Health);
int temp;
};
void Player::other(int Health)
{
for (int i = 0; i <= Health; i++)
{
for (int j = 0; j <= Health; j++)
{
if (j < i)
{
temp = j;
j = i;
i = temp;
}
}
}
}
int main()
{
Player p1{ 100 };
Player p2{ 55 };
Player p3{ 45 };
Player p4{ 12 };
}
|
#include "chandler.h"
Eigen::Matrix3f K = Eigen::Matrix3f::Zero();
std::string save_path = "";
CHandler::CHandler()
{
m_bGetLidarClouds = false;
m_bGetImage = false;
hasResult = false;
pointcloud_viewer = new pcl::visualization::PCLVisualizer("pointcloud_viewer");
m_pc = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>);
pointcloud_viewer -> setBackgroundColor(0, 0, 0);
//pcl::visualization::PCLVisualizer* my_viewer = new pcl::visualization::PCLVisualizer("my ");
//my_viewer -> setBackgroundColor(0, 0, 200);
m_mtuPclConfig.lock();
pcl_config.resize(7);
pcl_config[0] = -1.0;
pcl_config[1] = 0.5;
pcl_config[2] = -2.0;
pcl_config[3] = 1.5;
pcl_config[4] = 2.0;
pcl_config[5] = 5.0;
pcl_config[6] = 0.30;
m_mtuPclConfig.unlock();
m_mtuImageConfig.lock();
image_config.resize(7);
image_config[0] = 60;
image_config[1] = 130;
image_config[2] = 25;
image_config[3] = 255;
image_config[4] = 25;
image_config[5] = 255;
image_config[6] = 200;
m_mtuImageConfig.unlock();
}
void dynamic_callback(lidar_camera_offline_calibration::CalibrationConfig &config, uint32_t level)
{
ROS_INFO("Reconfigure Request: %s %s %s",
config.pointcloud_input.c_str(), config.image_input.c_str(),
config.camera_matrix.c_str()
);
// std::string tmp;
// Eigen::Matrix3f myK = Eigen::Matrix3f::Zero();
// std::stringstream input(config.camera_matrix.c_str());
// for (size_t i = 0; i < 3*3; i++)
// {
// getline(input, tmp, ',');
// myK<<atof(tmp.c_str());
// }
// ROS_INFO("myK double: %f %f %f",
// myK(0,0),myK(0,1),myK(0,2)
// );
}
void CHandler::ImageCallback(const sensor_msgs::Image::ConstPtr& image_msg)
{
m_mtuRawImageFrame.lock();
cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image_msg, "bgr8");
cv::Mat image = cv_image->image;
cv::Mat jpegimage;
cv::cvtColor(image, jpegimage, cv::COLOR_BGR2RGB);
jpegimage.copyTo(m_image);
m_mtuRawImageFrame.unlock();
m_bGetImage = true;
fprintf(stdout, "do image process....\n");
std::cout << jpegimage.rows << ", " << jpegimage.cols << std::endl;
//cv::namedWindow("image", cv::WINDOW_NORMAL);
// cv::createTrackbar("hl", "image", &hl, 180, NULL);
// cv::createTrackbar("sl", "image", &sl, 255, NULL);
// cv::createTrackbar("vl", "image", &vl, 255, NULL);
// cv::createTrackbar("hh", "image", &hh, 180, NULL);
// cv::createTrackbar("sh", "image", &sh, 255, NULL);
// cv::createTrackbar("vh", "image", &vh, 255, NULL);
// cv::createTrackbar("contours_num", "image", &contours_num, 1000, NULL);
// cv::createButton("Blur", blurCallback, NULL, cv::QT_CHECKBOX, 0);
// cv::createTrackbar("xia", "image", &xia, 200, NULL);
// cv::createTrackbar("shang", "image", &shang, 200, NULL);
// cv::createTrackbar("hou", "image", &hou, 200, NULL);
// cv::createTrackbar("qian", "image", &qian, 200, NULL);
// cv::createTrackbar("zuo", "image", &zuo, 200, NULL);
// cv::createTrackbar("you", "image", &you, 200, NULL);
// cv::createTrackbar("r", "image", &r, 100, NULL);
m_mtuImageConfig.lock();
int hl = image_config[0];
int hh = image_config[1];
int sl = image_config[2];
int sh = image_config[3];
int vl = image_config[4];
int vh = image_config[5];
int contours_num = image_config[6];
m_mtuImageConfig.unlock();
cv::Mat hsv_image;
cv::cvtColor(jpegimage, hsv_image, cv::COLOR_BGR2HSV);
cv::Mat mask;
cv::inRange(hsv_image, cv::Scalar(hl, sl, vl),
cv::Scalar(hh, sh, vh), mask);
cv::Mat element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5));
cv::erode(mask, mask, element);//腐蚀
element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(7, 7));
cv::dilate(mask, mask, element);//膨胀
element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));
cv::erode(mask, mask, element);
cv::Mat mask_color;
cv::cvtColor(mask, mask_color, cv::COLOR_GRAY2BGR);
std::vector<std::vector<cv::Point> > contours;
cv::findContours(mask, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Point2f ellips_center;
int ellipse_num = 0;
for(size_t i = 0; i < contours.size(); i++)
{
size_t count = contours[i].size();
if( count < contours_num )
continue;
cv::drawContours(mask_color, contours, i, cv::Scalar(0, 255, 0), 1);
cv::RotatedRect box = cv::fitEllipseDirect(contours[i]);
if( !(box.size.width>=0) || !(box.size.height>=0) )continue;
if( MAX(box.size.width, box.size.height) > MIN(box.size.width, box.size.height)*1.5 )
continue;
ellips_center.x = box.center.x;
ellips_center.y = box.center.y;
cv::ellipse(mask_color, box, cv::Scalar(0,0,255), 1, CV_AA);
cv::ellipse(jpegimage, box, cv::Scalar(0,0,255), 1, CV_AA);
ellipse_num++;
}
if(ellipse_num != 1){
cv::Mat dst;
dst.create(jpegimage.rows, jpegimage.cols * 2, CV_8UC3);
jpegimage.copyTo(dst(cv::Rect(0, 0, jpegimage.cols, jpegimage.rows)));
mask_color.copyTo(dst(cv::Rect(mask_color.cols, 0, mask_color.cols, mask_color.rows)));
m_mtuShowConfig.lock();
cv::imshow("image", dst);
cv::waitKey(10);
m_mtuShowConfig.unlock();
m_mtuRawImageFrame.unlock();
std::cout << "\033[33mWarning: have " << ellipse_num << " (!=1) ellipses\033[0m" << std::endl;
return;
}
m_mtuPoint2d.lock();
point_2d.x = ellips_center.x;
point_2d.y = ellips_center.y;
m_mtuPoint2d.unlock();
cv::circle(jpegimage, ellips_center, 2, cv::Scalar(255, 0, 0), -1);
cv::circle(mask_color, ellips_center, 2, cv::Scalar(255, 0, 0), -1);
std::cout << "ellipse_center (x, y): " << point_2d.x << ", " << point_2d.y << std::endl;
cv::Mat dst;
dst.create(jpegimage.rows, jpegimage.cols * 2, CV_8UC3);
jpegimage.copyTo(dst(cv::Rect(0, 0, jpegimage.cols, jpegimage.rows)));
mask_color.copyTo(dst(cv::Rect(mask_color.cols, 0, mask_color.cols, mask_color.rows)));
m_mtuShowConfig.lock();
cv::imshow("image", dst);
cv::waitKey(10);
m_mtuShowConfig.unlock();
}
void CHandler::CloudCallback(const sensor_msgs::PointCloud2::ConstPtr& cloud_msg)
{
m_mtuRawLidarFrame.lock();
pcl::PointCloud<pcl::PointXYZ>::Ptr raw_pc(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromROSMsg(*cloud_msg, *raw_pc);
m_bGetLidarClouds = true;
fprintf(stdout, "do lidar process....\n");
//std::cout << "get " << points_num << "points" << std::endl;
pcl::copyPointCloud(*raw_pc, *m_pc);
m_mtuRawLidarFrame.unlock();
m_mtuPclConfig.lock();
float zl = pcl_config[0];
float zh = pcl_config[1];
float xl = pcl_config[2];
float xh = pcl_config[3];
float yl = pcl_config[4];
float yh = pcl_config[5];
float ball_r = pcl_config[6];
m_mtuPclConfig.unlock();
pcl::PointCloud<pcl::PointXYZ>::Ptr pass_other_points(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered2(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered3(new pcl::PointCloud<pcl::PointXYZ>);
pcl::ModelCoefficients::Ptr coefficients_plane(new pcl::ModelCoefficients), coefficients_SPHERE(new pcl::ModelCoefficients);
std::vector<int> indices;
pcl::PointIndices::Ptr inliers_plane(new pcl::PointIndices), inliers_SPHERE(new pcl::PointIndices);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_plane(new pcl::PointCloud<pcl::PointXYZ>()), cloud_SPHERE(new pcl::PointCloud<pcl::PointXYZ>());
/******************************************************************************/
pcl::PassThrough<pcl::PointXYZ> pass;
pass.setInputCloud(raw_pc);
pass.setFilterFieldName("z");
pass.setNegative(false);
pass.setFilterLimits(MIN(zl, zh), MAX(zl, zh));
pass.filter(*cloud_filtered);
pass.setNegative(true);
pass.filter(*cloud_filtered2);
*pass_other_points += *cloud_filtered2;
pass.setNegative(false);
pass.setInputCloud(cloud_filtered);
pass.setFilterFieldName("x");
pass.setFilterLimits(MIN(xl, xh), MAX(xl, xh));
pass.filter(*raw_pc);
pass.setNegative(true);
pass.filter(*cloud_filtered2);
*pass_other_points += *cloud_filtered2;
pass.setNegative(false);
pass.setInputCloud(raw_pc);
pass.setFilterFieldName("y");
pass.setFilterLimits(MIN(yl, yh), MAX(yl, yh));
pass.filter(*cloud_filtered);
pass.setNegative(true);
pass.filter(*cloud_filtered2);
*pass_other_points += *cloud_filtered2;
//std::cout<<"Points num: "<<raw->points.size()<<" change to "<<cloud_filtered->points.size()<<std::endl;
/******************************************************************************/
// pcl::StatisticalOutlierRemoval<pcl::PointXYZI> sor;
// sor.setInputCloud(cloud_filtered);
// sor.setMeanK(OutlierRemoval_k);
// sor.setStddevMulThresh(OutlierRemoval_StddevMulThresh);
// sor.filter(*cloud_filtered);
//
// sensor_msgs::PointCloud2::Ptr filter_msg_ptr2(new sensor_msgs::PointCloud2);
// pcl::toROSMsg(*cloud_filtered, *filter_msg_ptr2);
// filter_msg_ptr2 -> header = input -> header;
// FilteredPublisher2.publish(*filter_msg_ptr2);
/******************************************************************************/
/*
pcl::SACSegmentation<pcl::PointXYZ> seg;
seg.setOptimizeCoefficients(true);
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setMethodType(pcl::SAC_RANSAC);
seg.setMaxIterations(100);
seg.setDistanceThreshold(0.05);
seg.setInputCloud(cloud_filtered);
seg.segment(*inliers_plane, *coefficients_plane);
// std::cout<<"Plane coefficients: "<<*coefficients_plane<<std::endl;
pcl::ExtractIndices<pcl::PointXYZ> extract;
extract.setInputCloud(cloud_filtered);
extract.setIndices(inliers_plane);
extract.setNegative(false);
extract.filter(*cloud_plane);
extract.setNegative(true);
extract.filter(*cloud_filtered2);
//std::cout<<"Plane has "<<cloud_plane->points.size()<<" points"<<std::endl;
*/
pcl::PointXYZ center_p;
if(cloud_filtered -> size() > 10){
pcl::SACSegmentation<pcl::PointXYZ> seg;
seg.setInputCloud(cloud_filtered);
seg.setOptimizeCoefficients(true);
seg.setModelType(pcl::SACMODEL_SPHERE);
seg.setMethodType(pcl::SAC_RANSAC);
seg.setMaxIterations(3000);
seg.setDistanceThreshold(0.03);
seg.setRadiusLimits(ball_r-0.05, ball_r+0.05);
seg.segment(*inliers_SPHERE, *coefficients_SPHERE);
//std::cout << "Spheer coefficients: " << *coefficients_SPHERE;
std::cout << "(x, y, z, r): " << "(" << coefficients_SPHERE->values[0] << ", " << coefficients_SPHERE->values[1] << ", " << coefficients_SPHERE->values[2] << ", " << coefficients_SPHERE->values[3] << std::endl;
m_mtuPoint3d.lock();
point_3d.x = coefficients_SPHERE->values[0];
point_3d.y = coefficients_SPHERE->values[1];
point_3d.z = coefficients_SPHERE->values[2];
m_mtuPoint3d.unlock();
center_p.x = point_3d.x;
center_p.y = point_3d.y;
center_p.z = point_3d.z;
pcl::ExtractIndices<pcl::PointXYZ> extract;
extract.setInputCloud(cloud_filtered);
extract.setIndices(inliers_SPHERE);
extract.setNegative(false);
extract.filter(*cloud_SPHERE);
extract.setNegative(true);
extract.filter(*cloud_filtered3);
}
else{
std::cout << "pos error" << std::endl;
}
//std::cout<<"Spheer has "<<cloud_cylinder->points.size()<<" points"<<std::endl;
//std::cout<<"lidar ok"<<std::endl<<std::endl;
if(pointcloud_viewer -> removeAllPointClouds()){
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> color_pass_other_points(pass_other_points, 255, 255, 255);
//pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> color_cloud_plane(cloud_plane, 0, 0, 255);
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> color_cloud_SPHERE(cloud_SPHERE, 0, 255, 0);
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> color_cloud_filtered3(cloud_filtered3, 255, 0, 0);
pointcloud_viewer -> addPointCloud<pcl::PointXYZ>(pass_other_points, color_pass_other_points, "pass_other_points");
//pointcloud_viewer -> addPointCloud<pcl::PointXYZ>(cloud_plane, color_cloud_plane, "plane_pointcloud");
pointcloud_viewer -> addPointCloud<pcl::PointXYZ>(cloud_SPHERE, color_cloud_SPHERE, "SPHERE_pointcloud");
pointcloud_viewer -> addPointCloud<pcl::PointXYZ>(cloud_filtered3, color_cloud_filtered3, "other_pointcloud");
//if(cloud_filtered -> size() > 10){
// pointcloud_viewer -> addSphere(center_p, pcl_config[6], "Sphere", 0);
//}
}
pointcloud_viewer -> spinOnce(100);
}
const bool CHandler::ClockDiv(const int div )
{
return !( (m_nRollingCounter++)%div );
}
void CHandler::project2image(pcl::PointCloud<pcl::PointXYZ>::Ptr input_pc, cv::Mat &raw_image, cv::Mat& output_image, Eigen::Matrix4f RT, Eigen::Matrix3f camera_param){
Eigen::Matrix<float, 3, 4> TT_local, TTT_local;//lida2image=T*(T2)*T3
pcl::PointCloud<pcl::PointXYZ>::Ptr pc(new pcl::PointCloud<pcl::PointXYZ>);
TT_local = RT.topRows(3);
TTT_local = camera_param * TT_local;
m_mtuRawImageFrame.lock();
m_mtuRawLidarFrame.lock();
raw_image.copyTo(output_image);
pcl::copyPointCloud(*input_pc, *pc);
m_mtuRawImageFrame.unlock();
m_mtuRawLidarFrame.unlock();
pcl::PointXYZ r;
Eigen::Vector4f raw_point;
Eigen::Vector3f trans_point;
double deep, deep_config;//deep_config: normalize, max deep
int point_r;
deep_config = 80;
point_r = 1;
//std::cout << "image size; " << raw_image.cols << " * " << raw_image.rows << std::endl;
for(int i=0; i<pc->size(); i++){
r = pc->points[i];
raw_point(0, 0) = r.x;
raw_point(1, 0) = r.y;
raw_point(2, 0) = r.z;
raw_point(3, 0) = 1;
trans_point = TTT_local * raw_point;
int x = (int)(trans_point(0, 0) / trans_point(2, 0));
int y = (int)(trans_point(1, 0) / trans_point(2, 0));
if(x<0 || x>(raw_image.cols-1) || y<0 || y>(raw_image.rows-1))continue;
deep = trans_point(2, 0) / deep_config;
//deep = r.intensity / deep_config;
int blue, red, green;
if(deep <= 0.5){
green = (int)((0.5-deep)/0.5*255);
red = (int)(deep/0.5*255);
blue = 0;
}
else if(deep <= 1){
green = 0;
red = (int)((1-deep)/0.5*255);
blue = (int)((deep-0.5)/0.5*255);
}
else{
blue = 0;
green = 0;
red = 255;
};
cv::circle(output_image, cv::Point2f(x, y), point_r, cv::Scalar(blue,green,red), -1);
//cv::circle(edge_distance_image2, cv::Point2f(x, y), point_r, cv::Scalar(red,green,blue), -1);
}
}
int CHandler::countRT(){
// cv::Matx33d camera_p(
// 475.0, 0, 240,
// 0, 475.0, 151,
// 0, 0, 1);
cv::Matx33d camera_p;
for (size_t i = 0; i < 3*3; i++)
camera_p(i/3,i%3)=K(i/3,i%3);
std::vector<cv::Point3d> points_3d4;
std::vector<cv::Point2d> points_2d4;
int point_number = points_2d.size();
if (point_number != points_3d.size()) {
std::cout << "\033[33mWarning: 3D num != 2D num\033[0m" << std::endl;
return -1;
}
int num[4] = {point_number, point_number, point_number, point_number};
int n = 10;
unsigned seed = std::time(0);
std::srand(seed);
cv::Mat Rod_r, TransMatrix, RotationR, pos;
cv::Mat trans = cv::Mat(3, 1, CV_64F);
cv::Mat rr = cv::Mat(3, 1, CV_64F);
trans.at<double>(0) = 0;
trans.at<double>(1) = 0;
trans.at<double>(2) = 0;
rr.at<double>(0) = 0;
rr.at<double>(1) = 0;
rr.at<double>(2) = 0;
std::cout << "start compute" << std::endl;
for (int i = 0; i < n; i++) {
for (int ii = 0; ii < 4; ii++) {
num[ii] = std::rand() % point_number;
for (int iii = 0; iii < ii; iii++) {
if (num[ii] == num[iii]) {
num[ii] = std::rand() % point_number;
iii = -1;
}
}
points_3d4.push_back(points_3d[num[ii]]);
points_2d4.push_back(points_2d[num[ii]]);
}
bool success = cv::solvePnP(points_3d4, points_2d4, camera_p, cv::noArray(), Rod_r, TransMatrix, false,
cv::SOLVEPNP_P3P);
// std::cout << "r:" << std::endl << Rod_r << std::endl;
// std::cout << "R:" << std::endl << RotationR << std::endl;
// std::cout << "T:" << std::endl << TransMatrix << std::endl;
points_3d4.clear();
points_2d4.clear();
for (int ii = 0; ii < 4; ii++) {
num[ii] = point_number;
}
rr.at<double>(0) += Rod_r.at<double>(0);
rr.at<double>(1) += Rod_r.at<double>(1);
rr.at<double>(2) += Rod_r.at<double>(2);
trans.at<double>(0) += TransMatrix.at<double>(0);
trans.at<double>(1) += TransMatrix.at<double>(1);
trans.at<double>(2) += TransMatrix.at<double>(2);
}
rr.at<double>(0) = rr.at<double>(0) / 10.0;
rr.at<double>(1) = rr.at<double>(1) / 10.0;
rr.at<double>(2) = rr.at<double>(2) / 10.0;
trans.at<double>(0) = trans.at<double>(0) / 10.0;
trans.at<double>(1) = trans.at<double>(1) / 10.0;
trans.at<double>(2) = trans.at<double>(2) / 10.0;
cv::Rodrigues(rr, RotationR);
RotationR.copyTo(R);
trans.copyTo(T);
std::cout << "R:" << R << std::endl;
std::cout << "T:" << T << std::endl;
ofstream outfile;
outfile.open(save_path + "/test_result.txt");
outfile << R << endl;
outfile << T << endl;
outfile.close();
return 1;
}
void CHandler::recordPair(){
m_mtuPoint2d.lock();
points_2d.push_back(point_2d);
m_mtuPoint2d.unlock();
m_mtuPoint3d.lock();
points_3d.push_back(point_3d);
m_mtuPoint3d.unlock();
std::cout << "\033[32m******************************\033[0m"<<std::endl;
std::cout << "\033[32mrecord one pair\033[0m" << std::endl;
std::cout << "\033[32mnow has pair num: " << points_3d.size() << "\033[0m" << std::endl;
std::cout << "\033[32m******************************\033[0m"<<std::endl;
}
void CHandler::clearRecord(){
points_2d.clear();
points_3d.clear();
std::cout << "\033[32m******************************\033[0m"<<std::endl;
std::cout << "\033[32mclear finish\033[0m" << std::endl;
std::cout << "\033[32m******************************\033[0m"<<std::endl;
}
void CHandler::deleteLast(){
if(!(points_3d.size() > 0)){
std::cout << "\033[32m******************************\033[0m"<<std::endl;
std::cout << "\033[32mnow has no pair\033[0m" << std::endl;
std::cout << "\033[32m******************************\033[0m"<<std::endl;
return;
}
else{
points_3d.pop_back();
points_2d.pop_back();
std::cout << "\033[32m******************************\033[0m"<<std::endl;
std::cout << "\033[32mdelete one pair\033[0m" << std::endl;
std::cout << "\033[32mnow has pair num: " << points_3d.size() << "\033[0m" << std::endl;
std::cout << "\033[32m******************************\033[0m"<<std::endl;
return;
}
}
void CHandler::countTrans(){
if(points_2d.size() < 4){
std::cout << "\033[33mWarning: pair num < 4\033[0m" << std::endl;
return;
}
if(countRT() != 1){
std::cout << "\033[33mCount Error\033[0m" << std::endl;
return;
}
hasResult = true;
return;
}
void CHandler::showRecord(){
std::cout << "\033[32mnow has pair num: " << points_3d.size() << "\033[0m" << std::endl;
for(int i=0; i<points_3d.size(); i++){
std::cout << "\033[32m(" << points_3d[i].x << ", " << points_3d[i].y << ", " << points_3d[i].z << ") - (" << points_2d[i].x << ", " << points_2d[i].y << ")\033[0m" << std::endl;
}
return;
}
void CHandler::testResult(){
if(!hasResult){
std::cout << "\033[33mhas no result\033[0m" << std::endl;
return;
}
cv::Mat result_image;
Eigen::Matrix4f ET = Eigen::Matrix4f::Identity();
ET(0,0) = (float)R.at<double>(0, 0);
ET(0,1) = (float)R.at<double>(0, 1);
ET(0,2) = (float)R.at<double>(0, 2);
ET(1,0) = (float)R.at<double>(1, 0);
ET(1,1) = (float)R.at<double>(1, 1);
ET(1,2) = (float)R.at<double>(1, 2);
ET(2,0) = (float)R.at<double>(2, 0);
ET(2,1) = (float)R.at<double>(2, 1);
ET(2,2) = (float)R.at<double>(2, 2);
ET(0,3) = (float)T.at<double>(0);
ET(1,3) = (float)T.at<double>(1);
ET(2,3) = (float)T.at<double>(2);
ET(3,0) = 0.0;
ET(3,1) = 0.0;
ET(3,2) = 0.0;
ET(3,3) = 1.0;
// Eigen::Matrix3f K = Eigen::Matrix3f::Zero();
// K << 475.0, 0.0, 240.0, 0.0, 475.0, 151.0, 0.0, 0.0, 1.0;
project2image(m_pc, m_image, result_image, ET, K);
std::string image_name = "/test_result.png";
// std::string save_path = ros::package::getPath("lidar_camera_offline_calibration");
cv::imwrite(save_path+image_name, result_image);
std::cout << "\033[32mtest result has saved to " << save_path << "\033[0m" << std::endl;
return;
}
|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
using namespace std;
int calculate_bid(int player, int pos, int* first_moves, int* second_moves) {
int pBalance = 100, pPos = 0, draw = 1;
int bid;
// To check if bot is player 1 or 2
if (player != 1){
swap(first_moves, second_moves);
pPos = 10;
draw = 2;
}
// Calculate how much money left
for (int i = 0; i < 200; i++){
if (first_moves[i] == 0) break;//the bid can't be zero so if we got zero as a move we are out of input range (Optimization)
if (first_moves[i] > second_moves[i]){
pBalance -= first_moves[i];
}else if (first_moves[i] == second_moves[i]){
if (draw == 1){
pBalance -= *(first_moves + i);
draw = 2;
}
else{
draw = 1;
}
}
}
//Calculating the amount of bid the bot places in this current state
if (pBalance > 0){
int rPos;
rPos = 10 - abs(pPos - pos); //Calcaulating the dividing factor based on the distance between the bot's position and the scotch position. If the distance is low, then bid less.
bid = pBalance / rPos; //Bidding an amount based on remaining balance and the position factor.
if(bid <= 0){
bid = rand() % pBalance + 1;
}
}
else{
bid = 0;
}
return bid;
}
int main(void) {
int player; //1 if first player 2 if second
int scotch_pos; //position of the scotch
int bid, iter = 0; //Amount bid by the player
size_t buf_limit = 500;
char *first_move = (char *)malloc(buf_limit); //previous bids of the first player
char *second_move = (char *)malloc(buf_limit); //prevous bids of the second player
char remove_new_line[2];
int first_moves[200] = { 0 };
int second_moves[200] = { 0 };
char *tok_1, *tok_2;
srand(time(NULL));
cin >> player;
cin >> scotch_pos;
cin.getline(remove_new_line, 2); //removes a new line from the buffer
cin.getline(first_move, 200);
cin.getline(second_move, 200);
tok_1 = strtok(first_move, " ");
for (int i = 0; tok_1; i++) {
first_moves[i] = atoi(tok_1);
tok_1 = strtok(NULL, " ");
}
tok_2 = strtok(second_move, " ");
for (int i = 0; tok_2; i++) {
second_moves[i] = atoi(tok_2);
tok_2 = strtok(NULL, " ");
}
bid = calculate_bid(player, scotch_pos, first_moves, second_moves);
cout << bid;
return 0;
}
|
//===========================================================================
/*
This file is part of the CHAI 3D visualization and haptics libraries.
Copyright (C) 2003-2004 by CHAI 3D. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License("GPL") version 2
as published by the Free Software Foundation.
For using the CHAI 3D libraries with software that can not be combined
with the GNU GPL, and for taking advantage of the additional benefits
of our support services, please contact CHAI 3D about acquiring a
Professional Edition License.
\author: <http://www.chai3d.org>
\author: Chris Sewell
\version 1.0
\date 03/2005
*/
//===========================================================================
#if !defined(AFX_ACTIVE_XCTL_H__FDB105C0_4840_4D78_82CA_556C33490973__INCLUDED_)
#define AFX_ACTIVE_XCTL_H__FDB105C0_4840_4D78_82CA_556C33490973__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define _MSVC // compiler complains if this is not defined
#include <gl/gl.h>
#include "CWorld.h"
#include "CViewport.h"
#include "CGenericObject.h"
#include "CLight.h"
#include "CPhantom3dofPointer.h"
#include "CMeta3dofPointer.h"
#include "CPrecisionTimer.h"
// Active_xCtl.h : Declaration of the CActive_xCtrl ActiveX Control class.
/////////////////////////////////////////////////////////////////////////////
// CActive_xCtrl : See Active_xCtl.cpp for implementation.
class CActive_xCtrl : public COleControl
{
DECLARE_DYNCREATE(CActive_xCtrl)
// Constructor
public:
CActive_xCtrl();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CActive_xCtrl)
public:
virtual void OnDraw(CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid);
virtual void DoPropExchange(CPropExchange* pPX);
virtual void OnResetState();
//}}AFX_VIRTUAL
// Implementation
protected:
~CActive_xCtrl();
DECLARE_OLECREATE_EX(CActive_xCtrl) // Class factory and guid
DECLARE_OLETYPELIB(CActive_xCtrl) // GetTypeInfo
DECLARE_PROPPAGEIDS(CActive_xCtrl) // Property page IDs
DECLARE_OLECTLTYPE(CActive_xCtrl) // Type name and misc status
// Message maps
//{{AFX_MSG(CActive_xCtrl)
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
// Dispatch maps
//{{AFX_DISPATCH(CActive_xCtrl)
//}}AFX_DISPATCH
DECLARE_DISPATCH_MAP()
// Event maps
//{{AFX_EVENT(CActive_xCtrl)
//}}AFX_EVENT
DECLARE_EVENT_MAP()
// Dispatch and event IDs
public:
enum {
//{{AFX_DISP_ID(CActive_xCtrl)
//}}AFX_DISP_ID
};
// The interface to the haptic device
cGeneric3dofPointer *tool;
// The high-precision timer that's used (optionally) to run
// the haptic loop
//cPrecisionTimer timer;
// A flag that indicates whether haptics/graphics are currently enabled
int haptics_enabled;
int graphics_enabled;
// A flag that indicates whether the haptics thread is currently running
// This flag does not get set when the haptic callback is driven from a
// multimedia timer
int haptics_thread_running;
#define TOGGLE_HAPTICS_TOGGLE -1
#define TOGGLE_HAPTICS_DISABLE 0
#define TOGGLE_HAPTICS_ENABLE 1
// If the parameter is -1, haptics are toggled on/off
// If it's 0 haptics are turned off
// If it's 1 haptics are turned on
void toggle_haptics(int enable = TOGGLE_HAPTICS_TOGGLE);
// An object of some kind, to be rendered in the scene
cMesh* object;
cViewport* viewport;
cCamera* camera;
// virtual world
cWorld* world;
// Booleans indicating whether we're currently scrolling with
// the left and/or right mouse buttons
int m_left_scrolling_gl_area;
int m_right_scrolling_gl_area;
// The last point scrolled through by each mouse button,
// in _viewport_ coordinates (i.e. (0,0) is the top-left
// corner of the viewport area)
CPoint last_left_scroll_point;
CPoint last_right_scroll_point;
cVector3d original_point;
// The currently selected object (or zero when there's no selection)
cGenericObject* selected_object;
cVector3d obj_haptic_force;
// Handles mouse-scroll events (moves or rotates the selected object)
void scroll(CPoint p, int left_button = 1);
// Handles mouse clicks (marks the front-most clicked object as 'selected')
void select(CPoint p);
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_ACTIVE_XCTL_H__FDB105C0_4840_4D78_82CA_556C33490973__INCLUDED)
|
// FrequencyEdit
#include "FrequencyEdit.h"
// RsaToolbox
#include "General.h"
using namespace RsaToolbox;
// Qt
#include <QRegExp>
#include <QRegExpValidator>
#include <QKeyEvent>
#include <QDebug>
FrequencyEdit::FrequencyEdit(QWidget *parent) :
QLineEdit(parent),
_name("Value"),
_frequency_Hz(-1),
_isMinimum(true),
_isMaximum(true),
_minimum_Hz(1),
_maximum_Hz(1.0E12)
{
QRegExp regex("(([0-9]+\\.?[0-9]*)|(\\.0*[1-9]+0*))(\\s?[TGMK]?Hz)?", Qt::CaseInsensitive);
QRegExpValidator * validator = new QRegExpValidator(regex, this);
setValidator(validator);
connect(this, SIGNAL(returnPressed()),
this, SLOT(handleReturnPressed()));
}
FrequencyEdit::~FrequencyEdit()
{
}
// Public:
void FrequencyEdit::setParameterName(const QString &name) {
_name = name;
}
double FrequencyEdit::frequency_Hz() const {
return _frequency_Hz;
}
void FrequencyEdit::clearMinimum() {
_isMinimum = false;
_minimum_Hz = 1;
}
void FrequencyEdit::clearMaximum() {
_isMaximum = false;
_maximum_Hz = 1.0E12;
}
void FrequencyEdit::setMinimum(double frequency_Hz) {
clearAcceptedValues();
if (frequency_Hz < 1)
frequency_Hz = 1;
_isMinimum = true;
_minimum_Hz = frequency_Hz;
// Check for validity
if (!text().isEmpty())
setFrequency(_frequency_Hz);
}
void FrequencyEdit::setMinimum(double value, SiPrefix prefix) {
setMinimum(value * toDouble(prefix));
}
void FrequencyEdit::setMaximum(double frequency_Hz) {
clearAcceptedValues();
if (frequency_Hz < 1)
frequency_Hz = 1;
_isMaximum = true;
_maximum_Hz = frequency_Hz;
// Check for validity
if (!text().isEmpty())
setFrequency(_frequency_Hz);
}
void FrequencyEdit::setMaximum(double value, SiPrefix prefix) {
setMaximum(value * toDouble(prefix));
}
void FrequencyEdit::clearAcceptedValues() {
_acceptedValues_Hz.clear();
}
void FrequencyEdit::setAcceptedValues(const QRowVector &frequencies_Hz) {
clearMinimum();
clearMaximum();
_acceptedValues_Hz = frequencies_Hz;
for (int i = 0; i < _acceptedValues_Hz.size(); i++) {
if (_acceptedValues_Hz[i] < 0)
_acceptedValues_Hz.removeAt(i);
}
if (!text().isEmpty())
setFrequency(_frequency_Hz);
}
void FrequencyEdit::clearLimits() {
clearMinimum();
clearMaximum();
clearAcceptedValues();
}
// Slots:
void FrequencyEdit::setFrequency(double frequency_Hz) {
if (frequency_Hz < 1)
frequency_Hz = 1;
if (_isMinimum && frequency_Hz < _minimum_Hz)
frequency_Hz = _minimum_Hz;
if (_isMaximum && frequency_Hz > _maximum_Hz)
frequency_Hz = _maximum_Hz;
if (isAcceptedValues())
frequency_Hz = findClosest(frequency_Hz, _acceptedValues_Hz);
if (frequency_Hz == _frequency_Hz) {
updateText();
return;
}
_frequency_Hz = frequency_Hz;
updateText();
emit frequencyChanged(_frequency_Hz);
}
void FrequencyEdit::setFrequency(double value, SiPrefix prefix) {
const double frequency_Hz = value * toDouble(prefix);
setFrequency(frequency_Hz);
}
void FrequencyEdit::setText(const QString &text) {
QLineEdit::setText(text);
processText();
}
// Protected
void FrequencyEdit::keyPressEvent(QKeyEvent *event) {
Qt::Key key = Qt::Key(event->key());
if (key != Qt::Key_T
&& key != Qt::Key_G
&& key != Qt::Key_M
&& key != Qt::Key_K)
{
QLineEdit::keyPressEvent(event);
return;
}
event->accept();
SiPrefix prefix;
switch (key) {
case Qt::Key_T:
prefix = SiPrefix::Tera;
break;
case Qt::Key_G:
prefix = SiPrefix::Giga;
break;
case Qt::Key_M:
prefix = SiPrefix::Mega;
break;
case Qt::Key_K:
prefix = SiPrefix::Kilo;
break;
default:
prefix = SiPrefix::None;
}
QString text = this->text();
text = chopNonDigits(text);
updateText(text.toDouble() * toDouble(prefix));
processText();
selectAll();
}
void FrequencyEdit::focusInEvent(QFocusEvent *event) {
selectAll();
QLineEdit::focusInEvent(event);
}
void FrequencyEdit::focusOutEvent(QFocusEvent *event) {
processText();
QLineEdit::focusOutEvent(event);
}
// Private slots
void FrequencyEdit::handleReturnPressed() {
processText();
selectAll();
}
// Private
bool FrequencyEdit::containsT(const QString &text) {
return text.contains("T", Qt::CaseInsensitive);
}
bool FrequencyEdit::containsG(const QString &text) {
return text.contains("G", Qt::CaseInsensitive);
}
bool FrequencyEdit::containsM(const QString &text) {
return text.contains("M", Qt::CaseInsensitive);
}
bool FrequencyEdit::containsK(const QString &text) {
return text.contains("K", Qt::CaseInsensitive);
}
QString FrequencyEdit::chopNonDigits(QString text) {
int last = text.size() - 1;
while (!text.isEmpty() && !text[last].isDigit()) {
text.chop(1);
last = text.size() - 1;
}
return text;
}
void FrequencyEdit::updateText() {
updateText(_frequency_Hz);
}
void FrequencyEdit::updateText(const double &frequency_Hz) {
QString text = formatValue(frequency_Hz, 6, Units::Hertz);
bool isBlocked = blockSignals(true);
QLineEdit::setText(text);
blockSignals(isBlocked);
}
void FrequencyEdit::processText() {
QString text = this->text();
if (text.isEmpty() && _frequency_Hz == -1)
return;
SiPrefix prefix = SiPrefix::None;
if (containsT(text))
prefix = SiPrefix::Tera;
else if (containsG(text))
prefix = SiPrefix::Giga;
else if (containsM(text))
prefix = SiPrefix::Mega;
else if (containsK(text))
prefix = SiPrefix::Kilo;
// Apply prefix
text = chopNonDigits(text);
double frequency_Hz = text.toDouble() * toDouble(prefix);
// Round to acceptable value
if (_isMinimum && frequency_Hz < _minimum_Hz) {
QString name = _name;
if (name.isEmpty())
name = "Value";
QString msg = "*%1 must be at least %2";
msg = msg.arg(name);
msg = msg.arg(formatValue(_minimum_Hz, 3, Units::Hertz));
emit outOfRange(msg);
frequency_Hz = _minimum_Hz;
}
else if (_isMaximum && frequency_Hz > _maximum_Hz) {
QString name = _name;
if (name.isEmpty())
name = "Value";
QString msg = "*%1 must be at most %2";
msg = msg.arg(name);
msg = msg.arg(formatValue(_maximum_Hz, 3, Units::Hertz));
emit outOfRange(msg);
frequency_Hz = _maximum_Hz;
}
else if (isAcceptedValues() && !_acceptedValues_Hz.contains(frequency_Hz)) {
double newFrequency_Hz = findClosest(frequency_Hz, _acceptedValues_Hz);
if (newFrequency_Hz != frequency_Hz) {
QString msg = "*%1 Rounded to closest value: %2";
msg = msg.arg(formatValue(frequency_Hz, 3, Units::Hertz));
msg = msg.arg(formatValue(newFrequency_Hz, 3, Units::Hertz));
emit outOfRange(msg);
frequency_Hz = newFrequency_Hz;
}
}
// If value is unchanged, clean up
// display and return
if (frequency_Hz == _frequency_Hz) {
updateText();
return;
}
// Change value
_frequency_Hz = frequency_Hz;
updateText();
emit frequencyChanged(_frequency_Hz);
emit frequencyEdited(_frequency_Hz);
}
bool FrequencyEdit::isAcceptedValues() const {
return !_acceptedValues_Hz.isEmpty();
}
|
#include<stdio.h>
int a,s;
main()
{
scanf("%d",&a);
s=a*(a+1)*(2*a+1)/6;
printf("%d",s);
}
|
#pragma once
#include "ofMain.h"
#include "ofxEtherdream.h"
class testApp : public ofBaseApp{
enum DemoMode {
NONE = 0,
OSCILLATIONS,
DOODLES,
TEXT,
MILKYWAY
};
enum doodle {
EYE,
TRIANGLE
};
public:
void setup();
void update();
void draw();
void keyPressed (int key);
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void drawSomething(doodle d, ofPoint center, float scale, ofFloatColor c);
bool showHud;
float w,h;
DemoMode demo;
ofxIlda::Frame ildaFrame; // stores and manages ILDA frame drawings
ofxEtherdream etherdream; // interface to the etherdream device
};
|
#include "graphics.h"
#include "Button.h"
#include "Player.h"
#include <iostream>
#include <time.h>
#include <vector>
using namespace std;
GLdouble width, height;
bool rightRoomComplete = false;
int wd;
int counter = 0;
int expCounter = 0;
string userName;
Button spawn({1, 0, 0}, {250, 240}, 100, 50, userName);
Quad door1({0,0,1}, {0, 250}, 50, 100);
Quad door2({0,0,1}, {500, 250}, 50, 100);
Quad door3({0,0,1}, {250, 0}, 50, 100);
Quad door4({0,0,1}, {250, 500}, 50, 100);
Quad door5({0,0,1}, {250, 0}, 50, 100);
Quad door6({0,0,1}, {250, 500}, 50, 100);;//top2 bottom
Quad door7({0,0,1}, {250, 0}, 50, 100);//top2 top
Quad door8({0,0,1}, {0, 250}, 50, 100);//top2 left
Quad door9({0,0,1}, {500, 250}, 50, 100);//top2 right
Quad door10({0,0,1}, {0, 250}, 50, 100);//top2right left
Quad door11({0,0,1}, {500, 250}, 50, 100);//top2left right
Quad door12({0,0,1}, {250, 0}, 50, 100);//top2left top
Quad door13({0,0,1}, {250, 500}, 50, 100);//top3left bottom
Quad door14({0,0,1}, {500, 250}, 50, 100);//top3left right
Quad door15({0,0,1}, {0, 250}, 50, 100);//top3 left
Quad door16({0,0,1}, {250, 0}, 50, 100);//top3 top
Quad door17({0,0,1}, {500, 250}, 50, 100);//top3 right
Quad door18({0,0,1}, {0, 250}, 50, 100);//top3right left
Quad door19({0,0,1}, {500, 250}, 50, 100);//top3right right
Quad door20({0,0,1}, {0, 250}, 50, 100);//top3rightright left
Quad door21({0,0,1}, {250, 0}, 50, 100);//top3rightright top
Quad door22({0,0,1}, {250, 500}, 50, 100);//boss bottom
Quad door23({0,0,1}, {500, 250}, 50, 100);//boss left
Quad door24({0,0,1}, {0, 250}, 50, 100);//final right
Quad rightRoomObject ({0,.5,.5}, {250, 250}, 50, 50);
Quad leftRoomObject ({0,1,0}, {250, 250}, 50, 50);
Quad topRoomObject ({1,1,0}, {250, 250}, 50, 50);
Quad bottomRoomObject ({1,0,1}, {250, 250}, 50, 50);
Quad top2rightObject({1,1,1}, {250, 250}, 50, 50);
Quad top3rightObject({0.5,0,1}, {250, 250}, 50, 50);
//enemies
Quad rightEnemy({0,.5,.5}, {250, 250}, 50, 50);
Quad rightEnemyFight({0,.5,.5}, {150, 250}, 50, 50);
Quad topRoomEnemyQuad({0,1,0}, {100, 250}, 50, 50);
Quad topRoomEnemyFight({0,1,0}, {150, 250}, 50, 50);
Quad finalBossQuad({0,1,1}, {250, 250}, 100, 100);
Quad finalBossFight({0,1,1}, {150, 250}, 100, 100);
Quad top3EnemyOneQuad({.5,0,0}, {50,100}, 50, 50);
Quad top3EnemyOneFight({.5,0,0}, {150,250}, 50, 50);
Quad top3EnemyTwoQuad({1,1,0}, {250,100}, 50, 50);
Quad top3EnemyTwoFight({1,1,0}, {150,250}, 50, 50);
Quad exitDoor({0,1,1}, {250, 50}, 100, 100);
//battle graphics
Quad window1({1,1,1}, {250, 400},475, 175);
Quad window2({0,0,0}, {250, 400},450, 150);
Quad selector({1,1,1}, {375, 350},10, 10);
Quad seperator({1,1,1}, {375, 400},10, 150);
Quad playerHealth({0,1,0}, {430, 20},100, 10);
Quad enemyHealth({1,0,0}, {60, 20},100, 10);
Button button1({1,0,0}, {420, 350},50, 10, "");
Button button2({1,0,0}, {420, 380},50, 10, "");
Button button3({1,0,0}, {420, 410},50, 10, "");
// Player class
Player p;
Player enemyRightRoom(100, 5, 5, 1, 50);
Player enemyTopRoom(100, 5, 5, 1, 50);
Player finalBoss(250, 10, 10, 2, 100);
Player top3EnemyOne(150, 5, 5, 1, 50);
Player top3EnemyTwo(150, 5, 5, 1, 50);
string PlayerHealth;
string EnemyHealth;
vector<Quad> inventory;
enum screen {middle, leftSide, rightSide, top, bottom, endScreen, battleRight, top2, battleTop, top2right,
top2left, top3left, top3, top3right, top3rightright, bossroom, final, battleFinalBoss,
battletop3enemyone, battletop3enemytwo, winScreen, welcome};
screen currentScreen = welcome;
string endMessage = "You have been defeated...";
string secondEndMessage = "Game Over. Press 'Esc'";
string finalRoomMessage = "You found the exit to the dungeon. Go through it!";
string winMessage = "You escaped the dungeon!!!";
string youWin = "Press esc";
string hint2 = "I'm a potion! I heal 25 health! Press 'e' to pick me up. ";
string hint4 = "I'm also a potion. Press 'e' to pick me up!";
string inv = "Inventory: ";
string goal = "You are trapped in a dungeon, welcome to CubeQuest.";
string battleMessage = "A wild cube has appeared!";
string battleMessage2 = "What will you do?";
string battleMessage3 = "You have attacked!";
string rightRoomExperience = "You gained " + to_string(enemyRightRoom.getExperience())+ " experience!";
string bossRoomExperience = "You gained " + to_string(finalBoss.getExperience())+ " experience!";
string top3EnemyOneExperience = "You gained " + to_string(top3EnemyOne.getExperience())+ " experience!";
string top3EnemyTwoExperience = "You gained " + to_string(top3EnemyTwo.getExperience())+ " experience!";
string gameName = "CubeQuest";
string byline = "By: Josh Zuver and Donovan Lafontaine";
string gameStart = "Press 's' to start the game.";
string attack = "Attack";
string item = "Item";
string run = "Run";
bool playerIsAttacking = false;
bool enemyIsAttacking = false;
bool displayExpRightRoom = false;
bool displayExpTopRoom = false;
bool displayExpBossRoom = false;
bool displayExpTop3EnemyOne = false;
bool displayExpTop3EnemyTwo = false;
int numObjects = 0;
void init() {
width = 500;
height = 500;
srand(time(0));
}
/* Initialize OpenGL Graphics */
void initGL() {
// Set "clearing" or background color
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black and opaque
}
void displayWelcome() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glColor3f(1, 1, 1);
glRasterPos2i(50, 150);
for (const char &letter : gameName) {
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(50, 200);
for (const char &letter : byline) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(50, 200);
for (const char &letter : byline) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(0, 1, 0);
glRasterPos2i(50, 300);
for (const char &letter : gameStart) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glFlush(); // Render now
}
/* Handler for window-repaint event. Call back when the window first appears and
whenever the window needs to be re-painted. */
void displayMiddle() {
string objMessage = "Objects collected: " + to_string(numObjects);
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glColor3f(1, 1, 1);
glRasterPos2i(50, 350);
for (const char &letter : goal) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
door1.draw();
door2.draw();
door3.draw();
door4.draw();
// draw inventory
for(Quad &item : inventory){
item.draw();
}
glFlush(); // Render now
}
void displayBattleRight(){
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
spawn.draw();
rightEnemyFight.draw();
window1.draw();
window2.draw();
selector.draw();
button1.draw();
button2.draw();
button3.draw();
seperator.draw();
playerHealth.draw();
enemyHealth.draw();
// inventory
// draw inventory and message
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
for(Quad &item : inventory){
item.draw();
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 350);
for (const char &letter : attack) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 380);
for (const char &letter : item) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 410);
for (const char &letter : run) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
if(!playerIsAttacking) {
glColor3f(1, 1, 1);
glRasterPos2i(30, 350);
for (const char &letter : battleMessage) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(30, 370);
for (const char &letter : battleMessage2) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}else{
glColor3f(1, 1, 1);
glRasterPos2i(30, 350);
for (const char &letter : battleMessage3) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
PlayerHealth = "Player Health: " + to_string(p.getHealth());
EnemyHealth = "Enemy Health: " + to_string(enemyRightRoom.getHealth());
enemyHealth.resize(enemyRightRoom.getHealth(),10);
playerHealth.resize(p.getHealth(),10);
glColor3f(1, 1, 1);
glRasterPos2i(350, 10);
for (const char &letter : PlayerHealth) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(0, 10);
for (const char &letter : EnemyHealth) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
if(enemyRightRoom.getHealth() <= 0){
currentScreen = rightSide;
rightRoomComplete = true;
displayExpRightRoom = true;
}
glFlush();
}
void displayBattleTop(){
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
spawn.draw();
topRoomEnemyFight.draw();
window1.draw();
window2.draw();
selector.draw();
button1.draw();
button2.draw();
button3.draw();
seperator.draw();
playerHealth.draw();
enemyHealth.draw();
// inventory
// draw inventory and message
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
for(Quad &item : inventory){
item.draw();
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 350);
for (const char &letter : attack) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 380);
for (const char &letter : item) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 410);
for (const char &letter : run) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
if(!playerIsAttacking) {
glColor3f(1, 1, 1);
glRasterPos2i(30, 350);
for (const char &letter : battleMessage) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(30, 370);
for (const char &letter : battleMessage2) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
else{
glColor3f(1, 1, 1);
glRasterPos2i(30, 350);
for (const char &letter : battleMessage3) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
PlayerHealth = "Player Health: " + to_string(p.getHealth());
EnemyHealth = "Enemy Health: " + to_string(enemyTopRoom.getHealth());
enemyHealth.resize(enemyTopRoom.getHealth(),10);
playerHealth.resize(p.getHealth(),10);
glColor3f(1, 1, 1);
glRasterPos2i(350, 10);
for (const char &letter : PlayerHealth) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(0, 10);
for (const char &letter : EnemyHealth) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
if(enemyTopRoom.getHealth() <= 0){
currentScreen = top;
displayExpTopRoom = true;
}
glFlush();
}
void displayRight() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// draw
spawn.draw();
// inventory
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
for(Quad &item : inventory){
item.draw();
}
if(!rightRoomComplete){
rightEnemy.draw();
}
else if (displayExpRightRoom){
glColor3f(1, 1, 1);
glRasterPos2i(150, 150);
for (const char &letter : rightRoomExperience) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
door1.draw();
glFlush();
}
void displayLeft() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glColor3f(1, 1, 1);
glRasterPos2i(20, 350);
for (const char &letter : hint2) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw inventory and message
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
leftRoomObject.draw();
door2.draw();
for(Quad &item : inventory){
item.draw();
}
glFlush();
}
void displayTop() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//inventory display
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
//topRoomObject.draw();
door4.draw();
door5.draw();
if(enemyTopRoom.getHealth() > 0){
topRoomEnemyQuad.draw();
}
for(Quad &item : inventory){
item.draw();
}
if (displayExpTopRoom){
glColor3f(1, 1, 1);
glRasterPos2i(150, 150);
for (const char &letter : rightRoomExperience) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
glFlush();
}
void displayTop2() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//inventory display
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
door6.draw();
//door7.draw();
door8.draw();
door9.draw();
//topRoomObject.draw();
for(Quad &item : inventory){
item.draw();
}
glFlush();
}
void displayTop2Right() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//inventory display
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
door10.draw();
top2rightObject.draw();
//topRoomObject.draw();
for(Quad &item : inventory){
item.draw();
}
glFlush();
}
void displayTop2Left() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//inventory display
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
door11.draw();
door12.draw();
//topRoomObject.draw();
for(Quad &item : inventory){
item.draw();
}
glFlush();
}
void displayTop3Left() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//inventory display
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
door13.draw();
door14.draw();
if(top3EnemyOne.getHealth() > 0){
top3EnemyOneQuad.draw();
}
if(top3EnemyTwo.getHealth() > 0){
top3EnemyTwoQuad.draw();
}
for(Quad &item : inventory){
item.draw();
}
if (displayExpTop3EnemyOne){
glColor3f(1, 1, 1);
glRasterPos2i(150, 150);
for (const char &letter : top3EnemyOneExperience) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
if (displayExpTop3EnemyTwo){
glColor3f(1, 1, 1);
glRasterPos2i(150, 150);
for (const char &letter : top3EnemyTwoExperience) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
glFlush();
}
void displayTop3() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//inventory display
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
door15.draw();
//door16.draw();
door17.draw();
//topRoomObject.draw();
for(Quad &item : inventory){
item.draw();
}
glFlush();
}
void displayTop3Right() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//inventory display
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
door18.draw();
door19.draw();
top3rightObject.draw();
for(Quad &item : inventory){
item.draw();
}
glFlush();
}
void displayTop3RightRight() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//inventory display
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
door20.draw();
door21.draw();
//topRoomObject.draw();
for(Quad &item : inventory){
item.draw();
}
glFlush();
}
void displayBossRoom() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//inventory display
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
door22.draw();
door23.draw();
if(finalBoss.getHealth() > 0 ){
finalBossQuad.draw();
}
// display exp message upon fight completion
if (displayExpBossRoom){
glColor3f(1, 1, 1);
glRasterPos2i(150, 150);
for (const char &letter : bossRoomExperience) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
for(Quad &item : inventory){
item.draw();
}
glFlush();
}
void displayfinal() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//inventory display
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(50, 350);
for (const char &letter : finalRoomMessage) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
door24.draw();
exitDoor.draw();
//topRoomObject.draw();
for(Quad &item : inventory){
item.draw();
}
glFlush();
}
void displayBottom() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// display room hint and inventory message
glColor3f(1, 1, 1);
glRasterPos2i(100, 350);
for (const char &letter : hint4) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
// draw
spawn.draw();
bottomRoomObject.draw();
door3.draw();
for(Quad &item : inventory){
item.draw();
}
glFlush();
}
void displayEnd() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// display ending message
glColor3f(1, 1, 1);
glRasterPos2i(150, 150);
for (const char &letter : endMessage) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(150, 300);
for (const char &letter : secondEndMessage) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glFlush();
}
void displayWin() {
// tell OpenGL to use the whole window for drawing
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// display ending message
glColor3f(1, 1, 1);
glRasterPos2i(150, 150);
for (const char &letter : winMessage) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(150, 300);
for (const char &letter : youWin) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glFlush();
}
void displayBattleFinal(){
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
spawn.draw();
finalBossFight.draw();
window1.draw();
window2.draw();
selector.draw();
button1.draw();
button2.draw();
button3.draw();
seperator.draw();
playerHealth.draw();
enemyHealth.draw();
// inventory
// draw inventory and message
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
for(Quad &item : inventory){
item.draw();
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 350);
for (const char &letter : attack) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 380);
for (const char &letter : item) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 410);
for (const char &letter : run) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
if(!playerIsAttacking) {
glColor3f(1, 1, 1);
glRasterPos2i(30, 350);
for (const char &letter : battleMessage) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(30, 370);
for (const char &letter : battleMessage2) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}else{
glColor3f(1, 1, 1);
glRasterPos2i(30, 350);
for (const char &letter : battleMessage3) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
PlayerHealth = "Player Health: " + to_string(p.getHealth());
EnemyHealth = "Enemy Health: " + to_string(finalBoss.getHealth());
enemyHealth.resize(finalBoss.getHealth(),10);
playerHealth.resize(p.getHealth(),10);
glColor3f(1, 1, 1);
glRasterPos2i(350, 10);
for (const char &letter : PlayerHealth) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(0, 10);
for (const char &letter : EnemyHealth) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
if(finalBoss.getHealth() <= 0){
currentScreen = bossroom;
displayExpBossRoom = true;
}
glFlush();
}
void displayBattleTop3One(){
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
spawn.draw();
top3EnemyOneFight.draw();
window1.draw();
window2.draw();
selector.draw();
button1.draw();
button2.draw();
button3.draw();
seperator.draw();
playerHealth.draw();
enemyHealth.draw();
// inventory
// draw inventory and message
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
for(Quad &item : inventory){
item.draw();
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 350);
for (const char &letter : attack) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 380);
for (const char &letter : item) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 410);
for (const char &letter : run) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
if(!playerIsAttacking) {
glColor3f(1, 1, 1);
glRasterPos2i(30, 350);
for (const char &letter : battleMessage) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(30, 370);
for (const char &letter : battleMessage2) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}else{
glColor3f(1, 1, 1);
glRasterPos2i(30, 350);
for (const char &letter : battleMessage3) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
PlayerHealth = "Player Health: " + to_string(p.getHealth());
EnemyHealth = "Enemy Health: " + to_string(top3EnemyOne.getHealth());
enemyHealth.resize(top3EnemyOne.getHealth(),10);
playerHealth.resize(p.getHealth(),10);
glColor3f(1, 1, 1);
glRasterPos2i(350, 10);
for (const char &letter : PlayerHealth) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(0, 10);
for (const char &letter : EnemyHealth) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
if(top3EnemyOne.getHealth() <= 0){
currentScreen = top3left;
displayExpTop3EnemyOne = true;
}
glFlush();
}
void displayBattleTop3Two(){
glViewport(0, 0, width, height);
// do an orthographic parallel projection with the coordinate
// system set to first quadrant, limited by screen/window size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, -1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
spawn.draw();
top3EnemyTwoFight.draw();
window1.draw();
window2.draw();
selector.draw();
button1.draw();
button2.draw();
button3.draw();
seperator.draw();
playerHealth.draw();
enemyHealth.draw();
// inventory
// draw inventory and message
glColor3f(1, 1, 1);
glRasterPos2i(28, 470);
for (const char &letter : inv) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
for(Quad &item : inventory){
item.draw();
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 350);
for (const char &letter : attack) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 380);
for (const char &letter : item) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(400, 410);
for (const char &letter : run) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
if(!playerIsAttacking) {
glColor3f(1, 1, 1);
glRasterPos2i(30, 350);
for (const char &letter : battleMessage) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(30, 370);
for (const char &letter : battleMessage2) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}else{
glColor3f(1, 1, 1);
glRasterPos2i(30, 350);
for (const char &letter : battleMessage3) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
}
PlayerHealth = "Player Health: " + to_string(p.getHealth());
EnemyHealth = "Enemy Health: " + to_string(top3EnemyTwo.getHealth());
enemyHealth.resize(top3EnemyTwo.getHealth(),10);
playerHealth.resize(p.getHealth(),10);
glColor3f(1, 1, 1);
glRasterPos2i(350, 10);
for (const char &letter : PlayerHealth) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
glColor3f(1, 1, 1);
glRasterPos2i(0, 10);
for (const char &letter : EnemyHealth) {
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter);
}
if(top3EnemyTwo.getHealth() <= 0){
currentScreen = top3left;
displayExpTop3EnemyTwo = true;
}
glFlush();
}
void kbd(unsigned char key, int x, int y) {
// escape
if (key == 27) {
glutDestroyWindow(wd);
exit(0);
}
// logic for picking up items
if(key == 'e'){
if(rightRoomObject.isOverlapping(spawn) && currentScreen == rightSide){
rightRoomObject.setColor(0,0,0);
rightRoomObject.resize(1,1);
// add small version of item to inventory
inventory.push_back(Quad({0,.5,.5}, {110, 485}, 10, 10));
++numObjects;
}
else if(leftRoomObject.isOverlapping(spawn) && currentScreen == leftSide){
leftRoomObject.setColor(0,0,0);
leftRoomObject.resize(1,1);
// add small version of item to inventory
inventory.push_back(Quad({0,1,0}, {120, 466}, 10, 10));
++numObjects;
}
else if(bottomRoomObject.isOverlapping(spawn) && currentScreen == bottom){
bottomRoomObject.setColor(0,0,0);
bottomRoomObject.resize(1,1);
// add small version of item to inventory
inventory.push_back(Quad({1,0,1}, {140, 466}, 10, 10));
++numObjects;
}
else if(topRoomObject.isOverlapping(spawn) && currentScreen == top){
topRoomObject.setColor(0,0,0);
topRoomObject.resize(1,1);
// add small version of item to inventory
inventory.push_back(Quad({1,1,0}, {160, 466}, 10, 10));
++numObjects;
}
else if(top2rightObject.isOverlapping(spawn) && currentScreen == top2right){
top2rightObject.setColor(0,0,0);
top2rightObject.resize(1,1);
// add small version of item to inventory
inventory.push_back(Quad({1,1,1}, {180, 466}, 10, 10));
++numObjects;
}
else if(top3rightObject.isOverlapping(spawn) && currentScreen == top3right){
top3rightObject.setColor(0,0,0);
top3rightObject.resize(1,1);
// add small version of item to inventory
inventory.push_back(Quad({0.5,0,1}, {200, 466}, 10, 10));
++numObjects;
}
}
if(key == 'b'){
if(rightEnemy.isOverlapping(spawn) && currentScreen == rightSide){
currentScreen = battleRight;
spawn.move(100,0);
}
else if (topRoomEnemyQuad.isOverlapping(spawn) && currentScreen == top){
currentScreen = battleTop;
spawn.move(100,0);
}
else if(finalBossQuad.isOverlapping(spawn) && currentScreen == bossroom){
currentScreen = battleFinalBoss;
spawn.move(100, 20);
}
else if(top3EnemyOneQuad.isOverlapping(spawn) && currentScreen == top3left){
currentScreen = battletop3enemyone;
spawn.move(100, -20);
}
else if(top3EnemyTwoQuad.isOverlapping(spawn) && currentScreen == top3left){
currentScreen = battletop3enemytwo;
spawn.move(100, -20);
}
}
if(key == 's' && (currentScreen == welcome)){
currentScreen = middle;
}
if(key == 'i'){
const string python = "python";
string command = python + " ../display.py " + std::to_string(p.getAttackPower()) + " " + std::to_string(p.getDefensePower()) + " " + std::to_string(p.getExperience()) + " " + std::to_string(p.getHealth());
system(command.c_str());
}
glutPostRedisplay();
}
void kbdS(int key, int x, int y) {
switch(key) {
case GLUT_KEY_DOWN:
spawn.move(0, 20);
break;
case GLUT_KEY_LEFT:
spawn.move(-20,0);
break;
case GLUT_KEY_RIGHT:
spawn.move(20, 0);
break;
case GLUT_KEY_UP:
spawn.move(0, -20);
break;
}
glutPostRedisplay();
}
void cursor(int x, int y) {
if(button1.isOverlapping(x,y))
{
button1.hover();
}else{
button1.release();
}
if(button2.isOverlapping(x,y))
{
button2.hover();
}else{
button2.release();
}
if(button3.isOverlapping(x,y))
{
button3.hover();
}else{
button3.release();
}
glutPostRedisplay();
}
void mouse(int button, int state, int x, int y) {
// for right room enemy battle
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && button1.isOverlapping(x,y) && currentScreen == battleRight &&
!playerIsAttacking) {
p.attack(enemyRightRoom);
playerIsAttacking = true;
}
// for top room enemy battle
else if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && button1.isOverlapping(x,y) && currentScreen == battleTop &&
!playerIsAttacking) {
p.attack(enemyTopRoom);
playerIsAttacking = true;
}
else if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && button1.isOverlapping(x,y) && currentScreen == battleFinalBoss &&
!playerIsAttacking) {
p.attack(finalBoss);
playerIsAttacking = true;
}
else if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && button1.isOverlapping(x,y) && currentScreen == battletop3enemyone &&
!playerIsAttacking) {
p.attack(top3EnemyOne);
playerIsAttacking = true;
}
else if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && button1.isOverlapping(x,y) && currentScreen == battletop3enemytwo &&
!playerIsAttacking) {
p.attack(top3EnemyTwo);
playerIsAttacking = true;
}
// potions usage
else if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && button2.isOverlapping(x,y)) {
if(inventory.size() > 0){
p.setHealth(p.getHealth() + 25);
inventory.pop_back();
}
}
// run
else if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && button3.isOverlapping(x,y)) {
currentScreen = middle;
spawn.move(-170, 0);
}
glutPostRedisplay();
}
void timer(int dummy) {
// logic to allow enemies to patrol
if(dummy < 100){
rightEnemy.move(0, 1);
topRoomEnemyQuad.move(0, 1);
finalBossQuad.move(1, 0);
top3EnemyOneQuad.move(1,1);
top3EnemyTwoQuad.move(0,2);
}
else if(dummy > 100 && dummy < 200){
rightEnemy.move(0, -1);
topRoomEnemyQuad.move(0, -1);
finalBossQuad.move(-1, 0);
top3EnemyOneQuad.move(-1,-1);
top3EnemyTwoQuad.move(0,-2);
}
else if (dummy > 200){
dummy = 0;
}
dummy++;
// logic to allow for pause between enemy attacking and greyed out attack
if(playerIsAttacking){
counter++;
button1.setColor(128.0/255,128.0/255,128.0/255);
rightEnemyFight.setColor({0,.25,.25});
topRoomEnemyFight.setColor({0,.5,0});
finalBossFight.setColor({0,.5,.5});
top3EnemyOneFight.setColor({.25,0,0});
top3EnemyTwoFight.setColor({.5,.5,0});
if (counter > 50){
button1.setColor(1,0,0);
rightEnemyFight.setColor({0,.5,.5});
topRoomEnemyFight.setColor({0,1,0});
finalBossFight.setColor({0,1,1});
top3EnemyOneFight.setColor({.5,0,0});
top3EnemyTwoFight.setColor({1,1,0});
enemyRightRoom.attack(p);
playerIsAttacking = false;
counter = 0;
}
}
// logic for displaying experience from right room enemy experience
if(displayExpRightRoom){
expCounter++;
if(expCounter > 100){
displayExpRightRoom = false;
expCounter = 0;
}
}
else if(displayExpTopRoom){
expCounter++;
if(expCounter > 100){
displayExpTopRoom = false;
expCounter = 0;
}
}
else if(displayExpBossRoom){
expCounter++;
if(expCounter > 100){
displayExpBossRoom = false;
expCounter = 0;
}
}
else if(displayExpTop3EnemyOne){
expCounter++;
if(expCounter > 100){
displayExpTop3EnemyOne = false;
expCounter = 0;
}
}
else if(displayExpTop3EnemyTwo){
expCounter++;
if(expCounter > 100){
displayExpTop3EnemyTwo = false;
expCounter = 0;
}
}
// logic for going between rooms
if (currentScreen == middle && spawn.Quad::isOverlapping(door2)) {
currentScreen = rightSide;
spawn.move(-450, 0);
}
else if (currentScreen == leftSide && spawn.Quad::isOverlapping(door2)){
currentScreen = middle;
spawn.move(-450, 0);
}
else if (currentScreen == middle && spawn.Quad::isOverlapping(door1)){
currentScreen = leftSide;
spawn.move(450, 0);
}
else if(currentScreen == rightSide && spawn.Quad::isOverlapping(door1)){
currentScreen = middle;
spawn.move(450, 0);
}
else if (currentScreen == middle && door3.isOverlapping(spawn)){
currentScreen = top;
spawn.move(0, 350);
}
else if (currentScreen == top && door4.isOverlapping(spawn)){
currentScreen = middle;
spawn.move(0, -350);
}
else if (currentScreen == middle && door4.isOverlapping(spawn)){
currentScreen = bottom;
spawn.move(0, -350);
}
else if (currentScreen == bottom && door3.isOverlapping(spawn)){
currentScreen = middle;
spawn.move(0, 350);
}
else if (currentScreen == top && door5.isOverlapping(spawn)){
currentScreen = top2;
spawn.move(0, 350);
}
else if (currentScreen == top2 && door6.isOverlapping(spawn)){
currentScreen = top;
spawn.move(0, -350);
}
else if (currentScreen == top2 && spawn.Quad::isOverlapping(door9)){
currentScreen = top2right;
spawn.move(-450, 0);
}
else if (currentScreen == top2right && spawn.Quad::isOverlapping(door10)){
currentScreen = top2;
spawn.move(450, 0);
}
else if (currentScreen == top2 && spawn.Quad::isOverlapping(door8)){
currentScreen = top2left;
spawn.move(450, 0);
}
else if (currentScreen == top2left && spawn.Quad::isOverlapping(door11)){
currentScreen = top2;
spawn.move(-450, 0);
}
else if (currentScreen == top2left && door12.isOverlapping(spawn)){
currentScreen = top3left;
spawn.move(0, 350);
}
else if (currentScreen == top3left && door13.isOverlapping(spawn)){
currentScreen = top2left;
spawn.move(0, -350);
}
else if (currentScreen == top3left && spawn.Quad::isOverlapping(door14)){
currentScreen = top3;
spawn.move(-450, 0);
}
else if (currentScreen == top3 && spawn.Quad::isOverlapping(door15)){
currentScreen = top3left;
spawn.move(450, 0);
}
else if (currentScreen == top3 && spawn.Quad::isOverlapping(door17)){
currentScreen = top3right;
spawn.move(-450, 0);
}
else if (currentScreen == top3right && spawn.Quad::isOverlapping(door18)){
currentScreen = top3;
spawn.move(450, 0);
}
else if (currentScreen == top3right && spawn.Quad::isOverlapping(door19)){
currentScreen = top3rightright;
spawn.move(-450, 0);
}
else if (currentScreen == top3rightright && spawn.Quad::isOverlapping(door20)){
currentScreen = top3right;
spawn.move(450, 0);
}
else if (currentScreen == top3rightright && door21.isOverlapping(spawn)){
currentScreen = bossroom;
spawn.move(0, 350);
}
else if (currentScreen == bossroom && door22.Quad::isOverlapping(spawn)){
currentScreen = top3rightright;
spawn.move(0, -350);
}
else if (currentScreen == bossroom && spawn.Quad::isOverlapping(door23) && finalBoss.getHealth() <= 0){
currentScreen = final;
spawn.move(-450, 0);
}
else if (currentScreen == final && spawn.Quad::isOverlapping(door24)){
currentScreen = bossroom;
spawn.move(450, 0);
}
else if (currentScreen == final && exitDoor.Quad::isOverlapping(spawn)){
currentScreen = winScreen;
}
else if(p.getHealth() == 0){
currentScreen = endScreen;
}
// display appropriate screen
if (currentScreen == middle) {
glutDisplayFunc(displayMiddle);
}
else if(currentScreen == rightSide){
glutDisplayFunc(displayRight);
}
else if(currentScreen == leftSide){
glutDisplayFunc(displayLeft);
}
else if(currentScreen == top){
glutDisplayFunc(displayTop);
}
else if(currentScreen == bottom){
glutDisplayFunc(displayBottom);
}
else if(currentScreen == battleRight){
glutDisplayFunc(displayBattleRight);
}
else if(currentScreen == battleTop){
glutDisplayFunc(displayBattleTop);
}
else if(currentScreen == top2){
glutDisplayFunc(displayTop2);
}
else if(currentScreen == top2right){
glutDisplayFunc(displayTop2Right);
}
else if(currentScreen == top2left){
glutDisplayFunc(displayTop2Left);
}
else if(currentScreen == top3left){
glutDisplayFunc(displayTop3Left);
}
else if(currentScreen == top3){
glutDisplayFunc(displayTop3);
}
else if(currentScreen == top3right){
glutDisplayFunc(displayTop3Right);
}
else if(currentScreen == top3rightright){
glutDisplayFunc(displayTop3RightRight);
}
else if(currentScreen == bossroom){
glutDisplayFunc(displayBossRoom);
}
else if(currentScreen == final){
glutDisplayFunc(displayfinal);
}
else if(currentScreen == endScreen){
glutDisplayFunc(displayEnd);
}
else if(currentScreen == battleFinalBoss){
glutDisplayFunc(displayBattleFinal);
}
else if(currentScreen == battletop3enemyone){
glutDisplayFunc(displayBattleTop3One);
}
else if(currentScreen == battletop3enemytwo){
glutDisplayFunc(displayBattleTop3Two);
}
else if(currentScreen == winScreen){
glutDisplayFunc(displayWin);
}
else if(currentScreen == welcome){
glutDisplayFunc(displayWelcome);
}
glutPostRedisplay();
glutTimerFunc(30, timer, dummy);
}
int main(int argc, char** argv) {
// get name from user, validate input
cout << "Please enter your character name: ";
while((!(cin >> userName)) || userName.length() > 8){
cout << "Invalid input. Please enter a name that is <= 8 characters. \n";
cin.clear();
string junk;
getline(cin, junk);
}
spawn.setLabel(userName);
init();
glutInit(&argc, argv); // Initialize GLUT
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowSize((int)width, (int)height);
glutInitWindowPosition(100, 200); // Position the window's initial top-left corner
wd = glutCreateWindow("CubeQuest - By Josh Zuver and Donovan Lafontaine" /* title */ );
glutDisplayFunc(displayMiddle);
// Our own OpenGL initialization
initGL();
// register keyboard press event processing function
// works for numbers, letters, spacebar, etc.
glutKeyboardFunc(kbd);
// register special event: function keys, arrows, etc.
glutSpecialFunc(kbdS);
// handles mouse movement
glutPassiveMotionFunc(cursor);
// handles mouse click
glutMouseFunc(mouse);
// handles timer
glutTimerFunc(0, timer, 0);
// Enter the event-processing loop
glutMainLoop();
return 0;
}
|
// 问题的描述:拓扑结构相同子树
// 给定一个两棵二叉树,判断树A中是否存在一棵子树与B树的拓扑结构完全相同
// 普通解法:二叉树遍历 + 匹配 O(M * N)
// 最优解法:二叉树序列化 + KMP算法(判断A序列中是否包含B序列) O(M * N)
// 测试用例有3组:
// 1、空树
// 输入:nullptr; nullptr
// 输出:false
// 2、包含相同拓扑结构的子树
// 输入:
// 1 2
// / \ / \
// 2 3 4 5
// / \
// 4 5
// 输出:true
// 3、不包含相同拓扑结构的子树
// 输入:
// 1 2
// / \ /
// 2 3 4
// / \
// 4 5
// 输出:false
#include <iostream>
#include <vector>
#include <queue>
#include <string>
using namespace std;
// 树结点的定义
struct Node {
int data;
struct Node* lchild;
struct Node* rchild;
};
/*
// 普通解法:二叉树遍历 + 匹配
// 将结点按照层序遍历的方式保存在vector中,便于后面进行比较
void SaveNodeToVector(Node* root, vector<Node*> &vec) {
if (root == nullptr)
return;
queue<Node*> node_queue;
node_queue.push(root);
Node* node = nullptr;
while (!node_queue.empty()) {
node = node_queue.front();
node_queue.pop();
vec.push_back(node);
if (node->lchild != nullptr)
node_queue.push(node->lchild);
else
vec.push_back(nullptr);
if (node->rchild != nullptr)
node_queue.push(node->rchild);
else
vec.push_back(nullptr);
}
}
// 匹配比较函数,对满足条件的两棵子树进行比较
bool CompareTopology(Node* root1, vector<Node*> &root2_vector) {
if (root1 == nullptr || root2_vector.empty())
return false;
// 先将树2的结点以层序遍历的方式都保存在vector中
vector<Node*> root1_vector;
SaveNodeToVector(root1, root1_vector);
if (root1_vector.size() != root2_vector.size())
return false;
// 遍历vector,进行比较
for (int i = 0; i < root1_vector.size(); ++i) {
// 树1和树2结点均为空直接跳过
if (root1_vector[i] == nullptr && root2_vector[i] == nullptr)
continue;
// 树1和树2结点均不为空进行比较
else if (root1_vector[i] != nullptr && root2_vector[i] != nullptr) {
if (root1_vector[i]->data != root2_vector[i]->data)
return false;
}
// 树1和树2结点只有一个为空直接返回false
else
return false;
}
return true;
}
// 对两棵树进行比较判断
bool CheckSameTopology(Node* root1, Node* root2) {
if (root1 == nullptr || root2 == nullptr)
return false;
// 先将树2的结点以层序遍历的方式都保存在vector中,等下直接比较
vector<Node*> root2_vector;
SaveNodeToVector(root2, root2_vector);
// 遍历树1,找到结点值与树2根结点值相同的结点,进行匹配比较
bool flag = false;
queue<Node*> node_queue;
node_queue.push(root1);
Node* node = nullptr;
while (!node_queue.empty()) {
node = node_queue.front();
node_queue.pop();
if (node->data == root2->data)
flag = CompareTopology(node, root2_vector);
if (flag)
return true;
if (node->lchild != nullptr)
node_queue.push(node->lchild);
if (node->rchild != nullptr)
node_queue.push(node->rchild);
}
return false;
}
*/
// 最优解法:二叉树序列化 + KMP算法
// 前序遍历的序列化,根据一颗二叉树生成字符串
string SerializationByPreorder(Node* root) {
if (root == nullptr)
return "#!";
string sequence = to_string(root->data) + '!';
sequence += SerializationByPreorder(root->lchild);
sequence += SerializationByPreorder(root->rchild);
return sequence;
}
// 判断树2的序列化结果是否在树1的序列化结果中
bool CheckSameTopology(Node* root1, Node* root2) {
if (root1 == nullptr || root2 == nullptr)
return false;
// 对两棵树进行序列化
string tree1 = SerializationByPreorder(root1);
string tree2 = SerializationByPreorder(root2);
// 查找tree2是否在tree1中
if (tree1.find(tree2) != string::npos)
return true;
else
return false;
}
// 前序遍历的反序列化,根据序列构建一颗二叉树
Node* HelpDeserialization(queue<string> &values) {
string value = values.front();
values.pop();
if (value == "#")
return nullptr;
Node* root = new Node();
root->data = stoi(value);
root->lchild = HelpDeserialization(values);
root->rchild = HelpDeserialization(values);
return root;
}
Node* DeserializationByPreorder(const string &sequence) {
if (sequence.empty() || (sequence == "#!"))
return nullptr;
// 从sequence中提取出来每一个值,放在queue中
string temp_sequence = sequence;
queue<string> values;
string::size_type pos = 0;
while (!temp_sequence.empty()) {
pos = temp_sequence.find('!');
if (pos == string::npos)
break;
values.push(temp_sequence.substr(0, pos));
temp_sequence = temp_sequence.substr(pos + 1);
}
return HelpDeserialization(values);
}
// 清理前序遍历生成的二叉树结点
void FreeNodeByPreorder(Node* root) {
if (root == nullptr)
return;
FreeNodeByPreorder(root->lchild);
FreeNodeByPreorder(root->rchild);
delete root;
root = nullptr;
}
int main() {
// 空树
// string sequence1 = "#!";
// string sequence2 = "#!";
// 包含相同拓扑结构的子树
// string sequence1 = "1!2!4!#!#!5!#!#!3!#!#!";
// string sequence2 = "2!4!#!#!5!#!#!";
// 不包含相同拓扑结构的子树
string sequence1 = "1!2!4!#!#!5!#!#!3!#!#!";
string sequence2 = "2!4!#!#!#!";
Node* root1 = DeserializationByPreorder(sequence1);
Node* root2 = DeserializationByPreorder(sequence2);
if (CheckSameTopology(root1, root2))
cout << "true" << endl;
else
cout << "false" << endl;
FreeNodeByPreorder(root1);
FreeNodeByPreorder(root2);
system("pause");
return 0;
}
|
#include "utils/service_thread.hpp"
#include "utils/exception.hpp"
#include <cppunit/extensions/HelperMacros.h>
#include <condition_variable>
using namespace chrono;
namespace nora {
namespace test {
class service_thread_test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(service_thread_test);
CPPUNIT_TEST(test_add_timer_by_tp);
CPPUNIT_TEST(test_add_timer_by_du);
CPPUNIT_TEST(test_async_call);
CPPUNIT_TEST(test_multi_async_call_line_up);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() override;
void tearDown() override;
void test_add_timer_by_tp();
void test_add_timer_by_du();
void test_async_call();
void test_multi_async_call_line_up();
private:
shared_ptr<service_thread> st_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(service_thread_test);
void service_thread_test::setUp() {
st_ = make_shared<service_thread>("servicethreadtest");
st_->start();
}
void service_thread_test::tearDown() {
st_->stop();
st_.reset();
}
void service_thread_test::test_add_timer_by_tp() {
mutex m;
condition_variable cv;
auto tp = system_clock::now() + 30ms;
system_clock::time_point expired_tp;
ADD_TIMER(
st_,
([&m, &cv, &expired_tp] (auto canceled, const auto& timer) {
if (!canceled) {
{
lock_guard<mutex> lk(m);
expired_tp = system_clock::now();
}
cv.notify_one();
}
}),
tp);
unique_lock<mutex> lk(m);
cv.wait(lk, [&expired_tp] { return expired_tp != system_clock::time_point(); });
auto error = duration_cast<milliseconds>(expired_tp - tp).count();
CPPUNIT_ASSERT(error < 20);
}
void service_thread_test::test_add_timer_by_du() {
mutex m;
condition_variable cv;
auto start_tp = system_clock::now();
milliseconds expired_du(0);
auto du = 25ms;
ADD_TIMER(
st_,
([&m, &cv, &expired_du, start_tp = start_tp] (auto canceled, const auto& timer) {
if (!canceled) {
{
lock_guard<mutex> lk(m);
expired_du = duration_cast<milliseconds>(system_clock::now() - start_tp);
}
cv.notify_one();
}
}),
du);
unique_lock<mutex> lk(m);
cv.wait(lk, [&expired_du] { return expired_du != 0ms; });
if (expired_du > du) {
CPPUNIT_ASSERT(expired_du - du < 20ms);
} else {
CPPUNIT_ASSERT(du - expired_du < 20ms);
}
}
void service_thread_test::test_async_call() {
mutex m;
condition_variable cv;
thread::id called_thread_id;
st_->async_call(
[&called_thread_id, &cv, &m] () {
{
lock_guard<mutex> lk(m);
called_thread_id = this_thread::get_id();
}
cv.notify_one();
});
unique_lock<mutex> lk(m);
cv.wait(lk, [&called_thread_id] { return called_thread_id != thread::id(); });
CPPUNIT_ASSERT(called_thread_id != this_thread::get_id());
CPPUNIT_ASSERT(called_thread_id == st_->get_thread_id());
}
void service_thread_test::test_multi_async_call_line_up() {
mutex m;
condition_variable cv;
bool done = false;
vector<int> v;
for (int i = 0; i < 100; ++i) {
st_->async_call(
[&v, i] {
v.push_back(i);
});
}
st_->async_call(
[&m, &cv, &done] {
{
lock_guard<mutex> lk(m);
done = true;
}
cv.notify_one();
});
unique_lock<mutex> lk(m);
cv.wait(lk, [&done] { return done; });
CPPUNIT_ASSERT_EQUAL(100ul, v.size());
for (size_t i = 0; i < v.size(); ++i) {
CPPUNIT_ASSERT_EQUAL((int)i, v.at(i));
}
}
}
}
|
#include <souistd.h>
#include <core/SScrollBarHandler.h>
namespace SOUI
{
SScrollBarHandler::SScrollBarHandler(IScrollBarHost *pCB, bool bVert)
:m_bVert(bVert)
,m_pSbHost(pCB)
, m_iFrame(0)
, m_fadeMode(FADE_STOP)
, m_iHitPart(-1)
, m_iClickPart(-1)
, m_nClickPos(-1)
{
SASSERT(m_pSbHost);
}
void SScrollBarHandler::SetVertical(bool bVert)
{
m_bVert = bVert;
}
void SScrollBarHandler::OnNextFrame()
{
SASSERT(m_fadeMode != FADE_STOP);
if (m_iFrame>0 && m_iFrame < m_pSbHost->GetScrollFadeFrames())
{
m_iFrame += GetFadeStep();
m_pSbHost->OnScrollUpdatePart(m_bVert, -1);
}
else
{
m_fadeMode = FADE_STOP;
GetContainer()->UnregisterTimelineHandler(this);
}
}
CRect SScrollBarHandler::GetPartRect(int iPart) const
{
SASSERT(m_pSbHost->GetScrollBarSkin(m_bVert));
const SCROLLINFO * pSi = m_pSbHost->GetScrollBarInfo(m_bVert);
__int64 nTrackPos=pSi->nTrackPos;
int nMax=pSi->nMax;
if(nMax<pSi->nMin+(int)pSi->nPage-1) nMax=pSi->nMin+pSi->nPage-1;
if(nTrackPos==-1)
nTrackPos=pSi->nPos;
CRect rcAll = m_pSbHost->GetScrollBarRect(m_bVert);
int nLength=(IsVertical()?rcAll.Height():rcAll.Width());
if(nLength<=0)
return CRect();
int nArrowHei=m_pSbHost->GetScrollBarArrowSize(m_bVert);
int nInterHei=nLength-2*nArrowHei;
if(nInterHei<0)
nInterHei=0;
int nSlideHei=pSi->nPage*nInterHei/(nMax-pSi->nMin+1);
if(nMax==(int)(pSi->nMin+pSi->nPage-1))
nSlideHei=nInterHei;
if(nSlideHei<THUMB_MINSIZE)
nSlideHei=THUMB_MINSIZE;
if(nInterHei<THUMB_MINSIZE)
nSlideHei=0;
int nEmptyHei=nInterHei-nSlideHei;
if(nInterHei==0)
nArrowHei=nLength/2;
CRect rcRet(0,0,rcAll.Width(),nArrowHei);
if (iPart == kSbRail)
{
rcRet = CRect(0,0, rcAll.Width(), nLength);
rcRet.DeflateRect(0,nArrowHei);
goto end;
}
if(iPart==SB_LINEUP) goto end;
rcRet.top=rcRet.bottom;
if((pSi->nMax-pSi->nMin-pSi->nPage+1)==0)
rcRet.bottom+=nEmptyHei/2;
else
rcRet.bottom+=(int)(nEmptyHei*nTrackPos/(pSi->nMax-pSi->nMin-pSi->nPage+1));
if(iPart==SB_PAGEUP) goto end;
rcRet.top=rcRet.bottom;
rcRet.bottom+=nSlideHei;
if(iPart==SB_THUMBTRACK) goto end;
rcRet.top=rcRet.bottom;
rcRet.bottom=nLength-nArrowHei;
if(iPart==SB_PAGEDOWN) goto end;
rcRet.top=rcRet.bottom;
rcRet.bottom=nLength;
if(iPart==SB_LINEDOWN) goto end;
end:
if(!IsVertical())
{
rcRet.left=rcRet.top;
rcRet.right=rcRet.bottom;
rcRet.top=0;
rcRet.bottom=rcAll.Height();
}
rcRet.OffsetRect(rcAll.TopLeft());
return rcRet;
}
bool SScrollBarHandler::IsVertical() const
{
return m_bVert;
}
ISwndContainer * SScrollBarHandler::GetContainer()
{
return m_pSbHost->GetScrollBarContainer();
}
const IInterpolator * SScrollBarHandler::GetInterpolator() const
{
return m_pSbHost->GetScrollInterpolator();;
}
int SScrollBarHandler::HitTest(CPoint pt) const
{
static const int parts[] =
{
SB_LINEUP,
SB_PAGEUP,
SB_THUMBTRACK,
SB_PAGEDOWN,
SB_LINEDOWN,
};
for (int i = 0; i < ARRAYSIZE(parts); i++)
{
CRect rc = GetPartRect(parts[i]);
if (rc.PtInRect(pt))
return parts[i];
}
return -1;
}
void SScrollBarHandler::OnDraw(IRenderTarget *pRT, int iPart) const
{
CRect rcPart = GetPartRect(iPart);
DWORD dwState = GetPartState(iPart);
if (iPart == kSbRail) iPart = SB_PAGEUP;
BYTE byAlpha = GetAlpha(iPart);
m_pSbHost->GetScrollBarSkin(IsVertical())->DrawByState(pRT,rcPart,MAKESBSTATE(iPart,dwState,IsVertical()), byAlpha);
}
void SScrollBarHandler::OnTimer(char id)
{
if (id == IScrollBarHost::Timer_Wait)
{
m_pSbHost->OnScrollKillTimer(m_bVert, IScrollBarHost::Timer_Wait);
m_pSbHost->OnScrollSetTimer(m_bVert, IScrollBarHost::Timer_Go, IScrollBarHost::kTime_Go);
}
else if (id == IScrollBarHost::Timer_Go)
{
SASSERT(m_iClickPart != -1);
SASSERT(m_iClickPart != SB_THUMBTRACK);
if (m_iClickPart == m_iHitPart)
{
if (m_iClickPart == SB_PAGEUP || m_iClickPart == SB_PAGEDOWN)
{
int iHitPart = HitTest(m_ptCursor);
if (iHitPart == SB_THUMBTRACK)
return;
}
m_pSbHost->OnScrollCommand(m_bVert, m_iClickPart,0);
}
}
}
void SScrollBarHandler::OnDestroy()
{
if (m_fadeMode != FADE_STOP)
{
m_fadeMode = FADE_STOP;
GetContainer()->UnregisterTimelineHandler(this);
}
}
void SScrollBarHandler::OnMouseHover(CPoint pt)
{
if (!m_pSbHost->IsScrollBarEnable(m_bVert))
return;
if (m_iClickPart == SB_THUMBTRACK)
return;
if (m_iClickPart == -1)
{
if (m_pSbHost->GetScrollFadeFrames()>0)
{
m_iFrame = 1;
m_fadeMode = FADEIN;//to show
GetContainer()->RegisterTimelineHandler(this);
}
}
else
{
m_iHitPart = HitTest(pt);//update hit part.
m_pSbHost->OnScrollUpdatePart(m_bVert, m_iClickPart);
}
}
void SScrollBarHandler::OnMouseLeave()
{
if (!m_pSbHost->IsScrollBarEnable(m_bVert))
return;
if (m_iClickPart == SB_THUMBTRACK)
return;
int iOldHit = m_iHitPart;
m_iHitPart = -1;
if (m_iClickPart == -1)
{
if (m_pSbHost->GetScrollFadeFrames()==0)
{
if (iOldHit != -1) m_pSbHost->OnScrollUpdatePart(m_bVert, iOldHit);
}
else
{
m_iFrame = m_pSbHost->GetScrollFadeFrames() -1;
m_fadeMode = FADEOUT;//to hide
GetContainer()->RegisterTimelineHandler(this);
}
}
else
{
m_pSbHost->OnScrollUpdatePart(m_bVert, m_iClickPart);
}
}
void SScrollBarHandler::OnMouseMove(CPoint pt)
{
if (!m_pSbHost->IsScrollBarEnable(m_bVert))
return;
m_ptCursor = pt;
int iNewHit = HitTest(pt);
if (m_iClickPart==-1)
{
if (iNewHit != m_iHitPart)
{
int iOldHit = m_iHitPart;
m_iHitPart = iNewHit;
if(iOldHit!=-1)
m_pSbHost->OnScrollUpdatePart(m_bVert, iOldHit);
if(m_iHitPart!=-1)
m_pSbHost->OnScrollUpdatePart(m_bVert, m_iHitPart);
}
}
else if (m_iClickPart == SB_THUMBTRACK)
{//draging.
CRect rcWnd = m_pSbHost->GetScrollBarRect(m_bVert);
int nInterHei = (IsVertical() ? rcWnd.Height() : rcWnd.Width()) - 2 * m_pSbHost->GetScrollBarArrowSize(m_bVert);
const SCROLLINFO * psi = m_pSbHost->GetScrollBarInfo(m_bVert);
int nSlideHei = psi->nPage*nInterHei / (psi->nMax - psi->nMin + 1);
if (nSlideHei<THUMB_MINSIZE) nSlideHei = THUMB_MINSIZE;
if (nInterHei<THUMB_MINSIZE) nSlideHei = 0;
int nEmptyHei = nInterHei - nSlideHei;
int nDragLen = IsVertical() ? (pt.y - m_ptClick.y) : (pt.x - m_ptClick.x);
int nSlide = (int)((nEmptyHei == 0) ? 0 : (nDragLen*(__int64)(psi->nMax - psi->nMin - psi->nPage + 1) / nEmptyHei));
int nNewTrackPos = m_nClickPos + nSlide;
if (nNewTrackPos<psi->nMin)
{
nNewTrackPos = psi->nMin;
}
else if (nNewTrackPos>(int)(psi->nMax - psi->nMin - psi->nPage + 1))
{
nNewTrackPos = psi->nMax - psi->nMin - psi->nPage + 1;
}
if (nNewTrackPos != psi->nTrackPos)
{
m_pSbHost->OnScrollUpdateThumbTrack(m_bVert,nNewTrackPos);
}
m_iHitPart = iNewHit;
}
else if (m_iHitPart != iNewHit)
{
m_iHitPart = iNewHit;
if (m_iHitPart == m_iClickPart)
{
m_pSbHost->OnScrollSetTimer(m_bVert,IScrollBarHost::Timer_Go, IScrollBarHost::kTime_Go);
}
else
{
m_pSbHost->OnScrollKillTimer(m_bVert,IScrollBarHost::Timer_Go);
}
m_pSbHost->OnScrollUpdatePart(m_bVert, m_iClickPart);
}
}
void SScrollBarHandler::OnMouseUp(CPoint pt)
{
if (!m_pSbHost->IsScrollBarEnable(m_bVert))
return;
int iClickPart = m_iClickPart;
SASSERT(iClickPart != -1);
m_iClickPart = -1;
m_nClickPos = -1;
m_pSbHost->OnScrollUpdatePart(m_bVert, iClickPart);
if (m_iHitPart != -1 && m_iHitPart!= iClickPart)
{
m_pSbHost->OnScrollUpdatePart(m_bVert, m_iHitPart);
}
m_pSbHost->OnScrollKillTimer(m_bVert, IScrollBarHost::Timer_Wait);
m_pSbHost->OnScrollKillTimer(m_bVert, IScrollBarHost::Timer_Go);
if (iClickPart == SB_THUMBTRACK)
{
const SCROLLINFO *psi = m_pSbHost->GetScrollBarInfo(m_bVert);
if(psi->nTrackPos != -1)
m_pSbHost->OnScrollCommand(m_bVert, SB_THUMBPOSITION, psi->nTrackPos);
}
if (iClickPart != -1 && m_iHitPart==-1)
{
OnMouseLeave();
}
}
bool SScrollBarHandler::OnMouseDown(CPoint pt)
{
if (!m_pSbHost->IsScrollBarEnable(m_bVert))
return false;
int iClickPart = HitTest(pt);
if (iClickPart == -1)
return false;
m_iClickPart = iClickPart;
m_ptClick = pt;
if (m_fadeMode != FADE_STOP)
{
m_iFrame = m_pSbHost->GetScrollFadeFrames();//stop animate
m_pSbHost->OnScrollUpdatePart(m_bVert, -1);
}
else
{
m_pSbHost->OnScrollUpdatePart(m_bVert, m_iHitPart);
}
const SCROLLINFO * psi = m_pSbHost->GetScrollBarInfo(m_bVert);
if(iClickPart != SB_THUMBTRACK)
m_pSbHost->OnScrollCommand(m_bVert, iClickPart, 0);
m_nClickPos = psi->nPos;
switch (m_iClickPart)
{
case SB_LINEUP:
case SB_LINEDOWN:
case SB_PAGEUP:
case SB_PAGEDOWN:
m_pSbHost->OnScrollSetTimer(m_bVert, IScrollBarHost::Timer_Wait, IScrollBarHost::kTime_Wait);
break;
}
return true;
}
BYTE SScrollBarHandler::GetAlpha(int iPart) const
{
if(m_pSbHost->GetScrollFadeFrames()<=0)
return 0xFF;
float fProg = GetInterpolator()->getInterpolation(m_iFrame*1.0f/ m_pSbHost->GetScrollFadeFrames());
if (iPart == SB_THUMBTRACK)
{
return (BYTE)(fProg * (0xFF-m_pSbHost->GetScrollThumbTrackMinAlpha()) + m_pSbHost->GetScrollThumbTrackMinAlpha());
}
else
{
return (BYTE)(fProg * 0xFF);
}
}
int SScrollBarHandler::GetFadeStep() const
{
switch(m_fadeMode)
{
case FADEIN: return 1;
case FADEOUT:return -1;
case FADE_STOP:
default:return 0;
}
}
int SScrollBarHandler::GetHitPart() const
{
return m_iHitPart;
}
int SScrollBarHandler::GetClickPart() const
{
return m_iClickPart;
}
DWORD SScrollBarHandler::GetPartState(int iPart) const
{
if (iPart == kSbRail)
return SBST_NORMAL;
if (!m_pSbHost->IsScrollBarEnable(m_bVert))
return SBST_INACTIVE;
DWORD dwState = SBST_NORMAL;
if(iPart == m_iClickPart &&
(m_iClickPart == m_iHitPart || m_iClickPart == SB_THUMBTRACK))
dwState = SBST_PUSHDOWN;
else if(iPart == m_iHitPart)
dwState = SBST_HOVER;
return dwState;
}
}
|
// hello.h
// https://www.genivia.com/dev.html
int ns__hello(std::string name, std::string& greeting);
|
// vec_eigen_pair.h
// Mike Lujan
// July 2010
#pragma once
#include <string>
#include "complex.h"
#include "layout.h"
namespace qcd
{
template <class genvector>
struct vec_eigen_pair
{
int size;
double_complex* eval;
genvector** evec;
vec_eigen_pair(int size, lattice_desc& desc);
~vec_eigen_pair();
private:
vec_eigen_pair(vec_eigen_pair&);
vec_eigen_pair& operator=(vec_eigen_pair&);
};
template <class genvector>
void read_vec_eigen_pair(const char *feigenvecs, const char *feigenvals, vec_eigen_pair<genvector>& eigen_pair);
template <class genvector>
void read_vec_eigen_pair(const std::string &feigenvecs, const std::string &feigenvals, vec_eigen_pair<genvector>& eigen_pair)
{
read_vec_eigen_pair(feigenvecs.c_str(), feigenvals.c_str(), eigen_pair);
}
template <class genvector>
void read_vec_eigen_pair(const std::string &feigenvecs, vec_eigen_pair<genvector>& eigen_pair)
{
std::string feigenvals = feigenvecs + ".eigvals";
read_vec_eigen_pair(feigenvecs, feigenvals, eigen_pair);
}
template <class genvector, class genvector2>
void read_vec_eigen_pair(const char *feigenvecs, const char *feigenvals,
vec_eigen_pair<genvector>& eigen_pair, vec_eigen_pair<genvector2>& eigen_pair2);
template <class genvector, class genvector2>
void read_vec_eigen_pair(const std::string &feigenvecs, const std::string& feigenvals,
vec_eigen_pair<genvector>& eigen_pair, vec_eigen_pair<genvector2>& eigen_pair2)
{
read_vec_eigen_pair(feigenvecs.c_str(), feigenvals.c_str(), eigen_pair, eigen_pair2);
}
}// namespace qcd
|
volatile int32_t encoder1_ticks;
volatile uint32_t encoder1_period; // microseconds
volatile uint64_t encoder1_lastTick; // microseconds
volatile int32_t encoder2_ticks;
volatile uint32_t encoder2_period; // microseconds
volatile uint64_t encoder2_lastTick; // microseconds
void encoder_setup() {
attachInterrupt(digitalPinToInterrupt(encoderPin1A), encoder1_interrupt, RISING);
attachInterrupt(digitalPinToInterrupt(encoderPin2A), encoder2_interrupt, RISING);
}
int32_t encoder1_getTicks() { return encoder1_ticks; }
uint32_t encoder1_getPeriod() { return encoder1_period; }
int32_t encoder2_getTicks() { return encoder2_ticks; }
uint32_t encoder2_getPeriod() { return encoder2_period; }
void encoder1_interrupt() {
const uint64_t t = micros();
if (digitalRead(encoderPin1B)) encoder1_ticks--;
else encoder1_ticks++;
encoder1_period = t - encoder1_lastTick;
encoder1_lastTick = t;
}
void encoder2_interrupt() {
const uint64_t t = micros();
if (digitalRead(encoderPin2B)) encoder2_ticks--;
else encoder2_ticks++;
encoder2_period = t - encoder2_lastTick;
encoder2_lastTick = t;
}
|
#include <vector>
#include <memory>
#include <string>
#include <utility>
#include <stdexcept>
template<typename T>class Blob {
public:
typedef T value_type;
typedef typename std::vector<T>::size_type size_type;
Blob();
Blob(std::initializer_list<T> il);
size_type size() const;
bool empty() const;
void push_back(const T &t) { data->push_back(t); }
void push_back(T &&t) { data->push_back(std::move(t)); }
void pop_back();
void pop_back() const;
T& back();
T& operator[](size_type i);
Blob returnSelf();
private:
std::shared_ptr<std::vector<T>> data;
void check(size_type i, const std::string &msg) const;
};
template<typename T>
Blob<T> Blob<T>::returnSelf()
{
Blob temp = *this;
return temp;
}
template<typename T>
void Blob<T>::pop_back() const
{
const_cast<const T>(this)->pop_back();
}
//template <typename T>
//inline int compare(const T &v1, const T &v2) {
// if (v1 < v2) return -1;
// if (v2 < v1) return 1;
// return 0;
//}
//
//
//template <unsigned N,unsigned M>
//int compare(const char(&v1)[N], const char(&v2)[M]) {
// return strcmp(v1, v2);
//}
//
//#include <functional>
//
//template <typename T>
//int compare(const T &v1, const T &v2) {
// if (std::less<T>()(v1, v2)) return -1;
// if (std::less<T>()(v2, v1)) return 1;
// return 0;
//}
//
//
//#include <iostream>
//
//int main()
//{
// int i = 6, j = 16;
// int *ip = &i, *jp = &j;
// auto result = compare(ip, jp);
// auto result2 = compare("hi", "hello");
// return 0;
//}
template<typename T>
Blob<T>::Blob()
{
data = std::make_shared<std::vector<T>>();
}
template<typename T>
Blob<T>::Blob(std::initializer_list<T> il)
{
data = std::make_shared<std::vector<T>>(il);
}
template<typename T>
typename Blob<T>::size_type Blob<T>::size() const
{
return data->size();
}
template<typename T>
bool Blob<T>::empty() const
{
return data->empty();
}
template<typename T>
void Blob<T>::pop_back()
{
if (!empty())
data->pop_back();
}
template<typename T>
T & Blob<T>::back()
{
check(0, "back on empty Blob");
return data->back();
}
template<typename T>
T & Blob<T>::operator[](size_type i)
{
check(i, "out of range");
return (*data)[i];
}
template<typename T>
void Blob<T>::check(size_type i, const std::string & msg) const
{
if (i >= data->size())
throw std::out_of_range(msg);
}
int main()
{
return 0;
}
|
#pragma once
#pragma warning(disable : 4996)
//基于文件实现的一个vector
#include <string>
#include <iostream>
#include <stdio.h>
#include "tool.h"
using std::fstream;
template<class T>
class dataFile
{
FILE *_file;
long num;
const int Tsize;
public:
// 构造函数:参数为文件名,如果不存在就创建
dataFile(const std::string &name) : Tsize(sizeof(T))
{
_file = fopen(name.c_str(), "rb+");
if (!_file) _file = fopen(name.c_str(), "wb+"), num = 0;
else fread(&num, sizeof(long), 1, _file);
}
dataFile() = delete;
~dataFile()
{
fseek(_file, 0, SEEK_SET);
fwrite(&num, sizeof(long), 1, _file);
fclose(_file);
}
// get: return the i th record,
// 1-base and the following functions are the same
T get(int i) const;
// replace the i th record with 'now'
void replace(const T& now, int i);
// push in a new record
void push(const T& ele);
void pop();
int size() const { return num; }
void loadAll(T *ptr);
void load(int l, int r, T *ptr);
void upload(int __size, T *ptr);
void clear()
{
//fclose(_file);
//_file = fopen(_file, "wb+");
num = 0;
}
};
template<class T>
T dataFile<T>::get(int i) const
{
fseek(_file, (i - 1) * Tsize + sizeof(long), SEEK_SET);
T it;
fread(&it, Tsize, 1, _file);
return it;
}
template<class T>
void dataFile<T>::replace(const T& now, int i)
{
fseek(_file, (i - 1) * Tsize + sizeof(long), SEEK_SET);
fwrite(&now, Tsize, 1, _file);
}
template<class T>
void dataFile<T>::push(const T& ele)
{
fseek(_file, num * Tsize + sizeof(long), SEEK_SET);
fwrite(&ele, Tsize, 1, _file);
++num;
}
template<class T>
void dataFile<T>::loadAll(T* ptr)
{
fseek(_file, sizeof(long), SEEK_SET);
fread(ptr, Tsize, num * Tsize, _file);
}
template<class T>
void dataFile<T>::load(int l, int r, T *ptr) {
fseek(_file, sizeof(long) + (l - 1) * Tsize, SEEK_SET);
fread(ptr, Tsize, r - l + 1, _file);
}
template<class T>
void dataFile<T>::upload(int __size, T* ptr)
{
num = __size;
rewind(_file);
fwrite(&num, sizeof(long), 1, _file);
fwrite(ptr, Tsize, num, _file);
}
template<class T>
void dataFile<T>::pop()
{
--num;
}
|
// Created on: 1997-06-19
// Created by: Christophe LEYNADIER
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Standard_GUID_HeaderFile
#define _Standard_GUID_HeaderFile
#include <Standard_Handle.hxx>
#include <Standard_Integer.hxx>
#include <Standard_CString.hxx>
#include <Standard_UUID.hxx>
#include <Standard_PCharacter.hxx>
#include <Standard_PExtCharacter.hxx>
#include <Standard_OStream.hxx>
#define Standard_GUID_SIZE 36
#define Standard_GUID_SIZE_ALLOC Standard_GUID_SIZE+1
class Standard_GUID
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT Standard_GUID();
//! build a GUID from an ascii string with the
//! following format:
//! Length : 36 char
//! "00000000-0000-0000-0000-000000000000"
Standard_EXPORT Standard_GUID(const Standard_CString aGuid);
//! build a GUID from an unicode string with the
//! following format:
//!
//! "00000000-0000-0000-0000-000000000000"
Standard_EXPORT Standard_GUID(const Standard_ExtString aGuid);
Standard_EXPORT Standard_GUID(const Standard_Integer a32b, const Standard_ExtCharacter a16b1, const Standard_ExtCharacter a16b2, const Standard_ExtCharacter a16b3, const Standard_Byte a8b1, const Standard_Byte a8b2, const Standard_Byte a8b3, const Standard_Byte a8b4, const Standard_Byte a8b5, const Standard_Byte a8b6);
Standard_EXPORT Standard_GUID(const Standard_UUID& aGuid);
Standard_EXPORT Standard_GUID(const Standard_GUID& aGuid);
Standard_EXPORT Standard_UUID ToUUID() const;
//! translate the GUID into ascii string
//! the aStrGuid is allocated by user.
//! the guid have the following format:
//!
//! "00000000-0000-0000-0000-000000000000"
Standard_EXPORT void ToCString (const Standard_PCharacter aStrGuid) const;
//! translate the GUID into unicode string
//! the aStrGuid is allocated by user.
//! the guid have the following format:
//!
//! "00000000-0000-0000-0000-000000000000"
Standard_EXPORT void ToExtString (const Standard_PExtCharacter aStrGuid) const;
Standard_EXPORT Standard_Boolean IsSame (const Standard_GUID& uid) const;
Standard_Boolean operator == (const Standard_GUID& uid) const
{
return IsSame(uid);
}
Standard_EXPORT Standard_Boolean IsNotSame (const Standard_GUID& uid) const;
Standard_Boolean operator != (const Standard_GUID& uid) const
{
return IsNotSame(uid);
}
Standard_EXPORT void Assign (const Standard_GUID& uid);
void operator = (const Standard_GUID& uid)
{
Assign(uid);
}
Standard_EXPORT void Assign (const Standard_UUID& uid);
void operator = (const Standard_UUID& uid)
{
Assign(uid);
}
//! Display the GUID with the following format:
//!
//! "00000000-0000-0000-0000-000000000000"
Standard_EXPORT void ShallowDump (Standard_OStream& aStream) const;
//! Check the format of a GUID string.
//! It checks the size, the position of the '-' and the correct size of fields.
Standard_EXPORT static Standard_Boolean CheckGUIDFormat (const Standard_CString aGuid);
//! Hash function for GUID.
Standard_EXPORT Standard_Integer Hash (const Standard_Integer Upper) const;
//! Computes a hash code for the given GUID of the Standard_Integer type, in the range [1, theUpperBound]
//! @param theGUID the GUID which hash code is to be computed
//! @param theUpperBound the upper bound of the range a computing hash code must be within
//! @return a computed hash code, in the range [1, theUpperBound]
Standard_EXPORT static Standard_Integer HashCode (const Standard_GUID& theGUID, Standard_Integer theUpperBound);
//! Returns True when the two GUID are the same.
Standard_EXPORT static Standard_Boolean IsEqual (const Standard_GUID& string1, const Standard_GUID& string2);
protected:
private:
Standard_Integer my32b;
Standard_ExtCharacter my16b1;
Standard_ExtCharacter my16b2;
Standard_ExtCharacter my16b3;
Standard_Byte my8b1;
Standard_Byte my8b2;
Standard_Byte my8b3;
Standard_Byte my8b4;
Standard_Byte my8b5;
Standard_Byte my8b6;
};
#endif // _Standard_GUID_HeaderFile
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
char st[1000100];
int c[1010],r[1010];
int main() {
int n,m,cou = 0;
scanf("%d%d",&n,&m);
for (int i = 0;i < n; i++) scanf("%s",st+i*m);
for (int i = 0;i < n; i++)
for (int j = 0;j < m; j++)
if (st[i*m+j] == '*') {
r[i]++;c[j]++;cou++;
}
bool pass = false;
for (int i = 0;i < n && !pass; i++)
for (int j = 0;j < m && !pass; j++)
if (r[i] + c[j] - ((st[i*m+j] == '*')?1:0) == cou) {
pass = true;
printf("YES\n%d %d\n",i+1,j+1);
}
if (!pass) puts("NO");
return 0;
}
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;
void fun(int A){
vector<vector<int> > v;
vector<vector<int> > ::iterator it;
int mat[2*A-1][2*A-1];
int l = 2*A-1;
int r = A-1,c = A-1;
int k = 0;
for(int i = r;i>=0;i--){
for(int j =c;j>=0;j--){
mat[i][j] = A-j;
mat[j][i] = mat[i][j];
}
r--;
c--;
}
for(int i = 0;i<A;i++){
for(int j =A+1;j<2*A-1;j++){
mat[i][j] = mat[i][2*A-j-1];
mat[i][j-1] = mat[i][2*A-j-1];
}
}
for(int i = 0;i<A-1;i++){
vector<int> row;
for(int j =0;j<2*A-1;j++){
row.push_back(mat[i][j]);
}
v.push_back(row);
}
for(int i =A-1;i>=0;i--){
vector<int> r;
for(int j =0;j<2*A-1;j++){
r.push_back(mat[i][j]);
}
v.push_back(r);
}
// cout<<"Size"<<v.size();
// for(int i = 0;i<v.size();i++){
// for(int j =0;j<v.size();j++){
// cout<<v[i][j];
// }
// cout<<endl;
// }
return v;
}
int main(){
int A;
cin>>A;
fun(A);
}
// 4444444
// 4333334
// 4322234
// 4321234
// 4322234
// 4333334
// 4444444
|
#include "glib.h"
#include "iostream"
int main()
{
GLIB obj("file://myconnections.xml");
obj.writeTest("test_REG");
return 0;
}
|
#include <iostream>
#include <stdlib.h>
#include "MultiMap.h"
using namespace std;
int main() {
MultiMap<string,int> myMultiMap;
myMultiMap.add("key1",5);
myMultiMap.add("key2",4);
myMultiMap.add("key2",7);
myMultiMap.add("key1",9);
cout << myMultiMap;
cout << "After removeByKey"<<endl;
myMultiMap.removeByKey("key1");
cout << myMultiMap;
cout<< "Lenghth of 'key2': "<< myMultiMap.getLength("key2") << endl;
cout<< "getByKey : ";
cout << myMultiMap.getByKey("key2");
cout << "operator [] : ";
cout << myMultiMap["key2"];
system("pause");
return 0;
}
|
#ifndef MOUSE_EVENT_HANDLER_H
#define MOUSE_EVENT_HANDLER_H
namespace sf
{
class Event;
class RenderWindow;
}
namespace Platy
{
namespace Game
{
class MouseEventHandler
{
public:
MouseEventHandler() = delete;
~MouseEventHandler() = default;
static void HandleEvent(const sf::Event& anEvent, const sf::RenderWindow& aWindow);
};
}
}
#endif
|
#include <iostream>
using namespace std;
union tipo1{
float f;
char c[4];
};
int main()
{
tipo1 A;
A.f = 13.5;
for(int i=0;i<=3;i++)
cout << "A.c[" << i << "]= " << A.c[i] << endl;
return 0;
}
|
#include "sudoku/LedSolver.h"
LedSolver::LedSolver()
{
//hog = NULL;
}
//void LedSolver::init(const char* file)
void LedSolver::init()
{
//svm = SVM::create();
//svm = svm->load(file);
kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
//hog = new cv::HOGDescriptor(cvSize(28, 28), cvSize(14, 14), cvSize(7, 7), cvSize(7, 7), 9);
for (int i = 0; i < 5; ++i)
results[i] = -1;
param[RED_THRESHOLD] = 128;
param[GRAY_THRESHOLD] = 128;
param[BOUND_AREA_MAX] = 30;
param[BOUND_AREA_MAX] = 100;
param[HW_RATIO_MIN] = 130;
param[HW_RATIO_MAX] = 1000;
param[HW_RATIO_FOR_DIGIT_ONE] = 250;
param[ROTATION_DEGREE] = 5;
}
LedSolver::~LedSolver()
{
//if (hog != NULL)
//delete hog;
}
void LedSolver::setParam(int index, int value)
{
if (0 <= index && index < PARAM_SIZE) {
param[index] = value;
return;
} else {
cout << "Set Param Error!" << endl;
}
}
void LedSolver::getRed(Mat& led_roi, Mat& led_roi_binary)
{
static Mat bgr_split[3];
//static Mat led_roi_red;
static Mat led_roi_gray;
cvtColor(led_roi, led_roi_gray, COLOR_BGR2GRAY);
threshold(led_roi_gray, led_roi_gray, param[GRAY_THRESHOLD], 255, THRESH_BINARY);
//split(led_roi, bgr_split);
//led_roi_red = 2 * bgr_split[2] - bgr_split[1] - bgr_split[0];
//threshold(led_roi_red, led_roi_red, param[RED_THRESHOLD], 255, THRESH_BINARY);
//led_roi = led_roi_red & led_roi_gray;
led_roi = led_roi_gray;
//led_roi_binary = led_roi_gray;
//erode(led_roi, led_roi_binary, kernel);
//dilate(led_roi, led_roi_binary, kernel);
dilate(led_roi, led_roi_binary, kernel);
//imshow("original binary:", led_roi);
#if DRAW == SHOW_ALL
imshow("Led Red Binary dilated: ", led_roi_binary);
#endif
}
bool LedSolver::process(Mat& led_roi, Rect& bound_all_rect)
{
static Mat led_roi_binary;
#if DRAW == SHOW_ALL
static Mat draw;
#endif
static vector<vector<Point> > contours;
vector<Rect> digits;
#if DRAW == SHOW_ALL
draw = led_roi.clone();
#endif
getRed(led_roi, led_roi_binary);
findContours(led_roi_binary.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
digits.clear();
Rect led_roi_rect = Rect(0, 0, led_roi_binary.size().width, led_roi_binary.size().height);
for (uint i = 0; i < contours.size(); ++i) {
Rect bound = boundingRect(contours[i]);
//if (bound.x < 10 || bound.x + bound.width > led_roi.cols - 10
//|| bound.y < 10 || bound.y + bound.height > led_roi.rows)
//continue;
if (bound.area() < param[BOUND_AREA_MIN] || bound.area() > param[BOUND_AREA_MAX])
continue;
ROS_INFO_STREAM("Led Area: " << bound.area());
float hw_ratio = (float)bound.height / bound.width;
if (hw_ratio < 1.0)
continue;
//hw_ratio = 1.0 / hw_ratio;
//cout << "HW ratio: " << hw_ratio << endl;
ROS_INFO_STREAM("HW ration: " << hw_ratio);
if (hw_ratio < param[HW_RATIO_MIN] / 100.0 || hw_ratio > param[HW_RATIO_MAX] / 100.0)
continue;
ROS_INFO_STREAM("Led Area: " << bound.area());
digits.push_back(bound);
}
sort(digits.begin(), digits.end(), compareRectX);
if (digits.size() < 5 && !digits.empty()) {
int curSize = digits.size(), maxwidth = digits.front().width, maxheight = digits.front().height;
for (int i = 0; i < curSize - 1 && digits.size() < 5; i++) {
maxwidth = max(maxwidth, digits[i].width);
maxheight = max(maxheight, digits[i].height);
if (digits[i].x + digits[i].width * 2 >= digits[i + 1].x) {
continue;
} else {
int newx = (digits[i + 1].x + digits[i].x) / 2, newy = (digits[i].y + digits[i + 1].y) / 2,
newwidth = max(digits[i].width, digits[i + 1].width), newheight = max(digits[i].height, digits[i + 1].height);
if ((float)digits[i].height / digits[i].width > param[HW_RATIO_FOR_DIGIT_ONE] / 100.0) {
newx = (digits[i + 1].x + digits[i].x) / 2 + digits[i].width - digits[i + 1].width;
newx = (digits[i].x + digits[i].width + digits[i + 1].x + digits[i + 1].width) / 2 - digits[i + 1].width;
}
if ((float)digits[i + 1].height / digits[i + 1].width > param[HW_RATIO_FOR_DIGIT_ONE] / 100.0) {
newx = (digits[i].x + digits[i + 1].x) / 2;
}
Rect bound = Rect(newx, newy, newwidth, newheight);
if (!(led_roi_rect.contains(bound.tl())&&led_roi_rect.contains(bound.br()))) {
ROS_ERROR("Led Guess Out Bound");
continue;
}
ROS_INFO_STREAM("Led Guess Rect: " << bound);
digits.push_back(bound);
}
}
sort(digits.begin(), digits.end(), compareRectX);
if (digits.size() < 5 && !digits.empty()) {
bool left = true, right = true;
while (left && digits.size() < 5) {
int newx = digits.front().x - maxwidth * 4 / 3 - 3, newy = digits.front().y, newwidth = maxwidth + 3, newheight = digits.front().height;
Rect bound = Rect(newx, newy, newwidth, newheight);
if (!(led_roi_rect.contains(bound.tl())&&led_roi_rect.contains(bound.br()))) {
ROS_ERROR("Led Guess Out Bound left");
left = false;
continue;
}
Mat roi = (led_roi_binary)(bound).clone();
if (predictCross(roi) == -1)
left = false;
if (left)
digits.insert(digits.begin(), bound);
}
while (right && digits.size() < 5) {
int newx = digits.back().x + maxwidth * 4 / 3 - 3, newy = digits.back().y, newwidth = maxwidth + 3, newheight = digits.back().height;
Rect bound = Rect(newx, newy, newwidth, newheight);
if (!(led_roi_rect.contains(bound.tl())&&led_roi_rect.contains(bound.br()))) {
ROS_ERROR("Led Guess Out Bound right");
right = false;
continue;
}
Mat roi = (led_roi_binary)(bound).clone();
if (predictCross(roi) == -1)
right = false;
if (right)
digits.push_back(bound);
}
}
sort(digits.begin(), digits.end(), compareRectX);
}
if (digits.size() != 5) {
cout << "digit size error, current size:" << digits.size() << endl;
ROS_INFO("Clear vector");
digits.clear(); // add for secure, otherwise munmap_chunk() error will be raised if there are too many elements in the vector (about 30)
return false;
}
for (uint i = 0; i < digits.size(); ++i) {
float hw_ratio = (float)digits[i].height / digits[i].width;
if (hw_ratio < 1.0)
hw_ratio = 1.0 / hw_ratio;
Mat roi = (led_roi_binary)(digits[i]).clone();
if (hw_ratio > param[HW_RATIO_FOR_DIGIT_ONE] / 100.0) {
int segment1 = scanSegmentY(roi, roi.rows / 3, 0, roi.cols);
int segment2 = scanSegmentY(roi, roi.rows * 2 / 3, 0, roi.cols);
if (segment1 > 1 && segment2 > 1)
results[i] = 1;
else
results[i] = -1;
continue;
}
Point center = Point(digits[i].width / 2, digits[i].height / 2);
Mat M2 = getRotationMatrix2D(center, param[ROTATION_DEGREE], 1);
warpAffine(roi, roi, M2, roi.size(), 1, 0, 0);
results[i] = predictCross(roi);
}
bound_all_rect = Rect(digits[0].tl() - Point(10, 10),
digits[4].br() + Point(10, 10));
#if DRAW == SHOW_ALL
for (uint i = 0; i < digits.size(); ++i) {
rectangle(draw, digits[i], Scalar(255, 0, 0), 2);
}
imshow("draw", draw);
//imshow("Cross Led Red Binary: ", led_roi);
#endif
return true;
}
int LedSolver::scanSegmentX(Mat& roi, int line_x, int y_begin, int y_end)
{
int hit_ctr = 0;
for (int i = y_begin; i < y_end; ++i) {
uchar* pixel = roi.ptr<uchar>(i) + line_x;
if (*pixel == 255 || *pixel == 128) {
*pixel = 128;
++hit_ctr;
}
}
return hit_ctr;
}
int LedSolver::scanSegmentY(Mat& roi, int line_y, int x_begin, int x_end)
{
uchar* pixel = roi.ptr<uchar>(line_y) + x_begin;
int hit_ctr = 0;
for (int i = x_begin; i < x_end; ++i, ++pixel) {
if (*pixel == 255 || *pixel == 128) {
*pixel = 128;
++hit_ctr;
}
}
return hit_ctr;
}
int LedSolver::predictCross(Mat& roi)
{
#define SEGMENT_A 0x01
#define SEGMENT_B 0x02
#define SEGMENT_C 0x04
#define SEGMENT_D 0x08
#define SEGMENT_E 0x10
#define SEGMENT_F 0x20
#define SEGMENT_G 0x40
#define SEGMENT_THRES 0
int mid_x = roi.cols / 2;
int one_sixth_x = roi.cols / 6;
int one_third_y = roi.rows / 3;
int two_thirds_y = roi.rows * 2 / 3;
int one_twelvth_y = roi.rows / 12;
int segment = 0x00;
int segment_hit[7] = { 0 };
int supporta[7] = { 0 }, supportb[7] = { 0 };
segment_hit[0] = (scanSegmentY(roi, one_third_y, 0, mid_x));
supporta[0] = scanSegmentY(roi, one_third_y - one_twelvth_y, 0, mid_x);
supportb[0] = scanSegmentY(roi, one_third_y + one_twelvth_y, 0, mid_x);
segment_hit[1] = (scanSegmentY(roi, one_third_y, mid_x, roi.cols));
supporta[1] = scanSegmentY(roi, one_third_y - one_twelvth_y, mid_x, roi.cols);
supportb[1] = scanSegmentY(roi, one_third_y + one_twelvth_y, mid_x, roi.cols);
segment_hit[2] = (scanSegmentY(roi, two_thirds_y, 0, mid_x));
supporta[2] = scanSegmentY(roi, two_thirds_y - one_twelvth_y, 0, mid_x);
supportb[2] = scanSegmentY(roi, two_thirds_y + one_twelvth_y, 0, mid_x);
segment_hit[3] = (scanSegmentY(roi, two_thirds_y, mid_x, roi.cols));
supporta[3] = scanSegmentY(roi, two_thirds_y - one_twelvth_y, mid_x, roi.cols);
supportb[3] = scanSegmentY(roi, two_thirds_y + one_twelvth_y, mid_x, roi.cols);
segment_hit[4] = (scanSegmentX(roi, mid_x, 0, one_third_y));
supporta[4] = scanSegmentX(roi, mid_x - one_sixth_x, 0, one_third_y);
supportb[4] = scanSegmentX(roi, mid_x + one_sixth_x, 0, one_third_y);
segment_hit[5] = (scanSegmentX(roi, mid_x, one_third_y, two_thirds_y));
supporta[5] = scanSegmentX(roi, mid_x - one_sixth_x, one_third_y, two_thirds_y);
supportb[5] = scanSegmentX(roi, mid_x + one_sixth_x, one_third_y, two_thirds_y);
segment_hit[6] = (scanSegmentX(roi, mid_x, two_thirds_y, roi.rows));
supporta[6] = scanSegmentX(roi, mid_x - one_sixth_x, two_thirds_y, roi.rows);
supportb[6] = scanSegmentX(roi, mid_x + one_sixth_x, two_thirds_y, roi.rows);
//for (int i=0; i<7; ++i) {
//cout << "segment " << i << " hit: " <<supporta[i]<<" "<< segment_hit[i] << " "<<supportb[i] << endl;}
if (segment_hit[0] > SEGMENT_THRES && supporta[0] > SEGMENT_THRES && supportb[0] > SEGMENT_THRES)
segment |= SEGMENT_F;
if (segment_hit[1] > SEGMENT_THRES && supporta[1] > SEGMENT_THRES && supportb[1] > SEGMENT_THRES)
segment |= SEGMENT_B;
if (segment_hit[2] > SEGMENT_THRES && supporta[2] > SEGMENT_THRES && supportb[2] > SEGMENT_THRES)
segment |= SEGMENT_E;
if (segment_hit[3] > SEGMENT_THRES && supporta[3] > SEGMENT_THRES && supportb[3] > SEGMENT_THRES)
segment |= SEGMENT_C;
if (segment_hit[4] > SEGMENT_THRES && supporta[4] > SEGMENT_THRES && supportb[4] > SEGMENT_THRES)
segment |= SEGMENT_A;
if (segment_hit[5] > SEGMENT_THRES && supporta[5] > SEGMENT_THRES && supportb[5] > SEGMENT_THRES)
segment |= SEGMENT_G;
if (segment_hit[6] > SEGMENT_THRES && supporta[6] > SEGMENT_THRES && supportb[6] > SEGMENT_THRES)
segment |= SEGMENT_D;
//cout << "Segment: " << segment << endl;
switch (segment) {
case 0x3f:
return 0;
case 0x06:
return 1;
case 0x5b:
return 2;
case 0x4f:
return 3;
case 0x66:
return 4;
case 0x6d:
return 5;
case 0x7d:
return 6;
case 0x07:
return 7;
case 0x7f:
return 8;
case 0x6f:
return 9;
default:
return -1;
}
}
//int LedSolver::predictSVM(Mat& roi)
//{
//vector<float> descriptors;
////dilate(roi, roi, kernel);
////erode(roi, roi, kernel);
//resize(roi, roi, Size(20, 20));
//Mat inner = Mat::ones(28, 28, CV_8UC1) + 254;
//roi.copyTo(inner(Rect(4, 4, 20, 20)));
////imshow("inner", inner);
//hog->compute(inner, descriptors, Size(1, 1), Size(0, 0));
//Mat SVMPredictMat = Mat(1, (int)descriptors.size(), CV_32FC1);
//memcpy(SVMPredictMat.data, descriptors.data(), descriptors.size() * sizeof(float));
//return (svm->predict(SVMPredictMat));
//}
int LedSolver::getResult(int index)
{
if (index >= 5 || index < 0)
return -1;
return results[index];
}
bool LedSolver::confirmLed()
{
for (int i = 0; i < 5; ++i) {
if (results[i] == -1) {
return false;
}
}
return true;
}
|
#include <iostream>
#include "helpersStudent.h"
#include "Student.h"
int main()
{
std::string name;
std::string last_name;
std::string subjet_name;
int age;
/* Task 34 */
fillStiudentParameters(name, last_name, subjet_name, age);
Student first_student(name, last_name, subjet_name, age);
/* Task 35 */
fillStiudentParameters(name, last_name, subjet_name, age);
Student second_student(name, last_name, subjet_name, age);
std::cout << compareStudents(first_student, second_student) << std::endl;
/* Task 36 */
int avg_age = (first_student.GetAge() + second_student.GetAge()) / 2;
Student third_student(
first_student.GetName(),
second_student.GetLastName(),
"",
avg_age);
third_student.PrintInfo();
/* PrintInfo(); to print student information */
return 0;
}
|
// PropPg2.cpp : 实现文件
//
#include "stdafx.h"
#include "MyProp.h"
#include "PropPg2.h"
// CPropPg2 对话框
IMPLEMENT_DYNCREATE(CPropPg2, CPropertyPage)
// 消息映射
BEGIN_MESSAGE_MAP(CPropPg2, CPropertyPage)
END_MESSAGE_MAP()
// 初始化类工厂和 guid
// {8895306F-6D49-4B6B-9F65-1343B8ADCFE0}
IMPLEMENT_OLECREATE_EX(CPropPg2, "MyProp.PropPg2",
0x8895306f, 0x6d49, 0x4b6b, 0x9f, 0x65, 0x13, 0x43, 0xb8, 0xad, 0xcf, 0xe0)
// CPropPg2::CPropPg2Factory::UpdateRegistry -
// 添加或移除 CPropPg2 的系统注册表项
BOOL CPropPg2::CPropPg2Factory::UpdateRegistry(BOOL bRegister)
{
// TODO: 定义页类型的字符串资源;用 ID 替换下面的“0”。
if (bRegister)
return AfxOleRegisterPropertyPageClass(AfxGetInstanceHandle(),
m_clsid, 0);
else
return AfxOleUnregisterClass(m_clsid, NULL);
}
// CPropPg2::CPropPg2 - 构造函数
// TODO: 定义页标题的字符串资源;用 ID 替换下面的“0”。
CPropPg2::CPropPg2() :
CPropertyPage(IDD, 0)
{
}
// CPropPg2::DoDataExchange - 在页和属性间移动数据
void CPropPg2::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
}
// CPropPg2 消息处理程序
|
#include "Indicator.h"
#include "NamedValue/NamedValue.h"
#include "Tree.h"
// :: Constants ::
const QString NAME_JSON_KEY = "name";
const QString VALUE_JSON_KEY = "value";
// :: Serilizable ::
QJsonObject Indicator::toJson() const {
QJsonObject json;
json[NAME_JSON_KEY] = getName();
json[VALUE_JSON_KEY] = getValue();
return json;
}
void Indicator::initWithJsonObject(const QJsonObject &json) {
if (json.contains(NAME_JSON_KEY) && json[NAME_JSON_KEY].isString()) {
setName(json[NAME_JSON_KEY].toString());
}
if (json.contains(VALUE_JSON_KEY) && json[VALUE_JSON_KEY].isDouble()) {
setValue(json[VALUE_JSON_KEY].toDouble());
}
}
// :: Public accessors ::
// :: Name ::
QString Indicator::getName() const {
return m_name;
}
void Indicator::setName(const QString &name) {
m_name = name;
}
// :: Value ::
double Indicator::getValue() const {
return m_value;
}
void Indicator::setValue(double value) {
m_value = value;
}
// :: Public methods ::
Tree::NodePtr<NamedValue> Indicator::toTreeNodePtr(const Tree::NodePtr<NamedValue> &parent) const {
NamedValue namedValue(getName(), getValue());
return Tree::makeNodePtr(namedValue, parent);
}
|
/*
* target.h
* deflektor-ds
*
* Created by Hugh Cole-Baker on 18/12/2008.
*
*/
#ifndef deflektor_target_h
#define deflektor_target_h
#include "tile.h"
class Level;
class Target : public Tile
{
protected:
const unsigned int tileBase;
Level* const level;
unsigned int state;
unsigned int frameCounter;
public:
Target(int bg, int x, int y, unsigned int palIdx, unsigned int tile, Level* level);
virtual void drawUpdate();
virtual BeamResult beamEnters(unsigned int x, unsigned int y, BeamDirection atAngle);
};
#endif
|
#include "Plugin.h"
#include "Netmap.h"
#include <iosource/Component.h>
namespace plugin { namespace Zeek_Netmap { Plugin plugin; } }
using namespace plugin::Zeek_Netmap;
plugin::Configuration Plugin::Configure()
{
AddComponent(new ::iosource::PktSrcComponent("NetmapReader", "netmap", ::iosource::PktSrcComponent::LIVE, ::iosource::pktsrc::NetmapSource::InstantiateNetmap));
AddComponent(new ::iosource::PktSrcComponent("NetmapReader", "vale", ::iosource::PktSrcComponent::LIVE, ::iosource::pktsrc::NetmapSource::InstantiateVale));
plugin::Configuration config;
config.name = "Zeek::Netmap";
config.description = "Packet acquisition via Netmap";
config.version.major = 1;
config.version.minor = 0;
return config;
}
|
#include <iostream>
#include <cmath>
#include <string>
#include <unistd.h>
#include <fcntl.h>
#include <error.h>
#include <cstring>
#include <fstream>
#include <deque>
#include "./Node.hpp"
#define NEXT 0
using std::getline;
using std::cout;
using std::endl;
using std::string;
using std::ifstream;
using std::deque;
//dumb list class for interview practice
class List{
public:
List() = delete;
List(int n);
~List();
int size;
Node* root;
void Insert(int n);
void Insert(Node* node);
void FloydsAlgorithm(); //aka, hasCycle()
void MakeCycle();
bool HasCycle();
void PrintCycle();
void Print();
};
|
#include "PropertyObjectWidget.hpp"
#include "ui_PropertyObjectWidget.h"
#include "PropertyObjectModel.hpp"
#include "PropertyItemDelegate.hpp"
using namespace Maint;
PropertyObjectWidget::PropertyObjectWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::PropertyObjectWidget)
{
_model = new PropertyObjectModel(this);
ui->setupUi(this);
_itemDelegate = new PropertyItemDelegate(ui->listView, this);
ui->listView->setModel(_model);
ui->listView->setItemDelegate(_itemDelegate);
}
PropertyObjectWidget::~PropertyObjectWidget()
{
delete ui;
}
|
#pragma once
#include <iberbar/Lua/LuaBase.h>
#include <iberbar/Lua/LuaCppCommon.h>
#include <iberbar/Utility/Result.h>
#include <functional>
namespace iberbar
{
namespace Lua
{
class CClassBuilder;
class CEnumBuilder;
class CVariableBuilder;
class CBuilder;
class CScopeBuilder;
typedef void (PHowToBuildClass)(const char* moduleName, CClassBuilder* classBuilder);
typedef void (*PHowToBuildVariable)(const char* moduleName, CVariableBuilder* classBuilder);
typedef void (*PHowToBuildEnum)( CEnumBuilder* pEnum );
typedef void (*PHowToBuildScope)(CScopeBuilder* scope);
typedef void (*PHowToBuildTable)(const char* moduleName);
enum UClassStandardMethodFlag
{
ToString,
OperatorAdd
};
struct UClassDefinition
{
const char* classname;
const char* classnamefull;
const char* classname_extends;
lua_CFunction __constructor;
lua_CFunction __distructor;
const luaL_Reg* __methods;
//lua_CFunction __tostring;
//lua_CFunction __add;
//lua_CFunction __sub;
//lua_CFunction __mul;
//lua_CFunction __div;
//lua_CFunction __mod;
//lua_CFunction __unm;
//lua_CFunction __concat;
//lua_CFunction __eq;
//lua_CFunction __lt;
//lua_CFunction __le;
};
class __iberbarLuaApi__ CClassBuilder
{
public:
enum __iberbarLuaApi__ UpValueType
{
UpValue_Boolean,
UpValue_Integer,
UpValue_Number,
UpValue_String,
UpValue_Pointer
};
struct __iberbarLuaApi__ UpValue
{
union
{
bool v_b;
lua_Integer v_i;
lua_Number v_n;
const char* v_s;
void* v_p;
} v;
UpValueType t;
};
public:
CClassBuilder( lua_State* pLuaState, const char* classNameFull, const char* strClassNameExtends, int metatable );
public:
// 添加构造函数
CClassBuilder* AddConstructor( lua_CFunction func );
// 添加析构函数
CClassBuilder* AddDistructor( lua_CFunction func );
// 添加成员方法
CClassBuilder* AddMemberMethod( const char* name, lua_CFunction func, UpValue* upvalues = nullptr, int upvaluesCount = 0 );
// 添加静态方法
CClassBuilder* AddStaticMethod( const char* name, lua_CFunction func );
// 重载标准方法,方法对应的字段参考 ClassStandardMethod_xxx
CClassBuilder* AddStandardMethod( const char* name, lua_CFunction func );
const char* ClassName() { return m_classNameFull.c_str(); }
const char* ClassName_Extends() { return m_strClassName_Extends.c_str(); }
private:
lua_State* m_pLuaState;
std::string m_classNameFull;
std::string m_strClassName_Extends;
int m_metatable;
int m_methods;
//int m_nLuaMetatable_Extends;
//int m_nLuaMethods_Extends;
};
class __iberbarLuaApi__ CEnumBuilder
{
public:
CEnumBuilder( lua_State* pLuaState, int nValueCount );
void AddValueInt( const char* strKey, lua_Integer Value );
void AddValueString( const char* strKey, const char* Value );
private:
lua_State* m_pLuaState;
int m_nTable;
};
class __iberbarLuaApi__ CScopeBuilder
{
public:
CScopeBuilder( lua_State* pLuaState );
CScopeBuilder( lua_State* pLuaState, const char* strModuleName, int nLuaModule );
public:
// 注册class类型
// @extends 继承的父类
void AddClass( const char* strClassName, std::function<PHowToBuildClass> pHowToAddClass, const char* extends = nullptr );
void AddClass( const char* strClassName, const char* strClassNameFull, std::function<PHowToBuildClass> pHowToAddClass, const char* extends = nullptr );
void AddClass( const UClassDefinition& Definition );
void AddEnum( const char* strEnumTypeName, PHowToBuildEnum pHow, int nCount = -1 );
void AddFunctionOne( const char* functionName, lua_CFunction pFunction );
void AddFunctions( const luaL_Reg* pFunctionRegs );
const std::string& GetModuleName() const { return m_name; }
protected:
lua_State* m_pLuaState;
// 域名,空字符串为全局,不然为table路径名称
std::string m_name;
int m_nLuaModule;
};
class __iberbarLuaApi__ CBuilder
{
public:
CBuilder( lua_State* pLuaState );
void ResolveScope( PHowToBuildScope pHowToBuildScope, const char* moduleName = nullptr );
private:
lua_State* m_pLuaState;
};
}
}
|
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "Kismet/GameplayStatics.h"
#include "SMITElabs/Public/SLGod.h"
#include "SMITElabsGameModeBase.generated.h"
class UGameplayStatics;
class ASLGod;
/**
*
*/
UCLASS()
class SMITELABS_API ASMITElabsGameModeBase : public AGameModeBase
{
GENERATED_BODY()
public:
UFUNCTION(Exec, Category = "ExecFunctions")
void SetMovementSpeed(float Val);
UFUNCTION(Exec, Category = "ExecFunctions")
void SetBasicAttackSpeed(float Val);
UFUNCTION(Exec, Category = "ExecFunctions")
void SetGodLevel(float Val);
};
|
// Created on: 1994-02-18
// Created by: Bruno DUMORTIER
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GeomFill_SectionGenerator_HeaderFile
#define _GeomFill_SectionGenerator_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TColStd_HArray1OfReal.hxx>
#include <GeomFill_Profiler.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <TColStd_Array1OfInteger.hxx>
#include <TColgp_Array1OfPnt.hxx>
#include <TColgp_Array1OfVec.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <TColgp_Array1OfVec2d.hxx>
//! gives the functions needed for instantiation from
//! AppSurf in AppBlend. Allow to evaluate a surface
//! passing by all the curves if the Profiler.
class GeomFill_SectionGenerator : public GeomFill_Profiler
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT GeomFill_SectionGenerator();
Standard_EXPORT void SetParam (const Handle(TColStd_HArray1OfReal)& Params);
Standard_EXPORT void GetShape (Standard_Integer& NbPoles, Standard_Integer& NbKnots, Standard_Integer& Degree, Standard_Integer& NbPoles2d) const;
Standard_EXPORT void Knots (TColStd_Array1OfReal& TKnots) const;
Standard_EXPORT void Mults (TColStd_Array1OfInteger& TMults) const;
//! Used for the first and last section
//! The method returns Standard_True if the derivatives
//! are computed, otherwise it returns Standard_False.
Standard_EXPORT Standard_Boolean Section (const Standard_Integer P, TColgp_Array1OfPnt& Poles, TColgp_Array1OfVec& DPoles, TColgp_Array1OfPnt2d& Poles2d, TColgp_Array1OfVec2d& DPoles2d, TColStd_Array1OfReal& Weigths, TColStd_Array1OfReal& DWeigths) const;
Standard_EXPORT void Section (const Standard_Integer P, TColgp_Array1OfPnt& Poles, TColgp_Array1OfPnt2d& Poles2d, TColStd_Array1OfReal& Weigths) const;
//! Returns the parameter of Section<P>, to impose it for the
//! approximation.
Standard_EXPORT Standard_Real Parameter (const Standard_Integer P) const;
protected:
Handle(TColStd_HArray1OfReal) myParams;
private:
};
#endif // _GeomFill_SectionGenerator_HeaderFile
|
int main()
{
int lim = 1e6;
Segtree st(lim+100);
int n, m, y, x, l, r;
cin >> n >> m;
int open=-1, close=INF; // open -> check -> close
vector< pair<int, pii> > sweep;
ll ans = 0;
for(int i=0;i<n;i++){ // horizontal
cin >> y >> l >> r;
sweep.pb({l, {open, y}});
sweep.pb({r, {close, y}});
}
for(int i=0;i<m;i++){ // vertical
cin >> x >> l >> r;
sweep.pb({x, {l, r}});
}
sort(sweep.begin(), sweep.end());
// set<int> on;
for(auto s: sweep){
if(s.ss.ff==open){
st.update(s.ss.ss, 1);
// on.insert(s.ss.ss);
}
else if(s.ss.ff==close){
st.update(s.ss.ss, -1);
// on.erase(s.ss.ss);
}
else{
ans += st.query(s.ss.ff, s.ss.ss);
// auto it1 = on.lower_bound(s.ss.ff);
// auto it2 = on.upper_bound(s.ss.ss);
// for(auto it = it1; it!=it2; it++){
// intersection -> (s.ff, it);
// }
}
}
cout << ans << endl;
return 0;
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
int a[100100];
int main() {
int n,m;
scanf("%d%d",&n,&m);
for (int i = 1;i <= n; i++) scanf("%d",&a[i]);
sort(a+1,a+n+1);
int l = 0,r = INF;
while (r-l > 1) {
int mid = l + ((r-l) >> 1);
int loc = -1,cou = 0;
for (int i = 1;i <= n; i++) {
if (a[i] >= loc) {
cou++;
loc = a[i] + mid;
if (cou >= m) break;
}
}
//cout << mid << " " << cou << endl;
if (cou >= m) l = mid;
else r = mid;
}
printf("%d\n",l);
return 0;
}
|
#include "include/Logica.h"
#include <iostream>
/////////////////////////Variables////////////////////////////////
string id, nombre, idb, idp;
int dia, mes, anio;
float cargaDespacho;
//////////////////////////////////////////////////////////////////
int main()
{
int opcion = 21;
int opc = 0;
while (opcion != 0)
{
cout << "1) Agregar puerto" << '\n';
cout << "2) Agregar barco" << '\n';
cout << "3) Listar puertos" << '\n';
cout << "4) Agregar arribo" << '\n';
cout << "5) Obtener arribos en puerto" << '\n';
cout << "6) Eliminar arribos" << '\n';
cout << "7) Listar barcos" << '\n';
cout << "8) Imprimir barcos" << '\n';
cout << "0) Salir" << '\n';
cout << ">> ";
cin >> opcion;
switch (opcion)
{
case 1: //Agregar puerto
{
try
{
cout << "Ingrese el id del puerto: ";
cin >> id;
if (idPuertoRepetido(id))
{
throw std::invalid_argument("Ya existe un puerto con ese identificador.");
}
cout << "Ingrese el nombre del puerto: ";
cin >> nombre;
cout << "Ingrese fecha de creación del puerto. \n";
cout << "Dia: ";
cin >> dia;
cout << "Mes: ";
cin >> mes;
cout << "Año: ";
cin >> anio;
DtFecha FechaPuerto(dia, mes, anio);
agregarPuerto(id, nombre, FechaPuerto);
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
}
break;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case 2:
cout << "Ingrese el id del barco: ";
cin >> id;
try
{
if (controlIdBarco(id))
throw std::invalid_argument("Ya existe barco con ese identificador.");
cout << "Ingrese el nombre del barco: ";
cin >> nombre;
cout << "De que tipo es el barco a ingresar?" << '\n';
cout << "1)Pesquero" << '\n';
cout << "2)Pasajeros" << '\n';
cout << ">> ";
cin >> opc;
if (opc == 1)
{
int capacidad, carga;
cout << "Capacidad: ";
cin >> capacidad;
cout << "Carga: ";
cin >> carga;
DtBarcoPesquero barcoPes(nombre, id, capacidad, carga);
agregarBarco(barcoPes);
}
else if (opc == 2)
{
TipoTamanio tam;
int cantPasajeros;
cout << "Que tipo de tamaño: \n1)Bote\n2)Crucero\n3)Galeon\n4)Transatlantico\n";
cout << ">> ";
cin >> opc;
if (opc == 1)
tam = bote;
else if (opc == 2)
tam = crucero;
else if (opc == 3)
tam = galeon;
else if (opc == 4)
tam = transatlantico;
else
{
cout << "Ingrese una opcion correcta\n";
break;
}
cout << "Cantidad de pasajeros: ";
cin >> cantPasajeros;
DtBarcoPasajeros barcoPas(nombre, id, cantPasajeros, tam);
agregarBarco(barcoPas);
}
else
{
cout << "Ingrese una opcion correcta"
<< "\n";
}
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
break;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case 3:
{
col_dtPuerto ListaPuertos = listarPuertos();
break;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case 4: //Agregar arribo
try//agregar exception de cuando se le intenta agregar arribo de mas a puerto
{
cout << "Ingrese el id del barco: ";
cin >> idb;
if (!controlIdBarco(idb))
throw std::invalid_argument("\n No existe barco con ese identificador.");
else
{
try
{
cout << "\n Ingrese el id del puerto: ";
cin >> idp;
if (!idPuertoRepetido(idp))
throw std::invalid_argument("\n No existe un puerto con ese identificador.");
else
{
cout << "\n Ingrese la carga de despacho: ";
cin >> cargaDespacho;
agregarArribo(idp, idb, cargaDespacho);
}
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
}
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
break;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case 5: //Obtener arribos en puerto
{
cout << "\n Ingrese el id del puerto: ";
cin >> idp;
try
{
if (!idPuertoRepetido(idp))
throw std::invalid_argument("\n No existe un puerto con ese identificador.");
else
{
//arr_Arribos arribosdePuerto = obtenerInfoArribosEnPuerto(idp);
obtenerInfoArribosEnPuerto(idp);
}
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
}
break;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case 6: //Eliminar arribos
/* { try
{ cout << "\n Ingrese el id del puerto: ";
cin >> idp;
if (!idPuertoRepetido(idp))
throw std::invalid_argument("\n No existe un puerto con ese identificador.");
else {
cout << "Ingrese fecha de los arribos. \n";
cout << "Dia: ";
cin >> dia;
cout << "Mes: ";
cin >> mes;
cout << "Año: ";
cin >> anio;
DtFecha FechaArribos(dia, mes, anio);
eliminarArribos(idp,FechaArribos);
// delete(FechaArribos);
}
}
catch(const std::exception &e)
{
std::cerr << e.what() << '\n';
}}
break;*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case 7:
{
Col_barcos Barcos = listarBarcos();
cout << Barcos.colBarco[Barcos.tope]->get_id();
//cout << Barcos.tope;
}
break;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case 8:
imprimirBarcos();
break;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
case 0: //Salir
cout << "Saliendo... \n";
break;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
default:
cout << "Opción no válida, volviendo...\n";
break;
} //switch
} //While
} // Main
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "StringInputStream.h"
#include <string.h>
namespace common {
StringInputStream::StringInputStream(const std::string& in) : in(in), offset(0) {
}
size_t StringInputStream::readSome(void* data, size_t size) {
if (size > in.size() - offset) {
size = in.size() - offset;
}
memcpy(data, in.data() + offset, size);
offset += size;
return size;
}
}
|
#ifndef TREEFACE_SCENE_GUTS_H
#define TREEFACE_SCENE_GUTS_H
#include "treeface/scene/Scene.h"
#include "treeface/scene/SceneNode.h"
namespace treeface {
TREECORE_ALN_BEGIN(16)
struct Scene::Guts
{
TREECORE_ALIGNED_ALLOCATOR(Scene::Guts);
treecore::RefCountHolder<SceneNode> root_node = new SceneNode();
treecore::RefCountHolder<SceneNodeManager> node_mgr;
treecore::RefCountHolder<MaterialManager> mat_mgr;
treecore::RefCountHolder<GeometryManager> geo_mgr;
Vec4f global_light_direction{0.577350269, 0.577350269, 0.577350269, 0};
Vec4f global_light_color{1, 1, 1, 1};
Vec4f global_light_ambient{0, 0, 0, 1};
} TREECORE_ALN_END(16);
} // namespace treeface
#endif // TREEFACE_SCENE_GUTS_H
|
#ifndef Core_GItemListCtrlItem_h
#define Core_GItemListCtrlItem_h
#include "GStateListCtrlItem.h"
#include "GnINumberLabel.h"
class GItemListCtrlItem : public GStateListCtrlItem
{
GnDeclareRTTI;
private:
bool mCreateLabelPrice;
GnINumberLabel mLabelPrice;
GnINumberLabel mItemCount;
GnInterfacePtr mpsIconMoney;
public:
GItemListCtrlItem(const gchar* pcDefaultImage, const gchar* pcClickImage = "Upgrade/items/30_140 s.png"
, const gchar* pcDisableImage = NULL, eButtonType eDefaultType = TYPE_NORMAL);
virtual ~GItemListCtrlItem(){};
public:
void CreateLabelPrice();
void CreateIconMoney();
void SetPosition(GnVector2& cPos);
public:
inline void SetPrice(guint32 val) {
mLabelPrice.SetNumber( val );
}
inline void SetItemCount(guint32 val) {
mItemCount.SetNumber( val );
}
};
#endif
|
#include <iostream>
using namespace std;
class node{
public:
int data;
node* next;
};
class linkedList{
private:
node* head;
node* tail;
int k;
public:
linkedList(){
head = NULL;
tail = NULL;
k=0;
}
void addNode(int d){
node* temp = new node; //imp
temp->data = d;
temp->next = NULL;
if (head==NULL){
head = temp;
tail = temp;
k++;
}
else {
tail->next = temp;
tail = temp;
k++; //k means the no. of nodes in the linked list
}
}
void displayList(){
if (head==NULL){ //imp
cout << "Nothing" << endl;
}
else{
node* temp=head;
while (temp != NULL){ //imp
cout << temp->data << endl;
temp = temp->next;
}
}
cout << endl;
}
void insertNode(int d, int i){ //i means the insert position
node* n = new node;
n->data=d;
if (i==0){
n->next = head;
head = n;
++k;
}
else if (i==k){
n->next = NULL;
tail->next = n;
tail = n;
++k;
}
else {
node* p = head;
for (int j=0; j<=i-2; j++){ //...
p=p->next;
}
n->next = p->next;
p->next = n;
++k;
}
}
void deleteNode(int i){
if (i==0){
node* p = head;
head = head->next;
delete p;
--k;
}
else if (i==k-1){
node* p = head;
for (int j = 0;j<=k-2; j++){
p = p->next;
}
tail = p;
delete tail->next;
--k;
}
else{
node* p = head;
node* q = head;
for (int j = 0;j<=i-2; j++){
p = p->next;
}
for (int j = 0;j<=i-1; j++){
q = q->next;
}
p->next = q->next;
delete q;
--k;
}
}
};
int main(){
linkedList l1;
for (int i=0;i<10;i++){
l1.addNode(i);
}
cout << "Linked list l1:" << endl;
l1.displayList();
l1.insertNode(56,2);
cout << "Inserted a node at position i=2" << endl;
l1.displayList();
l1.insertNode(56,0);
cout << "Inserted a node at position i=0" << endl;
l1.displayList();
l1.insertNode(56,9);
cout << "Inserted a node at position i=9" << endl;
l1.displayList();
l1.deleteNode(0);
cout << "Deleted a node at position i=0" << endl;
l1.displayList();
l1.deleteNode(2);
cout << "Deleted a node at position i=2" << endl;
l1.displayList();
l1.deleteNode(10);
cout << "Deleted a node at position i=10" << endl;
l1.displayList();
return 0;
}
|
#ifndef __maze3dflyer_h__
#define __maze3dflyer_h__
#include <stdlib.h>
#include <gl/glut.h>
#include "glCamera.h"
extern void debugMsg(const char *str, ...);
extern void errorMsg(const char *str, ...);
extern void setMainMsg(float secs, const char *str, ...);
extern glCamera Cam;
extern float keyTurnRate; // how fast to turn in response to keys
extern float keyAccelRate; // how fast to accelerate in response to keys
extern float keyMoveRate; // how fast to move in response to keys
extern int pictureRarity;
extern GLuint pictureTexture;
extern GLuint mazeTextures[]; // texture indexes ("names")
class Image;
extern Image images[];
extern GLuint facadeDL; // needed by Wall.cpp
typedef enum { ground, wall1, wall2, portal, roof } Material;
typedef enum { fadingIn, playing, autopilot, celebrating, fadingOut } GameState;
extern GLUquadricObj *diskQuadric, *cylQuadric, *sphereQuadric;
#endif /* __maze3dflyer_h__ */
|
// -----------------------------------------------------------------------------
// TrackingAction.h
//
//
// * Author: Everybody is an author!
// * Creation date: 4 August 2020
// -----------------------------------------------------------------------------
#ifndef TRACKING_ACTION_H
#define TRACKING_ACTION_H 1
#include "G4UserTrackingAction.hh"
class TrackingAction : public G4UserTrackingAction
{
public:
TrackingAction();
~TrackingAction();
void PreUserTrackingAction(const G4Track*);
void PostUserTrackingAction(const G4Track*);
};
#endif
|
class Ant {
private:
byte x, y, dir;
void turn();
public:
Ant() {
init();
}
void init(byte _x, byte _y, byte _dir) {
x = _x;
y = _y;
dir = _dir;
}
void init() {
init(random(0, BM_SIDE), random(0, BM_SIDE), random(0,4));
}
void walk(BitMatrix *board) {
#ifdef DEBUGGING
Serial.print("ant: ");
Serial.print(x);
Serial.print(",");
Serial.print(y);
Serial.print("; dir=");
Serial.println(dir);
#endif
if (board->get(x,y)) {
#ifdef DEBUGGING
Serial.println("high");
#endif
turn(LEFT);
} else {
#ifdef DEBUGGING
Serial.println("low");
#endif
turn(RIGHT);
}
board->set(x,y,!board->get(x,y));
step();
}
private:
void turn(byte _dir) {
if (_dir == LEFT) {
switch(dir) {
case UP:
dir = LEFT;
break;
case LEFT:
dir = DOWN;
break;
case DOWN:
dir = RIGHT;
break;
case RIGHT:
dir = UP;
break;
}
} else {
switch(dir) {
case UP:
dir = RIGHT;
break;
case RIGHT:
dir = DOWN;
break;
case DOWN:
dir = LEFT;
break;
case LEFT:
dir = UP;
break;
}
}
} // turn(_dir)
void step() {
switch (dir) {
case UP:
y = (y == 0 ? BM_SIDE - 1 : y - 1);
break;
case LEFT:
x = (x == 0 ? BM_SIDE - 1 : x - 1);
break;
case DOWN:
y = (y == BM_SIDE - 1 ? 0 : y + 1);
break;
case RIGHT:
x = (x == BM_SIDE - 1 ? 0 : x + 1);
}
} // step()
};
|
#include "stdio.h"
#include "conio.h"
#include "string.h"
void main(){
clrscr();
FILE *fptr;
char *name; int count=0;
printf("Enter File Name : ");
gets(name);
strcat(name,".txt");
char ch[80];
fptr=fopen(name,"r+");
while(fgets(ch, 80, fptr)!=NULL)
/*if(ch==(char)32) */count++;
printf("%d",count);
fclose(fptr);
getch();
}
|
/****************************************************************
* TianGong RenderLab *
* Copyright (c) Gaiyitp9. All rights reserved. *
* This code is licensed under the MIT License (MIT). *
*****************************************************************/
#include "Diagnostics/Win32Exception.hpp"
#include "Utility.hpp"
#include <format>
namespace TG
{
Win32Exception::Win32Exception(HRESULT hr, const std::wstring& description)
: BaseException(description), m_errorCode(hr)
{
// 提取错误码中的信息
TranslateHrErrorCode();
}
Win32Exception::~Win32Exception() = default;
char const* Win32Exception::what() const
{
// 记录异常信息
std::wstring wWhatBuffer = std::format(L"Exception type: {}\n", GetType());
wWhatBuffer += std::format(L"HRESULT: {:#010x}\nError Message: {}", m_errorCode, m_errorMsg);
wWhatBuffer += m_description;
wWhatBuffer += Separator;
for (const auto& info : m_stackFrameInfo)
{
wWhatBuffer += std::format(L"Frame: {}\nFile: {}\nFunction: {}\nLine: {}",
info.index, info.file, info.function, info.line);
wWhatBuffer += Separator;
}
m_whatBuffer = Utility::Utf16ToUtf8(wWhatBuffer);
return m_whatBuffer.c_str();
}
wchar_t const* Win32Exception::GetType() const noexcept
{
return L"Windows API Exception";
}
void Win32Exception::TranslateHrErrorCode()
{
/*
注意:FormatMessage中的lpBuffer参数与dwFlags有关。
如果不包含FORMAT_MESSAGE_ALLOCATE_BUFFER,则写法如下:
wchar_t msgBuf[256];
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, m_errorCode, LANG_SYSTEM_DEFAULT, msgBuf, 256, nullptr);
如果包含FORMAT_MESSAGE_ALLOCATE_BUFFER,则写法如下:
wchar_t* msgBuf = nullptr;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, m_errorCode, LANG_SYSTEM_DEFAULT, (wchar_t*)&msgBuf, 0, nullptr);
LocalFree(msgBuf);
不同之处在于,lpBuffer需要传入指针的地址,这样才能将分配的内存地址赋给lpBuffer,
所以要做一个看上去很奇怪的转换:取wchar_t指针的地址,再强转为whar_t指针*/
wchar_t msgBuf[256];
DWORD msgLen = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, m_errorCode, LANG_SYSTEM_DEFAULT, msgBuf, 256, nullptr);
m_errorMsg = msgLen > 0 ? msgBuf : L"Unidentified error code";
}
}
|
/*
Copyright (c) 2018-2019, tevador <tevador@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RANDOMX_H
#define RANDOMX_H
#include <cstddef>
#include <cstdint>
#include <type_traits>
#include "base/crypto/Algorithm.h"
#include "crypto/randomx/intrin_portable.h"
#define RANDOMX_HASH_SIZE 32
#define RANDOMX_DATASET_ITEM_SIZE 64
#ifndef RANDOMX_EXPORT
#define RANDOMX_EXPORT
#endif
enum randomx_flags {
RANDOMX_FLAG_DEFAULT = 0,
RANDOMX_FLAG_LARGE_PAGES = 1,
RANDOMX_FLAG_HARD_AES = 2,
RANDOMX_FLAG_FULL_MEM = 4,
RANDOMX_FLAG_JIT = 8,
RANDOMX_FLAG_1GB_PAGES = 16,
RANDOMX_FLAG_AMD = 64,
};
struct randomx_dataset;
struct randomx_cache;
class randomx_vm;
struct RandomX_ConfigurationBase
{
RandomX_ConfigurationBase();
void Apply();
// Common parameters for all RandomX variants
enum Params : uint64_t
{
SuperscalarLatency = 170,
DatasetExtraSize = 33554368,
JumpBits = 8,
JumpOffset = 8,
DatasetExtraItems_Calculated = DatasetExtraSize / RANDOMX_DATASET_ITEM_SIZE,
ConditionMask_Calculated = ((1 << JumpBits) - 1) << JumpOffset,
};
uint32_t ArgonMemory;
uint32_t CacheAccesses;
uint32_t DatasetBaseSize;
uint32_t ArgonIterations;
uint32_t ArgonLanes;
const char* ArgonSalt;
uint32_t ScratchpadL1_Size;
uint32_t ScratchpadL2_Size;
uint32_t ScratchpadL3_Size;
uint32_t ProgramSize;
uint32_t ProgramIterations;
uint32_t ProgramCount;
uint32_t RANDOMX_FREQ_IADD_RS;
uint32_t RANDOMX_FREQ_IADD_M;
uint32_t RANDOMX_FREQ_ISUB_R;
uint32_t RANDOMX_FREQ_ISUB_M;
uint32_t RANDOMX_FREQ_IMUL_R;
uint32_t RANDOMX_FREQ_IMUL_M;
uint32_t RANDOMX_FREQ_IMULH_R;
uint32_t RANDOMX_FREQ_IMULH_M;
uint32_t RANDOMX_FREQ_ISMULH_R;
uint32_t RANDOMX_FREQ_ISMULH_M;
uint32_t RANDOMX_FREQ_IMUL_RCP;
uint32_t RANDOMX_FREQ_INEG_R;
uint32_t RANDOMX_FREQ_IXOR_R;
uint32_t RANDOMX_FREQ_IXOR_M;
uint32_t RANDOMX_FREQ_IROR_R;
uint32_t RANDOMX_FREQ_IROL_R;
uint32_t RANDOMX_FREQ_ISWAP_R;
uint32_t RANDOMX_FREQ_FSWAP_R;
uint32_t RANDOMX_FREQ_FADD_R;
uint32_t RANDOMX_FREQ_FADD_M;
uint32_t RANDOMX_FREQ_FSUB_R;
uint32_t RANDOMX_FREQ_FSUB_M;
uint32_t RANDOMX_FREQ_FSCAL_R;
uint32_t RANDOMX_FREQ_FMUL_R;
uint32_t RANDOMX_FREQ_FDIV_M;
uint32_t RANDOMX_FREQ_FSQRT_R;
uint32_t RANDOMX_FREQ_CBRANCH;
uint32_t RANDOMX_FREQ_CFROUND;
uint32_t RANDOMX_FREQ_ISTORE;
uint32_t RANDOMX_FREQ_NOP;
rx_vec_i128 fillAes4Rx4_Key[8];
uint8_t codeShhPrefetchTweaked[20];
uint8_t codeReadDatasetTweaked[64];
uint32_t codeReadDatasetTweakedSize;
uint8_t codeReadDatasetRyzenTweaked[72];
uint32_t codeReadDatasetRyzenTweakedSize;
uint8_t codePrefetchScratchpadTweaked[28];
uint32_t codePrefetchScratchpadTweakedSize;
uint32_t CacheLineAlignMask_Calculated;
uint32_t AddressMask_Calculated[4];
uint32_t ScratchpadL3Mask_Calculated;
uint32_t ScratchpadL3Mask64_Calculated;
#if defined(XMRIG_ARMv8)
uint32_t Log2_ScratchpadL1;
uint32_t Log2_ScratchpadL2;
uint32_t Log2_ScratchpadL3;
uint32_t Log2_DatasetBaseSize;
uint32_t Log2_CacheSize;
#endif
};
struct RandomX_ConfigurationMonero : public RandomX_ConfigurationBase {};
struct RandomX_ConfigurationWownero : public RandomX_ConfigurationBase { RandomX_ConfigurationWownero(); };
struct RandomX_ConfigurationArqma : public RandomX_ConfigurationBase { RandomX_ConfigurationArqma(); };
struct RandomX_ConfigurationSafex : public RandomX_ConfigurationBase { RandomX_ConfigurationSafex(); };
struct RandomX_ConfigurationKeva : public RandomX_ConfigurationBase { RandomX_ConfigurationKeva(); };
struct RandomX_ConfigurationScala : public RandomX_ConfigurationBase { RandomX_ConfigurationScala(); };
extern RandomX_ConfigurationMonero RandomX_MoneroConfig;
extern RandomX_ConfigurationWownero RandomX_WowneroConfig;
extern RandomX_ConfigurationArqma RandomX_ArqmaConfig;
extern RandomX_ConfigurationSafex RandomX_SafexConfig;
extern RandomX_ConfigurationKeva RandomX_KevaConfig;
extern RandomX_ConfigurationScala RandomX_ScalaConfig;
extern RandomX_ConfigurationBase RandomX_CurrentConfig;
template<typename T>
void randomx_apply_config(const T& config)
{
static_assert(sizeof(T) == sizeof(RandomX_ConfigurationBase), "Invalid RandomX configuration struct size");
static_assert(std::is_base_of<RandomX_ConfigurationBase, T>::value, "Incompatible RandomX configuration struct");
RandomX_CurrentConfig = config;
RandomX_CurrentConfig.Apply();
}
void randomx_set_scratchpad_prefetch_mode(int mode);
void randomx_set_huge_pages_jit(bool hugePages);
void randomx_set_optimized_dataset_init(int value);
#if defined(__cplusplus)
extern "C" {
#endif
/**
* Creates a randomx_cache structure and allocates memory for RandomX Cache.
*
* @param flags is any combination of these 2 flags (each flag can be set or not set):
* RANDOMX_FLAG_LARGE_PAGES - allocate memory in large pages
* RANDOMX_FLAG_JIT - create cache structure with JIT compilation support; this makes
* subsequent Dataset initialization faster
*
* @return Pointer to an allocated randomx_cache structure.
* NULL is returned if memory allocation fails or if the RANDOMX_FLAG_JIT
* is set and JIT compilation is not supported on the current platform.
*/
RANDOMX_EXPORT randomx_cache *randomx_create_cache(randomx_flags flags, uint8_t *memory);
/**
* Initializes the cache memory and SuperscalarHash using the provided key value.
*
* @param cache is a pointer to a previously allocated randomx_cache structure. Must not be NULL.
* @param key is a pointer to memory which contains the key value. Must not be NULL.
* @param keySize is the number of bytes of the key.
*/
RANDOMX_EXPORT void randomx_init_cache(randomx_cache *cache, const void *key, size_t keySize);
/**
* Releases all memory occupied by the randomx_cache structure.
*
* @param cache is a pointer to a previously allocated randomx_cache structure.
*/
RANDOMX_EXPORT void randomx_release_cache(randomx_cache* cache);
/**
* Creates a randomx_dataset structure and allocates memory for RandomX Dataset.
*
* @param flags is the initialization flags. Only one flag is supported (can be set or not set):
* RANDOMX_FLAG_LARGE_PAGES - allocate memory in large pages
*
* @return Pointer to an allocated randomx_dataset structure.
* NULL is returned if memory allocation fails.
*/
RANDOMX_EXPORT randomx_dataset *randomx_create_dataset(uint8_t *memory);
/**
* Gets the number of items contained in the dataset.
*
* @return the number of items contained in the dataset.
*/
RANDOMX_EXPORT unsigned long randomx_dataset_item_count(void);
/**
* Initializes dataset items.
*
* Note: In order to use the Dataset, all items from 0 to (randomx_dataset_item_count() - 1) must be initialized.
* This may be done by several calls to this function using non-overlapping item sequences.
*
* @param dataset is a pointer to a previously allocated randomx_dataset structure. Must not be NULL.
* @param cache is a pointer to a previously allocated and initialized randomx_cache structure. Must not be NULL.
* @param startItem is the item number where intialization should start.
* @param itemCount is the number of items that should be initialized.
*/
RANDOMX_EXPORT void randomx_init_dataset(randomx_dataset *dataset, randomx_cache *cache, unsigned long startItem, unsigned long itemCount);
/**
* Returns a pointer to the internal memory buffer of the dataset structure. The size
* of the internal memory buffer is randomx_dataset_item_count() * RANDOMX_DATASET_ITEM_SIZE.
*
* @param dataset is dataset is a pointer to a previously allocated randomx_dataset structure. Must not be NULL.
*
* @return Pointer to the internal memory buffer of the dataset structure.
*/
RANDOMX_EXPORT void *randomx_get_dataset_memory(randomx_dataset *dataset);
/**
* Releases all memory occupied by the randomx_dataset structure.
*
* @param dataset is a pointer to a previously allocated randomx_dataset structure.
*/
RANDOMX_EXPORT void randomx_release_dataset(randomx_dataset *dataset);
/**
* Creates and initializes a RandomX virtual machine.
*
* @param flags is any combination of these 4 flags (each flag can be set or not set):
* RANDOMX_FLAG_LARGE_PAGES - allocate scratchpad memory in large pages
* RANDOMX_FLAG_HARD_AES - virtual machine will use hardware accelerated AES
* RANDOMX_FLAG_FULL_MEM - virtual machine will use the full dataset
* RANDOMX_FLAG_JIT - virtual machine will use a JIT compiler
* The numeric values of the flags are ordered so that a higher value will provide
* faster hash calculation and a lower numeric value will provide higher portability.
* Using RANDOMX_FLAG_DEFAULT (all flags not set) works on all platforms, but is the slowest.
* @param cache is a pointer to an initialized randomx_cache structure. Can be
* NULL if RANDOMX_FLAG_FULL_MEM is set.
* @param dataset is a pointer to a randomx_dataset structure. Can be NULL
* if RANDOMX_FLAG_FULL_MEM is not set.
*
* @return Pointer to an initialized randomx_vm structure.
* Returns NULL if:
* (1) Scratchpad memory allocation fails.
* (2) The requested initialization flags are not supported on the current platform.
* (3) cache parameter is NULL and RANDOMX_FLAG_FULL_MEM is not set
* (4) dataset parameter is NULL and RANDOMX_FLAG_FULL_MEM is set
*/
RANDOMX_EXPORT randomx_vm *randomx_create_vm(randomx_flags flags, randomx_cache *cache, randomx_dataset *dataset, uint8_t *scratchpad, uint32_t node);
/**
* Reinitializes a virtual machine with a new Cache. This function should be called anytime
* the Cache is reinitialized with a new key.
*
* @param machine is a pointer to a randomx_vm structure that was initialized
* without RANDOMX_FLAG_FULL_MEM. Must not be NULL.
* @param cache is a pointer to an initialized randomx_cache structure. Must not be NULL.
*/
RANDOMX_EXPORT void randomx_vm_set_cache(randomx_vm *machine, randomx_cache* cache);
/**
* Reinitializes a virtual machine with a new Dataset.
*
* @param machine is a pointer to a randomx_vm structure that was initialized
* with RANDOMX_FLAG_FULL_MEM. Must not be NULL.
* @param dataset is a pointer to an initialized randomx_dataset structure. Must not be NULL.
*/
RANDOMX_EXPORT void randomx_vm_set_dataset(randomx_vm *machine, randomx_dataset *dataset);
/**
* Releases all memory occupied by the randomx_vm structure.
*
* @param machine is a pointer to a previously created randomx_vm structure.
*/
RANDOMX_EXPORT void randomx_destroy_vm(randomx_vm *machine);
/**
* Calculates a RandomX hash value.
*
* @param machine is a pointer to a randomx_vm structure. Must not be NULL.
* @param input is a pointer to memory to be hashed. Must not be NULL.
* @param inputSize is the number of bytes to be hashed.
* @param output is a pointer to memory where the hash will be stored. Must not
* be NULL and at least RANDOMX_HASH_SIZE bytes must be available for writing.
*/
RANDOMX_EXPORT void randomx_calculate_hash(randomx_vm *machine, const void *input, size_t inputSize, void *output, const xmrig::Algorithm algo);
RANDOMX_EXPORT void randomx_calculate_hash_first(randomx_vm* machine, uint64_t (&tempHash)[8], const void* input, size_t inputSize, const xmrig::Algorithm algo);
RANDOMX_EXPORT void randomx_calculate_hash_next(randomx_vm* machine, uint64_t (&tempHash)[8], const void* nextInput, size_t nextInputSize, void* output, const xmrig::Algorithm algo);
#if defined(__cplusplus)
}
#endif
#endif
|
#include<bits/stdc++.h>
#define rep(i,n) for (int i =0; i <(n); i++)
using namespace std;
using ll = long long;
int main(){
int N;
cin >> N;
string S,T;
cin >> S >> T;
string X;
for(int i = 0; i < N; i++){
X.push_back(S.at(i));
X.push_back(T.at(i));
}
cout << X << endl;
return 0;
}
|
#ifndef BONUSBOMB_H
#define BONUSBOMB_H
#include "Element.h"
#include "xil_types.h"
class BonusBomb : public Element
{
public:
BonusBomb();
void Init() override;
uint8_t IsCollidable() const override;
uint8_t IsFireCollidable() const override;
uint8_t Code() const override;
};
#endif
|
#include <iostream>
#include <vector>
using namespace std;
#include "TH1D.h"
#include "TH2D.h"
#include "TFile.h"
#include "TTree.h"
#include "TNtuple.h"
#include "SetStyle.h"
#include "PlotHelper4.h"
#include "CommandLine.h"
#include "ProgressBar.h"
#include "TauHelperFunctions2.h"
int main(int argc, char *argv[]);
double GetCorrection(int hiBin, double eta);
void HistogramXYDivide(TH2D &H);
void HistogramShiftCopy(TH2D &H, TH2D &H2);
void PlotDifference(PdfFileHelper &PdfFile, TH1D &H1, TH1D &H2, string Name);
int main(int argc, char *argv[])
{
SetThesisStyle();
CommandLine CL(argc, argv);
string InputFileName = CL.Get("Input", "vJetTrkSkim_pbpb_2018_data_zmm.root");
string OutputFileName = CL.Get("Output", "Plots");
double ZPtCut = CL.GetDouble("ZPtCut",20);
double TrkEtaCut = CL.GetDouble("TrkEtaCut",-10);
cout <<ZPtCut<<" "<<TrkEtaCut<<endl;
bool DoEE = CL.GetBool("EE", false);
TFile File(InputFileName.c_str());
TTree *HiTree = (TTree *)File.Get("HiTree");
// TTree *MixEventTree = (TTree *)File.Get("mixEventSkim");
TTree *EventTree = (TTree *)File.Get("EventTree");
TTree *TrackTree = (TTree *)File.Get("trackSkim");
int hiBin;
HiTree->SetBranchAddress("hiBin", &hiBin);
int nEle;
vector<int> *eleCharge = nullptr;
vector<float> *elePt = nullptr, *eleEta = nullptr, *elePhi = nullptr;
vector<float> *eleSCEn = nullptr, *eleSCEta = nullptr, *eleSCPhi = nullptr;
int nMu;
vector<int> *muCharge = nullptr;
vector<int> *muIDTight = nullptr;
vector<float> *muPt = nullptr, *muEta = nullptr, *muPhi = nullptr;
EventTree->SetBranchAddress("nEle", &nEle);
EventTree->SetBranchAddress("eleCharge", &eleCharge);
EventTree->SetBranchAddress("elePt", &elePt);
EventTree->SetBranchAddress("eleEta", &eleEta);
EventTree->SetBranchAddress("elePhi", &elePhi);
EventTree->SetBranchAddress("eleSCEn", &eleSCEn);
EventTree->SetBranchAddress("eleSCEta", &eleSCEta);
EventTree->SetBranchAddress("eleSCPhi", &eleSCPhi);
EventTree->SetBranchAddress("nMu", &nMu);
EventTree->SetBranchAddress("muCharge", &muCharge);
EventTree->SetBranchAddress("muPt", &muPt);
EventTree->SetBranchAddress("muEta", &muEta);
EventTree->SetBranchAddress("muPhi", &muPhi);
EventTree->SetBranchAddress("muIDTight", &muIDTight);
TFile OutputFile((OutputFileName + ".root").c_str(), "RECREATE");
TNtuple *ntZ = new TNtuple ("ntZ","","mass:pt:ch1:ch2:hiBin");
double ZCount = 0;
double ZCount0030 = 0, ZCount3090 = 0;
int EntryCount = EventTree->GetEntries();
ProgressBar Bar(cout, EntryCount);
for(int iE = 0; iE < EntryCount; iE++)
{
Bar.Update(iE);
Bar.Print();
HiTree->GetEntry(iE);
EventTree->GetEntry(iE);
int nLepton = (DoEE ? nEle : nMu);
FourVector P1, P2;
map<double, FourVector> Leptons;
for(int i = 0; i < nLepton; i++)
{
double Correction = (DoEE ? GetCorrection(hiBin, (*eleSCEta)[i]) : 1);
if(DoEE)
if((*eleSCEta)[i] < -1.392 && (*eleSCPhi)[i] < -0.872665 && (*eleSCPhi)[i] > -1.570796)
continue;
if (!DoEE) {
if ((*muIDTight)[i]==0) continue;
}
FourVector P;
if(DoEE)
P.SetPtEtaPhiMass((*elePt)[i] * Correction, (*eleEta)[i], (*elePhi)[i], 0.000511);
else
P.SetPtEtaPhiMass((*muPt)[i] * Correction, (*muEta)[i], (*muPhi)[i], 0.105658);
if(DoEE == true && (*eleCharge)[i] < 0)
P[0] = -P[0];
if(DoEE == false && (*muCharge)[i] < 0)
P[0] = -P[0];
Leptons.insert(pair<double, FourVector>(-P.GetPT(), P));
}
if(Leptons.size() < 2)
continue;
map<double, FourVector>::iterator iter = Leptons.begin();
P1 = iter->second;
iter++;
P2 = iter->second;
if(GetDR(P1, P2) < 0.2 && iter != Leptons.end())
{
iter++;
if(iter != Leptons.end())
P2 = iter->second;
else
P2.SetPtEtaPhiMass(0, 0, 0, 0);
}
int Charge1 = (P1[0] > 0) ? 1 : -1;
int Charge2 = (P2[0] > 0) ? 1 : -1;
P1[0] = fabs(P1[0]);
P2[0] = fabs(P2[0]);
if(P1.GetPT() < 20)
continue;
if(P2.GetPT() < 20)
continue;
if(P1.GetAbsEta() > 2.1)
continue;
if(P2.GetAbsEta() > 2.1)
continue;
FourVector LL = P1 + P2;
ntZ->Fill(LL.GetMass(),LL.GetPT(),Charge1,Charge2,hiBin);
}
Bar.Update(EntryCount);
Bar.Print();
Bar.PrintLine();
ntZ->Write();
OutputFile.Close();
return 0;
}
double GetCorrection(int hiBin, double eta)
{
eta = fabs(eta);
if(eta < 1.442)
{
if(hiBin < 20) return 0.990;
if(hiBin < 60) return 1.006;
return 1.016;
}
if(eta > 1.566 && eta < 2.5)
{
if(hiBin < 20) return 0.976;
if(hiBin < 60) return 1.015;
return 1.052;
}
return 0;
}
void HistogramXYDivide(TH2D &H)
{
TH1D *H1 = (TH1D *)H.ProjectionX();
TH1D *H2 = (TH1D *)H.ProjectionY();
for(int iX = 1; iX <= H1->GetNbinsX(); iX++)
for(int iY = 1; iY <= H2->GetNbinsX(); iY++)
H.SetBinContent(iX, iY, H.GetBinContent(iX, iY) / H1->GetBinContent(iX) / H2->GetBinContent(iY));
}
void HistogramShiftCopy(TH2D &H1, TH2D &H2)
{
int NX = H1.GetNbinsX();
int NY = H1.GetNbinsY();
for(int iX = 1; iX <= NX; iX++)
for(int iY = 1; iY <= NY; iY++)
H2.SetBinContent(iX, iY, H1.GetBinContent((iX + NX / 2 + iY - 2) % NX + 1, iY));
}
void PlotDifference(PdfFileHelper &PdfFile, TH1D &H1, TH1D &H2, string Name)
{
TH1D *H = (TH1D *)H1.Clone(Name.c_str());
H->Add(&H2, -1);
H->SetMinimum(0);
H->SetMaximum(25);
H->Write();
PdfFile.AddPlot(H);
}
|
/* Author: Mincheul Kang */
#ifndef HARMONIOUS_SAMPLING_MANIPULATIONREGION_H
#define HARMONIOUS_SAMPLING_MANIPULATIONREGION_H
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <moveit_msgs/GetPlanningScene.h>
#include <moveit/move_group_interface/move_group_interface.h>
#include <harmonious_msgs/BaseConf.h>
#include <harmonious_sampling/HarmoniousParameters.h>
#include <harmonious_msgs/JointConf.h>
class MainpulationRegion
{
public:
MainpulationRegion(planning_scene::PlanningScenePtr& planning_scene,
std::string planning_group,
std::string collision_check_group,
HarmoniousParameters ¶ms,
std::vector<harmonious_msgs::BaseConf> &base_confs,
std::vector<harmonious_msgs::JointConf> &joint_confs);
~MainpulationRegion();
bool isValid(harmonious_msgs::BaseConf &bp);
void generate_regions(ompl::base::RealVectorBounds &bounds);
bool*** regions_;
private:
collision_detection::CollisionRequest collision_request_;
planning_scene::PlanningScenePtr planning_scene_;
std::string planning_group_;
std::vector<harmonious_msgs::BaseConf> &base_confs_;
std::vector<harmonious_msgs::JointConf> &joint_confs_;
HarmoniousParameters ¶ms_;
};
#endif //HARMONIOUS_SAMPLING_MANIPULATIONREGION_H
|
#include <iostream>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <vector>
const int size = 5;
//LOOK AT selectionSort AND swap, SWAPPING ARRAY ELEMENTS BY REFERENCE
// swap values at memory locations to which
// element1Ptr and element2Ptr point
void swap(int* const element1Ptr, int* const element2Ptr){
int hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
}//swap
void selectionSort( int * const array, const int size ){
int smallest; // index of smallest element
//loop over size-1 elements
for (int i = 0; i < size - 1; ++i){
smallest = i; //first index of remaining array
// loop to find index of smallest element
for (int index = i + 1; index < size; ++index){
if (array[index] < array[smallest]) //sets the smallest index
smallest = index;
}//for
swap(&array[i], &array[smallest]); //if already smallest swap, swaps itself
}//for
} //selectionSort
void fillArray(int array []){
std::srand(std::time(NULL));
for(int i = 0; i < ::size; ++i){
array[i] = 1 + std::rand() % 25; //passes by reference
}
return;
}
int main(){
int array [::size] = {};
fillArray(array);
for(int i = 0; i < ::size; ++i){
printf("%d ", array[i]);
}
printf("\n");
selectionSort(array, ::size);
for(int i = 0; i < ::size; ++i){
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
|
#pragma once
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
//#include <sstream>
#include "TFile.h"
#include "TTree.h"
#include "TH1F.h"
#include <TObject.h>
#include "TString.h"
#define NFEC 4
#define NAPV 16
#define NCH 128
#define DISCARD_THRESHOLD 200
using namespace std;
class RootFile: public TObject
{
public:
RootFile(TString fileName, TString pedestalName, bool isRawPedestalRun,
bool isPedestalRun, bool isZSRun, bool clusteringOn,
std::vector<int> xChips,
std::vector<int> yChips, int mapping);
~RootFile();
void InitRootFile();
void InitPedestalHistograms(int fecID, int apvID);
void InitPedestalData(int fecID, int apvID);
void SetRunFlags(bool isRawPedestalRun, bool isPedestalRun);
float GetStripRawPedestalNoise(int fecID, int apvID, int stripNr);
float GetStripRawPedestalOffset(int fecID, int apvID, int stripNr);
float GetStripPedestalNoise(int fecID, int apvID, int stripNr);
float GetStripPedestalOffset(int fecID, int apvID, int stripNr);
float GetMeanPedestalOffset(int fecID, int apvID);
void FillPedestalData(int fecID, int apvID, int stripNo, float mean);
void CreateHistograms(int minFECID, int maxFECID, int minAPVID,
int maxAPVID);
void FillStripData(int stripNo, float rawdata);
bool StripDataExists(int stripNo);
float GetMeanStripData(int stripNo);
float GetStripData(int stripNo, int timeBin);
void ClearStripData(int stripNo);
void WriteRootFile();
void AddHits(signed int timestamp, int us, int eventId, int fecID,
int apvID, int chNo, float maxADC, int timeBinMaxADC,
std::vector<float> &timeBinADCs);
void FillHits();
void DeleteHitsTree();
int GetStripNumber(int chNo);
void resetClusterData();
unsigned int GetPlaneID(unsigned int chipID);
unsigned int GetChannelX(unsigned int chipID, unsigned int channelID);
unsigned int GetChannelY(unsigned int chipID, unsigned int channelID);
private:
bool isRawPedestalRun;
bool isPedestalRun;
bool isZSRun;
bool clusteringOn;
ofstream fTextFile;
TFile * fFile;
TFile * fFilePedestal;
TTree * fHitTree;
TString fFileName;
TString fPedestalName;
std::vector<TH1F*> rawPedestalNoise;
std::vector<TH1F*> rawPedestalOffset;
std::vector<TH1F*> pedestalNoise;
std::vector<TH1F*> pedestalOffset;
std::vector<std::vector<TH1F*> > chipData;
std::vector<std::vector<float>*> stripData;
std::vector<int> xChipIDs;
std::vector<int> yChipIDs;
int mapping;
int m_timestamp; //Unix time stamp
int m_us;
int m_evtID;
long m_chID;
long m_nchX;
long m_nchY;
int * m_planeID; // Plane Number
int * m_fecID; // APVId
int * m_apvID; // APVId
int * m_strip_chip; // Strip Number chip
int * m_strip; // Strip Number
short * m_x;
short * m_y;
int * m_hitTimeBin; //time bin with maximum ADC
short* m_hitMaxADC; //Maximum ADC value of hit
short * m_adc0; //ADC value for 1st time sample
short * m_adc1; //ADC value for 2nd time sample
short * m_adc2; //ADC value for 3rd time sample
short * m_adc3; //ADC value for 4th time sample
short * m_adc4; //ADC value for 5th time sample
short * m_adc5; //ADC value for 6th time sample
short * m_adc6; //ADC value for 7th time sample
short * m_adc7; //ADC value for 8th time sample
short * m_adc8; //ADC value for 9th time sample
short * m_adc9; //ADC value for 10th time sample
short * m_adc10; //ADC value for 11th time sample
short * m_adc11; //ADC value for 12th time sample
short * m_adc12; //ADC value for 13th time sample
short * m_adc13; //ADC value for 14th time sample
short * m_adc14; //ADC value for 15th time sample
short * m_adc15; //ADC value for 16th time sample
short * m_adc16; //ADC value for 17th time sample
short * m_adc17; //ADC value for 18th time sample
short * m_adc18; //ADC value for 19th time sample
short * m_adc19; //ADC value for 20th time sample
short * m_adc20; //ADC value for 21th time sample
short * m_adc21; //ADC value for 22th time sample
short * m_adc22; //ADC value for 23th time sample
short * m_adc23; //ADC value for 24th time sample
short * m_adc24; //ADC value for 25th time sample
short * m_adc25; //ADC value for 26th time sample
short * m_adc26; //ADC value for 27th time sample
short * m_adc27; //ADC value for 28th time sample
short * m_adc28; //ADC value for 29th time sample
short * m_adc29; //ADC value for 30th time sample
std::vector<float> stripMaximaX;
std::vector<float> stripMaximaY;
std::vector<float> timeMaximaX;
std::vector<float> timeMaximaY;
std::vector<float> energyMaximaX;
std::vector<float> energyMaximaY;
/* C++ 2011
bool isFirstLine = true;
bool newData = false;
int amplitudeThreshold = 0;
int numMaximaX = 0;
int numMaximaY = 0;
double x0 = 0;
double y0 = 0;
double xf = 0;
double yf = 0;
double xm = 0;
double ym = 0;
double xi = 0;
double yi = 0;
double xs = 0;
double ys = 0;
double xd = 0;
double yd = 0;
double xmax = 0;
double ymax = 0;
double xAmplitude = 0;
double xIntegral = 0;
double yAmplitude = 0;
double yIntegral = 0;
double maxAmplitudeX = 0;
double maxAmplitudeY = 0;
double tMaxAmplitudeX = 0;
double tMaxAmplitudeY = 0;
double tx0 = 0;
double ty0 = 0;
double txf = 0;
double tyf = 0;
double txs = 0;
double tys = 0;
double txd = 0;
double tyd = 0;
double txmax = 0;
double tymax = 0;
double ex0 = 0;
double ey0 = 0;
double exf = 0;
double eyf = 0;
double exs = 0;
double eys = 0;
double exd = 0;
double eyd = 0;
double exmax = 0;
double eymax = 0;
int nx = 0;
int ny = 0;
int ntx = 0;
int nty = 0;
bool discardFlag = false;
*/
bool isFirstLine;
bool newData;
int amplitudeThreshold;
int numMaximaX;
int numMaximaY;
double x0;
double y0;
double xf;
double yf;
double xm;
double ym;
double xi;
double yi;
double xs;
double ys;
double xd;
double yd;
double xmax;
double ymax;
double xAmplitude;
double xIntegral;
double yAmplitude;
double yIntegral;
double maxAmplitudeX;
double maxAmplitudeY;
double tMaxAmplitudeX;
double tMaxAmplitudeY;
double tx0;
double ty0;
double txf;
double tyf;
double txs;
double tys;
double txd;
double tyd;
double txmax;
double tymax;
double ex0;
double ey0;
double exf;
double eyf;
double exs;
double eys;
double exd;
double eyd;
double exmax;
double eymax;
int nx;
int ny;
int ntx;
int nty;
bool discardFlag;
ClassDef(RootFile,1)
};
|
#ifndef REFERENCE_GKNP_KERNELS_H_
#define REFERENCE_GKNP_KERNELS_H_
/* -------------------------------------------------------------------------- *
* OpenMM-GKNP *
* -------------------------------------------------------------------------- */
#include "GKNPKernels.h"
#include "openmm/Platform.h"
#include <vector>
#include "gaussvol.h"
namespace GKNPPlugin {
/**
* This kernel is invoked by GKNPForce to calculate the forces acting
* on the system and the energy of the system.
*/
class ReferenceCalcGKNPForceKernel : public CalcGKNPForceKernel {
public:
ReferenceCalcGKNPForceKernel(std::string name, const OpenMM::Platform& platform) : CalcGKNPForceKernel(name, platform) {
gvol = 0;
}
~ReferenceCalcGKNPForceKernel(){
if(gvol) delete gvol;
positions.clear();
ishydrogen.clear();
radii_vdw.clear();
radii_large.clear();
gammas.clear();
vdw_alpha.clear();
charge.clear();
free_volume.clear();
self_volume.clear();
vol_force.clear();
vol_dv.clear();
volume_scaling_factor.clear();
}
/**
* Initialize the kernel.
*
* @param system the System this kernel will be applied to
* @param force the GKNPForce this kernel will be used for
*/
void initialize(const OpenMM::System& system, const GKNPForce& force);
/**
* Execute the kernel to calculate the forces and/or energy.
*
* @param context the context in which to execute this kernel
* @return the potential energy due to the force
*/
double execute(OpenMM::ContextImpl& context, bool includeForces, bool includeEnergy);
/**
* Copy changed parameters over to a context.
*
* @param context the context to copy parameters to
* @param force the GKNPForce to copy the parameters from
*/
void copyParametersToContext(OpenMM::ContextImpl& context, const GKNPForce& force);
private:
GaussVol *gvol; // gaussvol instance
//inputs
int numParticles;
std::vector<RealVec> positions;
std::vector<int> ishydrogen;
std::vector<RealOpenMM> radii_vdw;
std::vector<RealOpenMM> radii_large;
std::vector<RealOpenMM> gammas;
double common_gamma;
std::vector<RealOpenMM> vdw_alpha;
std::vector<RealOpenMM> charge;
//outputs
std::vector<RealOpenMM> free_volume, self_volume;
std::vector<RealOpenMM> free_volume_vdw, self_volume_vdw;
std::vector<RealOpenMM> free_volume_large, self_volume_large;
std::vector<RealVec> vol_force;
std::vector<RealOpenMM> vol_dv;
std::vector<RealOpenMM> volume_scaling_factor;
double solvent_radius;
double roffset;
double executeGVolSA(OpenMM::ContextImpl& context, bool includeForces, bool includeEnergy);
};
//class to record MS particles
class MSParticle {
public:
double vol;
double vol_large;
double vol_vdw;
double vol0;
double ssp_large;
double ssp_vdw;
RealVec pos;
int parent1;
int parent2;
RealVec gder;//used for volume derivatives
RealVec hder;//used for positional derivatives
double fms;
double G0_vdw; //accumulator for derivatives
double G0_large;
};
} // namespace GKNPPlugin
#endif /*REFERENCE_GKNP_KERNELS_H_*/
|
#include <gtk/gtk.h>
#include <string>
#include <stdbool.h>
#include <cmath>
#include <iostream>
#include <fstream>
#define MAX_X 43
#define MAX_Y 33
#define W_SOR 1.8
#define PRECISAO_CONVERGENCIA 0.00001
using namespace std;
typedef struct {
int x;
int y;
} posicao;
typedef struct{
float matPot[MAX_Y][MAX_X];
bool matBoolPot[MAX_Y][MAX_X];
} campoPot;
campoPot CampoPotencial;
void guardaMatriz() {
ofstream arquivo;
arquivo.open("dados.txt",ios::out | ios::trunc);
arquivo.precision(3);
if (!arquivo.is_open()) {
printf("\ndeu ruim !\n\n");
return;
}
for(int i=0; i<MAX_Y; i++) {
for (int j=0; j<MAX_X;j++) {
arquivo << CampoPotencial.matPot[i][j] << ' ';
}
arquivo << '\n';
}
arquivo << "\n\n";
for(int i=0; i<MAX_Y; i++) {
for (int j=0; j<MAX_X;j++) {
arquivo << CampoPotencial.matBoolPot[i][j] << ' ';
}
arquivo << '\n';
}
arquivo.close();
}
void geraCampo(posicao objetivo, posicao obstaculos[], int numObstaculos){
for (int i=0;i<numObstaculos;i++) {
CampoPotencial.matPot[obstaculos[i].x][obstaculos[i].y] = 1;
CampoPotencial.matBoolPot[obstaculos[i].x][obstaculos[i].y] = true;
}
for (int i = 0; i < MAX_Y; i++) { // Parede da esquerda
for (int j=0; j<MAX_X; j++) {
if (i==0 || i==MAX_Y-1 || j==0 || j==MAX_X-1) {
CampoPotencial.matPot[i][j] = 1;
CampoPotencial.matBoolPot[i][j] = true;
}
else {
CampoPotencial.matPot[i][j] = 0;
CampoPotencial.matBoolPot[i][j] = false;
}
}
}
CampoPotencial.matBoolPot[objetivo.x][objetivo.y] = true;
float resultTemp;
bool convergiu = true;
do {
convergiu = true;
for (int i = 1; i < MAX_Y - 1; i++) {
for (int j = 1; j < MAX_X - 1; j++) {
if (CampoPotencial.matBoolPot[i][j] == false) {
resultTemp =W_SOR* (CampoPotencial.matPot[i + 1][j]
+ CampoPotencial.matPot[i - 1][j]
+ CampoPotencial.matPot[i][j + 1]
+ CampoPotencial.matPot[i][j - 1]
- 4 * CampoPotencial.matPot[i][j]) / 4
+ CampoPotencial.matPot[i][j];
if ((CampoPotencial.matPot[i][j] - resultTemp > PRECISAO_CONVERGENCIA) || (resultTemp - CampoPotencial.matPot[i][j] > PRECISAO_CONVERGENCIA))
convergiu = false;
CampoPotencial.matPot[i][j] = resultTemp;
}
}
}
} while (!convergiu);
}
double anguloCelula(int i, int j) {
double resul = atan2((double) (CampoPotencial.matPot[i][j - 1] - CampoPotencial.matPot[i][j + 1]),
(double) (CampoPotencial.matPot[i - 1][j] - CampoPotencial.matPot[i + 1][j]));
return resul;
}
void desenhaCampo(cairo_t *cr) {
int larguraCanvas = 800;
int alturaCanvas = 600;
int proporcao = 3;
int grossuraParede = 3;
int larguraCampo = 150 * proporcao;
int alturaCampo = 130 * proporcao + 12;
int grossuraGrade = 1;
double larguraCelula = 3.75 * proporcao;
double alturaCelula = 4.34 * proporcao;
int numCelulasEmX = MAX_X;
int numCelulasEmY = MAX_Y;
//Seção que cria o campo.
int xCampo = (larguraCanvas - larguraCampo)/2;
int yCampo = (alturaCanvas - alturaCampo)/2;
double rCampo = 107.0/255;
double gCampo = 142.0/255;
double bCampo = 35.0/255;
cairo_set_source_rgb(cr, rCampo, gCampo, bCampo);
cairo_rectangle (cr, xCampo,yCampo ,larguraCampo,alturaCampo);
cairo_fill(cr);
cairo_set_source_rgb(cr, 0, 0, 0);
//Seção que cria a parede ao redor do campo.
int xParede = xCampo - grossuraParede;
int yParede = yCampo - grossuraParede;
int larguraParede = grossuraParede + larguraCampo + grossuraParede;
int alturaParede = grossuraParede + alturaCampo + grossuraParede;
double rParede = 165.0/255;
double gParede = 128.0/255;
double bParede = 100.0/255;
cairo_set_line_width(cr,grossuraParede*2);
cairo_set_source_rgb(cr, rParede, gParede, bParede);
cairo_rectangle (cr, xParede,yParede,larguraParede,alturaParede);
cairo_stroke(cr);
cairo_set_line_width(cr,2.0);
cairo_set_source_rgb(cr, 0, 0, 0);
//Seção que cria a grade sobre o campo.
int xCelula = xCampo - larguraCelula;
int yCelula = yCampo - alturaCelula;
cairo_set_line_width(cr,grossuraGrade*2);
for (int i=0; i< MAX_Y; i++) {
for (int j=0; j<MAX_X; j++) {
cairo_rectangle (cr, xCelula,yCelula,larguraCelula,alturaCelula);
xCelula += larguraCelula;
}
xCelula = xCampo - larguraCelula;
yCelula += alturaCelula;
}
cairo_stroke(cr);
cairo_set_line_width(cr,2.0);
//Seção que desenha obstaculos
double rObstaculo = 139.0/255;
double gObstaculo = 0.0/255;
double bObsatculo = 0.0/255;
xCelula = xCampo - larguraCelula;
yCelula = yCampo - alturaCelula;
cairo_set_source_rgb(cr, rObstaculo, gObstaculo, bObsatculo);
for (int i=0; i< MAX_Y; i++) {
for (int j=0; j< MAX_X; j++) {
if (CampoPotencial.matBoolPot[i][j] == true && CampoPotencial.matPot[i][j] == 1) {
cairo_rectangle (cr, xCelula + 1, yCelula + 1, larguraCelula - 2, alturaCelula - 2);
}
xCelula += larguraCelula;
}
xCelula = xCampo - larguraCelula;
yCelula += alturaCelula;
}
cairo_fill(cr);
cairo_set_source_rgb(cr, 0, 0, 0);
//Seção que desenha o objetivo
double rObjetivo = 212.0/255;
double gObjetivo = 175.0/255;
double bObjetivo = 55.0/255;
xCelula = xCampo - larguraCelula;
yCelula = yCampo - alturaCelula;
cairo_set_source_rgb(cr, rObjetivo, gObjetivo, bObjetivo);
for (int i=0; i< MAX_Y; i++) {
for (int j=0; j<MAX_X; j++) {
if (CampoPotencial.matBoolPot[i][j] == true && CampoPotencial.matPot[i][j] == 0) {
cairo_rectangle (cr, xCelula + 1, yCelula + 1, larguraCelula - 2, alturaCelula - 2);
}
xCelula += larguraCelula;
}
xCelula = xCampo - larguraCelula;
yCelula += alturaCelula;
}
cairo_fill(cr);
cairo_set_source_rgb(cr, 0, 0, 0);
}
void desenhaPotenciais(cairo_t *cr) {
double angulo;
double larguraCelula = 3.75 * 3;
double alturaCelula = 4.34 * 3;
double temp1,temp2;
int xCampo = 175;
int yCampo = 99;
int xCelula = xCampo;
int yCelula = yCampo;
cairo_surface_t *seta = cairo_image_surface_create_from_png("seta.png");
int larguraSeta = cairo_image_surface_get_width(seta);
int alturaSeta = cairo_image_surface_get_height(seta);
cairo_set_source_surface(cr,seta,0,0);
guardaMatriz();
for (int i = 1; i < MAX_Y - 1; i++) {
for (int j=1; j < MAX_X - 1; j++) {
if (CampoPotencial.matBoolPot[i][j] == false) {
angulo = anguloCelula(i,j);
cairo_move_to(cr,0,0);
cairo_save(cr);
cairo_translate(cr, xCelula + larguraCelula/2, yCelula + alturaCelula/2);
cairo_rotate(cr,angulo);
cairo_scale(cr,0.6,0.6);
cairo_translate(cr,- larguraSeta/2.0, -alturaSeta/2.0);
cairo_set_source_surface(cr,seta, 0, 0);
cairo_paint(cr);
cairo_restore(cr);
}
xCelula += larguraCelula;
}
xCelula = xCampo;
yCelula += alturaCelula;
}
}
void drawHandler(GtkWidget *area, cairo_t *cr, gpointer dados) {
desenhaCampo(cr);
desenhaPotenciais(cr);
}
GtkWidget* preparaJanela() {
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
GError *erro = NULL;
gtk_window_set_title (GTK_WINDOW (window), "Carrossel Caipira - Controle");
gtk_window_set_icon_from_file(GTK_WINDOW(window), "icone.png", &erro);
if (erro != NULL) {
cout << erro->message << '\n';
g_clear_error (&erro);
}
gtk_window_set_resizable(GTK_WINDOW(window),false);
gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER_ALWAYS);
g_signal_connect (window, "destroy", gtk_main_quit, NULL);
return window;
}
GtkWidget* preparaConteudo() {
GtkWidget* boxLayout = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
GtkWidget* canvas = gtk_drawing_area_new();
gtk_widget_set_size_request (canvas, 800, 600);
g_signal_connect (G_OBJECT (canvas), "draw", G_CALLBACK (drawHandler), NULL);
gtk_box_pack_start(GTK_BOX(boxLayout),canvas,0,0,0);
return boxLayout;
}
int main(int argc, char *argv[]) {
gtk_init(&argc, &argv);
GtkWidget *window = preparaJanela();
GtkWidget *layoutPrincipal = preparaConteudo();
posicao objetivo;
int numObstaculos=0;
posicao obstaculos[numObstaculos];
objetivo.x=22;
objetivo.y=17;
geraCampo(objetivo,obstaculos,numObstaculos);
gtk_container_add(GTK_CONTAINER(window),layoutPrincipal);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
|
#include <assert.h>
#include <chrono>
#include <iostream>
#include <petunia/petunia.h>
#include <petunia/ipc_medium.h>
#include <petunia/message.h>
#include <petunia/osutils.h>
#define CHANNEL_PATH_SUBFOLDER "petunia/"
namespace Petunia
{
Petunia::Petunia(IPCMedium* medium)
: m_ipc_medium(medium)
{
Connect();
}
void Petunia::Connect()
{
StartMQThread();
}
Petunia::~Petunia()
{
TerminateMQThread();
delete m_ipc_medium;
}
std::string Petunia::GetID()
{
return m_ipc_medium->GetChannel();
}
void Petunia::SendMessage(std::shared_ptr<Message> message)
{
std::lock_guard<std::mutex> locked(m_send_lock);
m_outbox_queue.push(message);
m_send_condition_variable.notify_all();
}
void Petunia::UpdateMessage(std::shared_ptr<Message> message)
{
message->SetOverwriteMode(true);
SendMessage(message);
}
bool Petunia::EnqueueReceivedMessages()
{
return m_ipc_medium->ReceiveMessages(m_inbox_queue);
}
bool Petunia::SendEnqueuedMessages()
{
return m_ipc_medium->SendMessages(m_outbox_queue);
}
void Petunia::StartMQThread()
{
m_running = true;
m_mq_receive_thread = new std::thread([&]() { ReceiveThreadLoop(); });
m_mq_send_thread = new std::thread([&]() { SendThreadLoop(); });
}
void Petunia::SendThreadLoop()
{
while (m_running)
{
std::unique_lock<std::mutex> locked(m_send_lock);
m_send_condition_variable.wait(locked, [&] {return m_outbox_queue.size() > 0 || !m_running;});
if (m_running) {
SendEnqueuedMessages();
}
}
}
void Petunia::ReceiveThreadLoop()
{
while (m_running)
{
std::unique_lock<std::mutex> locked(m_receive_lock);
if (!EnqueueReceivedMessages()) {
std::this_thread::sleep_for(std::chrono::nanoseconds(1));
} else {
Distribute();
}
}
}
void Petunia::TerminateMQThread()
{
m_running = false;
m_send_condition_variable.notify_all();
m_mq_receive_thread->join();
m_mq_send_thread->join();
delete m_mq_receive_thread;
delete m_mq_send_thread;
}
std::string Petunia::GetPetuniaFolder()
{
std::string petunia_folder_path = OSUtils::GetTemporaryFolder() + CHANNEL_PATH_SUBFOLDER;
if (!OSUtils::FolderExists(petunia_folder_path))
{
if (!OSUtils::CreateFolder(petunia_folder_path))
{
return nullptr;
}
}
return petunia_folder_path;
}
const std::string Petunia::GetChannel() const
{
return m_ipc_medium->GetChannel();
}
size_t Petunia::Distribute()
{
size_t count = m_inbox_queue.size();
while (!m_inbox_queue.empty()) {
std::shared_ptr<Message> message = m_inbox_queue.front();
m_inbox_queue.pop();
auto search = m_message_listeners.find(message->GetType());
if (search != m_message_listeners.end()) {
for (auto it = search->second->begin(); it != search->second->end(); ++it) {
(*it)(message);
}
}
}
return count;
}
size_t Petunia::AddListener(std::string name, std::function<void(std::shared_ptr<Message> message)> listener_function)
{
std::list <std::function<void(std::shared_ptr<Message> message)>> *list = nullptr;
auto search = m_message_listeners.find(name);
if (search == m_message_listeners.end()) {
list = new std::list <std::function<void(std::shared_ptr<Message> message)>>();
m_message_listeners.insert(std::make_pair(name, list));
}
list->push_front(listener_function);
return list->size();
}
bool Petunia::RemoveListeners(std::string name)
{
auto search = m_message_listeners.find(name);
if (search != m_message_listeners.end()) {
m_message_listeners.erase(search);
return true;
}
return false;
}
void Petunia::RemovePromises(std::string name)
{
}
void Petunia::Clear()
{
ClearPromises();
ClearListeners();
}
void Petunia::ClearListeners()
{
m_message_listeners.clear();
}
void Petunia::ClearPromises()
{
}
} // namespace Petunia
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#ifndef _MIMEUTIL_H_
#define _MIMEUTIL_H_
#ifdef _MIME_SUPPORT_
#include "modules/url/url_id.h"
#include "modules/formats/hdsplit.h"
class CharConverter;
class URL;
/**
* Convert an email header string into unicode
* @param target converted and decoded unicode string
* @param source header string in arbitrary charset and/or encoding
* @param maxlen maximum length od source to convert
* @param toplevel detect a charset and convert from it
* @param structured source can contain several levels marked by (), which will be treated recursively
* @param def_charset default charset of a document, if charset cannot be detected
* @param converter2 charset converter to be used if not toplevel
* @param contain_email_address don't break email address formating
*/
void RemoveHeaderEscapes(OpString &target,const char *&source,int maxlen,
BOOL toplevel=TRUE,BOOL structured=TRUE,
const char *def_charset=NULL, CharConverter *converter2=NULL, BOOL contain_email_address= FALSE);
/**
* Create an attachment URL
* @param base_url_type one of URL_ATTACHMENT, URL_NEWSATTACHMENT or URL_SNEWSATTACHMENT
* @param no_store do not store the created URL in cache
* @param content_id if not NULL, construct a cid: URL into content_id_url
* @param ext0 possible extension of suggested_filename, can be empty
* @param content_type mime type of the attachment
* @param suggested_filename possible name representing the URL
* @param content_id_url if not NULL, receives a cid: URL of content_id
* @param context_id if not 0, URL_Rep_Context will be created instead of URL_Rep.
* Enable the tweak TWEAK_MIME_SEPARATE_URL_SPACE_FOR_MIME to use this parameter.
* @return URL object represinting the attachment
*/
URL ConstructFullAttachmentURL_L(URLType base_url_type, BOOL no_store, HeaderEntry *content_id, const OpStringC &ext0,
HeaderEntry *content_type, const OpStringC &suggested_filename, URL *content_id_url
#ifdef URL_SEPARATE_MIME_URL_NAMESPACE
, URL_CONTEXT_ID context_id=0
#endif
);
#endif // _MIME_SUPPORT_
/**
* Get a line separated by CRLF, CR or LF from a text buffer
* @param data input buffer, doesn't need to end by 0
* @param startpos starting offset in data
* @param data_len length of data
* @param nextline_pos offset of the next line after the current line
* @param length length of the current line from startpos
* @param no_more TRUE if data_len is the final length of data
* @return TRUE if end of line was found in the current range <data + startpos, data + data_len)
*/
BOOL GetTextLine(const unsigned char *data, unsigned long startpos, unsigned long data_len,
unsigned long &nextline_pos, unsigned long &length, BOOL no_more);
/**
* Construct a URL object from a cid: address
* @param content_id Content-ID identifier
* @param context_id if not 0, URL_Rep_Context will be created instead of URL_Rep.
* Enable the tweak TWEAK_MIME_SEPARATE_URL_SPACE_FOR_MIME to use this parameter.
* @return URL object of the content_id or empty URL for invalid content_id
*/
URL ConstructContentIDURL_L(const OpStringC8 &content_id
#ifdef URL_SEPARATE_MIME_URL_NAMESPACE
, URL_CONTEXT_ID context_id=0
#endif
);
void InheritExpirationDataL(URL_InUse &child, URL_Rep *parent);
#endif
|
#include "Node.h"
#include "Mesh.h"
class ClosestPointQuery
{
public:
ClosestPointQuery(const Mesh& mesh);
//!finds the closest point to mesh within the specified maximum search distance.
//!returns whether the search was successful or not.
bool operator()(const Point& queryPoint, float maxDist, Point& closestPoint) const;
private:
Node * m_root; // root of the tree built to make fast distance queries
int m_numFaces;
TriangleVect m_triangles;
};
|
#ifndef GENOTYPE_H
#define GENOTYPE_H
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/progress.hpp>
#include <htslib/sam.h>
#include "util.h"
namespace torali
{
struct Geno {
int32_t svStartPrefix;
int32_t svStartSuffix;
int32_t svEndPrefix;
int32_t svEndSuffix;
int32_t svStart;
int32_t svEnd;
int32_t svt;
std::string ref;
std::string alt;
Geno() : svStartPrefix(-1), svStartSuffix(-1), svEndPrefix(-1), svEndSuffix(-1), svStart(-1), svEnd(-1), svt(-1) {}
};
inline float
percentIdentity(std::string const& s1, std::string const& s2, int32_t splitpos, int32_t window) {
// Get window boundaries
int32_t ws = std::max(splitpos - window, 0);
int32_t we = std::min(splitpos + window, (int32_t) s1.size());
// Find percent identity
bool varSeen = false;
bool refSeen = false;
int32_t refpos = 0;
uint32_t gapMM = 0;
uint32_t mm = 0;
uint32_t ma = 0;
float leftPerc = -1;
float rightPerc = -1;
bool inGap=false;
for(uint32_t j = 0; j < s1.size(); ++j) {
if (s2[j] != '-') varSeen = true;
if (s1[j] != '-') {
refSeen = true;
if ((refpos == splitpos) || (refpos == ws) || (refpos == we)) {
if (refpos == splitpos) {
leftPerc = 0;
if (ma + mm > 0) leftPerc = (float) ma / (float) (ma + mm);
}
if (refpos == we) {
rightPerc = 0;
if (ma + mm > 0) rightPerc = (float) ma / (float) (ma + mm);
}
mm = 0;
ma = 0;
gapMM = 0;
}
++refpos;
}
if ((refSeen) && (varSeen)) {
// Internal gap?
if ((s2[j] == '-') || (s1[j] == '-')) {
if (!inGap) {
inGap = true;
gapMM = 0;
}
gapMM += 1;
} else {
if (inGap) {
mm += gapMM;
inGap=false;
}
if (s2[j] == s1[j]) ma += 1;
else mm += 1;
}
}
}
if (rightPerc == -1) {
rightPerc = 0;
if (ma + mm > 0) rightPerc = (float) ma / (float) (ma + mm);
}
//std::cerr << ws << ',' << splitpos << ',' << we << ',' << leftPerc << ',' << rightPerc << std::endl;
return std::min(leftPerc, rightPerc);
}
template<typename TConfig, typename TJunctionMap, typename TReadCountMap>
inline void
trackRef(TConfig& c, std::vector<StructuralVariantRecord>& svs, TJunctionMap& jctMap, TReadCountMap& covMap) {
typedef std::vector<StructuralVariantRecord> TSVs;
typedef std::vector<uint8_t> TQuality;
typedef boost::multi_array<char, 2> TAlign;
if (svs.empty()) return;
// Open file handles
typedef std::vector<samFile*> TSamFile;
typedef std::vector<hts_idx_t*> TIndex;
typedef std::vector<bam_hdr_t*> THeader;
TSamFile samfile(c.files.size());
TIndex idx(c.files.size());
THeader hdr(c.files.size());
int32_t totalTarget = 0;
for(uint32_t file_c = 0; file_c < c.files.size(); ++file_c) {
samfile[file_c] = sam_open(c.files[file_c].string().c_str(), "r");
hts_set_fai_filename(samfile[file_c], c.genome.string().c_str());
idx[file_c] = sam_index_load(samfile[file_c], c.files[file_c].string().c_str());
hdr[file_c] = sam_hdr_read(samfile[file_c]);
totalTarget += hdr[file_c]->n_targets;
}
// Parse genome chr-by-chr
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "SV annotation" << std::endl;
boost::progress_display show_progress( hdr[0]->n_targets );
// Ref aligned reads
typedef std::vector<uint32_t> TRefAlignCount;
typedef std::vector<TRefAlignCount> TFileRefAlignCount;
TFileRefAlignCount refAlignedReadCount(c.files.size(), TRefAlignCount());
for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) refAlignedReadCount[file_c].resize(svs.size(), 0);
// Coverage distribution
typedef uint16_t TMaxCoverage;
uint32_t maxCoverage = std::numeric_limits<TMaxCoverage>::max();
typedef std::vector<uint32_t> TCovDist;
typedef std::vector<TCovDist> TSampleCovDist;
TSampleCovDist covDist(c.files.size(), TCovDist());
for(uint32_t i = 0; i < c.files.size(); ++i) covDist[i].resize(maxCoverage, 0);
// Error rates
std::vector<uint64_t> matchCount(c.files.size(), 0);
std::vector<uint64_t> mismatchCount(c.files.size(), 0);
std::vector<uint64_t> delCount(c.files.size(), 0);
std::vector<uint64_t> insCount(c.files.size(), 0);
// Read length distribution
typedef uint16_t TMaxReadLength;
uint32_t maxReadLength = std::numeric_limits<TMaxReadLength>::max();
uint32_t rlBinSize = 100;
typedef std::vector<uint32_t> TReadLengthDist;
typedef std::vector<TReadLengthDist> TSampleRLDist;
TSampleRLDist rlDist(c.files.size(), TReadLengthDist());
for(uint32_t i = 0; i < c.files.size(); ++i) rlDist[i].resize(maxReadLength * rlBinSize, 0);
// Dump file
boost::iostreams::filtering_ostream dumpOut;
if (c.hasDumpFile) {
dumpOut.push(boost::iostreams::gzip_compressor());
dumpOut.push(boost::iostreams::file_sink(c.dumpfile.string().c_str(), std::ios_base::out | std::ios_base::binary));
dumpOut << "#svid\tbam\tqname\tchr\tpos\tmatechr\tmatepos\tmapq\ttype" << std::endl;
}
// Iterate chromosomes
std::vector<std::string> refProbes(svs.size());
faidx_t* fai = fai_load(c.genome.string().c_str());
for(int32_t refIndex=0; refIndex < (int32_t) hdr[0]->n_targets; ++refIndex) {
++show_progress;
char* seq = NULL;
// Reference and consensus probes for this chromosome
typedef std::vector<Geno> TGenoRegion;
TGenoRegion gbp(svs.size(), Geno());
// Iterate all structural variants
for(typename TSVs::iterator itSV = svs.begin(); itSV != svs.end(); ++itSV) {
if ((itSV->chr != refIndex) && (itSV->chr2 != refIndex)) continue;
if ((itSV->svt != 2) && (itSV->svt != 4)) continue;
// Lazy loading of reference sequence
if (seq == NULL) {
int32_t seqlen = -1;
std::string tname(hdr[0]->target_name[refIndex]);
seq = faidx_fetch_seq(fai, tname.c_str(), 0, hdr[0]->target_len[refIndex], &seqlen);
}
// Set tag alleles
if (itSV->chr == refIndex) {
itSV->alleles = _addAlleles(boost::to_upper_copy(std::string(seq + itSV->svStart - 1, seq + itSV->svStart)), std::string(hdr[0]->target_name[itSV->chr2]), *itSV, itSV->svt);
}
if (!itSV->precise) continue;
// Get the reference sequence
if ((itSV->chr != itSV->chr2) && (itSV->chr2 == refIndex)) {
Breakpoint bp(*itSV);
_initBreakpoint(hdr[0], bp, (int32_t) itSV->consensus.size(), itSV->svt);
refProbes[itSV->id] = _getSVRef(seq, bp, refIndex, itSV->svt);
}
if (itSV->chr == refIndex) {
Breakpoint bp(*itSV);
if (_translocation(itSV->svt)) bp.part1 = refProbes[itSV->id];
if (itSV->svt ==4) {
int32_t bufferSpace = std::max((int32_t) ((itSV->consensus.size() - itSV->insLen) / 3), c.minimumFlankSize);
_initBreakpoint(hdr[0], bp, bufferSpace, itSV->svt);
} else _initBreakpoint(hdr[0], bp, (int32_t) itSV->consensus.size(), itSV->svt);
std::string svRefStr = _getSVRef(seq, bp, refIndex, itSV->svt);
// Find breakpoint to reference
TAlign align;
if (!_consRefAlignment(itSV->consensus, svRefStr, align, itSV->svt)) continue;
AlignDescriptor ad;
if (!_findSplit(c, itSV->consensus, svRefStr, align, ad, itSV->svt)) continue;
// Get exact alleles for INS and DEL
if ((itSV->svt == 2) || (itSV->svt == 4)) {
std::string refVCF;
std::string altVCF;
int32_t cpos = 0;
bool inSV = false;
for(uint32_t j = 0; j<align.shape()[1]; ++j) {
if (align[0][j] != '-') {
++cpos;
if (cpos == ad.cStart) inSV = true;
else if (cpos == ad.cEnd) inSV = false;
}
if (inSV) {
if (align[0][j] != '-') altVCF += align[0][j];
if (align[1][j] != '-') refVCF += align[1][j];
}
}
itSV->alleles = _addAlleles(refVCF, altVCF);
}
// Debug consensus to reference alignment
//std::cerr << "svid:" << itSV->id << ",consensus-to-reference-alignment" << std::endl;
//for(uint32_t i = 0; i<align.shape()[0]; ++i) {
//if (i == 0) {
//int32_t cpos = 0;
//for(uint32_t j = 0; j<align.shape()[1]; ++j) {
//if (align[i][j] != '-') ++cpos;
//if (cpos == ad.cStart) std::cerr << '|';
//else if (cpos == ad.cEnd) std::cerr << '|';
//else std::cerr << '#';
//}
//std::cerr << std::endl;
//}
//for(uint32_t j = 0; j<align.shape()[1]; ++j) std::cerr << align[i][j];
//std::cerr << std::endl;
//}
//std::cerr << std::endl;
// Trim aligned sequences
std::string altSeq;
std::string refSeq;
int32_t leadCrop = _trimAlignedSequences(align, altSeq, refSeq);
// Allele-tagging probes
gbp[itSV->id].svStartPrefix = std::max(ad.cStart - leadCrop, 0);
gbp[itSV->id].svStartSuffix = std::max((int32_t) altSeq.size() - gbp[itSV->id].svStartPrefix, 0);
gbp[itSV->id].svStart = itSV->svStart;
if (itSV->chr2 == refIndex) {
gbp[itSV->id].svEndPrefix = std::max(ad.cEnd - leadCrop, 0);
gbp[itSV->id].svEndSuffix = std::max((int32_t) altSeq.size() - gbp[itSV->id].svEndPrefix, 0);
gbp[itSV->id].svEnd = itSV->svEnd;
}
gbp[itSV->id].ref = refSeq;
gbp[itSV->id].alt = altSeq;
gbp[itSV->id].svt = itSV->svt;
}
}
if (seq != NULL) free(seq);
// Genotype
// Iterate samples
for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
// Check we have mapped reads on this chromosome
bool nodata = true;
std::string suffix("cram");
std::string str(c.files[file_c].string());
if ((str.size() >= suffix.size()) && (str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0)) nodata = false;
uint64_t mapped = 0;
uint64_t unmapped = 0;
hts_idx_get_stat(idx[file_c], refIndex, &mapped, &unmapped);
if (mapped) nodata = false;
if (nodata) continue;
// Coverage track
typedef std::vector<TMaxCoverage> TBpCoverage;
TBpCoverage covBases(hdr[file_c]->target_len[refIndex], 0);
// Flag breakpoints
typedef std::set<int32_t> TIdSet;
typedef std::map<uint32_t, TIdSet> TBpToIdMap;
TBpToIdMap bpid;
typedef boost::dynamic_bitset<> TBitSet;
TBitSet bpOccupied(hdr[file_c]->target_len[refIndex], false);
for(uint32_t i = 0; i < gbp.size(); ++i) {
if (gbp[i].svStart != -1) {
bpOccupied[gbp[i].svStart] = 1;
if (bpid.find(gbp[i].svStart) == bpid.end()) bpid.insert(std::make_pair(gbp[i].svStart, TIdSet()));
bpid[gbp[i].svStart].insert(i);
}
if (gbp[i].svEnd != -1) {
bpOccupied[gbp[i].svEnd] = 1;
if (bpid.find(gbp[i].svEnd) == bpid.end()) bpid.insert(std::make_pair(gbp[i].svEnd, TIdSet()));
bpid[gbp[i].svEnd].insert(i);
}
}
// Count reads
hts_itr_t* iter = sam_itr_queryi(idx[file_c], refIndex, 0, hdr[file_c]->target_len[refIndex]);
bam1_t* rec = bam_init1();
while (sam_itr_next(samfile[file_c], iter, rec) >= 0) {
// Genotyping only primary alignments
if (rec->core.flag & (BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP | BAM_FSUPPLEMENTARY | BAM_FUNMAP)) continue;
// Read length
int32_t readlen = readLength(rec);
if (readlen < (int32_t) (maxReadLength * rlBinSize)) ++rlDist[file_c][(int32_t) (readlen / rlBinSize)];
// Reference and sequence pointer
uint32_t rp = rec->core.pos; // reference pointer
uint32_t sp = 0; // sequence pointer
// All SV hits
typedef std::pair<int32_t, int32_t> TRefSeq;
typedef std::map<int32_t, TRefSeq> TSVSeqHit;
TSVSeqHit genoMap;
// Parse the CIGAR
uint32_t* cigar = bam_get_cigar(rec);
for (std::size_t i = 0; i < rec->core.n_cigar; ++i) {
if ((bam_cigar_op(cigar[i]) == BAM_CMATCH) || (bam_cigar_op(cigar[i]) == BAM_CEQUAL) || (bam_cigar_op(cigar[i]) == BAM_CDIFF)) {
// Fetch reference alignments
for(uint32_t k = 0; k < bam_cigar_oplen(cigar[i]); ++k) {
if ((rp < hdr[file_c]->target_len[refIndex]) && (covBases[rp] < maxCoverage - 1)) ++covBases[rp];
if (bpOccupied[rp]) {
for(typename TIdSet::const_iterator it = bpid[rp].begin(); it != bpid[rp].end(); ++it) {
// Ensure fwd alignment and each SV only once
if (genoMap.find(*it) == genoMap.end()) {
if (rec->core.flag & BAM_FREVERSE) genoMap.insert(std::make_pair(*it, std::make_pair(rp, readlen - sp)));
else genoMap.insert(std::make_pair(*it, std::make_pair(rp, sp)));
}
}
}
if ((bam_cigar_op(cigar[i]) == BAM_CMATCH) || (bam_cigar_op(cigar[i]) == BAM_CEQUAL)) ++matchCount[file_c];
else if (bam_cigar_op(cigar[i]) == BAM_CDIFF) ++mismatchCount[file_c];
++sp;
++rp;
}
} else if ((bam_cigar_op(cigar[i]) == BAM_CDEL) || (bam_cigar_op(cigar[i]) == BAM_CREF_SKIP)) {
++delCount[file_c];
for(uint32_t k = 0; k < bam_cigar_oplen(cigar[i]); ++k) {
if (bpOccupied[rp]) {
for(typename TIdSet::const_iterator it = bpid[rp].begin(); it != bpid[rp].end(); ++it) {
// Ensure fwd alignment and each SV only once
if (genoMap.find(*it) == genoMap.end()) {
if (rec->core.flag & BAM_FREVERSE) genoMap.insert(std::make_pair(*it, std::make_pair(rp, readlen - sp)));
else genoMap.insert(std::make_pair(*it, std::make_pair(rp, sp)));
}
}
}
++rp;
}
} else if (bam_cigar_op(cigar[i]) == BAM_CINS) {
++insCount[file_c];
sp += bam_cigar_oplen(cigar[i]);
} else if (bam_cigar_op(cigar[i]) == BAM_CSOFT_CLIP) {
sp += bam_cigar_oplen(cigar[i]);
} else if (bam_cigar_op(cigar[i]) == BAM_CHARD_CLIP) {
// Do nothing
} else {
std::cerr << "Unknown Cigar options" << std::endl;
}
}
// Read for genotyping?
if (!genoMap.empty()) {
// Get sequence
std::string sequence;
sequence.resize(rec->core.l_qseq);
uint8_t* seqptr = bam_get_seq(rec);
for (int i = 0; i < rec->core.l_qseq; ++i) sequence[i] = "=ACMGRSVTWYHKDBN"[bam_seqi(seqptr, i)];
// Genotype all SVs covered by this read
for(typename TSVSeqHit::iterator git = genoMap.begin(); git != genoMap.end(); ++git) {
int32_t svid = git->first;
uint32_t maxGenoReadCount = 500;
if ((jctMap[file_c][svid].ref.size() + jctMap[file_c][svid].alt.size()) >= maxGenoReadCount) continue;
int32_t rpHit = git->second.first;
int32_t spHit = git->second.second;
// Require spanning reads
std::string subseq;
if (rpHit == gbp[svid].svStart) {
if (rec->core.flag & BAM_FREVERSE) {
if (spHit < gbp[svid].svStartSuffix) continue;
if (readlen < gbp[svid].svStartPrefix + spHit) continue;
int32_t st = std::max((readlen - spHit) - gbp[svid].svStartPrefix - c.minimumFlankSize, 0);
subseq = sequence.substr(st, gbp[svid].svStartPrefix + gbp[svid].svStartSuffix + 2 * c.minimumFlankSize);
} else {
if (spHit < gbp[svid].svStartPrefix) continue;
if (readlen < gbp[svid].svStartSuffix + spHit) continue;
int32_t st = std::max(spHit - gbp[svid].svStartPrefix - c.minimumFlankSize, 0);
subseq = sequence.substr(st, gbp[svid].svStartPrefix + gbp[svid].svStartSuffix + 2 * c.minimumFlankSize);
}
} else {
if (rec->core.flag & BAM_FREVERSE) {
if (spHit < gbp[svid].svEndSuffix) continue;
if (readlen < gbp[svid].svEndPrefix + spHit) continue;
int32_t st = std::max((readlen - spHit) - gbp[svid].svEndPrefix - c.minimumFlankSize, 0);
subseq = sequence.substr(st, gbp[svid].svEndPrefix + gbp[svid].svEndSuffix + 2 * c.minimumFlankSize);
} else {
if (spHit < gbp[svid].svEndPrefix) continue;
if (readlen < gbp[svid].svEndSuffix + spHit) continue;
int32_t st = std::max(spHit - gbp[svid].svEndPrefix - c.minimumFlankSize, 0);
subseq = sequence.substr(st, gbp[svid].svEndPrefix + gbp[svid].svEndSuffix + 2 * c.minimumFlankSize);
}
}
// Compute alignment to alternative haplotype
DnaScore<int> simple(c.aliscore.match, c.aliscore.mismatch, c.aliscore.mismatch, c.aliscore.mismatch);
AlignConfig<true, false> semiglobal;
double scoreAlt = needleBanded(gbp[svid].alt, subseq, semiglobal, simple);
scoreAlt /= (double) (c.flankQuality * gbp[svid].alt.size() * simple.match + (1.0 - c.flankQuality) * gbp[svid].alt.size() * simple.mismatch);
// Compute alignment to reference haplotype
double scoreRef = needleBanded(gbp[svid].ref, subseq, semiglobal, simple);
scoreRef /= (double) (c.flankQuality * gbp[svid].ref.size() * simple.match + (1.0 - c.flankQuality) * gbp[svid].ref.size() * simple.mismatch);
// Any confident alignment?
if ((scoreRef > 1) || (scoreAlt > 1)) {
if (scoreRef > scoreAlt) {
// Account for reference bias
if (++refAlignedReadCount[file_c][svid] % 2) {
TQuality quality;
quality.resize(rec->core.l_qseq);
uint8_t* qualptr = bam_get_qual(rec);
for (int i = 0; i < rec->core.l_qseq; ++i) quality[i] = qualptr[i];
uint32_t rq = scoreRef * 35;
if (rq >= c.minGenoQual) {
uint8_t* hpptr = bam_aux_get(rec, "HP");
jctMap[file_c][svid].ref.push_back((uint8_t) std::min(rq, (uint32_t) rec->core.qual));
if (hpptr) {
c.isHaplotagged = true;
int hap = bam_aux2i(hpptr);
if (hap == 1) ++jctMap[file_c][svid].refh1;
else ++jctMap[file_c][svid].refh2;
}
}
}
} else {
TQuality quality;
quality.resize(rec->core.l_qseq);
uint8_t* qualptr = bam_get_qual(rec);
for (int i = 0; i < rec->core.l_qseq; ++i) quality[i] = qualptr[i];
uint32_t aq = scoreAlt * 35;
if (aq >= c.minGenoQual) {
uint8_t* hpptr = bam_aux_get(rec, "HP");
if (c.hasDumpFile) {
std::string svidStr(_addID(gbp[svid].svt));
std::string padNumber = boost::lexical_cast<std::string>(svid);
padNumber.insert(padNumber.begin(), 8 - padNumber.length(), '0');
svidStr += padNumber;
dumpOut << svidStr << "\t" << c.files[file_c].string() << "\t" << bam_get_qname(rec) << "\t" << hdr[file_c]->target_name[rec->core.tid] << "\t" << rec->core.pos << "\t" << hdr[file_c]->target_name[rec->core.mtid] << "\t" << rec->core.mpos << "\t" << (int32_t) rec->core.qual << "\tSR" << std::endl;
}
jctMap[file_c][svid].alt.push_back((uint8_t) std::min(aq, (uint32_t) rec->core.qual));
if (hpptr) {
c.isHaplotagged = true;
int hap = bam_aux2i(hpptr);
if (hap == 1) ++jctMap[file_c][svid].alth1;
else ++jctMap[file_c][svid].alth2;
}
}
}
}
}
}
}
// Clean-up
bam_destroy1(rec);
hts_itr_destroy(iter);
// Summarize coverage for this chromosome
for(uint32_t i = 0; i < hdr[file_c]->target_len[refIndex]; ++i) ++covDist[file_c][covBases[i]];
// Assign SV support
for(uint32_t i = 0; i < svs.size(); ++i) {
if (svs[i].chr == refIndex) {
int32_t halfSize = (svs[i].svEnd - svs[i].svStart)/2;
if ((_translocation(svs[i].svt)) || (svs[i].svt == 4)) halfSize = 500;
// Left region
int32_t lstart = std::max(svs[i].svStart - halfSize, 0);
int32_t lend = svs[i].svStart;
int32_t covbase = 0;
for(uint32_t k = lstart; ((k < (uint32_t) lend) && (k < hdr[file_c]->target_len[refIndex])); ++k) covbase += covBases[k];
covMap[file_c][svs[i].id].leftRC = covbase;
// Actual SV
covbase = 0;
int32_t mstart = svs[i].svStart;
int32_t mend = svs[i].svEnd;
if ((_translocation(svs[i].svt)) || (svs[i].svt == 4)) {
mstart = std::max(svs[i].svStart - halfSize, 0);
mend = std::min(svs[i].svStart + halfSize, (int32_t) hdr[file_c]->target_len[refIndex]);
}
for(uint32_t k = mstart; ((k < (uint32_t) mend) && (k < hdr[file_c]->target_len[refIndex])); ++k) covbase += covBases[k];
covMap[file_c][svs[i].id].rc = covbase;
// Right region
covbase = 0;
int32_t rstart = svs[i].svEnd;
int32_t rend = std::min(svs[i].svEnd + halfSize, (int32_t) hdr[file_c]->target_len[refIndex]);
if ((_translocation(svs[i].svt)) || (svs[i].svt == 4)) {
rstart = svs[i].svStart;
rend = std::min(svs[i].svStart + halfSize, (int32_t) hdr[file_c]->target_len[refIndex]);
}
for(uint32_t k = rstart; ((k < (uint32_t) rend) && (k < hdr[file_c]->target_len[refIndex])); ++k) covbase += covBases[k];
covMap[file_c][svs[i].id].rightRC = covbase;
}
}
}
}
// Clean-up
fai_destroy(fai);
// Output coverage info
std::cout << "Coverage distribution (^COV)" << std::endl;
for(uint32_t file_c = 0; file_c < c.files.size(); ++file_c) {
uint64_t totalCovCount = 0;
for (uint32_t i = 0; i < covDist[file_c].size(); ++i) totalCovCount += covDist[file_c][i];
std::vector<uint32_t> covPercentiles(5, 0); // 5%, 25%, 50%, 75%, 95%
uint64_t cumCovCount = 0;
for (uint32_t i = 0; i < covDist[file_c].size(); ++i) {
cumCovCount += covDist[file_c][i];
double frac = (double) cumCovCount / (double) totalCovCount;
if (frac < 0.05) covPercentiles[0] = i + 1;
if (frac < 0.25) covPercentiles[1] = i + 1;
if (frac < 0.5) covPercentiles[2] = i + 1;
if (frac < 0.75) covPercentiles[3] = i + 1;
if (frac < 0.95) covPercentiles[4] = i + 1;
}
std::cout << "COV\t" << c.sampleName[file_c] << "\t95% of bases are >= " << covPercentiles[0] << "x" << std::endl;
std::cout << "COV\t" << c.sampleName[file_c] << "\t75% of bases are >= " << covPercentiles[1] << "x" << std::endl;
std::cout << "COV\t" << c.sampleName[file_c] << "\t50% of bases are >= " << covPercentiles[2] << "x" << std::endl;
std::cout << "COV\t" << c.sampleName[file_c] << "\t25% of bases are >= " << covPercentiles[3] << "x" << std::endl;
std::cout << "COV\t" << c.sampleName[file_c] << "\t5% of bases are >= " << covPercentiles[4] << "x" << std::endl;
}
// Output read length info
std::cout << "Read-length distribution (^RL)" << std::endl;
for(uint32_t file_c = 0; file_c < c.files.size(); ++file_c) {
uint64_t totalRlCount = 0;
for (uint32_t i = 0; i < rlDist[file_c].size(); ++i) totalRlCount += rlDist[file_c][i];
std::vector<uint32_t> rlPercentiles(5, 0); // 5%, 25%, 50%, 75%, 95%
uint64_t cumRlCount = 0;
for (uint32_t i = 0; i < rlDist[file_c].size(); ++i) {
cumRlCount += rlDist[file_c][i];
double frac = (double) cumRlCount / (double) totalRlCount;
if (frac < 0.05) rlPercentiles[0] = (i + 1) * rlBinSize;
if (frac < 0.25) rlPercentiles[1] = (i + 1) * rlBinSize;
if (frac < 0.5) rlPercentiles[2] = (i + 1) * rlBinSize;
if (frac < 0.75) rlPercentiles[3] = (i + 1) * rlBinSize;
if (frac < 0.95) rlPercentiles[4] = (i + 1) * rlBinSize;
}
std::cout << "RL\t" << c.sampleName[file_c] << "\t95% of reads are >= " << rlPercentiles[0] << "bp" << std::endl;
std::cout << "RL\t" << c.sampleName[file_c] << "\t75% of reads are >= " << rlPercentiles[1] << "bp" << std::endl;
std::cout << "RL\t" << c.sampleName[file_c] << "\t50% of reads are >= " << rlPercentiles[2] << "bp" << std::endl;
std::cout << "RL\t" << c.sampleName[file_c] << "\t25% of reads are >= " << rlPercentiles[3] << "bp" << std::endl;
std::cout << "RL\t" << c.sampleName[file_c] << "\t5% of reads are >= " << rlPercentiles[4] << "bp" << std::endl;
}
// Output sequencing error rates
std::cout << "Sequencing error rates (^ERR)" << std::endl;
for(uint32_t file_c = 0; file_c < c.files.size(); ++file_c) {
uint64_t alignedbases = matchCount[file_c] + mismatchCount[file_c] + delCount[file_c] + insCount[file_c];
if (mismatchCount[file_c]) {
std::cout << "ERR\t" << c.sampleName[file_c] << "\tMatchRate\t" << (double) matchCount[file_c] / (double) alignedbases << std::endl;
std::cout << "ERR\t" << c.sampleName[file_c] << "\tMismatchRate\t" << (double) mismatchCount[file_c] / (double) alignedbases << std::endl;
}
std::cout << "ERR\t" << c.sampleName[file_c] << "\tDeletionRate\t" << (double) delCount[file_c] / (double) alignedbases << std::endl;
std::cout << "ERR\t" << c.sampleName[file_c] << "\tInsertionRate\t" << (double) insCount[file_c] / (double) alignedbases << std::endl;
}
// Clean-up
for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
bam_hdr_destroy(hdr[file_c]);
hts_idx_destroy(idx[file_c]);
sam_close(samfile[file_c]);
}
}
template<typename TConfig, typename TSRStore, typename TJunctionMap, typename TReadCountMap>
inline void
genotypeLR(TConfig& c, std::vector<StructuralVariantRecord>& svs, TSRStore& srStore, TJunctionMap& jctMap, TReadCountMap& covMap) {
typedef std::vector<StructuralVariantRecord> TSVs;
if (svs.empty()) return;
typedef uint16_t TMaxCoverage;
uint32_t maxCoverage = std::numeric_limits<TMaxCoverage>::max();
// Open file handles
typedef std::vector<samFile*> TSamFile;
typedef std::vector<hts_idx_t*> TIndex;
typedef std::vector<bam_hdr_t*> THeader;
TSamFile samfile(c.files.size());
TIndex idx(c.files.size());
THeader hdr(c.files.size());
int32_t totalTarget = 0;
for(uint32_t file_c = 0; file_c < c.files.size(); ++file_c) {
samfile[file_c] = sam_open(c.files[file_c].string().c_str(), "r");
hts_set_fai_filename(samfile[file_c], c.genome.string().c_str());
idx[file_c] = sam_index_load(samfile[file_c], c.files[file_c].string().c_str());
hdr[file_c] = sam_hdr_read(samfile[file_c]);
totalTarget += hdr[file_c]->n_targets;
}
// Parse genome chr-by-chr
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "SV annotation" << std::endl;
boost::progress_display show_progress( hdr[0]->n_targets );
// Ref aligned reads
typedef std::vector<uint32_t> TRefAlignCount;
typedef std::vector<TRefAlignCount> TFileRefAlignCount;
TFileRefAlignCount refAlignedReadCount(c.files.size(), TRefAlignCount());
for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) refAlignedReadCount[file_c].resize(svs.size(), 0);
// Dump file
boost::iostreams::filtering_ostream dumpOut;
if (c.hasDumpFile) {
dumpOut.push(boost::iostreams::gzip_compressor());
dumpOut.push(boost::iostreams::file_sink(c.dumpfile.string().c_str(), std::ios_base::out | std::ios_base::binary));
dumpOut << "#svid\tbam\tqname\tchr\tpos\tmatechr\tmatepos\tmapq\ttype" << std::endl;
}
faidx_t* fai = fai_load(c.genome.string().c_str());
// Iterate chromosomes
for(int32_t refIndex=0; refIndex < (int32_t) hdr[0]->n_targets; ++refIndex) {
++show_progress;
char* seq = NULL;
// Iterate samples
for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
// Check we have mapped reads on this chromosome
bool nodata = true;
std::string suffix("cram");
std::string str(c.files[file_c].string());
if ((str.size() >= suffix.size()) && (str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0)) nodata = false;
uint64_t mapped = 0;
uint64_t unmapped = 0;
hts_idx_get_stat(idx[file_c], refIndex, &mapped, &unmapped);
if (mapped) nodata = false;
if (nodata) continue;
// Flag breakpoints
typedef std::set<int32_t> TIdSet;
typedef std::map<uint32_t, TIdSet> TBpToIdMap;
TBpToIdMap bpid;
typedef boost::dynamic_bitset<> TBitSet;
TBitSet bpOccupied(hdr[file_c]->target_len[refIndex], false);
for(typename TSVs::iterator itSV = svs.begin(); itSV != svs.end(); ++itSV) {
if (itSV->chr == refIndex) {
bpOccupied[itSV->svStart] = 1;
if (bpid.find(itSV->svStart) == bpid.end()) bpid.insert(std::make_pair(itSV->svStart, TIdSet()));
bpid[itSV->svStart].insert(itSV->id);
}
if (itSV->chr2 == refIndex) {
bpOccupied[itSV->svEnd] = 1;
if (bpid.find(itSV->svEnd) == bpid.end()) bpid.insert(std::make_pair(itSV->svEnd, TIdSet()));
bpid[itSV->svEnd].insert(itSV->id);
}
}
if (bpid.empty()) continue;
// Lazy loading of reference sequence
if (seq == NULL) {
int32_t seqlen = -1;
std::string tname(hdr[0]->target_name[refIndex]);
seq = faidx_fetch_seq(fai, tname.c_str(), 0, hdr[0]->target_len[refIndex], &seqlen);
}
// Coverage track
typedef std::vector<TMaxCoverage> TBpCoverage;
TBpCoverage covBases(hdr[file_c]->target_len[refIndex], 0);
// Count reads
hts_itr_t* iter = sam_itr_queryi(idx[file_c], refIndex, 0, hdr[file_c]->target_len[refIndex]);
bam1_t* rec = bam_init1();
while (sam_itr_next(samfile[file_c], iter, rec) >= 0) {
// Genotyping only primary alignments
if (rec->core.flag & (BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP | BAM_FSUPPLEMENTARY | BAM_FUNMAP)) continue;
// Read hash
std::size_t seed = hash_lr(rec);
// Reference and sequence pointer
uint32_t rp = rec->core.pos; // reference pointer
uint32_t sp = 0; // sequence pointer
// Get sequence
std::string sequence;
sequence.resize(rec->core.l_qseq);
uint8_t* seqptr = bam_get_seq(rec);
for (int i = 0; i < rec->core.l_qseq; ++i) sequence[i] = "=ACMGRSVTWYHKDBN"[bam_seqi(seqptr, i)];
// Any REF support
std::string refAlign = "";
std::string altAlign = "";
std::vector<uint32_t> hits;
uint32_t* cigar = bam_get_cigar(rec);
for (std::size_t i = 0; i < rec->core.n_cigar; ++i) {
if ((bam_cigar_op(cigar[i]) == BAM_CMATCH) || (bam_cigar_op(cigar[i]) == BAM_CEQUAL) || (bam_cigar_op(cigar[i]) == BAM_CDIFF)) {
// Fetch reference alignments
for(uint32_t k = 0; k < bam_cigar_oplen(cigar[i]); ++k) {
if ((rp < hdr[file_c]->target_len[refIndex]) && (covBases[rp] < maxCoverage - 1)) ++covBases[rp];
refAlign += seq[rp];
altAlign += sequence[sp];
if (bpOccupied[rp]) hits.push_back(rp);
++sp;
++rp;
}
} else if ((bam_cigar_op(cigar[i]) == BAM_CDEL) || (bam_cigar_op(cigar[i]) == BAM_CREF_SKIP)) {
for(uint32_t k = 0; k < bam_cigar_oplen(cigar[i]); ++k) {
refAlign += seq[rp];
altAlign += "-";
if (bpOccupied[rp]) hits.push_back(rp);
++rp;
}
} else if (bam_cigar_op(cigar[i]) == BAM_CINS) {
for(uint32_t k = 0; k < bam_cigar_oplen(cigar[i]); ++k) {
refAlign += "-";
altAlign += sequence[sp];
++sp;
}
} else if (bam_cigar_op(cigar[i]) == BAM_CSOFT_CLIP) {
sp += bam_cigar_oplen(cigar[i]);
} else if (bam_cigar_op(cigar[i]) == BAM_CHARD_CLIP) {
// Do nothing
} else {
std::cerr << "Unknown Cigar options" << std::endl;
}
}
// Any ALT support?
TIdSet altAssigned;
if (srStore.find(seed) != srStore.end()) {
for(uint32_t ri = 0; ri < srStore[seed].size(); ++ri) {
int32_t svid = srStore[seed][ri].svid;
if (svid == -1) continue;
//if ((svs[svid].svt == 2) || (svs[svid].svt == 4)) continue;
altAssigned.insert(svid);
uint8_t* hpptr = bam_aux_get(rec, "HP");
if (c.hasDumpFile) {
std::string svidStr(_addID(svs[svid].svt));
std::string padNumber = boost::lexical_cast<std::string>(svid);
padNumber.insert(padNumber.begin(), 8 - padNumber.length(), '0');
svidStr += padNumber;
dumpOut << svidStr << "\t" << c.files[file_c].string() << "\t" << bam_get_qname(rec) << "\t" << hdr[file_c]->target_name[rec->core.tid] << "\t" << rec->core.pos << "\t" << hdr[file_c]->target_name[rec->core.mtid] << "\t" << rec->core.mpos << "\t" << (int32_t) rec->core.qual << "\tSR" << std::endl;
}
// ToDo
//jctMap[file_c][svid].alt.push_back((uint8_t) std::min((uint32_t) score, (uint32_t) rec->core.qual));
jctMap[file_c][svid].alt.push_back((uint8_t) std::min((uint32_t) 20, (uint32_t) rec->core.qual));
if (hpptr) {
c.isHaplotagged = true;
int hap = bam_aux2i(hpptr);
if (hap == 1) ++jctMap[file_c][svid].alth1;
else ++jctMap[file_c][svid].alth2;
}
}
}
// Any REF support
if (hits.empty()) continue;
// Sufficiently long flank mapping?
if ((rp - rec->core.pos) < c.minimumFlankSize) continue;
// Iterate all spanned SVs
for(uint32_t idx = 0; idx < hits.size(); ++idx) {
//std::cerr << hits[idx] - rec->core.pos << ',' << rp - hits[idx] << std::endl;
// Long enough flanking sequence
if (hits[idx] < rec->core.pos + c.minimumFlankSize) continue;
if (rp < hits[idx] + c.minimumFlankSize) continue;
// Confident mapping?
float percid = percentIdentity(refAlign, altAlign, hits[idx] - rec->core.pos, c.minRefSep * 2);
double score = percid * percid * percid * percid * percid * percid * percid * percid * 30;
if (score < c.minGenoQual) continue;
for(typename TIdSet::const_iterator its = bpid[hits[idx]].begin(); its != bpid[hits[idx]].end(); ++its) {
int32_t svid = *its;
//if ((svs[svid].svt == 2) || (svs[svid].svt == 4)) continue;
if (altAssigned.find(svid) != altAssigned.end()) continue;
//std::cerr << svs[svid].chr << ',' << svs[svid].svStart << ',' << svs[svid].chr2 << ',' << svs[svid].svEnd << std::endl;
if (++refAlignedReadCount[file_c][svid] % 2) {
uint8_t* hpptr = bam_aux_get(rec, "HP");
jctMap[file_c][svid].ref.push_back((uint8_t) std::min((uint32_t) score, (uint32_t) rec->core.qual));
if (hpptr) {
c.isHaplotagged = true;
int hap = bam_aux2i(hpptr);
if (hap == 1) ++jctMap[file_c][svid].refh1;
else ++jctMap[file_c][svid].refh2;
}
}
}
}
}
// Clean-up
bam_destroy1(rec);
hts_itr_destroy(iter);
// Assign SV support
for(uint32_t i = 0; i < svs.size(); ++i) {
if (svs[i].chr == refIndex) {
int32_t halfSize = (svs[i].svEnd - svs[i].svStart)/2;
if ((_translocation(svs[i].svt)) || (svs[i].svt == 4)) halfSize = 500;
// Left region
int32_t lstart = std::max(svs[i].svStart - halfSize, 0);
int32_t lend = svs[i].svStart;
int32_t covbase = 0;
for(uint32_t k = lstart; ((k < (uint32_t) lend) && (k < hdr[file_c]->target_len[refIndex])); ++k) covbase += covBases[k];
covMap[file_c][svs[i].id].leftRC = covbase;
// Actual SV
covbase = 0;
int32_t mstart = svs[i].svStart;
int32_t mend = svs[i].svEnd;
if ((_translocation(svs[i].svt)) || (svs[i].svt == 4)) {
mstart = std::max(svs[i].svStart - halfSize, 0);
mend = std::min(svs[i].svStart + halfSize, (int32_t) hdr[file_c]->target_len[refIndex]);
}
for(uint32_t k = mstart; ((k < (uint32_t) mend) && (k < hdr[file_c]->target_len[refIndex])); ++k) covbase += covBases[k];
covMap[file_c][svs[i].id].rc = covbase;
// Right region
covbase = 0;
int32_t rstart = svs[i].svEnd;
int32_t rend = std::min(svs[i].svEnd + halfSize, (int32_t) hdr[file_c]->target_len[refIndex]);
if ((_translocation(svs[i].svt)) || (svs[i].svt == 4)) {
rstart = svs[i].svStart;
rend = std::min(svs[i].svStart + halfSize, (int32_t) hdr[file_c]->target_len[refIndex]);
}
for(uint32_t k = rstart; ((k < (uint32_t) rend) && (k < hdr[file_c]->target_len[refIndex])); ++k) covbase += covBases[k];
covMap[file_c][svs[i].id].rightRC = covbase;
}
}
}
if (seq != NULL) free(seq);
}
// Clean-up
fai_destroy(fai);
// Clean-up
for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
bam_hdr_destroy(hdr[file_c]);
hts_idx_destroy(idx[file_c]);
sam_close(samfile[file_c]);
}
}
}
#endif
|
#pragma once
#include <vulkan\vulkan.h>
#include <stdexcept>
static void vkOk(VkResult vkResult, const char * message) {
if (vkResult != VK_SUCCESS) throw std::runtime_error(message);
}
static void vkOk(VkResult vkResult) {
vkOk(vkResult, "Vulkan call failed!");
}
|
#include "policies.hpp"
using mgr_t = WidgetManager1<OpNewCreator>;
void test0() {
mgr_t mgr{};
Widget* w = mgr.Create();
//mgr.SwitchPrototype(w); will work only for PrototypeCreator policy
}
int main() {
return 0;
}
|
/*
warrior.hpp
Purpose: Represent a warrior. A warrior is any of the characters in the game. This class is abstract, and should therefore never be instantiated. Instead instantiate a subclass-- Player or Enemy.
@author Jeremy Elkayam
*/
#pragma once
#include <cmath>
#include <SFML/Graphics.hpp>
#include <iostream>
#include "color_grid.hpp"
using std::cout;
using std::endl;
class Entity
{
protected:
sf::Sprite sprite;
sf::Color color = sf::Color::White;
/*
Constructor for the Entity class. Sets initial values.
@param xcor initial x-coordinate of the entity.
@param ycor initial y-coordinate of the entity.
*/
Entity(float xcor, float ycor, sf::Texture &texture);
void set_origin_to_center();
public:
/*
Returns the x-coordinate of the entity.
@return the entity's x-coordinate
*/
float get_xcor() const {return sprite.getPosition().x;}
/*
Returns the y-coordinate of the warrior.
@return the warrior's y-coordinate
*/
float get_ycor() const {return sprite.getPosition().y;}
float get_angle() const {return sprite.getRotation();}
virtual void draw(sf::RenderWindow &window, ColorGrid &color_grid) const;
bool intersects(const Entity &entity) const {return sprite.getGlobalBounds().intersects(entity.get_global_bounds());}
sf::FloatRect get_global_bounds() const {return sprite.getGlobalBounds();}
sf::Color get_color() const {return color;}
};
|
//By SCJ
//#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int unsigned int
int e[1005];
void pfip(int x)
{
for(int i=0;i<4;++i)
{
if(i) cout<<'.';
int tp=(x<<(i*8));
tp=(tp>>24);
cout<<tp;
}
}
main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int n;
while(cin>>n)
{
for(int i=0;i<n;++i)
{
int a,b,c,d;
char tp;
cin>>a>>tp>>b>>tp>>c>>tp>>d;
e[i]=0;
e[i]+=(a<<24);
e[i]+=(b<<16);
e[i]+=(c<<8);
e[i]+=d;
}
int S=(1LL<<32)-1;
for(int i=0;i<32;++i)
{
bool fg=1;
for(int j=1;j<n;++j)
{
if((e[j]&S)!=(e[j-1]&S)) {fg=0;break;}
}
if(fg) break;
S-=(1LL<<i);
}
pfip((S&e[0])&S);cout<<endl;
pfip(S);cout<<endl;
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
struct disjoin{
int group[MAXN+5];
void init(){
for(int i = 0 ; i < MAXN+5 ; i++ )
group[i] = i;
}
int find(int k){
return group[k]==k ? k:(group[k]=find(group[k]));
}
void uni(int a,int b){
group[find(a)] = group[find(b)];
}
bool is_group(int a, int b){
if( find(a) == find(b) )
return true;
return false;
}
}D;
struct point {
double x,y;
}P[MAXN+5];
double get_len(int a, int b){
return sqrt((P[a].x - P[b].x)*(P[a].x - P[b].x)+(P[a].y - P[b].y)*(P[a].y - P[b].y));
}
struct edge {
int a,b;
double len;
bool operator < (const edge &rhs){
return len < rhs.len;
}
}E[MAXN*MAXN+5];
int main(int argc, char const *argv[])
{
int kase;
scanf("%d",&kase);
int num;
while( kase-- ){
scanf("%d",&num);
for(int i = 0 ; i < num ; i++ ){
scanf("%lf %lf",&P[i].x,&P[i].y);
}
int k = 0;
for(int i = 0 ; i < num ; i++ ){
for(int j = i+1 ; j < num ; j++ ){
E[k].a = i;
E[k].b = j;
E[k++].len = get_len(i,j);
}
}
double ans = 0;
sort(E,E+k);
D.init();
for(int i = 0 ; i < k ; i++ ){
int a = E[i].a, b = E[i].b;
if( !D.is_group(a,b) ){
D.uni(a,b);
ans += E[i].len;
}
}
printf("%.2lf\n",ans);
if(kase)
printf("\n");
}
return 0;
}
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
string longestPalindrome(string s){
int l = s.length();
bool table[l][l];
for(int i=0;i<l;i++)
for(int j=0;j<l;j++)
table[i][j] = false;
string res;
int maxLen = 0;
for(int i=s.length()-1;i>=0;i--){
for(int j=i;j<s.length();j++){
if(s[i] == s[j] && (j-i<=2 || table[i+1][j-1])){
table[i][j] = true;
if(maxLen < j-i+1){
maxLen = j-i+1;
res = s.substr(i,j-i+1);
}
}
}
}
return res;
}
string longestPalindrome2(string s){
string res;
for(int i=0;i<s.length();i++){
string temp;
temp += s[i];
int k = i-1;
int j = i+1;
while(k>=0 && j<s.length()){
if(s[k]==s[j]){
temp = s[k] + temp + s[j];
k--;
j++;
}else
break;
}
if(res.length()<temp.length())
res = temp;
temp = "";
k = i;
j = i+1;
while(k>=0 && j<s.length()){
if(s[k]==s[j]){
temp = s[k] + temp + s[j];
k--;
j++;
}else
break;
}
if(res.length()<temp.length())
res = temp;
}
return res;
}
int main(){
string s;
cin >> s;
cout << longestPalindrome(s) << endl;
}
|
/*
* GroupSession.cpp
*
* Created on: Jun 11, 2017
* Author: root
*/
#include "GroupSession.h"
#include "../Log/Logger.h"
namespace CommBaseOut
{
GroupSession::GroupSession(Context * c):m_c(c)
{
}
GroupSession::~GroupSession()
{
}
void GroupSession::DeleteGroupSession(int group, int channel)
{
GUARD_WRITE(CRWLock, obj, &m_groupLock);
map<int, GroupSessionInfo>::iterator itCh = m_groupChannel.find(group);
if(itCh == m_groupChannel.end())
return;
bool isDel = itCh->second.DeleteChannel(channel);
if(!isDel)
{
map<WORD, int>::iterator it = m_group.begin();
for(; it!=m_group.end(); ++it)
{
if(it->second == group)
{
m_group.erase(it);
break;
}
}
}
}
int GroupSession::AddGroupSession(int type, int id, int channel, int count, bool &isSuccess)
{
WORD key = (type << 8) | id;
int ret = -1;
GUARD_WRITE(CRWLock, obj, &m_groupLock);
map<WORD, int>::iterator it = m_group.find(key);
if(it == m_group.end())
{
GroupSessionInfo info;
info.channel.push_back(channel);
info.count = count;
m_group[key] = channel;
ret = channel;
m_groupChannel[channel] = info;
if(info.channel.size() == (DWORD)count)
{
isSuccess = true;
}
ret = channel;
}
else
{
if(m_groupChannel[it->second].channel.size() >= m_groupChannel[it->second].count)
{
return -2;
}
else if(m_groupChannel[it->second].channel.size() == (DWORD)(m_groupChannel[it->second].count - 1))
{
isSuccess = true;
}
ret = it->second;
m_groupChannel[it->second].channel.push_back(channel);
}
return ret;
}
void GroupSession::UnBindSession(int64 key, int group)
{
// if( group < 0 || key < 0 )
// return ;
//
// GUARD_WRITE(CRWLock, obj1, &m_keyLock);
// map<int, map<int64, int> >::iterator itKey = m_keyChannel.find(group);
// if(m_keyChannel.end() == itKey)
// return ;
//
// map<int64, int>::iterator it = itKey->second.find(key);
// if(it != itKey->second.end())
// {
// itKey->second.erase(it);
// }
}
int GroupSession::BindSession(int64 key, int group)
{
if( group < 0 || key < 0 )
return group;
int channel = -1;
GUARD_WRITE(CRWLock, obj, &m_groupLock);
map<int, GroupSessionInfo>::iterator itCh = m_groupChannel.find(group);
if(itCh == m_groupChannel.end())
{
LOG_BASE(FILEINFO, "bind session error and group[%d] is null", group);
return group;
}
if(itCh->second.channel.size() <= 0)
{
LOG_BASE(FILEINFO, "group[%d] channel size is null and bind session error", group);
return group;
}
channel = itCh->second.GetChannel((int)key);
// obj.UnLock();
//
// GUARD_WRITE(CRWLock, obj1, &m_keyLock);
// map<int, map<int64, int> >::iterator itKey = m_keyChannel.find(group);
// if(itKey == m_keyChannel.end())
// {
// map<int64, int> tKey;
//
// tKey[key] = channel;
// m_keyChannel[group] = tKey;
// }
// else
// {
// itKey->second[key] = channel;
// }
return channel;
}
}
|
#pragma once
#include "RefCounter.h"
//参照を管理するシェーダーやオブジェクラスの基底クラス
class BufferBase
{
RefCounter *ref;
protected:
bool last() const{
return ref->count == 1;
}
bool newCounter(){
// 唯一のオブジェクトかどうか調べる
bool status(last());
// 元の参照カウンタの管理対象から外す
if (--ref->count == 0) delete ref;
// 新しい参照カウンタを作成して, それに付け替える
ref = new RefCounter;
// 元のオブジェクトの状態を返す
return status;
}
public:
//コンストラクタ
BufferBase() :ref(new RefCounter){}
//コピーコンストラクタ
BufferBase(const BufferBase &o) :ref(o.ref){
++ref->count;
}
//代入演算子
BufferBase &operator=(const BufferBase &o){
if (&o != this) ++(ref = o.ref)->count;
return *this;
}
virtual ~BufferBase()
{
// 参照カウンタを減じて 0 になったら参照カウンタを削除する
if (--ref->count == 0) delete ref;
}
};
|
//===-- OR1KFrameLowering.cpp - OR1K Frame Information --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the OR1K implementation of TargetFrameLowering class.
//
//===----------------------------------------------------------------------===//
#include "OR1KFrameLowering.h"
#include "OR1KInstrInfo.h"
#include "OR1KMachineFunctionInfo.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/IR/Function.h"
using namespace llvm;
bool OR1KFrameLowering::hasFP(const MachineFunction &MF) const {
const MachineFrameInfo *MFI = MF.getFrameInfo();
const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
MF.getFrameInfo()->hasVarSizedObjects() ||
MFI->isFrameAddressTaken() ||
TRI->needsStackRealignment(MF));
}
// determineFrameLayout - Determine the size of the frame and maximum call
/// frame size.
void OR1KFrameLowering::determineFrameLayout(MachineFunction &MF) const {
MachineFrameInfo *MFI = MF.getFrameInfo();
const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
// Get the number of bytes to allocate from the FrameInfo.
unsigned FrameSize = MFI->getStackSize();
// Get the alignment.
unsigned StackAlign = TRI->needsStackRealignment(MF) ?
MFI->getMaxAlignment() :
MF.getTarget().getFrameLowering()->getStackAlignment();
// Get the maximum call frame size of all the calls.
unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
// If we have dynamic alloca then maxCallFrameSize needs to be aligned so
// that allocations will be aligned.
if (MFI->hasVarSizedObjects())
maxCallFrameSize = RoundUpToAlignment(maxCallFrameSize, StackAlign);
// Update maximum call frame size.
MFI->setMaxCallFrameSize(maxCallFrameSize);
// Include call frame size in total.
if (!(hasReservedCallFrame(MF) && MFI->adjustsStack()))
FrameSize += maxCallFrameSize;
// Make sure the frame is aligned.
FrameSize = RoundUpToAlignment(FrameSize, StackAlign);
// Update frame info.
MFI->setStackSize(FrameSize);
}
// Iterates through each basic block in a machine function and replaces
// ADJDYNALLOC pseudo instructions with a OR1K:ADDI with the
// maximum call frame size as the immediate.
void OR1KFrameLowering::replaceAdjDynAllocPseudo(MachineFunction &MF) const {
const OR1KInstrInfo &TII =
*static_cast<const OR1KInstrInfo*>(MF.getTarget().getInstrInfo());
unsigned MaxCallFrameSize = MF.getFrameInfo()->getMaxCallFrameSize();
for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
MBB != E; ++MBB) {
MachineBasicBlock::iterator MBBI = MBB->begin();
while (MBBI != MBB->end()) {
MachineInstr *MI = MBBI++;
if (MI->getOpcode() == OR1K::ADJDYNALLOC) {
DebugLoc DL = MI->getDebugLoc();
unsigned Dst = MI->getOperand(0).getReg();
unsigned Src = MI->getOperand(1).getReg();
BuildMI(*MBB, MI, DL, TII.get(OR1K::ADDI), Dst)
.addReg(Src).addImm(MaxCallFrameSize);
MI->eraseFromParent();
}
}
}
}
void OR1KFrameLowering::emitPrologue(MachineFunction &MF) const {
MachineBasicBlock &MBB = MF.front();
MachineFrameInfo *MFI = MF.getFrameInfo();
const OR1KInstrInfo &TII =
*static_cast<const OR1KInstrInfo*>(MF.getTarget().getInstrInfo());
const OR1KRegisterInfo *TRI =
static_cast<const OR1KRegisterInfo*>(MF.getTarget().getRegisterInfo());
MachineBasicBlock::iterator MBBI = MBB.begin();
DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
bool IsPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
bool HasRA = MFI->adjustsStack() || IsPIC;
// Determine the correct frame layout
determineFrameLayout(MF);
// Get the number of bytes to allocate from the FrameInfo.
unsigned StackSize = MFI->getStackSize();
// No need to allocate space on the stack.
if (StackSize == 0 && !HasRA) return;
int Offset = -4;
// l.sw stack_lock(r1), r9
if (HasRA) {
BuildMI(MBB, MBBI, DL, TII.get(OR1K::SW))
.addReg(OR1K::R9).addReg(OR1K::R1).addImm(Offset);
Offset -= 4;
}
if (hasFP(MF)) {
// Save frame pointer onto stack
// l.sw stack_loc(r1), r2
BuildMI(MBB, MBBI, DL, TII.get(OR1K::SW))
.addReg(OR1K::R2).addReg(OR1K::R1).addImm(Offset);
Offset -= 4;
// In case of a base pointer, it need to be saved here
// before we start modifying it below.
// l.sw stack_loc(r1), basereg
if (TRI->hasBasePointer(MF)) {
BuildMI(MBB, MBBI, DL, TII.get(OR1K::SW))
.addReg(TRI->getBaseRegister()).addReg(OR1K::R1).addImm(Offset);
}
// Set frame pointer to stack pointer
// l.addi r2, r1, 0
BuildMI(MBB, MBBI, DL, TII.get(OR1K::ADDI), OR1K::R2)
.addReg(OR1K::R1).addImm(0);
}
// FIXME: Allocate a scratch register.
unsigned ScratchReg = OR1K::R13;
if (TRI->needsStackRealignment(MF)) {
assert(hasFP(MF) && "Stack realignment without FP not supported");
uint32_t AlignLog = Log2_32(MFI->getMaxAlignment());
// Realign the stackpointer by masking out the lower
// bits, i.e. r1 <= (r1 - stacksize) & ~alignmask.
// Since the stack grows down, the resulting stack pointer
// will be rounded down in case the stack pointer came in unaligned.
if (isInt<16>(StackSize)) {
BuildMI(MBB, MBBI, DL, TII.get(OR1K::ADDI), ScratchReg)
.addReg(OR1K::R1).addImm(-StackSize);
} else {
BuildMI(MBB, MBBI, DL, TII.get(OR1K::MOVHI), ScratchReg)
.addImm((uint32_t)-StackSize >> 16);
BuildMI(MBB, MBBI, DL, TII.get(OR1K::ORI), ScratchReg)
.addReg(ScratchReg).addImm(-StackSize & 0xffffU);
BuildMI(MBB, MBBI, DL, TII.get(OR1K::ADD), ScratchReg)
.addReg(ScratchReg).addReg(OR1K::R1);
}
BuildMI(MBB, MBBI, DL, TII.get(OR1K::SRL_ri), ScratchReg)
.addReg(ScratchReg).addImm(AlignLog);
BuildMI(MBB, MBBI, DL, TII.get(OR1K::SLL_ri), OR1K::R1)
.addReg(ScratchReg).addImm(AlignLog);
} else if (isInt<16>(StackSize)) {
// Adjust stack : l.addi r1, r1, -imm
if (StackSize) {
BuildMI(MBB, MBBI, DL, TII.get(OR1K::ADDI), OR1K::R1)
.addReg(OR1K::R1).addImm(-StackSize);
}
} else {
BuildMI(MBB, MBBI, DL, TII.get(OR1K::MOVHI), ScratchReg)
.addImm((uint32_t)-StackSize >> 16);
BuildMI(MBB, MBBI, DL, TII.get(OR1K::ORI), ScratchReg)
.addReg(ScratchReg).addImm(-StackSize & 0xffffU);
BuildMI(MBB, MBBI, DL, TII.get(OR1K::ADD), OR1K::R1)
.addReg(OR1K::R1).addReg(ScratchReg);
}
// If a base pointer is needed, set it up here.
// Any variable sized objects will be located after this,
// so local objects can be adressed with the base pointer.
if (TRI->hasBasePointer(MF)) {
BuildMI(MBB, MBBI, DL, TII.get(OR1K::ORI), TRI->getBaseRegister())
.addReg(OR1K::R1).addImm(0);
}
if (MFI->hasVarSizedObjects()) {
replaceAdjDynAllocPseudo(MF);
}
}
void OR1KFrameLowering::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
// Discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
MBB.erase(I);
}
void OR1KFrameLowering::emitEpilogue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
MachineFrameInfo *MFI = MF.getFrameInfo();
const OR1KInstrInfo &TII =
*static_cast<const OR1KInstrInfo*>(MF.getTarget().getInstrInfo());
const OR1KRegisterInfo *TRI =
static_cast<const OR1KRegisterInfo*>(MF.getTarget().getRegisterInfo());
bool IsPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
bool HasRA = MFI->adjustsStack() || IsPIC;
DebugLoc dl = MBBI->getDebugLoc();
int FPOffset = HasRA ? -8 : -4;
int RAOffset = -4;
int BPOffset = FPOffset - 4;
// Get the number of bytes from FrameInfo
int StackSize = (int) MFI->getStackSize();
if (hasFP(MF)) {
// Set stack pointer to frame pointer
// l.addi r1, r2, 0
BuildMI(MBB, MBBI, dl, TII.get(OR1K::ADDI), OR1K::R1)
.addReg(OR1K::R2).addImm(0);
// Load frame pointer from stack
// l.lwz r2, stack_loc(r1)
BuildMI(MBB, MBBI, dl, TII.get(OR1K::LWZ), OR1K::R2)
.addReg(OR1K::R1).addImm(FPOffset);
} else if (isInt<16>(StackSize)) {
// l.addi r1, r1, imm
if (StackSize) {
BuildMI(MBB, MBBI, dl, TII.get(OR1K::ADDI), OR1K::R1)
.addReg(OR1K::R1).addImm(StackSize);
}
} else {
// FIXME: Allocate a scratch register.
unsigned ScratchReg = OR1K::R13;
BuildMI(MBB, MBBI, dl, TII.get(OR1K::MOVHI), ScratchReg)
.addImm((uint32_t)StackSize >> 16);
BuildMI(MBB, MBBI, dl, TII.get(OR1K::ORI), ScratchReg)
.addReg(ScratchReg).addImm(StackSize & 0xffffU);
BuildMI(MBB, MBBI, dl, TII.get(OR1K::ADD), OR1K::R1)
.addReg(OR1K::R1).addReg(ScratchReg);
}
// l.lwz basereg, stack_loc(r1)
if (TRI->hasBasePointer(MF)) {
BuildMI(MBB, MBBI, dl, TII.get(OR1K::LWZ), TRI->getBaseRegister())
.addReg(OR1K::R1).addImm(BPOffset);
}
// l.lwz r9, stack_loc(r1)
if (HasRA) {
BuildMI(MBB, MBBI, dl, TII.get(OR1K::LWZ), OR1K::R9)
.addReg(OR1K::R1).addImm(RAOffset);
}
}
void OR1KFrameLowering::
processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
RegScavenger *RS) const {
MachineFrameInfo *MFI = MF.getFrameInfo();
MachineRegisterInfo& MRI = MF.getRegInfo();
const OR1KRegisterInfo *TRI =
static_cast<const OR1KRegisterInfo*>(MF.getTarget().getRegisterInfo());
bool IsPIC = MF.getTarget().getRelocationModel() == Reloc::PIC_;
int Offset = -4;
if (MFI->adjustsStack() || IsPIC) {
MFI->CreateFixedObject(4, Offset, true);
// Mark unused since we will save it manually in the prologue
MRI.setPhysRegUnused(OR1K::R9);
Offset -= 4;
}
if (hasFP(MF)) {
MFI->CreateFixedObject(4, Offset, true);
Offset -= 4;
}
if (TRI->hasBasePointer(MF)) {
MFI->CreateFixedObject(4, Offset, true);
MRI.setPhysRegUnused(TRI->getBaseRegister());
}
}
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
#include <cstdio>
//#include <cstdlib>
#include <cstring>
#include <numeric>
#include <bitset>
#include <deque>
#include <memory>
const long long LINF = (5e17);
const int INF = 1000000000;
#define EPS 1e-7
const int MOD = 1000000007;
using namespace std;
class ShufflingCardsDiv1 {
public:
int shuffle(vector <int> permutation) {
vector<int> ref(permutation);
sort(ref.begin(), ref.end());
if (ref == permutation)
return 0;
int N = (int)permutation.size() / 2;
int bB = 0;
for (int i=0; i<2*N; i+=2)
if (permutation[i] <= N)
++bB;
if (bB == N)
return 1;
if (bB == (N+1)/2)
return 2;
if (N&1 && bB==0)
return 4;
return 3;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {1,2,3,4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; verify_case(0, Arg1, shuffle(Arg0)); }
void test_case_1() { int Arr0[] = {1,4,3,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(1, Arg1, shuffle(Arg0)); }
void test_case_2() { int Arr0[] = {6,3,5,2,4,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 4; verify_case(2, Arg1, shuffle(Arg0)); }
void test_case_3() { int Arr0[] = {8,5,4,9,1,7,6,10,3,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(3, Arg1, shuffle(Arg0)); }
void test_case_4() { int Arr0[] = {9,1,7,2,10,3,6,4,8,5}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 4; verify_case(4, Arg1, shuffle(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
ShufflingCardsDiv1 ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include <display.h>
#include <texture.h>
#include <ctime>
#include <cmath>
#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
constexpr double PI = acos(-1);
Display::Display(int WIDTH, int HEIGHT)
{
this->WIDTH = WIDTH;
this->HEIGHT = HEIGHT;
this->gRenderer = NULL;
this->gWindow = NULL;
this->gBackgroundTexture = NULL;
this->gScreenSurface = NULL;
this->gFont = NULL;
this->gTextTexture = NULL;
}
bool Display::init()
{
if(SDL_Init(SDL_INIT_VIDEO))
{
printf("SDL_Init Error: %s\n", SDL_GetError());
return false;
}
gWindow = SDL_CreateWindow(
"Pong",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
WIDTH,
HEIGHT,
SDL_WINDOW_SHOWN
);
if(!gWindow)
{
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
return false;
}
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if(!gRenderer)
{
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
return false;
}
SDL_SetRenderDrawColor( gRenderer, 0x0A, 0x0A, 0x32, 0xFF );
int imgFlags = IMG_INIT_PNG;
if(!(IMG_Init(imgFlags) & imgFlags))
{
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
return false;
}
if(TTF_Init() == -1)
{
printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError());
return false;
}
gScreenSurface = SDL_GetWindowSurface(gWindow);
return true;
}
bool Display::loadMedia()
{
this->gFont = TTF_OpenFont("../res/fonts/consolab.ttf", 50);
if(!this->gFont)
{
printf("Failed to load font! SDL_ttf Error: %s\n", TTF_GetError());
return false;
}
return true;
}
void Display::close()
{
SDL_DestroyRenderer(gRenderer);
SDL_DestroyWindow(gWindow);
SDL_FreeSurface(gScreenSurface);
TTF_CloseFont(this->gFont);
this->gRenderer = NULL;
this->gWindow = NULL;
this->gBackgroundTexture = NULL;
this->gScreenSurface = NULL;
this->gFont = NULL;
this->gTextTexture = NULL;
TTF_Quit();
IMG_Quit();
SDL_Quit();
}
void Display::draw(std::vector<Player> players, Ball ball)
{
if(!init())
{
printf("Failed to initialize!\n");
return;
}
int player1 = 0;
int player2 = 0;
/* load textures */
Texture textTexture = Texture(gRenderer);
this->gTextTexture = &textTexture;
Texture playerTexture = Texture("../res/player/player.png", gRenderer);
Texture playerLeftTexture = Texture("../res/player/player_left.png", gRenderer);
Texture playerRightTexture = Texture("../res/player/player_right.png", gRenderer);
Texture ballTexture = Texture("../res/ball/ball.png", gRenderer);
Texture backgroundTexture = Texture("../res/background/field.png", gRenderer);
for(std::size_t i = 0; i < players.size(); i++)
{
players[i].set_texture(&playerTexture);
}
ball.set_texture(&ballTexture);
this->gBackgroundTexture = &backgroundTexture;
if(!loadMedia())
printf("Failed to load media!\n");
else
printf("Media Loaded\n");
/* physics */
double t = 0.0;
const double dt = 1.0/60;
Uint32 currentTime = SDL_GetTicks();
double accumulator = 0.0;
double velocity = 0.0;
/* init teams */
//Team team1 = Team(players[0]);
//Team team2 = Team(players[1]);
bool quit = false;
SDL_Event e;
while(!quit)
{
/* physics */
Uint32 newTime = SDL_GetTicks();
Uint32 frameTime = newTime - currentTime;
currentTime = newTime;
accumulator += frameTime;
while(accumulator >= dt)
{
velocity = (velocity + 550) * dt;
accumulator -= dt;
t += dt;
}
/* input */
while(SDL_PollEvent(&e))
{
switch(e.type)
{
case SDL_QUIT: quit = true;
break;
case SDL_KEYDOWN:
{
switch(e.key.keysym.sym)
{
case SDLK_LEFT:
{
players[0].set_texture(&playerLeftTexture);
players[0].set_velocity(-1 * velocity);
}
break;
case SDLK_RIGHT:
{
players[0].set_texture(&playerRightTexture);
players[0].set_velocity(velocity);
}
break;
default:
break;
}
}
break;
case SDL_KEYUP:
{
switch(e.key.keysym.sym)
{
case SDLK_LEFT:
if(players[0].get_velocity() < 0)
{
players[0].set_texture(&playerTexture);
players[0].set_velocity(0);
}
break;
case SDLK_RIGHT:
if(players[0].get_velocity() > 0)
{
players[0].set_texture(&playerTexture);
players[0].set_velocity(0);
}
break;
default:
break;
}
}
break;
default:
break;
}
}
/* draw */
SDL_SetRenderDrawColor(gRenderer, 0x0A, 0x0A, 0x32, 0xFF);
SDL_RenderClear(gRenderer);
//printf("FPS: %d\n", int(1000.0/frameTime));
gBackgroundTexture->render(0, 0);
/* ball movement detection */
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0x00, 0x00, 0xFF);
double ball_center_x = ball.get_x() + (ball.get_size()/2);
double ball_center_y = ball.get_y() + (ball.get_size()/2);
double tanTheta = ball.get_x_vel()/ball.get_y_vel();
//double height_mod = 0;
double width_mod = 0;
double dist = 0;
if(ball.get_y_vel() > 0)
{
dist = (HEIGHT - ball_center_y) * tanTheta;
//height_mod = HEIGHT;
}
else
dist = -1 * ball_center_y * tanTheta;
//double gradient = (ball_center_y - height_mod) / (ball_center_x - (ball_center_x + dist));
//double intercept = ball_center_y - (gradient * ball_center_x);
//double y2 = intercept;
// SDL_RenderDrawLine(gRenderer,
// round(ball_center_x),
// round(ball_center_y),
// round(ball_center_x + dist),
// round(height_mod));
if(ball.get_x() + (ball.get_size()/2) + dist > WIDTH)
width_mod = WIDTH;
//y2 = (gradient * width_mod) + intercept;
// SDL_RenderDrawLine(gRenderer,
// width_mod,
// round(y2),
// round((2 * width_mod) - (ball_center_x + dist)),
// round(height_mod));
double final_x = 0;
if(ball_center_x + dist <= WIDTH && ball_center_x + dist >= 0)
final_x = ball_center_x + dist;
else final_x = (2 * width_mod) - (ball_center_x + dist);
/* artificial intelligence */
if(final_x < players[1].get_x() + players[1].get_width()/10)
{
players[1].set_texture(&playerLeftTexture);
players[1].set_velocity(-1 * velocity);
}
else if(final_x > players[1].get_x() + players[1].get_width() - players[1].get_width()/10)
{
players[1].set_texture(&playerRightTexture);
players[1].set_velocity(velocity);
}
else
{
players[1].set_texture(&playerTexture);
players[1].set_velocity(0);
}
/* collision detection */
for(std::size_t i = 0; i < players.size(); i++)
{
/* restrict x-axis movement range */
if(players[i].get_x() + players[i].get_velocity() <= (this->WIDTH-players[i].get_width()) && players[i].get_x() + players[i].get_velocity() >= 0)
players[i].move();
else
if(players[i].get_velocity() > 0)
players[i].set_x(WIDTH-players[i].get_width()-2);
else
players[i].set_x(2);
/* assign variables to reduce code repetition */
double player_center_x = players[i].get_x() + (players[i].get_width()/2);
double player_center_y = players[i].get_y() + (players[i].get_height()/2);
double x_dist = round(ball_center_x - player_center_x);
double y_dist = round(ball_center_y - player_center_y);
//if distance between the centers of two rectangles is less than the sum of their sizes then:
if(
std::abs(round(x_dist)) < (ball.get_size()/2) + (players[i].get_width()/2) &&
std::abs(round(y_dist)) < (ball.get_size()/2) + (players[i].get_height()/2)
)
{
/* get angle from center to corner*/
double angle_i = std::abs(atan(double(players[i].get_height()/2) / double(players[i].get_width()/2)) * 180 / PI);
double angle_o;
//printf("Angle_i: %.2f | %.2f/%.2f\n", angle_i, double(players[i].get_height()/2), double(players[i].get_width()/2));
/* y direction of ball */
if(ball.get_y_vel() < 0)
angle_o = std::abs(atan((y_dist + (ball.get_size()/2)) / x_dist) * 180 / PI);
else
angle_o = std::abs(atan((y_dist - (ball.get_size()/2)) / x_dist) * 180 / PI);
//printf("Angle_o: %.2f | %.2f/%.2f\n", angle_o, y_dist + (ball.get_size()/2), x_dist);
//printf("Angle_o: %.2f | %.2f/%.2f\n", angle_o, y_dist - (ball.get_size()/2), x_dist);
//printf("x_dist = %.1f, %.2f\n", round(x_dist), x_dist);
//printf("y_dist = %.1f, %.2f\n", round(y_dist), y_dist);
/* angle of incidence of collision */
if(angle_o > angle_i)
{
if(ball.get_y_vel() < 0)
ball.set_y(players[i].get_y() + players[i].get_height());
else
ball.set_y(players[i].get_y() - players[i].get_height());
ball.toggle_y_vel();
}
else
{
if(ball.get_x_vel() < 0)
ball.set_x(players[i].get_x() + players[i].get_width());
else
ball.set_x(players[i].get_x());
ball.toggle_x_vel();
}
ball.set_velocity(ball.get_x_vel() + players[i].get_velocity() + (0.05 * x_dist), ball.get_y_vel() * 1.05);
std::cout << ball.toString() << std::endl;
}
players[i].draw();
}
/* bump off the sides */
if(ball.get_x() + ball.get_x_vel() <= this->WIDTH-ball.get_size() &&
ball.get_x() + ball.get_x_vel() >= 0)
ball.move();
else
ball.toggle_x_vel();
/* check score */
if(ball.get_y() + ball.get_y_vel() > this->HEIGHT-ball.get_size())
{
player1++;
ball.reset(WIDTH/2, HEIGHT/2);
}
else if(ball.get_y() + ball.get_y_vel() < 0)
{
player2++;
ball.reset(WIDTH/2, HEIGHT/2);
}
else
ball.move();
ball.draw();
SDL_Color textColor = {255, 255, 255, 0};
std::ostringstream player1stream;
player1stream << player1;
this->gTextTexture->loadFromRenderedText(this->gFont, player1stream.str(), textColor);
gTextTexture->render(WIDTH - gTextTexture->get_width() - 10, (HEIGHT - gTextTexture->get_height())/2 - 25);
std::ostringstream player2stream;
player2stream << player2;
this->gTextTexture->loadFromRenderedText(this->gFont, player2stream.str(), textColor);
gTextTexture->render(10, (HEIGHT - gTextTexture->get_height())/2 + 30);
SDL_RenderPresent(gRenderer);
}
playerTexture.free();
playerLeftTexture.free();
playerRightTexture.free();
backgroundTexture.free();
textTexture.free();
ballTexture.free();
}
|
#pragma once
#include "EnemyLogicCalculator.h"
class EnemyPatrollingVerticallyLogicCalculator : public EnemyLogicCalculator
{
public:
EnemyPatrollingVerticallyLogicCalculator();
~EnemyPatrollingVerticallyLogicCalculator();
public:
void computeLogic();
private:
bool m_patrolling;
float m_referencePosX;
float m_referencePosY;
bool m_movingUp;
int m_attackCountDown;
};
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Job.cpp
* Author: ssridhar
*
* Created on October 11, 2017, 1:06 PM
*/
#include "Job.h"
/**
* Set_Job Allows the user to set the job parameters.
* @param local_port Local port on the host where you need to bind.
* @param local_ipv4 Local IPv4 address on the host where you need to bind.
* @param remote_ipv4 Remote IPv4 address where you need to connect.
* @param remote_address Remote domain name where you need to connect.
*/
void webclient::Job::set_Job(uint16_t local_port,
uint32_t local_ipv4,
uint32_t remote_ipv4,
char remote_address[]) {
this->local_port = local_port;
this->local_ipv4 = local_ipv4;
this->remote_ipv4 = remote_ipv4;
//int len_of_remote_address = sizeof(remote_address)/sizeof(remote_address[0]);
int len_of_remote_address = strlen(remote_address);
if (len_of_remote_address < MAX_REMOTE_DOMAIN_NAME) {
memcpy(this->remote_domain_name, remote_address, len_of_remote_address);
}
this->job_current_state = 0;
this->total_number_of_iterations = 0;
}
/**
* print_Job Prints out the job related parameters.
* @return
*/
void webclient::Job::print_Job() {
LOG_NOTICE("%s:%s:%d local_port=%d,local_ipv4=0x%08x,remote_ipv4=0x%08x,current_state=%d,total_no_of_iter=%ld,socket_fd=%d.\n"
, __FILE__, __FUNCTION__, __LINE__,
this->local_port,
this->local_ipv4,
this->remote_ipv4,
this->job_current_state,
this->total_number_of_iterations,
this->socket_file_descriptor);
}
/**
* ~Job Destructor.
*/
webclient::Job::~Job() {
//Do nothing
}
/**
* return_iteration_count Returns the running count of the number of the cycles the job successfully completed.
* @return
*/
webclient::uint64_t webclient::Job::return_iteration_count() {
return this->total_number_of_iterations;
}
/**
* return_current_job_state Returns the current state of the job.
* @return
*/
uint8_t webclient::Job::return_current_job_state() {
return this->job_current_state;
}
/**
* increment_iteration_count Increment the number of iterations/loops/cycles this job has successfully completed.
*/
void webclient::Job::increment_iteration_count() {
this->total_number_of_iterations++;
}
/**
* set_current_job_state Sets the new state of the job.
* @param new_state
*/
void webclient::Job::set_current_job_state(uint8_t new_state) {
this->job_current_state = new_state;
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <quic/api/QuicTransportBase.h>
#include <folly/Chrono.h>
#include <folly/ScopeGuard.h>
#include <quic/api/LoopDetectorCallback.h>
#include <quic/api/QuicBatchWriterFactory.h>
#include <quic/api/QuicTransportFunctions.h>
#include <quic/common/TimeUtil.h>
#include <quic/congestion_control/Pacer.h>
#include <quic/congestion_control/TokenlessPacer.h>
#include <quic/logging/QLoggerConstants.h>
#include <quic/loss/QuicLossFunctions.h>
#include <quic/state/QuicPacingFunctions.h>
#include <quic/state/QuicStateFunctions.h>
#include <quic/state/QuicStreamFunctions.h>
#include <quic/state/QuicStreamUtilities.h>
#include <quic/state/SimpleFrameFunctions.h>
#include <quic/state/stream/StreamSendHandlers.h>
#include <sstream>
namespace quic {
QuicTransportBase::QuicTransportBase(
QuicBackingEventBase* evb,
std::unique_ptr<QuicAsyncUDPSocketType> socket,
bool useConnectionEndWithErrorCallback)
: socket_(std::move(socket)),
useConnectionEndWithErrorCallback_(useConnectionEndWithErrorCallback),
lossTimeout_(this),
ackTimeout_(this),
pathValidationTimeout_(this),
idleTimeout_(this),
keepaliveTimeout_(this),
drainTimeout_(this),
pingTimeout_(this),
readLooper_(new FunctionLooper(
evb ? &qEvb_ : nullptr,
[this]() { invokeReadDataAndCallbacks(); },
LooperType::ReadLooper)),
peekLooper_(new FunctionLooper(
evb ? &qEvb_ : nullptr,
[this]() { invokePeekDataAndCallbacks(); },
LooperType::PeekLooper)),
writeLooper_(new FunctionLooper(
evb ? &qEvb_ : nullptr,
[this]() { pacedWriteDataToSocket(); },
LooperType::WriteLooper)) {
qEvbPtr_ = evb ? &qEvb_ : nullptr;
qEvb_.setBackingEventBase(evb);
writeLooper_->setPacingFunction([this]() -> auto {
if (isConnectionPaced(*conn_)) {
return conn_->pacer->getTimeUntilNextWrite();
}
return 0us;
});
if (socket_) {
socket_->setAdditionalCmsgsFunc(
[&]() { return getAdditionalCmsgsForAsyncUDPSocket(); });
}
}
void QuicTransportBase::scheduleTimeout(
QuicTimerCallback* callback,
std::chrono::milliseconds timeout) {
qEvb_.scheduleTimeout(callback, timeout);
}
void QuicTransportBase::setPacingTimer(
TimerHighRes::SharedPtr pacingTimer) noexcept {
if (pacingTimer) {
writeLooper_->setPacingTimer(std::move(pacingTimer));
}
}
void QuicTransportBase::setCongestionControllerFactory(
std::shared_ptr<CongestionControllerFactory> ccFactory) {
CHECK(ccFactory);
CHECK(conn_);
conn_->congestionControllerFactory = ccFactory;
conn_->congestionController.reset();
}
QuicBackingEventBase* QuicTransportBase::getEventBase() const {
return qEvb_.getBackingEventBase();
}
const std::shared_ptr<QLogger> QuicTransportBase::getQLogger() const {
return conn_->qLogger;
}
void QuicTransportBase::setQLogger(std::shared_ptr<QLogger> qLogger) {
// setQLogger can be called multiple times for the same connection and with
// the same qLogger we track the number of times it gets set and the number
// of times it gets reset, and only stop qlog collection when the number of
// resets equals the number of times the logger was set
if (!conn_->qLogger) {
CHECK_EQ(qlogRefcnt_, 0);
} else {
CHECK_GT(qlogRefcnt_, 0);
}
if (qLogger) {
conn_->qLogger = std::move(qLogger);
conn_->qLogger->setDcid(conn_->clientChosenDestConnectionId);
if (conn_->nodeType == QuicNodeType::Server) {
conn_->qLogger->setScid(conn_->serverConnectionId);
} else {
conn_->qLogger->setScid(conn_->clientConnectionId);
}
qlogRefcnt_++;
} else {
if (conn_->qLogger) {
qlogRefcnt_--;
if (qlogRefcnt_ == 0) {
conn_->qLogger = nullptr;
}
}
}
}
folly::Optional<ConnectionId> QuicTransportBase::getClientConnectionId() const {
return conn_->clientConnectionId;
}
folly::Optional<ConnectionId> QuicTransportBase::getServerConnectionId() const {
return conn_->serverConnectionId;
}
folly::Optional<ConnectionId>
QuicTransportBase::getClientChosenDestConnectionId() const {
return conn_->clientChosenDestConnectionId;
}
const folly::SocketAddress& QuicTransportBase::getPeerAddress() const {
return conn_->peerAddress;
}
const folly::SocketAddress& QuicTransportBase::getOriginalPeerAddress() const {
return conn_->originalPeerAddress;
}
const folly::SocketAddress& QuicTransportBase::getLocalAddress() const {
return socket_ && socket_->isBound() ? socket_->address()
: localFallbackAddress;
}
QuicTransportBase::~QuicTransportBase() {
resetConnectionCallbacks();
// closeImpl and closeUdpSocket should have been triggered by destructor of
// derived class to ensure that observers are properly notified
DCHECK_NE(CloseState::OPEN, closeState_);
DCHECK(!socket_.get()); // should be no socket
}
bool QuicTransportBase::good() const {
return closeState_ == CloseState::OPEN && hasWriteCipher() && !error();
}
bool QuicTransportBase::replaySafe() const {
return (conn_->oneRttWriteCipher != nullptr);
}
bool QuicTransportBase::error() const {
return conn_->localConnectionError.has_value();
}
QuicError QuicTransportBase::maybeSetGenericAppError(
folly::Optional<QuicError> error) {
return error ? error.value()
: QuicError(
GenericApplicationErrorCode::NO_ERROR,
toString(GenericApplicationErrorCode::NO_ERROR));
}
void QuicTransportBase::close(folly::Optional<QuicError> errorCode) {
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
// The caller probably doesn't need a conn callback any more because they
// explicitly called close.
resetConnectionCallbacks();
// If we were called with no error code, ensure that we are going to write
// an application close, so the peer knows it didn't come from the transport.
errorCode = maybeSetGenericAppError(errorCode);
closeImpl(std::move(errorCode), true);
}
void QuicTransportBase::closeNow(folly::Optional<QuicError> errorCode) {
DCHECK(getEventBase() && getEventBase()->isInEventBaseThread());
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
VLOG(4) << __func__ << " " << *this;
errorCode = maybeSetGenericAppError(errorCode);
closeImpl(std::move(errorCode), false);
// the drain timeout may have been scheduled by a previous close, in which
// case, our close would not take effect. This cancels the drain timeout in
// this case and expires the timeout.
if (drainTimeout_.isScheduled()) {
drainTimeout_.cancelTimeout();
drainTimeoutExpired();
}
}
void QuicTransportBase::closeGracefully() {
if (closeState_ == CloseState::CLOSED ||
closeState_ == CloseState::GRACEFUL_CLOSING) {
return;
}
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
resetConnectionCallbacks();
closeState_ = CloseState::GRACEFUL_CLOSING;
updatePacingOnClose(*conn_);
if (conn_->qLogger) {
conn_->qLogger->addConnectionClose(kNoError, kGracefulExit, true, false);
}
// Stop reads and cancel all the app callbacks.
VLOG(10) << "Stopping read and peek loopers due to graceful close " << *this;
readLooper_->stop();
peekLooper_->stop();
cancelAllAppCallbacks(
QuicError(QuicErrorCode(LocalErrorCode::NO_ERROR), "Graceful Close"));
// All streams are closed, close the transport for realz.
if (conn_->streamManager->streamCount() == 0) {
closeImpl(folly::none);
}
}
// TODO: t64691045 change the closeImpl API to include both the sanitized and
// unsanited error message, remove exceptionCloseWhat_.
void QuicTransportBase::closeImpl(
folly::Optional<QuicError> errorCode,
bool drainConnection,
bool sendCloseImmediately) {
if (closeState_ == CloseState::CLOSED) {
return;
}
if (getSocketObserverContainer()) {
SocketObserverInterface::CloseStartedEvent event;
event.maybeCloseReason = errorCode;
getSocketObserverContainer()->invokeInterfaceMethodAllObservers(
[&event](auto observer, auto observed) {
observer->closeStarted(observed, event);
});
}
drainConnection = drainConnection & conn_->transportSettings.shouldDrain;
uint64_t totalCryptoDataWritten = 0;
uint64_t totalCryptoDataRecvd = 0;
if (conn_->cryptoState) {
totalCryptoDataWritten +=
conn_->cryptoState->initialStream.currentWriteOffset;
totalCryptoDataWritten +=
conn_->cryptoState->handshakeStream.currentWriteOffset;
totalCryptoDataWritten +=
conn_->cryptoState->oneRttStream.currentWriteOffset;
totalCryptoDataRecvd += conn_->cryptoState->initialStream.maxOffsetObserved;
totalCryptoDataRecvd +=
conn_->cryptoState->handshakeStream.maxOffsetObserved;
totalCryptoDataRecvd += conn_->cryptoState->oneRttStream.maxOffsetObserved;
}
if (conn_->qLogger) {
conn_->qLogger->addTransportSummary(
{conn_->lossState.totalBytesSent,
conn_->lossState.totalBytesRecvd,
conn_->flowControlState.sumCurWriteOffset,
conn_->flowControlState.sumMaxObservedOffset,
conn_->flowControlState.sumCurStreamBufferLen,
conn_->lossState.totalBytesRetransmitted,
conn_->lossState.totalStreamBytesCloned,
conn_->lossState.totalBytesCloned,
totalCryptoDataWritten,
totalCryptoDataRecvd,
conn_->congestionController
? conn_->congestionController->getWritableBytes()
: std::numeric_limits<uint64_t>::max(),
getSendConnFlowControlBytesWire(*conn_),
conn_->lossState.totalPacketsSpuriouslyMarkedLost,
conn_->lossState.reorderingThreshold,
uint64_t(conn_->transportSettings.timeReorderingThreshDividend),
conn_->usedZeroRtt,
conn_->version.value_or(QuicVersion::MVFST_INVALID),
conn_->dsrPacketCount});
}
// TODO: truncate the error code string to be 1MSS only.
closeState_ = CloseState::CLOSED;
updatePacingOnClose(*conn_);
auto cancelCode = QuicError(
QuicErrorCode(LocalErrorCode::NO_ERROR),
toString(LocalErrorCode::NO_ERROR).str());
if (conn_->peerConnectionError) {
cancelCode = *conn_->peerConnectionError;
} else if (errorCode) {
cancelCode = *errorCode;
}
// cancelCode is used for communicating error message to local app layer.
// errorCode will be used for localConnectionError, and sent in close frames.
// It's safe to include the unsanitized error message in cancelCode
if (exceptionCloseWhat_) {
cancelCode.message = exceptionCloseWhat_.value();
}
bool isReset = false;
bool isAbandon = false;
bool isInvalidMigration = false;
LocalErrorCode* localError = cancelCode.code.asLocalErrorCode();
TransportErrorCode* transportError = cancelCode.code.asTransportErrorCode();
if (localError) {
isReset = *localError == LocalErrorCode::CONNECTION_RESET;
isAbandon = *localError == LocalErrorCode::CONNECTION_ABANDONED;
}
isInvalidMigration = transportError &&
*transportError == TransportErrorCode::INVALID_MIGRATION;
VLOG_IF(4, isReset) << "Closing transport due to stateless reset " << *this;
VLOG_IF(4, isAbandon) << "Closing transport due to abandoned connection "
<< *this;
if (errorCode) {
conn_->localConnectionError = errorCode;
std::string errorStr = conn_->localConnectionError->message;
std::string errorCodeStr = errorCode->message;
if (conn_->qLogger) {
conn_->qLogger->addConnectionClose(
errorStr, errorCodeStr, drainConnection, sendCloseImmediately);
}
} else {
auto reason = folly::to<std::string>(
"Server: ",
kNoError,
", Peer: isReset: ",
isReset,
", Peer: isAbandon: ",
isAbandon);
if (conn_->qLogger) {
conn_->qLogger->addConnectionClose(
kNoError, reason, drainConnection, sendCloseImmediately);
}
}
cancelLossTimeout();
ackTimeout_.cancelTimeout();
pathValidationTimeout_.cancelTimeout();
idleTimeout_.cancelTimeout();
keepaliveTimeout_.cancelTimeout();
pingTimeout_.cancelTimeout();
VLOG(10) << "Stopping read looper due to immediate close " << *this;
readLooper_->stop();
peekLooper_->stop();
writeLooper_->stop();
cancelAllAppCallbacks(cancelCode);
// Clear out all the pending events, we don't need them any more.
closeTransport();
// Clear out all the streams, we don't need them any more. When the peer
// receives the conn close they will implicitly reset all the streams.
QUIC_STATS_FOR_EACH(
conn_->streamManager->streams().cbegin(),
conn_->streamManager->streams().cend(),
conn_->statsCallback,
onQuicStreamClosed);
conn_->streamManager->clearOpenStreams();
// Clear out all the buffered datagrams
conn_->datagramState.readBuffer.clear();
conn_->datagramState.writeBuffer.clear();
// Clear out all the pending events.
conn_->pendingEvents = QuicConnectionStateBase::PendingEvents();
conn_->streamManager->clearActionable();
conn_->streamManager->clearWritable();
if (conn_->ackStates.initialAckState) {
conn_->ackStates.initialAckState->acks.clear();
}
if (conn_->ackStates.handshakeAckState) {
conn_->ackStates.handshakeAckState->acks.clear();
}
conn_->ackStates.appDataAckState.acks.clear();
if (transportReadyNotified_) {
processConnectionCallbacks(cancelCode);
} else {
processConnectionSetupCallbacks(cancelCode);
}
// can't invoke connection callbacks any more.
resetConnectionCallbacks();
// Don't need outstanding packets.
conn_->outstandings.reset();
// We don't need no congestion control.
conn_->congestionController = nullptr;
sendCloseImmediately = sendCloseImmediately && !isReset && !isAbandon;
if (sendCloseImmediately) {
// We might be invoked from the destructor, so just send the connection
// close directly.
try {
writeData();
} catch (const std::exception& ex) {
// This could happen if the writes fail.
LOG(ERROR) << "close threw exception " << ex.what() << " " << *this;
}
}
drainConnection =
drainConnection && !isReset && !isAbandon && !isInvalidMigration;
if (drainConnection) {
// We ever drain once, and the object ever gets created once.
DCHECK(!drainTimeout_.isScheduled());
scheduleTimeout(
&drainTimeout_,
folly::chrono::ceil<std::chrono::milliseconds>(
kDrainFactor * calculatePTO(*conn_)));
} else {
drainTimeoutExpired();
}
}
void QuicTransportBase::closeUdpSocket() {
if (!socket_) {
return;
}
if (getSocketObserverContainer()) {
SocketObserverInterface::ClosingEvent event; // empty for now
getSocketObserverContainer()->invokeInterfaceMethodAllObservers(
[&event](auto observer, auto observed) {
observer->closing(observed, event);
});
}
auto sock = std::move(socket_);
socket_ = nullptr;
sock->pauseRead();
sock->close();
}
bool QuicTransportBase::processCancelCode(const QuicError& cancelCode) {
bool noError = false;
switch (cancelCode.code.type()) {
case QuicErrorCode::Type::LocalErrorCode: {
LocalErrorCode localErrorCode = *cancelCode.code.asLocalErrorCode();
noError = localErrorCode == LocalErrorCode::NO_ERROR ||
localErrorCode == LocalErrorCode::IDLE_TIMEOUT ||
localErrorCode == LocalErrorCode::SHUTTING_DOWN;
break;
}
case QuicErrorCode::Type::TransportErrorCode: {
TransportErrorCode transportErrorCode =
*cancelCode.code.asTransportErrorCode();
noError = transportErrorCode == TransportErrorCode::NO_ERROR;
break;
}
case QuicErrorCode::Type::ApplicationErrorCode:
auto appErrorCode = *cancelCode.code.asApplicationErrorCode();
noError = appErrorCode == GenericApplicationErrorCode::NO_ERROR;
}
return noError;
}
void QuicTransportBase::processConnectionSetupCallbacks(
const QuicError& cancelCode) {
// connSetupCallback_ could be null if start() was never
// invoked and the transport was destroyed or if the app initiated close.
if (!connSetupCallback_) {
return;
}
connSetupCallback_->onConnectionSetupError(
QuicError(cancelCode.code, cancelCode.message));
}
void QuicTransportBase::processConnectionCallbacks(
const QuicError& cancelCode) {
// connCallback_ could be null if start() was never
// invoked and the transport was destroyed or if the app initiated close.
if (!connCallback_) {
return;
}
QUIC_STATS(conn_->statsCallback, onConnectionClose, cancelCode.code);
if (useConnectionEndWithErrorCallback_) {
connCallback_->onConnectionEnd(cancelCode);
return;
}
bool noError = processCancelCode(cancelCode);
if (noError) {
connCallback_->onConnectionEnd();
} else {
connCallback_->onConnectionError(cancelCode);
}
}
void QuicTransportBase::drainTimeoutExpired() noexcept {
closeUdpSocket();
unbindConnection();
}
folly::Expected<size_t, LocalErrorCode> QuicTransportBase::getStreamReadOffset(
StreamId) const {
return 0;
}
folly::Expected<size_t, LocalErrorCode> QuicTransportBase::getStreamWriteOffset(
StreamId id) const {
if (isReceivingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
try {
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
return stream->currentWriteOffset;
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
return folly::makeUnexpected(ex.errorCode());
} catch (const QuicTransportException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
return folly::makeUnexpected(LocalErrorCode::TRANSPORT_ERROR);
} catch (const std::exception& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
return folly::makeUnexpected(LocalErrorCode::INTERNAL_ERROR);
}
}
folly::Expected<size_t, LocalErrorCode>
QuicTransportBase::getStreamWriteBufferedBytes(StreamId id) const {
if (isReceivingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
try {
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
return stream->writeBuffer.chainLength();
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
return folly::makeUnexpected(ex.errorCode());
} catch (const QuicTransportException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
return folly::makeUnexpected(LocalErrorCode::TRANSPORT_ERROR);
} catch (const std::exception& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
return folly::makeUnexpected(LocalErrorCode::INTERNAL_ERROR);
}
}
/**
* Getters for details from the transport/security layers such as
* RTT, rxmit, cwnd, mss, app protocol, handshake latency,
* client proposed ciphers, etc.
*/
QuicSocket::TransportInfo QuicTransportBase::getTransportInfo() const {
CongestionControlType congestionControlType = CongestionControlType::None;
uint64_t writableBytes = std::numeric_limits<uint64_t>::max();
uint64_t congestionWindow = std::numeric_limits<uint64_t>::max();
folly::Optional<CongestionController::State> maybeCCState;
uint64_t burstSize = 0;
std::chrono::microseconds pacingInterval = 0ms;
if (conn_->congestionController) {
congestionControlType = conn_->congestionController->type();
writableBytes = conn_->congestionController->getWritableBytes();
congestionWindow = conn_->congestionController->getCongestionWindow();
maybeCCState = conn_->congestionController->getState();
if (isConnectionPaced(*conn_)) {
burstSize = conn_->pacer->getCachedWriteBatchSize();
pacingInterval = conn_->pacer->getTimeUntilNextWrite();
}
}
TransportInfo transportInfo;
transportInfo.connectionTime = conn_->connectionTime;
transportInfo.srtt = conn_->lossState.srtt;
transportInfo.rttvar = conn_->lossState.rttvar;
transportInfo.lrtt = conn_->lossState.lrtt;
transportInfo.maybeLrtt = conn_->lossState.maybeLrtt;
transportInfo.maybeLrttAckDelay = conn_->lossState.maybeLrttAckDelay;
if (conn_->lossState.mrtt != kDefaultMinRtt) {
transportInfo.maybeMinRtt = conn_->lossState.mrtt;
}
transportInfo.maybeMinRttNoAckDelay = conn_->lossState.maybeMrttNoAckDelay;
transportInfo.mss = conn_->udpSendPacketLen;
transportInfo.congestionControlType = congestionControlType;
transportInfo.writableBytes = writableBytes;
transportInfo.congestionWindow = congestionWindow;
transportInfo.pacingBurstSize = burstSize;
transportInfo.pacingInterval = pacingInterval;
transportInfo.packetsRetransmitted = conn_->lossState.rtxCount;
transportInfo.totalPacketsSent = conn_->lossState.totalPacketsSent;
transportInfo.totalAckElicitingPacketsSent =
conn_->lossState.totalAckElicitingPacketsSent;
transportInfo.totalPacketsMarkedLost =
conn_->lossState.totalPacketsMarkedLost;
transportInfo.totalPacketsMarkedLostByTimeout =
conn_->lossState.totalPacketsMarkedLostByTimeout;
transportInfo.totalPacketsMarkedLostByReorderingThreshold =
conn_->lossState.totalPacketsMarkedLostByReorderingThreshold;
transportInfo.totalPacketsSpuriouslyMarkedLost =
conn_->lossState.totalPacketsSpuriouslyMarkedLost;
transportInfo.timeoutBasedLoss = conn_->lossState.timeoutBasedRtxCount;
transportInfo.totalBytesRetransmitted =
conn_->lossState.totalBytesRetransmitted;
transportInfo.pto = calculatePTO(*conn_);
transportInfo.bytesSent = conn_->lossState.totalBytesSent;
transportInfo.bytesAcked = conn_->lossState.totalBytesAcked;
transportInfo.bytesRecvd = conn_->lossState.totalBytesRecvd;
transportInfo.bytesInFlight = conn_->lossState.inflightBytes;
transportInfo.bodyBytesSent = conn_->lossState.totalBodyBytesSent;
transportInfo.bodyBytesAcked = conn_->lossState.totalBodyBytesAcked;
transportInfo.totalStreamBytesSent = conn_->lossState.totalStreamBytesSent;
transportInfo.totalNewStreamBytesSent =
conn_->lossState.totalNewStreamBytesSent;
transportInfo.ptoCount = conn_->lossState.ptoCount;
transportInfo.totalPTOCount = conn_->lossState.totalPTOCount;
transportInfo.largestPacketAckedByPeer =
conn_->ackStates.appDataAckState.largestAckedByPeer;
transportInfo.largestPacketSent = conn_->lossState.largestSent;
transportInfo.usedZeroRtt = conn_->usedZeroRtt;
transportInfo.maybeCCState = maybeCCState;
return transportInfo;
}
folly::Optional<std::string> QuicTransportBase::getAppProtocol() const {
return conn_->handshakeLayer->getApplicationProtocol();
}
void QuicTransportBase::setReceiveWindow(
StreamId /*id*/,
size_t /*recvWindowSize*/) {}
void QuicTransportBase::setSendBuffer(
StreamId /*id*/,
size_t /*maxUnacked*/,
size_t /*maxUnsent*/) {}
uint64_t QuicTransportBase::getConnectionBufferAvailable() const {
return bufferSpaceAvailable();
}
uint64_t QuicTransportBase::bufferSpaceAvailable() const {
auto bytesBuffered = conn_->flowControlState.sumCurStreamBufferLen;
auto totalBufferSpaceAvailable =
conn_->transportSettings.totalBufferSpaceAvailable;
return bytesBuffered > totalBufferSpaceAvailable
? 0
: totalBufferSpaceAvailable - bytesBuffered;
}
folly::Expected<QuicSocket::FlowControlState, LocalErrorCode>
QuicTransportBase::getConnectionFlowControl() const {
return QuicSocket::FlowControlState(
getSendConnFlowControlBytesAPI(*conn_),
conn_->flowControlState.peerAdvertisedMaxOffset,
getRecvConnFlowControlBytes(*conn_),
conn_->flowControlState.advertisedMaxOffset);
}
folly::Expected<QuicSocket::FlowControlState, LocalErrorCode>
QuicTransportBase::getStreamFlowControl(StreamId id) const {
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
return QuicSocket::FlowControlState(
getSendStreamFlowControlBytesAPI(*stream),
stream->flowControlState.peerAdvertisedMaxOffset,
getRecvStreamFlowControlBytes(*stream),
stream->flowControlState.advertisedMaxOffset);
}
folly::Expected<uint64_t, LocalErrorCode>
QuicTransportBase::getMaxWritableOnStream(StreamId id) const {
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
if (isReceivingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
return maxWritableOnStream(*stream);
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::setConnectionFlowControlWindow(uint64_t windowSize) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
conn_->flowControlState.windowSize = windowSize;
maybeSendConnWindowUpdate(*conn_, Clock::now());
updateWriteLooper(true);
return folly::unit;
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::setStreamFlowControlWindow(
StreamId id,
uint64_t windowSize) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
stream->flowControlState.windowSize = windowSize;
maybeSendStreamWindowUpdate(*stream, Clock::now());
updateWriteLooper(true);
return folly::unit;
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::setReadCallback(
StreamId id,
ReadCallback* cb,
folly::Optional<ApplicationErrorCode> err) {
if (isSendingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
return setReadCallbackInternal(id, cb, err);
}
void QuicTransportBase::unsetAllReadCallbacks() {
for (auto& streamCallbackPair : readCallbacks_) {
setReadCallbackInternal(
streamCallbackPair.first,
nullptr,
GenericApplicationErrorCode::NO_ERROR);
}
}
void QuicTransportBase::unsetAllPeekCallbacks() {
for (auto& streamCallbackPair : peekCallbacks_) {
setPeekCallbackInternal(streamCallbackPair.first, nullptr);
}
}
void QuicTransportBase::unsetAllDeliveryCallbacks() {
auto deliveryCallbacksCopy = deliveryCallbacks_;
for (auto& streamCallbackPair : deliveryCallbacksCopy) {
cancelDeliveryCallbacksForStream(streamCallbackPair.first);
}
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::setReadCallbackInternal(
StreamId id,
ReadCallback* cb,
folly::Optional<ApplicationErrorCode> err) noexcept {
VLOG(4) << "Setting setReadCallback for stream=" << id << " cb=" << cb << " "
<< *this;
auto readCbIt = readCallbacks_.find(id);
if (readCbIt == readCallbacks_.end()) {
// Don't allow initial setting of a nullptr callback.
if (!cb) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
readCbIt = readCallbacks_.emplace(id, ReadCallbackData(cb)).first;
}
auto& readCb = readCbIt->second.readCb;
if (readCb == nullptr && cb != nullptr) {
// It's already been set to nullptr we do not allow unsetting it.
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
} else {
readCb = cb;
if (readCb == nullptr && err) {
return stopSending(id, err.value());
}
}
updateReadLooper();
return folly::unit;
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::pauseRead(
StreamId id) {
VLOG(4) << __func__ << " " << *this << " stream=" << id;
return pauseOrResumeRead(id, false);
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::stopSending(
StreamId id,
ApplicationErrorCode error) {
if (isSendingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto* stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
if (stream->recvState == StreamRecvState::Closed) {
// skip STOP_SENDING if ingress is already closed
return folly::unit;
}
if (conn_->transportSettings.dropIngressOnStopSending) {
processTxStopSending(*stream);
}
// send STOP_SENDING frame to peer
sendSimpleFrame(*conn_, StopSendingFrame(id, error));
updateWriteLooper(true);
return folly::unit;
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::resumeRead(
StreamId id) {
VLOG(4) << __func__ << " " << *this << " stream=" << id;
return pauseOrResumeRead(id, true);
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::pauseOrResumeRead(StreamId id, bool resume) {
if (isSendingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto readCb = readCallbacks_.find(id);
if (readCb == readCallbacks_.end()) {
return folly::makeUnexpected(LocalErrorCode::APP_ERROR);
}
if (readCb->second.resumed != resume) {
readCb->second.resumed = resume;
updateReadLooper();
}
return folly::unit;
}
void QuicTransportBase::invokeReadDataAndCallbacks() {
auto self = sharedGuard();
SCOPE_EXIT {
self->checkForClosedStream();
self->updateReadLooper();
self->updateWriteLooper(true);
};
// Need a copy since the set can change during callbacks.
std::vector<StreamId> readableStreamsCopy;
const auto& readableStreams = self->conn_->streamManager->readableStreams();
readableStreamsCopy.reserve(readableStreams.size());
std::copy(
readableStreams.begin(),
readableStreams.end(),
std::back_inserter(readableStreamsCopy));
if (self->conn_->transportSettings.orderedReadCallbacks) {
std::sort(readableStreamsCopy.begin(), readableStreamsCopy.end());
}
for (StreamId streamId : readableStreamsCopy) {
auto callback = self->readCallbacks_.find(streamId);
if (callback == self->readCallbacks_.end()) {
// Stream doesn't have a read callback set, skip it.
continue;
}
auto readCb = callback->second.readCb;
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(streamId));
if (readCb && stream->streamReadError) {
self->conn_->streamManager->readableStreams().erase(streamId);
readCallbacks_.erase(callback);
// if there is an error on the stream - it's not readable anymore, so
// we cannot peek into it as well.
self->conn_->streamManager->peekableStreams().erase(streamId);
peekCallbacks_.erase(streamId);
VLOG(10) << "invoking read error callbacks on stream=" << streamId << " "
<< *this;
if (!stream->groupId) {
readCb->readError(streamId, QuicError(*stream->streamReadError));
} else {
readCb->readErrorWithGroup(
streamId, *stream->groupId, QuicError(*stream->streamReadError));
}
} else if (
readCb && callback->second.resumed && stream->hasReadableData()) {
VLOG(10) << "invoking read callbacks on stream=" << streamId << " "
<< *this;
if (!stream->groupId) {
readCb->readAvailable(streamId);
} else {
readCb->readAvailableWithGroup(streamId, *stream->groupId);
}
}
}
if (self->datagramCallback_ && !conn_->datagramState.readBuffer.empty()) {
self->datagramCallback_->onDatagramsAvailable();
}
}
void QuicTransportBase::updateReadLooper() {
if (closeState_ != CloseState::OPEN) {
VLOG(10) << "Stopping read looper " << *this;
readLooper_->stop();
return;
}
auto iter = std::find_if(
conn_->streamManager->readableStreams().begin(),
conn_->streamManager->readableStreams().end(),
[&readCallbacks = readCallbacks_](StreamId s) {
auto readCb = readCallbacks.find(s);
if (readCb == readCallbacks.end()) {
return false;
}
// TODO: if the stream has an error and it is also paused we should
// still return an error
return readCb->second.readCb && readCb->second.resumed;
});
if (iter != conn_->streamManager->readableStreams().end() ||
!conn_->datagramState.readBuffer.empty()) {
VLOG(10) << "Scheduling read looper " << *this;
readLooper_->run();
} else {
VLOG(10) << "Stopping read looper " << *this;
readLooper_->stop();
}
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::setPeekCallback(
StreamId id,
PeekCallback* cb) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
setPeekCallbackInternal(id, cb);
return folly::unit;
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::setPeekCallbackInternal(
StreamId id,
PeekCallback* cb) noexcept {
VLOG(4) << "Setting setPeekCallback for stream=" << id << " cb=" << cb << " "
<< *this;
auto peekCbIt = peekCallbacks_.find(id);
if (peekCbIt == peekCallbacks_.end()) {
// Don't allow initial setting of a nullptr callback.
if (!cb) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
peekCbIt = peekCallbacks_.emplace(id, PeekCallbackData(cb)).first;
}
if (!cb) {
VLOG(10) << "Resetting the peek callback to nullptr "
<< "stream=" << id << " peekCb=" << peekCbIt->second.peekCb;
}
peekCbIt->second.peekCb = cb;
updatePeekLooper();
return folly::unit;
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::pausePeek(
StreamId id) {
VLOG(4) << __func__ << " " << *this << " stream=" << id;
return pauseOrResumePeek(id, false);
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::resumePeek(
StreamId id) {
VLOG(4) << __func__ << " " << *this << " stream=" << id;
return pauseOrResumePeek(id, true);
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::pauseOrResumePeek(StreamId id, bool resume) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto peekCb = peekCallbacks_.find(id);
if (peekCb == peekCallbacks_.end()) {
return folly::makeUnexpected(LocalErrorCode::APP_ERROR);
}
if (peekCb->second.resumed != resume) {
peekCb->second.resumed = resume;
updatePeekLooper();
}
return folly::unit;
}
void QuicTransportBase::invokePeekDataAndCallbacks() {
auto self = sharedGuard();
SCOPE_EXIT {
self->checkForClosedStream();
self->updatePeekLooper();
self->updateWriteLooper(true);
};
// TODO: add protection from calling "consume" in the middle of the peek -
// one way is to have a peek counter that is incremented when peek calblack
// is called and decremented when peek is done. once counter transitions
// to 0 we can execute "consume" calls that were done during "peek", for that,
// we would need to keep stack of them.
std::vector<StreamId> peekableStreamsCopy;
const auto& peekableStreams = self->conn_->streamManager->peekableStreams();
peekableStreamsCopy.reserve(peekableStreams.size());
std::copy(
peekableStreams.begin(),
peekableStreams.end(),
std::back_inserter(peekableStreamsCopy));
VLOG(10) << __func__
<< " peekableListCopy.size()=" << peekableStreamsCopy.size();
for (StreamId streamId : peekableStreamsCopy) {
auto callback = self->peekCallbacks_.find(streamId);
// This is a likely bug. Need to think more on whether events can
// be dropped
// remove streamId from list of peekable - as opposed to "read", "peek" is
// only called once per streamId and not on every EVB loop until application
// reads the data.
self->conn_->streamManager->peekableStreams().erase(streamId);
if (callback == self->peekCallbacks_.end()) {
VLOG(10) << " No peek callback for stream=" << streamId;
continue;
}
auto peekCb = callback->second.peekCb;
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(streamId));
if (peekCb && stream->streamReadError) {
VLOG(10) << "invoking peek error callbacks on stream=" << streamId << " "
<< *this;
peekCb->peekError(streamId, QuicError(*stream->streamReadError));
} else if (
peekCb && !stream->streamReadError && stream->hasPeekableData()) {
VLOG(10) << "invoking peek callbacks on stream=" << streamId << " "
<< *this;
peekDataFromQuicStream(
*stream,
[&](StreamId id, const folly::Range<PeekIterator>& peekRange) {
peekCb->onDataAvailable(id, peekRange);
});
} else {
VLOG(10) << "Not invoking peek callbacks on stream=" << streamId;
}
}
}
void QuicTransportBase::invokeStreamsAvailableCallbacks() {
if (conn_->streamManager->consumeMaxLocalBidirectionalStreamIdIncreased()) {
// check in case new streams were created in preceding callbacks
// and max is already reached
auto numStreams = getNumOpenableBidirectionalStreams();
if (numStreams > 0) {
connCallback_->onBidirectionalStreamsAvailable(numStreams);
}
}
if (conn_->streamManager->consumeMaxLocalUnidirectionalStreamIdIncreased()) {
// check in case new streams were created in preceding callbacks
// and max is already reached
auto numStreams = getNumOpenableUnidirectionalStreams();
if (numStreams > 0) {
connCallback_->onUnidirectionalStreamsAvailable(numStreams);
}
}
}
void QuicTransportBase::updatePeekLooper() {
if (peekCallbacks_.empty() || closeState_ != CloseState::OPEN) {
VLOG(10) << "Stopping peek looper " << *this;
peekLooper_->stop();
return;
}
VLOG(10) << "Updating peek looper, has "
<< conn_->streamManager->peekableStreams().size()
<< " peekable streams";
auto iter = std::find_if(
conn_->streamManager->peekableStreams().begin(),
conn_->streamManager->peekableStreams().end(),
[&peekCallbacks = peekCallbacks_](StreamId s) {
VLOG(10) << "Checking stream=" << s;
auto peekCb = peekCallbacks.find(s);
if (peekCb == peekCallbacks.end()) {
VLOG(10) << "No peek callbacks for stream=" << s;
return false;
}
if (!peekCb->second.resumed) {
VLOG(10) << "peek callback for stream=" << s << " not resumed";
}
if (!peekCb->second.peekCb) {
VLOG(10) << "no peekCb in peekCb stream=" << s;
}
return peekCb->second.peekCb && peekCb->second.resumed;
});
if (iter != conn_->streamManager->peekableStreams().end()) {
VLOG(10) << "Scheduling peek looper " << *this;
peekLooper_->run();
} else {
VLOG(10) << "Stopping peek looper " << *this;
peekLooper_->stop();
}
}
void QuicTransportBase::updateWriteLooper(bool thisIteration) {
if (closeState_ == CloseState::CLOSED) {
VLOG(10) << nodeToString(conn_->nodeType)
<< " stopping write looper because conn closed " << *this;
writeLooper_->stop();
return;
}
// TODO: Also listens to write event from libevent. Only schedule write when
// the socket itself is writable.
auto writeDataReason = shouldWriteData(*conn_);
if (writeDataReason != WriteDataReason::NO_WRITE) {
VLOG(10) << nodeToString(conn_->nodeType)
<< " running write looper thisIteration=" << thisIteration << " "
<< *this;
writeLooper_->run(thisIteration);
if (conn_->loopDetectorCallback) {
conn_->writeDebugState.needsWriteLoopDetect =
(conn_->loopDetectorCallback != nullptr);
}
} else {
VLOG(10) << nodeToString(conn_->nodeType) << " stopping write looper "
<< *this;
writeLooper_->stop();
if (conn_->loopDetectorCallback) {
conn_->writeDebugState.needsWriteLoopDetect = false;
conn_->writeDebugState.currentEmptyLoopCount = 0;
}
}
if (conn_->loopDetectorCallback) {
conn_->writeDebugState.writeDataReason = writeDataReason;
}
}
void QuicTransportBase::cancelDeliveryCallbacksForStream(StreamId id) {
cancelByteEventCallbacksForStream(ByteEvent::Type::ACK, id);
}
void QuicTransportBase::cancelDeliveryCallbacksForStream(
StreamId id,
uint64_t offset) {
cancelByteEventCallbacksForStream(ByteEvent::Type::ACK, id, offset);
}
void QuicTransportBase::cancelByteEventCallbacksForStream(
const StreamId id,
const folly::Optional<uint64_t>& offset) {
invokeForEachByteEventType(([this, id, &offset](const ByteEvent::Type type) {
cancelByteEventCallbacksForStream(type, id, offset);
}));
}
void QuicTransportBase::cancelByteEventCallbacksForStream(
const ByteEvent::Type type,
const StreamId id,
const folly::Optional<uint64_t>& offset) {
if (isReceivingStream(conn_->nodeType, id)) {
return;
}
auto& byteEventMap = getByteEventMap(type);
auto byteEventMapIt = byteEventMap.find(id);
if (byteEventMapIt == byteEventMap.end()) {
switch (type) {
case ByteEvent::Type::ACK:
conn_->streamManager->removeDeliverable(id);
break;
case ByteEvent::Type::TX:
conn_->streamManager->removeTx(id);
break;
}
return;
}
auto& streamByteEvents = byteEventMapIt->second;
// Callbacks are kept sorted by offset, so we can just walk the queue and
// invoke those with offset below provided offset.
while (!streamByteEvents.empty()) {
// decomposition not supported for xplat
const auto cbOffset = streamByteEvents.front().offset;
const auto callback = streamByteEvents.front().callback;
if (!offset.has_value() || cbOffset < *offset) {
streamByteEvents.pop_front();
ByteEventCancellation cancellation = {};
cancellation.id = id;
cancellation.offset = cbOffset;
cancellation.type = type;
callback->onByteEventCanceled(cancellation);
if (closeState_ != CloseState::OPEN) {
// socket got closed - we can't use streamByteEvents anymore,
// closeImpl should take care of cleaning up any remaining callbacks
return;
}
} else {
// Only larger or equal offsets left, exit the loop.
break;
}
}
// Clean up state for this stream if no callbacks left to invoke.
if (streamByteEvents.empty()) {
switch (type) {
case ByteEvent::Type::ACK:
conn_->streamManager->removeDeliverable(id);
break;
case ByteEvent::Type::TX:
conn_->streamManager->removeTx(id);
break;
}
// The callback could have changed the map so erase by id.
byteEventMap.erase(id);
}
}
void QuicTransportBase::cancelAllByteEventCallbacks() {
invokeForEachByteEventType(
([this](const ByteEvent::Type type) { cancelByteEventCallbacks(type); }));
}
void QuicTransportBase::cancelByteEventCallbacks(const ByteEvent::Type type) {
ByteEventMap byteEventMap = std::move(getByteEventMap(type));
for (const auto& byteEventMapIt : byteEventMap) {
const auto streamId = byteEventMapIt.first;
const auto callbackMap = byteEventMapIt.second;
for (const auto& callbackMapIt : callbackMap) {
const auto offset = callbackMapIt.offset;
const auto callback = callbackMapIt.callback;
ByteEventCancellation cancellation = {};
cancellation.id = streamId;
cancellation.offset = offset;
cancellation.type = type;
callback->onByteEventCanceled(cancellation);
}
}
}
size_t QuicTransportBase::getNumByteEventCallbacksForStream(
const StreamId id) const {
size_t total = 0;
invokeForEachByteEventTypeConst(
([this, id, &total](const ByteEvent::Type type) {
total += getNumByteEventCallbacksForStream(type, id);
}));
return total;
}
size_t QuicTransportBase::getNumByteEventCallbacksForStream(
const ByteEvent::Type type,
const StreamId id) const {
const auto& byteEventMap = getByteEventMapConst(type);
const auto byteEventMapIt = byteEventMap.find(id);
if (byteEventMapIt == byteEventMap.end()) {
return 0;
}
const auto& streamByteEvents = byteEventMapIt->second;
return streamByteEvents.size();
}
folly::Expected<std::pair<Buf, bool>, LocalErrorCode> QuicTransportBase::read(
StreamId id,
size_t maxLen) {
if (isSendingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
SCOPE_EXIT {
updateReadLooper();
updatePeekLooper(); // read can affect "peek" API
updateWriteLooper(true);
};
try {
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
auto result = readDataFromQuicStream(*stream, maxLen);
if (result.second) {
VLOG(10) << "Delivered eof to app for stream=" << stream->id << " "
<< *this;
auto it = readCallbacks_.find(id);
if (it != readCallbacks_.end()) {
// it's highly unlikely that someone called read() without having a read
// callback so we don't deal with the case of someone installing a read
// callback after reading the EOM.
it->second.deliveredEOM = true;
}
}
return folly::makeExpected<LocalErrorCode>(std::move(result));
} catch (const QuicTransportException& ex) {
VLOG(4) << "read() error " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(
QuicError(QuicErrorCode(ex.errorCode()), std::string("read() error")));
return folly::makeUnexpected(LocalErrorCode::TRANSPORT_ERROR);
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(
QuicError(QuicErrorCode(ex.errorCode()), std::string("read() error")));
return folly::makeUnexpected(ex.errorCode());
} catch (const std::exception& ex) {
VLOG(4) << "read() error " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR),
std::string("read() error")));
return folly::makeUnexpected(LocalErrorCode::INTERNAL_ERROR);
}
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::peek(
StreamId id,
const folly::Function<void(StreamId id, const folly::Range<PeekIterator>&)
const>& peekCallback) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
SCOPE_EXIT {
updatePeekLooper();
updateWriteLooper(true);
};
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
if (stream->streamReadError) {
switch (stream->streamReadError->type()) {
case QuicErrorCode::Type::LocalErrorCode:
return folly::makeUnexpected(
*stream->streamReadError->asLocalErrorCode());
default:
return folly::makeUnexpected(LocalErrorCode::INTERNAL_ERROR);
}
}
peekDataFromQuicStream(*stream, std::move(peekCallback));
return folly::makeExpected<LocalErrorCode>(folly::Unit());
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::consume(
StreamId id,
size_t amount) {
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
auto result = consume(id, stream->currentReadOffset, amount);
if (result.hasError()) {
return folly::makeUnexpected(result.error().first);
}
return folly::makeExpected<LocalErrorCode>(result.value());
}
folly::
Expected<folly::Unit, std::pair<LocalErrorCode, folly::Optional<uint64_t>>>
QuicTransportBase::consume(StreamId id, uint64_t offset, size_t amount) {
using ConsumeError = std::pair<LocalErrorCode, folly::Optional<uint64_t>>;
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(
ConsumeError{LocalErrorCode::CONNECTION_CLOSED, folly::none});
}
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
SCOPE_EXIT {
updatePeekLooper();
updateReadLooper(); // consume may affect "read" API
updateWriteLooper(true);
};
folly::Optional<uint64_t> readOffset;
try {
// Need to check that the stream exists first so that we don't
// accidentally let the API create a peer stream that was not
// sent by the peer.
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(
ConsumeError{LocalErrorCode::STREAM_NOT_EXISTS, readOffset});
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
readOffset = stream->currentReadOffset;
if (stream->currentReadOffset != offset) {
return folly::makeUnexpected(
ConsumeError{LocalErrorCode::INTERNAL_ERROR, readOffset});
}
if (stream->streamReadError) {
switch (stream->streamReadError->type()) {
case QuicErrorCode::Type::LocalErrorCode:
return folly::makeUnexpected(ConsumeError{
*stream->streamReadError->asLocalErrorCode(), folly::none});
default:
return folly::makeUnexpected(
ConsumeError{LocalErrorCode::INTERNAL_ERROR, folly::none});
}
}
consumeDataFromQuicStream(*stream, amount);
return folly::makeExpected<ConsumeError>(folly::Unit());
} catch (const QuicTransportException& ex) {
VLOG(4) << "consume() error " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()), std::string("consume() error")));
return folly::makeUnexpected(
ConsumeError{LocalErrorCode::TRANSPORT_ERROR, readOffset});
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()), std::string("consume() error")));
return folly::makeUnexpected(ConsumeError{ex.errorCode(), readOffset});
} catch (const std::exception& ex) {
VLOG(4) << "consume() error " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR),
std::string("consume() error")));
return folly::makeUnexpected(
ConsumeError{LocalErrorCode::INTERNAL_ERROR, readOffset});
}
}
void QuicTransportBase::handlePingCallbacks() {
if (conn_->pendingEvents.notifyPingReceived && pingCallback_ != nullptr) {
conn_->pendingEvents.notifyPingReceived = false;
if (pingCallback_ != nullptr) {
pingCallback_->onPing();
}
}
if (!conn_->pendingEvents.cancelPingTimeout) {
return; // nothing to cancel
}
if (!pingTimeout_.isScheduled()) {
// set cancelpingTimeOut to false, delayed acks
conn_->pendingEvents.cancelPingTimeout = false;
return; // nothing to do, as timeout has already fired
}
pingTimeout_.cancelTimeout();
if (pingCallback_ != nullptr) {
pingCallback_->pingAcknowledged();
}
conn_->pendingEvents.cancelPingTimeout = false;
}
void QuicTransportBase::processCallbacksAfterWriteData() {
if (closeState_ != CloseState::OPEN) {
return;
}
auto txStreamId = conn_->streamManager->popTx();
while (txStreamId.has_value()) {
auto streamId = *txStreamId;
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(streamId));
auto largestOffsetTxed = getLargestWriteOffsetTxed(*stream);
// if it's in the set of streams with TX, we should have a valid offset
CHECK(largestOffsetTxed.has_value());
// lambda to help get the next callback to call for this stream
auto getNextTxCallbackForStreamAndCleanup =
[this, &largestOffsetTxed](
const auto& streamId) -> folly::Optional<ByteEventDetail> {
auto txCallbacksForStreamIt = txCallbacks_.find(streamId);
if (txCallbacksForStreamIt == txCallbacks_.end() ||
txCallbacksForStreamIt->second.empty()) {
return folly::none;
}
auto& txCallbacksForStream = txCallbacksForStreamIt->second;
if (txCallbacksForStream.front().offset > *largestOffsetTxed) {
return folly::none;
}
// extract the callback, pop from the queue, then check for cleanup
auto result = txCallbacksForStream.front();
txCallbacksForStream.pop_front();
if (txCallbacksForStream.empty()) {
txCallbacks_.erase(txCallbacksForStreamIt);
}
return result;
};
folly::Optional<ByteEventDetail> nextOffsetAndCallback;
while (
(nextOffsetAndCallback =
getNextTxCallbackForStreamAndCleanup(streamId))) {
ByteEvent byteEvent = {};
byteEvent.id = streamId;
byteEvent.offset = nextOffsetAndCallback->offset;
byteEvent.type = ByteEvent::Type::TX;
nextOffsetAndCallback->callback->onByteEvent(byteEvent);
// connection may be closed by callback
if (closeState_ != CloseState::OPEN) {
return;
}
}
// pop the next stream
txStreamId = conn_->streamManager->popTx();
}
}
void QuicTransportBase::handleKnobCallbacks() {
if (!conn_->transportSettings.advertisedKnobFrameSupport) {
VLOG(4) << "Received knob frames without advertising support";
conn_->pendingEvents.knobs.clear();
return;
}
for (auto& knobFrame : conn_->pendingEvents.knobs) {
if (knobFrame.knobSpace != kDefaultQuicTransportKnobSpace) {
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::knobFrameEvents>()) {
getSocketObserverContainer()
->invokeInterfaceMethod<
SocketObserverInterface::Events::knobFrameEvents>(
[event = quic::SocketObserverInterface::KnobFrameEvent(
Clock::now(), knobFrame)](auto observer, auto observed) {
observer->knobFrameReceived(observed, event);
});
}
connCallback_->onKnob(
knobFrame.knobSpace, knobFrame.id, std::move(knobFrame.blob));
} else {
// KnobId is ignored
onTransportKnobs(std::move(knobFrame.blob));
}
}
conn_->pendingEvents.knobs.clear();
}
void QuicTransportBase::handleAckEventCallbacks() {
auto& lastProcessedAckEvents = conn_->lastProcessedAckEvents;
if (lastProcessedAckEvents.empty()) {
return; // nothing to do
}
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::acksProcessedEvents>()) {
getSocketObserverContainer()
->invokeInterfaceMethod<
SocketObserverInterface::Events::acksProcessedEvents>(
[event =
quic::SocketObserverInterface::AcksProcessedEvent::Builder()
.setAckEvents(lastProcessedAckEvents)
.build()](auto observer, auto observed) {
observer->acksProcessed(observed, event);
});
}
lastProcessedAckEvents.clear();
}
void QuicTransportBase::handleCancelByteEventCallbacks() {
for (auto pendingResetIt = conn_->pendingEvents.resets.begin();
pendingResetIt != conn_->pendingEvents.resets.end();
pendingResetIt++) {
cancelByteEventCallbacksForStream(pendingResetIt->first);
if (closeState_ != CloseState::OPEN) {
return;
}
}
}
void QuicTransportBase::logStreamOpenEvent(StreamId streamId) {
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::streamEvents>()) {
getSocketObserverContainer()
->invokeInterfaceMethod<SocketObserverInterface::Events::streamEvents>(
[event = SocketObserverInterface::StreamOpenEvent(
streamId,
getStreamInitiator(streamId),
getStreamDirectionality(streamId))](
auto observer, auto observed) {
observer->streamOpened(observed, event);
});
}
}
void QuicTransportBase::handleNewStreams(std::vector<StreamId>& streamStorage) {
const auto& newPeerStreamIds = streamStorage;
for (const auto& streamId : newPeerStreamIds) {
CHECK_NOTNULL(connCallback_);
if (isBidirectionalStream(streamId)) {
connCallback_->onNewBidirectionalStream(streamId);
} else {
connCallback_->onNewUnidirectionalStream(streamId);
}
logStreamOpenEvent(streamId);
if (closeState_ != CloseState::OPEN) {
return;
}
}
streamStorage.clear();
}
void QuicTransportBase::handleNewGroupedStreams(
std::vector<StreamId>& streamStorage) {
const auto& newPeerStreamIds = streamStorage;
for (const auto& streamId : newPeerStreamIds) {
CHECK_NOTNULL(connCallback_);
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(streamId));
CHECK(stream->groupId);
if (isBidirectionalStream(streamId)) {
connCallback_->onNewBidirectionalStreamInGroup(
streamId, *stream->groupId);
} else {
connCallback_->onNewUnidirectionalStreamInGroup(
streamId, *stream->groupId);
}
logStreamOpenEvent(streamId);
if (closeState_ != CloseState::OPEN) {
return;
}
}
streamStorage.clear();
}
void QuicTransportBase::handleNewStreamCallbacks(
std::vector<StreamId>& streamStorage) {
streamStorage =
conn_->streamManager->consumeNewPeerStreams(std::move(streamStorage));
handleNewStreams(streamStorage);
}
void QuicTransportBase::handleNewGroupedStreamCallbacks(
std::vector<StreamId>& streamStorage) {
auto newStreamGroups = conn_->streamManager->consumeNewPeerStreamGroups();
for (auto newStreamGroupId : newStreamGroups) {
if (isBidirectionalStream(newStreamGroupId)) {
connCallback_->onNewBidirectionalStreamGroup(newStreamGroupId);
} else {
connCallback_->onNewUnidirectionalStreamGroup(newStreamGroupId);
}
}
streamStorage = conn_->streamManager->consumeNewGroupedPeerStreams(
std::move(streamStorage));
handleNewGroupedStreams(streamStorage);
}
void QuicTransportBase::handleDeliveryCallbacks() {
auto deliverableStreamId = conn_->streamManager->popDeliverable();
while (deliverableStreamId.has_value()) {
auto streamId = *deliverableStreamId;
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(streamId));
auto maxOffsetToDeliver = getLargestDeliverableOffset(*stream);
while (maxOffsetToDeliver.has_value()) {
auto deliveryCallbacksForAckedStream = deliveryCallbacks_.find(streamId);
if (deliveryCallbacksForAckedStream == deliveryCallbacks_.end() ||
deliveryCallbacksForAckedStream->second.empty()) {
break;
}
if (deliveryCallbacksForAckedStream->second.front().offset >
*maxOffsetToDeliver) {
break;
}
auto deliveryCallbackAndOffset =
deliveryCallbacksForAckedStream->second.front();
deliveryCallbacksForAckedStream->second.pop_front();
auto currentDeliveryCallbackOffset = deliveryCallbackAndOffset.offset;
auto deliveryCallback = deliveryCallbackAndOffset.callback;
ByteEvent byteEvent = {};
byteEvent.id = streamId;
byteEvent.offset = currentDeliveryCallbackOffset;
byteEvent.type = ByteEvent::Type::ACK;
byteEvent.srtt = conn_->lossState.srtt;
deliveryCallback->onByteEvent(byteEvent);
if (closeState_ != CloseState::OPEN) {
return;
}
}
auto deliveryCallbacksForAckedStream = deliveryCallbacks_.find(streamId);
if (deliveryCallbacksForAckedStream != deliveryCallbacks_.end() &&
deliveryCallbacksForAckedStream->second.empty()) {
deliveryCallbacks_.erase(deliveryCallbacksForAckedStream);
}
deliverableStreamId = conn_->streamManager->popDeliverable();
}
}
void QuicTransportBase::handleStreamFlowControlUpdatedCallbacks(
std::vector<StreamId>& streamStorage) {
// Iterate over streams that changed their flow control window and give
// their registered listeners their updates.
// We don't really need flow control notifications when we are closed.
streamStorage =
conn_->streamManager->consumeFlowControlUpdated(std::move(streamStorage));
const auto& flowControlUpdated = streamStorage;
for (auto streamId : flowControlUpdated) {
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(streamId));
if (!stream->writable()) {
pendingWriteCallbacks_.erase(streamId);
continue;
}
connCallback_->onFlowControlUpdate(streamId);
if (closeState_ != CloseState::OPEN) {
return;
}
// In case the callback modified the stream map, get it again.
stream = CHECK_NOTNULL(conn_->streamManager->getStream(streamId));
auto maxStreamWritable = maxWritableOnStream(*stream);
if (maxStreamWritable != 0 && !pendingWriteCallbacks_.empty()) {
auto pendingWriteIt = pendingWriteCallbacks_.find(stream->id);
if (pendingWriteIt != pendingWriteCallbacks_.end()) {
auto wcb = pendingWriteIt->second;
pendingWriteCallbacks_.erase(stream->id);
wcb->onStreamWriteReady(stream->id, maxStreamWritable);
if (closeState_ != CloseState::OPEN) {
return;
}
}
}
}
streamStorage.clear();
}
void QuicTransportBase::handleStreamStopSendingCallbacks() {
const auto stopSendingStreamsCopy =
conn_->streamManager->consumeStopSending();
for (const auto& itr : stopSendingStreamsCopy) {
connCallback_->onStopSending(itr.first, itr.second);
if (closeState_ != CloseState::OPEN) {
return;
}
}
}
void QuicTransportBase::handleConnWritable() {
auto maxConnWrite = maxWritableOnConn();
if (maxConnWrite != 0) {
// If the connection now has flow control, we may either have been blocked
// before on a pending write to the conn, or a stream's write.
if (connWriteCallback_) {
auto connWriteCallback = connWriteCallback_;
connWriteCallback_ = nullptr;
connWriteCallback->onConnectionWriteReady(maxConnWrite);
}
// If the connection flow control is unblocked, we might be unblocked
// on the streams now.
auto writeCallbackIt = pendingWriteCallbacks_.begin();
while (writeCallbackIt != pendingWriteCallbacks_.end()) {
auto streamId = writeCallbackIt->first;
auto wcb = writeCallbackIt->second;
++writeCallbackIt;
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(streamId));
if (!stream->writable()) {
pendingWriteCallbacks_.erase(streamId);
continue;
}
auto maxStreamWritable = maxWritableOnStream(*stream);
if (maxStreamWritable != 0) {
pendingWriteCallbacks_.erase(streamId);
wcb->onStreamWriteReady(streamId, maxStreamWritable);
if (closeState_ != CloseState::OPEN) {
return;
}
}
}
}
}
void QuicTransportBase::cleanupAckEventState() {
// if there's no bytes in flight, clear any memory allocated for AckEvents
if (conn_->outstandings.packets.empty()) {
std::vector<AckEvent> empty;
conn_->lastProcessedAckEvents.swap(empty);
} // memory allocated for vector will be freed
}
void QuicTransportBase::processCallbacksAfterNetworkData() {
if (closeState_ != CloseState::OPEN) {
return;
}
// We reuse this storage for storing streams which need callbacks.
std::vector<StreamId> tempStorage;
handleNewStreamCallbacks(tempStorage);
if (closeState_ != CloseState::OPEN) {
return;
}
handleNewGroupedStreamCallbacks(tempStorage);
if (closeState_ != CloseState::OPEN) {
return;
}
handlePingCallbacks();
if (closeState_ != CloseState::OPEN) {
return;
}
handleKnobCallbacks();
if (closeState_ != CloseState::OPEN) {
return;
}
handleAckEventCallbacks();
if (closeState_ != CloseState::OPEN) {
return;
}
handleCancelByteEventCallbacks();
if (closeState_ != CloseState::OPEN) {
return;
}
handleDeliveryCallbacks();
if (closeState_ != CloseState::OPEN) {
return;
}
handleStreamFlowControlUpdatedCallbacks(tempStorage);
if (closeState_ != CloseState::OPEN) {
return;
}
handleStreamStopSendingCallbacks();
if (closeState_ != CloseState::OPEN) {
return;
}
handleConnWritable();
if (closeState_ != CloseState::OPEN) {
return;
}
invokeStreamsAvailableCallbacks();
cleanupAckEventState();
}
void QuicTransportBase::onNetworkData(
const folly::SocketAddress& peer,
NetworkData&& networkData) noexcept {
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
SCOPE_EXIT {
checkForClosedStream();
updateReadLooper();
updatePeekLooper();
updateWriteLooper(true);
};
try {
conn_->lossState.totalBytesRecvd += networkData.totalData;
auto originalAckVersion = currentAckStateVersion(*conn_);
// handle PacketsReceivedEvent if requested by observers
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::packetsReceivedEvents>()) {
auto builder = SocketObserverInterface::PacketsReceivedEvent::Builder()
.setReceiveLoopTime(TimePoint::clock::now())
.setNumPacketsReceived(networkData.packets.size())
.setNumBytesReceived(networkData.totalData);
for (auto& packet : networkData.packets) {
builder.addReceivedPacket(
SocketObserverInterface::PacketsReceivedEvent::ReceivedPacket::
Builder()
.setPacketReceiveTime(networkData.receiveTimePoint)
.setPacketNumBytes(packet->computeChainDataLength())
.build());
}
getSocketObserverContainer()
->invokeInterfaceMethod<
SocketObserverInterface::Events::packetsReceivedEvents>(
[event = std::move(builder).build()](
auto observer, auto observed) {
observer->packetsReceived(observed, event);
});
}
for (auto& packet : networkData.packets) {
onReadData(
peer,
NetworkDataSingle(std::move(packet), networkData.receiveTimePoint));
if (conn_->peerConnectionError) {
closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::NO_ERROR), "Peer closed"));
return;
}
}
processCallbacksAfterNetworkData();
if (closeState_ != CloseState::CLOSED) {
if (currentAckStateVersion(*conn_) != originalAckVersion) {
setIdleTimer();
conn_->receivedNewPacketBeforeWrite = true;
if (conn_->loopDetectorCallback) {
conn_->readDebugState.noReadReason = NoReadReason::READ_OK;
conn_->readDebugState.loopCount = 0;
}
} else if (conn_->loopDetectorCallback) {
conn_->readDebugState.noReadReason = NoReadReason::STALE_DATA;
conn_->loopDetectorCallback->onSuspiciousReadLoops(
++conn_->readDebugState.loopCount,
conn_->readDebugState.noReadReason);
}
// Reading data could process an ack and change the loss timer.
setLossDetectionAlarm(*conn_, *self);
// Reading data could change the state of the acks which could change the
// ack timer. But we need to call scheduleAckTimeout() for it to take
// effect.
scheduleAckTimeout();
// Received data could contain valid path response, in which case
// path validation timeout should be canceled
schedulePathValidationTimeout();
} else {
// In the closed state, we would want to write a close if possible however
// the write looper will not be set.
writeSocketData();
}
} catch (const QuicTransportException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
return closeImpl(
QuicError(QuicErrorCode(ex.errorCode()), std::string(ex.what())));
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
return closeImpl(
QuicError(QuicErrorCode(ex.errorCode()), std::string(ex.what())));
} catch (const QuicApplicationException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
return closeImpl(
QuicError(QuicErrorCode(ex.errorCode()), std::string(ex.what())));
} catch (const std::exception& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
return closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR),
std::string("error onNetworkData()")));
}
}
void QuicTransportBase::setIdleTimer() {
if (closeState_ == CloseState::CLOSED) {
return;
}
idleTimeout_.cancelTimeout();
keepaliveTimeout_.cancelTimeout();
auto localIdleTimeout = conn_->transportSettings.idleTimeout;
// The local idle timeout being zero means it is disabled.
if (localIdleTimeout == 0ms) {
return;
}
auto peerIdleTimeout =
conn_->peerIdleTimeout > 0ms ? conn_->peerIdleTimeout : localIdleTimeout;
auto idleTimeout = timeMin(localIdleTimeout, peerIdleTimeout);
scheduleTimeout(&idleTimeout_, idleTimeout);
auto idleTimeoutCount = idleTimeout.count();
if (conn_->transportSettings.enableKeepalive) {
std::chrono::milliseconds keepaliveTimeout = std::chrono::milliseconds(
idleTimeoutCount - static_cast<int64_t>(idleTimeoutCount * .15));
scheduleTimeout(&keepaliveTimeout_, keepaliveTimeout);
}
}
uint64_t QuicTransportBase::getNumOpenableBidirectionalStreams() const {
return conn_->streamManager->openableLocalBidirectionalStreams();
}
uint64_t QuicTransportBase::getNumOpenableUnidirectionalStreams() const {
return conn_->streamManager->openableLocalUnidirectionalStreams();
}
folly::Expected<StreamId, LocalErrorCode>
QuicTransportBase::createStreamInternal(
bool bidirectional,
const folly::Optional<StreamGroupId>& streamGroupId) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
folly::Expected<QuicStreamState*, LocalErrorCode> streamResult;
if (bidirectional) {
streamResult =
conn_->streamManager->createNextBidirectionalStream(streamGroupId);
} else {
streamResult =
conn_->streamManager->createNextUnidirectionalStream(streamGroupId);
}
if (streamResult) {
const StreamId streamId = streamResult.value()->id;
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::streamEvents>()) {
getSocketObserverContainer()
->invokeInterfaceMethod<
SocketObserverInterface::Events::streamEvents>(
[event = SocketObserverInterface::StreamOpenEvent(
streamId,
getStreamInitiator(streamId),
getStreamDirectionality(streamId))](
auto observer, auto observed) {
observer->streamOpened(observed, event);
});
}
return streamId;
} else {
return folly::makeUnexpected(streamResult.error());
}
}
folly::Expected<StreamId, LocalErrorCode>
QuicTransportBase::createBidirectionalStream(bool /*replaySafe*/) {
return createStreamInternal(true);
}
folly::Expected<StreamId, LocalErrorCode>
QuicTransportBase::createUnidirectionalStream(bool /*replaySafe*/) {
return createStreamInternal(false);
}
folly::Expected<StreamGroupId, LocalErrorCode>
QuicTransportBase::createBidirectionalStreamGroup() {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
return conn_->streamManager->createNextBidirectionalStreamGroup();
}
folly::Expected<StreamGroupId, LocalErrorCode>
QuicTransportBase::createUnidirectionalStreamGroup() {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
return conn_->streamManager->createNextUnidirectionalStreamGroup();
}
folly::Expected<StreamId, LocalErrorCode>
QuicTransportBase::createBidirectionalStreamInGroup(StreamGroupId groupId) {
return createStreamInternal(true, groupId);
}
folly::Expected<StreamId, LocalErrorCode>
QuicTransportBase::createUnidirectionalStreamInGroup(StreamGroupId groupId) {
return createStreamInternal(false, groupId);
}
bool QuicTransportBase::isClientStream(StreamId stream) noexcept {
return quic::isClientStream(stream);
}
bool QuicTransportBase::isServerStream(StreamId stream) noexcept {
return quic::isServerStream(stream);
}
StreamInitiator QuicTransportBase::getStreamInitiator(
StreamId stream) noexcept {
return quic::getStreamInitiator(conn_->nodeType, stream);
}
bool QuicTransportBase::isUnidirectionalStream(StreamId stream) noexcept {
return quic::isUnidirectionalStream(stream);
}
bool QuicTransportBase::isBidirectionalStream(StreamId stream) noexcept {
return quic::isBidirectionalStream(stream);
}
StreamDirectionality QuicTransportBase::getStreamDirectionality(
StreamId stream) noexcept {
return quic::getStreamDirectionality(stream);
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::notifyPendingWriteOnConnection(WriteCallback* wcb) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (connWriteCallback_ != nullptr) {
return folly::makeUnexpected(LocalErrorCode::INVALID_WRITE_CALLBACK);
}
// Assign the write callback before going into the loop so that if we close
// the connection while we are still scheduled, the write callback will get
// an error synchronously.
connWriteCallback_ = wcb;
runOnEvbAsync([](auto self) {
if (!self->connWriteCallback_) {
// The connection was probably closed.
return;
}
auto connWritableBytes = self->maxWritableOnConn();
if (connWritableBytes != 0) {
auto connWriteCallback = self->connWriteCallback_;
self->connWriteCallback_ = nullptr;
connWriteCallback->onConnectionWriteReady(connWritableBytes);
}
});
return folly::unit;
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::unregisterStreamWriteCallback(StreamId id) {
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
if (pendingWriteCallbacks_.find(id) == pendingWriteCallbacks_.end()) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
pendingWriteCallbacks_.erase(id);
return folly::unit;
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::notifyPendingWriteOnStream(StreamId id, WriteCallback* wcb) {
if (isReceivingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
if (!stream->writable()) {
return folly::makeUnexpected(LocalErrorCode::STREAM_CLOSED);
}
if (wcb == nullptr) {
return folly::makeUnexpected(LocalErrorCode::INVALID_WRITE_CALLBACK);
}
// Add the callback to the pending write callbacks so that if we are closed
// while we are scheduled in the loop, the close will error out the callbacks.
auto wcbEmplaceResult = pendingWriteCallbacks_.emplace(id, wcb);
if (!wcbEmplaceResult.second) {
if ((wcbEmplaceResult.first)->second != wcb) {
return folly::makeUnexpected(LocalErrorCode::INVALID_WRITE_CALLBACK);
} else {
return folly::makeUnexpected(LocalErrorCode::CALLBACK_ALREADY_INSTALLED);
}
}
runOnEvbAsync([id](auto self) {
auto wcbIt = self->pendingWriteCallbacks_.find(id);
if (wcbIt == self->pendingWriteCallbacks_.end()) {
// the connection was probably closed.
return;
}
auto writeCallback = wcbIt->second;
if (!self->conn_->streamManager->streamExists(id)) {
self->pendingWriteCallbacks_.erase(wcbIt);
writeCallback->onStreamWriteError(
id, QuicError(LocalErrorCode::STREAM_NOT_EXISTS));
return;
}
auto stream = CHECK_NOTNULL(self->conn_->streamManager->getStream(id));
if (!stream->writable()) {
self->pendingWriteCallbacks_.erase(wcbIt);
writeCallback->onStreamWriteError(
id, QuicError(LocalErrorCode::STREAM_NOT_EXISTS));
return;
}
auto maxCanWrite = self->maxWritableOnStream(*stream);
if (maxCanWrite != 0) {
self->pendingWriteCallbacks_.erase(wcbIt);
writeCallback->onStreamWriteReady(id, maxCanWrite);
}
});
return folly::unit;
}
uint64_t QuicTransportBase::maxWritableOnStream(
const QuicStreamState& stream) const {
auto connWritableBytes = maxWritableOnConn();
auto streamFlowControlBytes = getSendStreamFlowControlBytesAPI(stream);
auto flowControlAllowedBytes =
std::min(streamFlowControlBytes, connWritableBytes);
return flowControlAllowedBytes;
}
uint64_t QuicTransportBase::maxWritableOnConn() const {
auto connWritableBytes = getSendConnFlowControlBytesAPI(*conn_);
auto availableBufferSpace = bufferSpaceAvailable();
return std::min(connWritableBytes, availableBufferSpace);
}
QuicSocket::WriteResult QuicTransportBase::writeChain(
StreamId id,
Buf data,
bool eof,
ByteEventCallback* cb) {
if (isReceivingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
try {
// Check whether stream exists before calling getStream to avoid
// creating a peer stream if it does not exist yet.
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
if (!stream->writable()) {
return folly::makeUnexpected(LocalErrorCode::STREAM_CLOSED);
}
// Register DeliveryCallback for the data + eof offset.
if (cb) {
auto dataLength =
(data ? data->computeChainDataLength() : 0) + (eof ? 1 : 0);
if (dataLength) {
auto currentLargestWriteOffset = getLargestWriteOffsetSeen(*stream);
registerDeliveryCallback(
id, currentLargestWriteOffset + dataLength - 1, cb);
}
}
bool wasAppLimitedOrIdle = false;
if (conn_->congestionController) {
wasAppLimitedOrIdle = conn_->congestionController->isAppLimited();
wasAppLimitedOrIdle |= conn_->streamManager->isAppIdle();
}
writeDataToQuicStream(*stream, std::move(data), eof);
// If we were previously app limited restart pacing with the current rate.
if (wasAppLimitedOrIdle && conn_->pacer) {
conn_->pacer->reset();
}
updateWriteLooper(true);
} catch (const QuicTransportException& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()), std::string("writeChain() error")));
return folly::makeUnexpected(LocalErrorCode::TRANSPORT_ERROR);
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()), std::string("writeChain() error")));
return folly::makeUnexpected(ex.errorCode());
} catch (const std::exception& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR),
std::string("writeChain() error")));
return folly::makeUnexpected(LocalErrorCode::INTERNAL_ERROR);
}
return folly::unit;
}
QuicSocket::WriteResult QuicTransportBase::writeBufMeta(
StreamId id,
const BufferMeta& data,
bool eof,
ByteEventCallback* cb) {
if (isReceivingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
try {
// Check whether stream exists before calling getStream to avoid
// creating a peer stream if it does not exist yet.
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
if (!stream->writable()) {
return folly::makeUnexpected(LocalErrorCode::STREAM_CLOSED);
}
if (!stream->dsrSender) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (stream->currentWriteOffset == 0 && stream->writeBuffer.empty()) {
// If nothing has been written to writeBuffer ever, meta writing isn't
// allowed.
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
// Register DeliveryCallback for the data + eof offset.
if (cb) {
auto dataLength = data.length + (eof ? 1 : 0);
if (dataLength) {
auto currentLargestWriteOffset = getLargestWriteOffsetSeen(*stream);
registerDeliveryCallback(
id, currentLargestWriteOffset + dataLength - 1, cb);
}
}
bool wasAppLimitedOrIdle = false;
if (conn_->congestionController) {
wasAppLimitedOrIdle = conn_->congestionController->isAppLimited();
wasAppLimitedOrIdle |= conn_->streamManager->isAppIdle();
}
writeBufMetaToQuicStream(*stream, data, eof);
// If we were previously app limited restart pacing with the current rate.
if (wasAppLimitedOrIdle && conn_->pacer) {
conn_->pacer->reset();
}
updateWriteLooper(true);
} catch (const QuicTransportException& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()), std::string("writeChain() error")));
return folly::makeUnexpected(LocalErrorCode::TRANSPORT_ERROR);
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()), std::string("writeChain() error")));
return folly::makeUnexpected(ex.errorCode());
} catch (const std::exception& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR),
std::string("writeChain() error")));
return folly::makeUnexpected(LocalErrorCode::INTERNAL_ERROR);
}
return folly::unit;
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::registerDeliveryCallback(
StreamId id,
uint64_t offset,
ByteEventCallback* cb) {
return registerByteEventCallback(ByteEvent::Type::ACK, id, offset, cb);
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::registerTxCallback(
StreamId id,
uint64_t offset,
ByteEventCallback* cb) {
return registerByteEventCallback(ByteEvent::Type::TX, id, offset, cb);
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::registerByteEventCallback(
const ByteEvent::Type type,
const StreamId id,
const uint64_t offset,
ByteEventCallback* cb) {
if (isReceivingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
if (!cb) {
return folly::unit;
}
ByteEventMap& byteEventMap = getByteEventMap(type);
auto byteEventMapIt = byteEventMap.find(id);
if (byteEventMapIt == byteEventMap.end()) {
byteEventMap.emplace(
id,
std::initializer_list<std::remove_reference<
decltype(byteEventMap)>::type::mapped_type::value_type>(
{{offset, cb}}));
} else {
// Keep ByteEvents for the same stream sorted by offsets:
auto pos = std::upper_bound(
byteEventMapIt->second.begin(),
byteEventMapIt->second.end(),
offset,
[&](uint64_t o, const ByteEventDetail& p) { return o < p.offset; });
if (pos != byteEventMapIt->second.begin()) {
auto matchingEvent = std::find_if(
byteEventMapIt->second.begin(),
pos,
[offset, cb](const ByteEventDetail& p) {
return ((p.offset == offset) && (p.callback == cb));
});
if (matchingEvent != pos) {
// ByteEvent has been already registered for the same type, id,
// offset and for the same recipient, return an INVALID_OPERATION error
// to prevent duplicate registrations.
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
}
byteEventMapIt->second.emplace(pos, offset, cb);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
// Notify recipients that the registration was successful.
ByteEvent byteEvent = {};
byteEvent.id = id;
byteEvent.offset = offset;
byteEvent.type = type;
cb->onByteEventRegistered(byteEvent);
// if the callback is already ready, we still insert, but schedule to process
folly::Optional<uint64_t> maxOffsetReady;
switch (type) {
case ByteEvent::Type::ACK:
maxOffsetReady = getLargestDeliverableOffset(*stream);
break;
case ByteEvent::Type::TX:
maxOffsetReady = getLargestWriteOffsetTxed(*stream);
break;
}
if (maxOffsetReady.has_value() && (offset <= *maxOffsetReady)) {
runOnEvbAsync([id, cb, offset, type](auto selfObj) {
if (selfObj->closeState_ != CloseState::OPEN) {
// Close will error out all byte event callbacks.
return;
}
auto& byteEventMapL = selfObj->getByteEventMap(type);
auto streamByteEventCbIt = byteEventMapL.find(id);
if (streamByteEventCbIt == byteEventMapL.end()) {
return;
}
// This is scheduled to run in the future (during the next iteration of
// the event loop). It is possible that the ByteEventDetail list gets
// mutated between the time it was scheduled to now when we are ready to
// run it. Look at the current outstanding ByteEvents for this stream ID
// and confirm that our ByteEvent's offset and recipient callback are
// still present.
auto pos = std::find_if(
streamByteEventCbIt->second.begin(),
streamByteEventCbIt->second.end(),
[offset, cb](const ByteEventDetail& p) {
return ((p.offset == offset) && (p.callback == cb));
});
// if our byteEvent is not present, it must have been delivered already.
if (pos == streamByteEventCbIt->second.end()) {
return;
}
streamByteEventCbIt->second.erase(pos);
ByteEvent byteEvent = {};
byteEvent.id = id;
byteEvent.offset = offset;
byteEvent.type = type;
cb->onByteEvent(byteEvent);
});
}
return folly::unit;
}
folly::Optional<LocalErrorCode> QuicTransportBase::shutdownWrite(StreamId id) {
if (isReceivingStream(conn_->nodeType, id)) {
return LocalErrorCode::INVALID_OPERATION;
}
return folly::none;
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::resetStream(
StreamId id,
ApplicationErrorCode errorCode) {
if (isReceivingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
SCOPE_EXIT {
checkForClosedStream();
updateReadLooper();
updatePeekLooper();
updateWriteLooper(true);
};
try {
// Check whether stream exists before calling getStream to avoid
// creating a peer stream if it does not exist yet.
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
// Invoke state machine
sendRstSMHandler(*stream, errorCode);
for (auto pendingResetIt = conn_->pendingEvents.resets.begin();
closeState_ == CloseState::OPEN &&
pendingResetIt != conn_->pendingEvents.resets.end();
pendingResetIt++) {
cancelByteEventCallbacksForStream(pendingResetIt->first);
}
pendingWriteCallbacks_.erase(id);
QUIC_STATS(conn_->statsCallback, onQuicStreamReset, errorCode);
} catch (const QuicTransportException& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()), std::string("resetStream() error")));
return folly::makeUnexpected(LocalErrorCode::TRANSPORT_ERROR);
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()), std::string("resetStream() error")));
return folly::makeUnexpected(ex.errorCode());
} catch (const std::exception& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR),
std::string("resetStream() error")));
return folly::makeUnexpected(LocalErrorCode::INTERNAL_ERROR);
}
return folly::unit;
}
void QuicTransportBase::checkForClosedStream() {
if (closeState_ == CloseState::CLOSED) {
return;
}
auto itr = conn_->streamManager->closedStreams().begin();
while (itr != conn_->streamManager->closedStreams().end()) {
const auto& streamId = *itr;
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::streamEvents>()) {
getSocketObserverContainer()
->invokeInterfaceMethod<
SocketObserverInterface::Events::streamEvents>(
[event = SocketObserverInterface::StreamCloseEvent(
streamId,
getStreamInitiator(streamId),
getStreamDirectionality(streamId))](
auto observer, auto observed) {
observer->streamClosed(observed, event);
});
}
// We may be in an active read cb when we close the stream
auto readCbIt = readCallbacks_.find(*itr);
// We use the read callback as a way to defer destruction of the stream.
if (readCbIt != readCallbacks_.end() &&
readCbIt->second.readCb != nullptr) {
if (conn_->transportSettings.removeStreamAfterEomCallbackUnset ||
!readCbIt->second.deliveredEOM) {
VLOG(10) << "Not closing stream=" << *itr
<< " because it has active read callback";
++itr;
continue;
}
}
// We may be in the active peek cb when we close the stream
auto peekCbIt = peekCallbacks_.find(*itr);
if (peekCbIt != peekCallbacks_.end() &&
peekCbIt->second.peekCb != nullptr) {
VLOG(10) << "Not closing stream=" << *itr
<< " because it has active peek callback";
++itr;
continue;
}
// If we have pending byte events, delay closing the stream
auto numByteEventCb = getNumByteEventCallbacksForStream(*itr);
if (numByteEventCb > 0) {
VLOG(10) << "Not closing stream=" << *itr << " because it has "
<< numByteEventCb << " pending byte event callbacks";
++itr;
continue;
}
VLOG(10) << "Closing stream=" << *itr;
if (conn_->qLogger) {
conn_->qLogger->addTransportStateUpdate(
getClosingStream(folly::to<std::string>(*itr)));
}
conn_->streamManager->removeClosedStream(*itr);
maybeSendStreamLimitUpdates(*conn_);
if (readCbIt != readCallbacks_.end()) {
readCallbacks_.erase(readCbIt);
}
if (peekCbIt != peekCallbacks_.end()) {
peekCallbacks_.erase(peekCbIt);
}
itr = conn_->streamManager->closedStreams().erase(itr);
} // while
if (closeState_ == CloseState::GRACEFUL_CLOSING &&
conn_->streamManager->streamCount() == 0) {
closeImpl(folly::none);
}
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::setPingCallback(
PingCallback* cb) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
VLOG(4) << "Setting ping callback "
<< " cb=" << cb << " " << *this;
pingCallback_ = cb;
return folly::unit;
}
void QuicTransportBase::sendPing(std::chrono::milliseconds pingTimeout) {
/* Step 0: Connection should not be closed */
if (closeState_ == CloseState::CLOSED) {
return;
}
// Step 1: Send a simple ping frame
conn_->pendingEvents.sendPing = true;
updateWriteLooper(true);
// Step 2: Schedule the timeout on event base
if (pingCallback_ && pingTimeout != 0ms) {
schedulePingTimeout(pingCallback_, pingTimeout);
}
}
void QuicTransportBase::lossTimeoutExpired() noexcept {
CHECK_NE(closeState_, CloseState::CLOSED);
// onLossDetectionAlarm will set packetToSend in pending events
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
try {
onLossDetectionAlarm(*conn_, markPacketLoss);
if (conn_->qLogger) {
conn_->qLogger->addTransportStateUpdate(kLossTimeoutExpired);
}
pacedWriteDataToSocket();
} catch (const QuicTransportException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()),
std::string("lossTimeoutExpired() error")));
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()),
std::string("lossTimeoutExpired() error")));
} catch (const std::exception& ex) {
VLOG(4) << __func__ << " " << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR),
std::string("lossTimeoutExpired() error")));
}
}
void QuicTransportBase::ackTimeoutExpired() noexcept {
CHECK_NE(closeState_, CloseState::CLOSED);
VLOG(10) << __func__ << " " << *this;
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
updateAckStateOnAckTimeout(*conn_);
pacedWriteDataToSocket();
}
void QuicTransportBase::pingTimeoutExpired() noexcept {
// If timeout expired just call the call back Provided
if (pingCallback_ != nullptr) {
pingCallback_->pingTimeout();
}
}
void QuicTransportBase::pathValidationTimeoutExpired() noexcept {
CHECK(conn_->outstandingPathValidation);
conn_->pendingEvents.schedulePathValidationTimeout = false;
conn_->outstandingPathValidation.reset();
if (conn_->qLogger) {
conn_->qLogger->addPathValidationEvent(false);
}
// TODO junqiw probing is not supported, so pathValidation==connMigration
// We decide to close conn when pathValidation to migrated path fails.
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::INVALID_MIGRATION),
std::string("Path validation timed out")));
}
void QuicTransportBase::idleTimeoutExpired(bool drain) noexcept {
VLOG(4) << __func__ << " " << *this;
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
// idle timeout is expired, just close the connection and drain or
// send connection close immediately depending on 'drain'
DCHECK_NE(closeState_, CloseState::CLOSED);
uint64_t numOpenStreans = conn_->streamManager->streamCount();
auto localError =
drain ? LocalErrorCode::IDLE_TIMEOUT : LocalErrorCode::SHUTTING_DOWN;
closeImpl(
quic::QuicError(
QuicErrorCode(localError),
folly::to<std::string>(
toString(localError),
", num non control streams: ",
numOpenStreans - conn_->streamManager->numControlStreams())),
drain /* drainConnection */,
!drain /* sendCloseImmediately */);
}
void QuicTransportBase::keepaliveTimeoutExpired() noexcept {
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
conn_->pendingEvents.sendPing = true;
updateWriteLooper(true);
}
void QuicTransportBase::scheduleLossTimeout(std::chrono::milliseconds timeout) {
if (closeState_ == CloseState::CLOSED) {
return;
}
timeout = timeMax(timeout, qEvb_.getTimerTickInterval());
scheduleTimeout(&lossTimeout_, timeout);
}
void QuicTransportBase::scheduleAckTimeout() {
if (closeState_ == CloseState::CLOSED) {
return;
}
if (conn_->pendingEvents.scheduleAckTimeout) {
if (!ackTimeout_.isScheduled()) {
auto factoredRtt = std::chrono::duration_cast<std::chrono::microseconds>(
kAckTimerFactor * conn_->lossState.srtt);
// If we are using ACK_FREQUENCY, disable the factored RTT heuristic
// and only use the update max ACK delay.
if (conn_->ackStates.appDataAckState.ackFrequencySequenceNumber) {
factoredRtt = conn_->ackStates.maxAckDelay;
}
auto timeout = timeMax(
std::chrono::duration_cast<std::chrono::microseconds>(
qEvb_.getTimerTickInterval()),
timeMin(conn_->ackStates.maxAckDelay, factoredRtt));
auto timeoutMs = folly::chrono::ceil<std::chrono::milliseconds>(timeout);
VLOG(10) << __func__ << " timeout=" << timeoutMs.count() << "ms"
<< " factoredRtt=" << factoredRtt.count() << "us"
<< " " << *this;
scheduleTimeout(&ackTimeout_, timeoutMs);
}
} else {
if (ackTimeout_.isScheduled()) {
VLOG(10) << __func__ << " cancel timeout " << *this;
ackTimeout_.cancelTimeout();
}
}
}
void QuicTransportBase::schedulePingTimeout(
PingCallback* pingCb,
std::chrono::milliseconds timeout) {
// if a ping timeout is already scheduled, nothing to do, return
if (pingTimeout_.isScheduled()) {
return;
}
pingCallback_ = pingCb;
scheduleTimeout(&pingTimeout_, timeout);
}
void QuicTransportBase::schedulePathValidationTimeout() {
if (closeState_ == CloseState::CLOSED) {
return;
}
if (!conn_->pendingEvents.schedulePathValidationTimeout) {
if (pathValidationTimeout_.isScheduled()) {
VLOG(10) << __func__ << " cancel timeout " << *this;
// This means path validation succeeded, and we should have updated to
// correct state
pathValidationTimeout_.cancelTimeout();
}
} else if (!pathValidationTimeout_.isScheduled()) {
auto pto = conn_->lossState.srtt +
std::max(4 * conn_->lossState.rttvar, kGranularity) +
conn_->lossState.maxAckDelay;
auto validationTimeout =
std::max(3 * pto, 6 * conn_->transportSettings.initialRtt);
auto timeoutMs =
folly::chrono::ceil<std::chrono::milliseconds>(validationTimeout);
VLOG(10) << __func__ << " timeout=" << timeoutMs.count() << "ms " << *this;
scheduleTimeout(&pathValidationTimeout_, timeoutMs);
}
}
void QuicTransportBase::cancelLossTimeout() {
lossTimeout_.cancelTimeout();
}
bool QuicTransportBase::isLossTimeoutScheduled() const {
return lossTimeout_.isScheduled();
}
void QuicTransportBase::setSupportedVersions(
const std::vector<QuicVersion>& versions) {
conn_->originalVersion = versions.at(0);
conn_->supportedVersions = versions;
}
void QuicTransportBase::setConnectionSetupCallback(
ConnectionSetupCallback* callback) {
connSetupCallback_ = callback;
}
void QuicTransportBase::setConnectionCallback(ConnectionCallback* callback) {
connCallback_ = callback;
}
void QuicTransportBase::setEarlyDataAppParamsFunctions(
folly::Function<bool(const folly::Optional<std::string>&, const Buf&) const>
validator,
folly::Function<Buf()> getter) {
conn_->earlyDataAppParamsValidator = std::move(validator);
conn_->earlyDataAppParamsGetter = std::move(getter);
}
void QuicTransportBase::cancelAllAppCallbacks(const QuicError& err) noexcept {
SCOPE_EXIT {
checkForClosedStream();
updateReadLooper();
updatePeekLooper();
updateWriteLooper(true);
};
conn_->streamManager->clearActionable();
// Cancel any pending ByteEvent callbacks
cancelAllByteEventCallbacks();
// TODO: this will become simpler when we change the underlying data
// structure of read callbacks.
// TODO: this approach will make the app unable to setReadCallback to
// nullptr during the loop. Need to fix that.
// TODO: setReadCallback to nullptr closes the stream, so the app
// may just do that...
auto readCallbacksCopy = readCallbacks_;
for (auto& cb : readCallbacksCopy) {
readCallbacks_.erase(cb.first);
if (cb.second.readCb) {
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(cb.first));
if (!stream->groupId) {
cb.second.readCb->readError(cb.first, err);
} else {
cb.second.readCb->readErrorWithGroup(cb.first, *stream->groupId, err);
}
}
}
VLOG(4) << "Clearing datagram callback";
datagramCallback_ = nullptr;
VLOG(4) << "Clearing ping callback";
pingCallback_ = nullptr;
VLOG(4) << "Clearing " << peekCallbacks_.size() << " peek callbacks";
auto peekCallbacksCopy = peekCallbacks_;
for (auto& cb : peekCallbacksCopy) {
peekCallbacks_.erase(cb.first);
if (cb.second.peekCb) {
cb.second.peekCb->peekError(cb.first, err);
}
}
if (connWriteCallback_) {
auto connWriteCallback = connWriteCallback_;
connWriteCallback_ = nullptr;
connWriteCallback->onConnectionWriteError(err);
}
auto pendingWriteCallbacksCopy = pendingWriteCallbacks_;
for (auto& wcb : pendingWriteCallbacksCopy) {
pendingWriteCallbacks_.erase(wcb.first);
wcb.second->onStreamWriteError(wcb.first, err);
}
}
void QuicTransportBase::resetNonControlStreams(
ApplicationErrorCode error,
folly::StringPiece errorMsg) {
std::vector<StreamId> nonControlStreamIds;
nonControlStreamIds.reserve(conn_->streamManager->streamCount());
conn_->streamManager->streamStateForEach(
[&nonControlStreamIds](const auto& stream) {
if (!stream.isControl) {
nonControlStreamIds.push_back(stream.id);
}
});
for (auto id : nonControlStreamIds) {
if (isSendingStream(conn_->nodeType, id) || isBidirectionalStream(id)) {
auto writeCallbackIt = pendingWriteCallbacks_.find(id);
if (writeCallbackIt != pendingWriteCallbacks_.end()) {
writeCallbackIt->second->onStreamWriteError(
id, QuicError(error, errorMsg.str()));
}
resetStream(id, error);
}
if (isReceivingStream(conn_->nodeType, id) || isBidirectionalStream(id)) {
auto readCallbackIt = readCallbacks_.find(id);
if (readCallbackIt != readCallbacks_.end() &&
readCallbackIt->second.readCb) {
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
if (!stream->groupId) {
readCallbackIt->second.readCb->readError(
id, QuicError(error, errorMsg.str()));
} else {
readCallbackIt->second.readCb->readErrorWithGroup(
id, *stream->groupId, QuicError(error, errorMsg.str()));
}
}
peekCallbacks_.erase(id);
stopSending(id, error);
}
}
}
QuicConnectionStats QuicTransportBase::getConnectionsStats() const {
QuicConnectionStats connStats;
if (!conn_) {
return connStats;
}
connStats.peerAddress = conn_->peerAddress;
connStats.duration = Clock::now() - conn_->connectionTime;
if (conn_->congestionController) {
connStats.cwnd_bytes = conn_->congestionController->getCongestionWindow();
connStats.congestionController = conn_->congestionController->type();
conn_->congestionController->getStats(connStats.congestionControllerStats);
}
connStats.ptoCount = conn_->lossState.ptoCount;
connStats.srtt = conn_->lossState.srtt;
connStats.mrtt = conn_->lossState.mrtt;
connStats.rttvar = conn_->lossState.rttvar;
connStats.peerAckDelayExponent = conn_->peerAckDelayExponent;
connStats.udpSendPacketLen = conn_->udpSendPacketLen;
if (conn_->streamManager) {
connStats.numStreams = conn_->streamManager->streams().size();
}
if (conn_->clientChosenDestConnectionId.hasValue()) {
connStats.clientChosenDestConnectionId =
conn_->clientChosenDestConnectionId->hex();
}
if (conn_->clientConnectionId.hasValue()) {
connStats.clientConnectionId = conn_->clientConnectionId->hex();
}
if (conn_->serverConnectionId.hasValue()) {
connStats.serverConnectionId = conn_->serverConnectionId->hex();
}
connStats.totalBytesSent = conn_->lossState.totalBytesSent;
connStats.totalBytesReceived = conn_->lossState.totalBytesRecvd;
connStats.totalBytesRetransmitted = conn_->lossState.totalBytesRetransmitted;
if (conn_->version.hasValue()) {
connStats.version = static_cast<uint32_t>(*conn_->version);
}
return connStats;
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::setDatagramCallback(DatagramCallback* cb) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
VLOG(4) << "Setting datagram callback "
<< " cb=" << cb << " " << *this;
datagramCallback_ = cb;
updateReadLooper();
return folly::unit;
}
uint16_t QuicTransportBase::getDatagramSizeLimit() const {
CHECK(conn_);
auto maxDatagramPacketSize = std::min<decltype(conn_->udpSendPacketLen)>(
conn_->datagramState.maxWriteFrameSize, conn_->udpSendPacketLen);
return std::max<decltype(maxDatagramPacketSize)>(
0, maxDatagramPacketSize - kMaxDatagramPacketOverhead);
}
folly::Expected<folly::Unit, LocalErrorCode> QuicTransportBase::writeDatagram(
Buf buf) {
// TODO(lniccolini) update max datagram frame size
// https://github.com/quicwg/datagram/issues/3
// For now, max_datagram_size > 0 means the peer supports datagram frames
if (conn_->datagramState.maxWriteFrameSize == 0) {
QUIC_STATS(conn_->statsCallback, onDatagramDroppedOnWrite);
return folly::makeUnexpected(LocalErrorCode::INVALID_WRITE_DATA);
}
if (conn_->datagramState.writeBuffer.size() >=
conn_->datagramState.maxWriteBufferSize) {
QUIC_STATS(conn_->statsCallback, onDatagramDroppedOnWrite);
if (!conn_->transportSettings.datagramConfig.sendDropOldDataFirst) {
// TODO(lniccolini) use different return codes to signal the application
// exactly why the datagram got dropped
return folly::makeUnexpected(LocalErrorCode::INVALID_WRITE_DATA);
} else {
conn_->datagramState.writeBuffer.pop_front();
}
}
conn_->datagramState.writeBuffer.emplace_back(std::move(buf));
updateWriteLooper(true);
return folly::unit;
}
folly::Expected<std::vector<ReadDatagram>, LocalErrorCode>
QuicTransportBase::readDatagrams(size_t atMost) {
CHECK(conn_);
auto datagrams = &conn_->datagramState.readBuffer;
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (atMost == 0) {
atMost = datagrams->size();
} else {
atMost = std::min(atMost, datagrams->size());
}
std::vector<ReadDatagram> retDatagrams;
retDatagrams.reserve(atMost);
std::transform(
datagrams->begin(),
datagrams->begin() + atMost,
std::back_inserter(retDatagrams),
[](ReadDatagram& dg) { return std::move(dg); });
datagrams->erase(datagrams->begin(), datagrams->begin() + atMost);
return retDatagrams;
}
folly::Expected<std::vector<Buf>, LocalErrorCode>
QuicTransportBase::readDatagramBufs(size_t atMost) {
CHECK(conn_);
auto datagrams = &conn_->datagramState.readBuffer;
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (atMost == 0) {
atMost = datagrams->size();
} else {
atMost = std::min(atMost, datagrams->size());
}
std::vector<Buf> retDatagrams;
retDatagrams.reserve(atMost);
std::transform(
datagrams->begin(),
datagrams->begin() + atMost,
std::back_inserter(retDatagrams),
[](ReadDatagram& dg) { return dg.bufQueue().move(); });
datagrams->erase(datagrams->begin(), datagrams->begin() + atMost);
return retDatagrams;
}
void QuicTransportBase::writeSocketData() {
if (socket_) {
++(conn_->writeCount); // incremented on each write (or write attempt)
// record current number of sent packets to detect delta
const auto beforeTotalBytesSent = conn_->lossState.totalBytesSent;
const auto beforeTotalPacketsSent = conn_->lossState.totalPacketsSent;
const auto beforeTotalAckElicitingPacketsSent =
conn_->lossState.totalAckElicitingPacketsSent;
const auto beforeNumOutstandingPackets =
conn_->outstandings.numOutstanding();
updatePacketProcessorsPrewriteRequests();
// if we're starting to write from app limited, notify observers
if (conn_->appLimitedTracker.isAppLimited() &&
conn_->congestionController) {
conn_->appLimitedTracker.setNotAppLimited();
notifyStartWritingFromAppRateLimited();
}
writeData();
if (closeState_ != CloseState::CLOSED) {
if (conn_->pendingEvents.closeTransport == true) {
throw QuicTransportException(
"Max packet number reached",
TransportErrorCode::PROTOCOL_VIOLATION);
}
setLossDetectionAlarm(*conn_, *this);
// check for change in number of packets
const auto afterTotalBytesSent = conn_->lossState.totalBytesSent;
const auto afterTotalPacketsSent = conn_->lossState.totalPacketsSent;
const auto afterTotalAckElicitingPacketsSent =
conn_->lossState.totalAckElicitingPacketsSent;
const auto afterNumOutstandingPackets =
conn_->outstandings.numOutstanding();
CHECK_LE(beforeTotalPacketsSent, afterTotalPacketsSent);
CHECK_LE(
beforeTotalAckElicitingPacketsSent,
afterTotalAckElicitingPacketsSent);
CHECK_LE(beforeNumOutstandingPackets, afterNumOutstandingPackets);
CHECK_EQ(
afterNumOutstandingPackets - beforeNumOutstandingPackets,
afterTotalAckElicitingPacketsSent -
beforeTotalAckElicitingPacketsSent);
const bool newPackets = (afterTotalPacketsSent > beforeTotalPacketsSent);
const bool newOutstandingPackets =
(afterTotalAckElicitingPacketsSent >
beforeTotalAckElicitingPacketsSent);
// if packets sent, notify observers
if (newPackets) {
notifyPacketsWritten(
afterTotalPacketsSent - beforeTotalPacketsSent
/* numPacketsWritten */,
afterTotalAckElicitingPacketsSent -
beforeTotalAckElicitingPacketsSent
/* numAckElicitingPacketsWritten */,
afterTotalBytesSent - beforeTotalBytesSent /* numBytesWritten */);
}
if (conn_->loopDetectorCallback && newOutstandingPackets) {
conn_->writeDebugState.currentEmptyLoopCount = 0;
} else if (
conn_->writeDebugState.needsWriteLoopDetect &&
conn_->loopDetectorCallback) {
// TODO: Currently we will to get some stats first. Then we may filter
// out some errors here. For example, socket fail to write might be a
// legit case to filter out.
conn_->loopDetectorCallback->onSuspiciousWriteLoops(
++conn_->writeDebugState.currentEmptyLoopCount,
conn_->writeDebugState.writeDataReason,
conn_->writeDebugState.noWriteReason,
conn_->writeDebugState.schedulerName);
}
// If we sent a new packet and the new packet was either the first
// packet after quiescence or after receiving a new packet.
if (newOutstandingPackets &&
(beforeNumOutstandingPackets == 0 ||
conn_->receivedNewPacketBeforeWrite)) {
// Reset the idle timer because we sent some data.
setIdleTimer();
conn_->receivedNewPacketBeforeWrite = false;
}
// Check if we are app-limited after finish this round of sending
auto currentSendBufLen = conn_->flowControlState.sumCurStreamBufferLen;
auto lossBufferEmpty = !conn_->streamManager->hasLoss() &&
conn_->cryptoState->initialStream.lossBuffer.empty() &&
conn_->cryptoState->handshakeStream.lossBuffer.empty() &&
conn_->cryptoState->oneRttStream.lossBuffer.empty();
if (conn_->congestionController &&
currentSendBufLen < conn_->udpSendPacketLen && lossBufferEmpty &&
conn_->congestionController->getWritableBytes()) {
conn_->congestionController->setAppLimited();
// notify via connection call and any observer callbacks
if (transportReadyNotified_ && connCallback_) {
connCallback_->onAppRateLimited();
}
conn_->appLimitedTracker.setAppLimited();
notifyAppRateLimited();
}
}
}
// Writing data could write out an ack which could cause us to cancel
// the ack timer. But we need to call scheduleAckTimeout() for it to take
// effect.
scheduleAckTimeout();
schedulePathValidationTimeout();
updateWriteLooper(false);
}
void QuicTransportBase::writeSocketDataAndCatch() {
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
try {
writeSocketData();
processCallbacksAfterWriteData();
} catch (const QuicTransportException& ex) {
VLOG(4) << __func__ << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()),
std::string("writeSocketDataAndCatch() error")));
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()),
std::string("writeSocketDataAndCatch() error")));
} catch (const std::exception& ex) {
VLOG(4) << __func__ << " error=" << ex.what() << " " << *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR),
std::string("writeSocketDataAndCatch() error")));
}
}
void QuicTransportBase::setTransportSettings(
TransportSettings transportSettings) {
if (conn_->nodeType == QuicNodeType::Client) {
if (useSinglePacketInplaceBatchWriter(
transportSettings.maxBatchSize, transportSettings.dataPathType)) {
createBufAccessor(conn_->udpSendPacketLen);
} else {
// Reset client's batching mode only if SinglePacketInplaceBatchWriter is
// not in use.
conn_->transportSettings.dataPathType = DataPathType::ChainedMemory;
}
}
// If transport parameters are encoded, we can only update congestion control
// related params. Setting other transport settings again would be buggy.
// TODO should we throw or return Expected here?
if (conn_->transportParametersEncoded) {
updateCongestionControlSettings(transportSettings);
} else {
// TODO: We should let chain based GSO to use bufAccessor in the future as
// well.
CHECK(
conn_->bufAccessor ||
transportSettings.dataPathType != DataPathType::ContinuousMemory);
conn_->transportSettings = std::move(transportSettings);
conn_->streamManager->refreshTransportSettings(conn_->transportSettings);
}
// A few values cannot be overridden to be lower than default:
// TODO refactor transport settings to avoid having to update params twice.
if (conn_->transportSettings.defaultCongestionController !=
CongestionControlType::None) {
conn_->transportSettings.initCwndInMss =
std::max(conn_->transportSettings.initCwndInMss, kInitCwndInMss);
conn_->transportSettings.minCwndInMss =
std::max(conn_->transportSettings.minCwndInMss, kMinCwndInMss);
conn_->transportSettings.initCwndInMss = std::max(
conn_->transportSettings.minCwndInMss,
conn_->transportSettings.initCwndInMss);
}
validateCongestionAndPacing(
conn_->transportSettings.defaultCongestionController);
if (conn_->transportSettings.pacingEnabled) {
if (writeLooper_->hasPacingTimer()) {
bool usingBbr =
(conn_->transportSettings.defaultCongestionController ==
CongestionControlType::BBR ||
conn_->transportSettings.defaultCongestionController ==
CongestionControlType::BBRTesting ||
conn_->transportSettings.defaultCongestionController ==
CongestionControlType::BBR2);
auto minCwnd = usingBbr ? kMinCwndInMssForBbr
: conn_->transportSettings.minCwndInMss;
conn_->pacer = std::make_unique<TokenlessPacer>(*conn_, minCwnd);
conn_->pacer->setExperimental(conn_->transportSettings.experimentalPacer);
conn_->canBePaced = conn_->transportSettings.pacingEnabledFirstFlight;
} else {
LOG(ERROR) << "Pacing cannot be enabled without a timer";
conn_->transportSettings.pacingEnabled = false;
}
}
setCongestionControl(conn_->transportSettings.defaultCongestionController);
if (conn_->transportSettings.datagramConfig.enabled) {
conn_->datagramState.maxReadFrameSize = kMaxDatagramFrameSize;
conn_->datagramState.maxReadBufferSize =
conn_->transportSettings.datagramConfig.readBufSize;
conn_->datagramState.maxWriteBufferSize =
conn_->transportSettings.datagramConfig.writeBufSize;
}
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::setMaxPacingRate(uint64_t maxRateBytesPerSec) {
if (conn_->pacer) {
conn_->pacer->setMaxPacingRate(maxRateBytesPerSec);
return folly::unit;
} else {
LOG(WARNING)
<< "Cannot set max pacing rate without a pacer. Pacing Enabled = "
<< conn_->transportSettings.pacingEnabled;
return folly::makeUnexpected(LocalErrorCode::PACER_NOT_AVAILABLE);
}
}
void QuicTransportBase::updateCongestionControlSettings(
const TransportSettings& transportSettings) {
conn_->transportSettings.defaultCongestionController =
transportSettings.defaultCongestionController;
conn_->transportSettings.initCwndInMss = transportSettings.initCwndInMss;
conn_->transportSettings.minCwndInMss = transportSettings.minCwndInMss;
conn_->transportSettings.maxCwndInMss = transportSettings.maxCwndInMss;
conn_->transportSettings.limitedCwndInMss =
transportSettings.limitedCwndInMss;
conn_->transportSettings.pacingEnabled = transportSettings.pacingEnabled;
conn_->transportSettings.pacingTickInterval =
transportSettings.pacingTickInterval;
conn_->transportSettings.pacingTimerResolution =
transportSettings.pacingTimerResolution;
conn_->transportSettings.minBurstPackets = transportSettings.minBurstPackets;
conn_->transportSettings.copaDeltaParam = transportSettings.copaDeltaParam;
conn_->transportSettings.copaUseRttStanding =
transportSettings.copaUseRttStanding;
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::setKnob(uint64_t knobSpace, uint64_t knobId, Buf knobBlob) {
if (isKnobSupported()) {
sendSimpleFrame(*conn_, KnobFrame(knobSpace, knobId, std::move(knobBlob)));
return folly::unit;
}
LOG(ERROR) << "Cannot set knob. Peer does not support the knob frame";
return folly::makeUnexpected(LocalErrorCode::KNOB_FRAME_UNSUPPORTED);
}
bool QuicTransportBase::isKnobSupported() const {
return conn_->peerAdvertisedKnobFrameSupport;
}
const TransportSettings& QuicTransportBase::getTransportSettings() const {
return conn_->transportSettings;
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::setStreamPriority(StreamId id, Priority priority) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (priority.level > kDefaultMaxPriority) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (!conn_->streamManager->streamExists(id)) {
// It's not an error to try to prioritize a non-existent stream.
return folly::unit;
}
// It's not an error to prioritize a stream after it's sent its FIN - this
// can reprioritize retransmissions.
bool updated = conn_->streamManager->setStreamPriority(id, priority);
if (updated && conn_->qLogger) {
conn_->qLogger->addPriorityUpdate(id, priority.level, priority.incremental);
}
return folly::unit;
}
folly::Expected<Priority, LocalErrorCode> QuicTransportBase::getStreamPriority(
StreamId id) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
auto stream = conn_->streamManager->findStream(id);
if (!stream) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
return stream->priority;
}
void QuicTransportBase::validateCongestionAndPacing(
CongestionControlType& type) {
// Fallback to Cubic if Pacing isn't enabled with BBR together
if ((type == CongestionControlType::BBR ||
type == CongestionControlType::BBRTesting ||
type == CongestionControlType::BBR2) &&
(!conn_->transportSettings.pacingEnabled ||
!writeLooper_->hasPacingTimer())) {
LOG(ERROR) << "Unpaced BBR isn't supported";
type = CongestionControlType::Cubic;
}
if (type == CongestionControlType::BBR2 ||
type == CongestionControlType::BBRTesting) {
// We need to have the pacer rate be as accurate as possible for BBR2 and
// BBRTesting.
// The current BBR behavior is dependent on the existing pacing
// behavior so the override is only for BBR2.
// TODO: This should be removed once the pacer changes are adopted as
// the defaults or the pacer is fixed in another way.
conn_->transportSettings.experimentalPacer = true;
conn_->transportSettings.defaultRttFactor = {1, 1};
conn_->transportSettings.startupRttFactor = {1, 1};
if (conn_->pacer) {
conn_->pacer->setExperimental(conn_->transportSettings.experimentalPacer);
conn_->pacer->setRttFactor(
conn_->transportSettings.defaultRttFactor.first,
conn_->transportSettings.defaultRttFactor.second);
}
writeLooper_->setFireLoopEarly(true);
}
}
void QuicTransportBase::setCongestionControl(CongestionControlType type) {
DCHECK(conn_);
if (!conn_->congestionController ||
type != conn_->congestionController->type()) {
CHECK(conn_->congestionControllerFactory);
validateCongestionAndPacing(type);
conn_->congestionController =
conn_->congestionControllerFactory->makeCongestionController(
*conn_, type);
if (conn_->qLogger) {
std::stringstream s;
s << "CCA set to " << congestionControlTypeToString(type);
conn_->qLogger->addTransportStateUpdate(s.str());
}
}
}
void QuicTransportBase::addPacketProcessor(
std::shared_ptr<PacketProcessor> packetProcessor) {
DCHECK(conn_);
conn_->packetProcessors.push_back(std::move(packetProcessor));
}
void QuicTransportBase::setThrottlingSignalProvider(
std::shared_ptr<ThrottlingSignalProvider> throttlingSignalProvider) {
DCHECK(conn_);
conn_->throttlingSignalProvider = throttlingSignalProvider;
}
bool QuicTransportBase::isDetachable() {
// only the client is detachable.
return conn_->nodeType == QuicNodeType::Client;
}
void QuicTransportBase::attachEventBase(QuicBackingEventBase* evb) {
VLOG(10) << __func__ << " " << *this;
DCHECK(!getEventBase());
DCHECK(evb && evb->isInEventBaseThread());
qEvb_.setBackingEventBase(evb);
qEvbPtr_ = &qEvb_;
if (socket_) {
socket_->attachEventBase(evb);
}
scheduleAckTimeout();
schedulePathValidationTimeout();
setIdleTimer();
readLooper_->attachEventBase(&qEvb_);
peekLooper_->attachEventBase(&qEvb_);
writeLooper_->attachEventBase(&qEvb_);
updateReadLooper();
updatePeekLooper();
updateWriteLooper(false);
#ifndef MVFST_USE_LIBEV
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::evbEvents>()) {
getSocketObserverContainer()
->invokeInterfaceMethod<SocketObserverInterface::Events::evbEvents>(
[this](auto observer, auto observed) {
observer->evbAttach(observed, qEvb_.getBackingEventBase());
});
}
#endif
}
void QuicTransportBase::detachEventBase() {
VLOG(10) << __func__ << " " << *this;
DCHECK(getEventBase() && getEventBase()->isInEventBaseThread());
if (socket_) {
socket_->detachEventBase();
}
connWriteCallback_ = nullptr;
pendingWriteCallbacks_.clear();
lossTimeout_.cancelTimeout();
ackTimeout_.cancelTimeout();
pathValidationTimeout_.cancelTimeout();
idleTimeout_.cancelTimeout();
keepaliveTimeout_.cancelTimeout();
drainTimeout_.cancelTimeout();
readLooper_->detachEventBase();
peekLooper_->detachEventBase();
writeLooper_->detachEventBase();
#ifndef MVFST_USE_LIBEV
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::evbEvents>()) {
getSocketObserverContainer()
->invokeInterfaceMethod<SocketObserverInterface::Events::evbEvents>(
[this](auto observer, auto observed) {
observer->evbDetach(observed, qEvb_.getBackingEventBase());
});
}
#endif
qEvb_.setBackingEventBase(nullptr);
qEvbPtr_ = nullptr;
}
folly::Optional<LocalErrorCode> QuicTransportBase::setControlStream(
StreamId id) {
if (!conn_->streamManager->streamExists(id)) {
return LocalErrorCode::STREAM_NOT_EXISTS;
}
auto stream = conn_->streamManager->getStream(id);
conn_->streamManager->setStreamAsControl(*stream);
return folly::none;
}
void QuicTransportBase::runOnEvbAsync(
folly::Function<void(std::shared_ptr<QuicTransportBase>)> func) {
auto evb = getEventBase();
evb->runInLoop(
[self = sharedGuard(), func = std::move(func), evb]() mutable {
if (self->getEventBase() != evb) {
// The eventbase changed between scheduling the loop and invoking the
// callback, ignore this
return;
}
func(std::move(self));
},
true);
}
void QuicTransportBase::pacedWriteDataToSocket() {
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
if (!isConnectionPaced(*conn_)) {
// Not paced and connection is still open, normal write. Even if pacing is
// previously enabled and then gets disabled, and we are here due to a
// timeout, we should do a normal write to flush out the residue from pacing
// write.
writeSocketDataAndCatch();
return;
}
// We are in the middle of a pacing interval. Leave it be.
if (writeLooper_->isScheduled()) {
// The next burst is already scheduled. Since the burst size doesn't depend
// on much data we currently have in buffer at all, no need to change
// anything.
return;
}
// Do a burst write before waiting for an interval. This will also call
// updateWriteLooper, but inside FunctionLooper we will ignore that.
writeSocketDataAndCatch();
}
folly::Expected<QuicSocket::StreamTransportInfo, LocalErrorCode>
QuicTransportBase::getStreamTransportInfo(StreamId id) const {
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
auto packets = getNumPacketsTxWithNewData(*stream);
return StreamTransportInfo{
stream->totalHolbTime,
stream->holbCount,
bool(stream->lastHolbTime),
packets,
stream->streamLossCount,
stream->finalWriteOffset,
stream->finalReadOffset};
}
void QuicTransportBase::describe(std::ostream& os) const {
CHECK(conn_);
os << *conn_;
}
std::ostream& operator<<(std::ostream& os, const QuicTransportBase& qt) {
qt.describe(os);
return os;
}
inline std::ostream& operator<<(
std::ostream& os,
const CloseState& closeState) {
switch (closeState) {
case CloseState::OPEN:
os << "OPEN";
break;
case CloseState::GRACEFUL_CLOSING:
os << "GRACEFUL_CLOSING";
break;
case CloseState::CLOSED:
os << "CLOSED";
break;
}
return os;
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::maybeResetStreamFromReadError(
StreamId id,
QuicErrorCode error) {
quic::ApplicationErrorCode* code = error.asApplicationErrorCode();
if (code) {
return resetStream(id, *code);
}
return folly::Expected<folly::Unit, LocalErrorCode>(folly::unit);
}
QuicTransportBase::ByteEventMap& QuicTransportBase::getByteEventMap(
const ByteEvent::Type type) {
switch (type) {
case ByteEvent::Type::ACK:
return deliveryCallbacks_;
case ByteEvent::Type::TX:
return txCallbacks_;
}
LOG(FATAL) << "Unhandled case in getByteEventMap";
folly::assume_unreachable();
}
const QuicTransportBase::ByteEventMap& QuicTransportBase::getByteEventMapConst(
const ByteEvent::Type type) const {
switch (type) {
case ByteEvent::Type::ACK:
return deliveryCallbacks_;
case ByteEvent::Type::TX:
return txCallbacks_;
}
LOG(FATAL) << "Unhandled case in getByteEventMapConst";
folly::assume_unreachable();
}
void QuicTransportBase::onTransportKnobs(Buf knobBlob) {
// Not yet implemented,
VLOG(4) << "Received transport knobs: "
<< std::string(
reinterpret_cast<const char*>(knobBlob->data()),
knobBlob->length());
}
QuicSocket::WriteResult QuicTransportBase::setDSRPacketizationRequestSender(
StreamId id,
std::unique_ptr<DSRPacketizationRequestSender> sender) {
if (closeState_ != CloseState::OPEN) {
return folly::makeUnexpected(LocalErrorCode::CONNECTION_CLOSED);
}
if (isReceivingStream(conn_->nodeType, id)) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
FOLLY_MAYBE_UNUSED auto self = sharedGuard();
try {
// Check whether stream exists before calling getStream to avoid
// creating a peer stream if it does not exist yet.
if (!conn_->streamManager->streamExists(id)) {
return folly::makeUnexpected(LocalErrorCode::STREAM_NOT_EXISTS);
}
auto stream = CHECK_NOTNULL(conn_->streamManager->getStream(id));
// Only allow resetting it back to nullptr once set.
if (stream->dsrSender && sender != nullptr) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (stream->dsrSender != nullptr) {
// If any of these aren't true then we are abandoning stream data.
CHECK_EQ(stream->writeBufMeta.length, 0) << stream;
CHECK_EQ(stream->lossBufMetas.size(), 0) << stream;
CHECK_EQ(stream->retransmissionBufMetas.size(), 0) << stream;
stream->dsrSender->release();
stream->dsrSender = nullptr;
return folly::unit;
}
if (!stream->writable()) {
return folly::makeUnexpected(LocalErrorCode::STREAM_CLOSED);
}
stream->dsrSender = std::move(sender);
// Default to disabling opportunistic ACKing for DSR since it causes extra
// writes and spurious losses.
conn_->transportSettings.opportunisticAcking = false;
// Also turn on the default of 5 nexts per stream which has empirically
// shown good results.
if (conn_->transportSettings.priorityQueueWritesPerStream == 1) {
conn_->transportSettings.priorityQueueWritesPerStream = 5;
conn_->streamManager->writeQueue().setMaxNextsPerStream(5);
}
// Fow now, no appLimited or appIdle update here since we are not writing
// either BufferMetas yet. The first BufferMeta write will update it.
} catch (const QuicTransportException& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()), std::string("writeChain() error")));
return folly::makeUnexpected(LocalErrorCode::TRANSPORT_ERROR);
} catch (const QuicInternalException& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(ex.errorCode()), std::string("writeChain() error")));
return folly::makeUnexpected(ex.errorCode());
} catch (const std::exception& ex) {
VLOG(4) << __func__ << " streamId=" << id << " " << ex.what() << " "
<< *this;
exceptionCloseWhat_ = ex.what();
closeImpl(QuicError(
QuicErrorCode(TransportErrorCode::INTERNAL_ERROR),
std::string("writeChain() error")));
return folly::makeUnexpected(LocalErrorCode::INTERNAL_ERROR);
}
return folly::unit;
}
void QuicTransportBase::notifyStartWritingFromAppRateLimited() {
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::appRateLimitedEvents>()) {
getSocketObserverContainer()
->invokeInterfaceMethod<
SocketObserverInterface::Events::appRateLimitedEvents>(
[event = SocketObserverInterface::AppLimitedEvent::Builder()
.setOutstandingPackets(conn_->outstandings.packets)
.setWriteCount(conn_->writeCount)
.setLastPacketSentTime(
conn_->lossState.maybeLastPacketSentTime)
.setCwndInBytes(
conn_->congestionController
? folly::Optional<uint64_t>(
conn_->congestionController
->getCongestionWindow())
: folly::none)
.setWritableBytes(
conn_->congestionController
? folly::Optional<uint64_t>(
conn_->congestionController
->getWritableBytes())
: folly::none)
.build()](auto observer, auto observed) {
observer->startWritingFromAppLimited(observed, event);
});
}
}
void QuicTransportBase::notifyPacketsWritten(
uint64_t numPacketsWritten,
uint64_t numAckElicitingPacketsWritten,
uint64_t numBytesWritten) {
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::packetsWrittenEvents>()) {
getSocketObserverContainer()
->invokeInterfaceMethod<
SocketObserverInterface::Events::packetsWrittenEvents>(
[event = SocketObserverInterface::PacketsWrittenEvent::Builder()
.setOutstandingPackets(conn_->outstandings.packets)
.setWriteCount(conn_->writeCount)
.setLastPacketSentTime(
conn_->lossState.maybeLastPacketSentTime)
.setCwndInBytes(
conn_->congestionController
? folly::Optional<uint64_t>(
conn_->congestionController
->getCongestionWindow())
: folly::none)
.setWritableBytes(
conn_->congestionController
? folly::Optional<uint64_t>(
conn_->congestionController
->getWritableBytes())
: folly::none)
.setNumPacketsWritten(numPacketsWritten)
.setNumAckElicitingPacketsWritten(
numAckElicitingPacketsWritten)
.setNumBytesWritten(numBytesWritten)
.build()](auto observer, auto observed) {
observer->packetsWritten(observed, event);
});
}
}
void QuicTransportBase::notifyAppRateLimited() {
if (getSocketObserverContainer() &&
getSocketObserverContainer()
->hasObserversForEvent<
SocketObserverInterface::Events::appRateLimitedEvents>()) {
getSocketObserverContainer()
->invokeInterfaceMethod<
SocketObserverInterface::Events::appRateLimitedEvents>(
[event = SocketObserverInterface::AppLimitedEvent::Builder()
.setOutstandingPackets(conn_->outstandings.packets)
.setWriteCount(conn_->writeCount)
.setLastPacketSentTime(
conn_->lossState.maybeLastPacketSentTime)
.setCwndInBytes(
conn_->congestionController
? folly::Optional<uint64_t>(
conn_->congestionController
->getCongestionWindow())
: folly::none)
.setWritableBytes(
conn_->congestionController
? folly::Optional<uint64_t>(
conn_->congestionController
->getWritableBytes())
: folly::none)
.build()](auto observer, auto observed) {
observer->appRateLimited(observed, event);
});
}
}
void QuicTransportBase::setCmsgs(const folly::SocketOptionMap& options) {
socket_->setCmsgs(options);
}
void QuicTransportBase::appendCmsgs(const folly::SocketOptionMap& options) {
socket_->appendCmsgs(options);
}
void QuicTransportBase::setBackgroundModeParameters(
PriorityLevel maxBackgroundPriority,
float backgroundUtilizationFactor) {
backgroundPriorityThreshold_.assign(maxBackgroundPriority);
backgroundUtilizationFactor_.assign(backgroundUtilizationFactor);
conn_->streamManager->setPriorityChangesObserver(this);
onStreamPrioritiesChange();
}
void QuicTransportBase::clearBackgroundModeParameters() {
backgroundPriorityThreshold_.clear();
backgroundUtilizationFactor_.clear();
conn_->streamManager->resetPriorityChangesObserver();
onStreamPrioritiesChange();
}
// If backgroundPriorityThreshold_ and backgroundUtilizationFactor_ are set and
// all streams have equal or lower priority than the threshold
// (value >= threshold), set the connection's congestion controller to use
// background mode with the set utilization factor.
// In all other cases, turn off the congestion controller's background mode.
void QuicTransportBase::onStreamPrioritiesChange() {
if (conn_->congestionController == nullptr) {
return;
}
if (!backgroundPriorityThreshold_.hasValue() ||
!backgroundUtilizationFactor_.hasValue()) {
conn_->congestionController->setBandwidthUtilizationFactor(1.0);
return;
}
bool allStreamsBackground = conn_->streamManager->getHighestPriorityLevel() >=
backgroundPriorityThreshold_.value();
float targetUtilization =
allStreamsBackground ? backgroundUtilizationFactor_.value() : 1.0f;
VLOG(10) << fmt::format(
"Updating transport background mode. Highest Priority={} Threshold={} TargetUtilization={}",
conn_->streamManager->getHighestPriorityLevel(),
backgroundPriorityThreshold_.value(),
targetUtilization);
conn_->congestionController->setBandwidthUtilizationFactor(targetUtilization);
}
bool QuicTransportBase::checkCustomRetransmissionProfilesEnabled() const {
return quic::checkCustomRetransmissionProfilesEnabled(*conn_);
}
folly::Expected<folly::Unit, LocalErrorCode>
QuicTransportBase::setStreamGroupRetransmissionPolicy(
StreamGroupId groupId,
std::optional<QuicStreamGroupRetransmissionPolicy> policy) noexcept {
// Reset the policy to default one.
if (policy == std::nullopt) {
conn_->retransmissionPolicies.erase(groupId);
return folly::unit;
}
if (!checkCustomRetransmissionProfilesEnabled()) {
return folly::makeUnexpected(LocalErrorCode::INVALID_OPERATION);
}
if (conn_->retransmissionPolicies.size() >=
conn_->transportSettings.advertisedMaxStreamGroups) {
return folly::makeUnexpected(LocalErrorCode::RTX_POLICIES_LIMIT_EXCEEDED);
}
conn_->retransmissionPolicies.emplace(groupId, *policy);
return folly::unit;
}
void QuicTransportBase::updatePacketProcessorsPrewriteRequests() {
folly::SocketOptionMap cmsgs;
for (const auto& pp : conn_->packetProcessors) {
// In case of overlapping cmsg keys, the priority is given to
// that were added to the QuicSocket first.
auto writeRequest = pp->prewrite();
if (writeRequest && writeRequest->cmsgs) {
cmsgs.insert(writeRequest->cmsgs->begin(), writeRequest->cmsgs->end());
}
}
if (!cmsgs.empty()) {
conn_->socketCmsgsState.additionalCmsgs = cmsgs;
} else {
conn_->socketCmsgsState.additionalCmsgs.reset();
}
conn_->socketCmsgsState.targetWriteCount = conn_->writeCount;
}
folly::Optional<folly::SocketOptionMap>
QuicTransportBase::getAdditionalCmsgsForAsyncUDPSocket() {
if (conn_->socketCmsgsState.additionalCmsgs) {
// This callback should be happening for the target write
DCHECK(conn_->writeCount == conn_->socketCmsgsState.targetWriteCount);
return conn_->socketCmsgsState.additionalCmsgs;
} else {
return folly::none;
}
}
} // namespace quic
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/dom/src/domfile/domfilereader.h"
#include "modules/dom/src/domfile/domfilereadersync.h"
#include "modules/dom/src/domfile/domfile.h"
#include "modules/dom/src/domfile/domblob.h"
#include "modules/dom/src/domfile/domfileerror.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domevents/domevent.h"
#include "modules/dom/src/domevents/domprogressevent.h"
#include "modules/dom/src/domglobaldata.h"
#include "modules/encodings/decoders/inputconverter.h"
#include "modules/formats/uri_escape.h"
#include "modules/formats/base64_decode.h"
#include "modules/pi/OpSystemInfo.h"
/* virtual */ int
DOM_FileReader_Constructor::Construct(ES_Value* argv, int argc, ES_Value* return_value, ES_Runtime *origining_runtime)
{
DOM_FileReader* reader;
CALL_FAILED_IF_ERROR(DOM_FileReader::Make(reader, static_cast<DOM_Runtime*>(origining_runtime)));
DOMSetObject(return_value, reader);
return ES_VALUE;
}
/* virtual */
DOM_FileReader::~DOM_FileReader()
{
GetEnvironment()->RemoveFileReader(this);
}
/* static */ OP_STATUS
DOM_FileReader::Make(DOM_FileReader*& reader, DOM_Runtime* runtime)
{
return DOMSetObjectRuntime(reader = OP_NEW(DOM_FileReader, ()), runtime, runtime->GetPrototype(DOM_Runtime::FILEREADER_PROTOTYPE), "FileReader");
}
/* static */ void
DOM_FileReader::ConstructFileReaderObjectL(ES_Object* object, DOM_Runtime* runtime)
{
PutNumericConstantL(object, "EMPTY", EMPTY, runtime);
PutNumericConstantL(object, "LOADING", LOADING, runtime);
PutNumericConstantL(object, "DONE", DONE, runtime);
}
/* virtual */ void
DOM_FileReader::GCTrace()
{
GCMark(event_target);
GCMark(m_error);
DOM_FileReader_Base::GCTrace(GetRuntime());
}
void
DOM_FileReader::Abort()
{
GetEnvironment()->RemoveFileReader(this);
if (m_current_read_view)
{
CloseBlob();
g_main_message_handler->UnsetCallBack(this, MSG_DOM_READ_FILE);
m_delayed_progress_event_pending = FALSE;
}
m_public_state = DONE;
}
/* virtual */ ES_GetState
DOM_FileReader::GetName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime)
{
if (property_name[0] == 'o' && property_name[1] == 'n')
{
ES_GetState res = GetEventProperty(property_name, value, static_cast<DOM_Runtime*>(origining_runtime));
if (res != GET_FAILED)
return res;
}
return DOM_Object::GetName(property_name, property_code, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_FileReader::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_result:
if (value)
GET_FAILED_IF_ERROR(GetResult(this, value, GetEmptyTempBuf(), &(g_DOM_globalData->string_with_length_holder)));
return GET_SUCCESS;
case OP_ATOM_error:
DOMSetObject(value, m_error);
return GET_SUCCESS;
case OP_ATOM_readyState:
DOMSetNumber(value, m_public_state);
return GET_SUCCESS;
}
return DOM_Object::GetName(property_name, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_FileReader::PutName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime)
{
if (property_name[0] == 'o' && property_name[1] == 'n')
{
ES_PutState res = PutEventProperty(property_name, value, static_cast<DOM_Runtime*>(origining_runtime));
if (res != PUT_FAILED)
return res;
}
return DOM_Object::PutName(property_name, property_code, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_FileReader::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_result:
case OP_ATOM_error:
case OP_ATOM_readyState:
return PUT_SUCCESS;
}
return DOM_Object::PutName(property_name, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_FileReader::FetchPropertiesL(ES_PropertyEnumerator *enumerator, ES_Runtime *origining_runtime)
{
ES_GetState result = DOM_Object::FetchPropertiesL(enumerator, origining_runtime);
if (result != GET_SUCCESS)
return result;
enumerator->AddPropertyL("onabort");
enumerator->AddPropertyL("onerror");
enumerator->AddPropertyL("onload");
#ifdef PROGRESS_EVENTS_SUPPORT
enumerator->AddPropertyL("onloadstart");
enumerator->AddPropertyL("onloadend");
enumerator->AddPropertyL("onprogress");
#endif // PROGRESS_EVENTS_SUPPORT
return GET_SUCCESS;
}
DOM_FileReader_Base::~DOM_FileReader_Base()
{
OP_DELETE(m_text_result_decoder);
OP_DELETEA(m_data_url_content_type);
CloseBlob();
OP_ASSERT(!m_current_read_view);
}
OP_STATUS
DOM_FileReader_Base::FlushToResult()
{
if (m_current_output_type == DATA_URL && m_data_url_use_base64 && m_result_pending_len > 0)
{
MIME_Encode_Error base64_encoding_status;
int output_len;
char* output = NULL;
base64_encoding_status = MIME_Encode_SetStr(output, output_len, reinterpret_cast<char *>(m_result_pending), m_result_pending_len, NULL, GEN_BASE64_ONELINE);
if (base64_encoding_status != MIME_NO_ERROR)
return OpStatus::ERR_NO_MEMORY;
OP_STATUS status = m_result.Append(output, output_len);
OP_DELETEA(output);
return status;
}
else if (m_current_output_type == TEXT && m_result_pending_len > 0)
{
if (m_text_result_decoder)
return OpStatus::ERR; // Not decodable or we would have decoded it already.
// We delayed converting because we couldn't decide charset encoding.
OP_ASSERT(m_result_pending_len == 1);
// Our single byte should be converted as utf-8 (the default) which
// makes decoding it trivial.
if ((m_result_pending[0] & 0x7f) != m_result_pending[0])
return OpStatus::ERR; // Not decodable.
uni_char ch = m_result_pending[0];
return m_binary_result.Append(reinterpret_cast<char *>(&ch), sizeof(uni_char));
}
return OpStatus::OK;
}
OP_STATUS
DOM_FileReader_Base::InitResult(OutputType output_type, int argc, ES_Value* argv, DOM_Blob* blob)
{
m_current_output_type = output_type;
switch (m_current_output_type)
{
case TEXT:
if (argc > 1 && argv[1].type == VALUE_STRING)
RETURN_IF_ERROR(m_text_result_charset.SetUTF8FromUTF16(argv[1].value.string));
break;
case DATA_URL:
{
const uni_char *content_type = blob->GetContentType();
if (content_type)
{
m_data_url_content_type = SetNewStr(content_type);
if (!m_data_url_content_type)
return OpStatus::ERR_NO_MEMORY;
}
}
break;
case ARRAY_BUFFER:
case BINARY_STRING:
break; // Nothing special.
}
return OpStatus::OK;
}
OP_STATUS
DOM_FileReader_Base::AppendToResult(const unsigned char *prefix_buffer, unsigned prefix_length, const unsigned char *data, unsigned data_length)
{
OP_ASSERT(m_result_pending_len == 0 || !"ReadOldData() wasn't called");
unsigned total_data_length = prefix_length + data_length;
TempBuffer tempbuf;
if (m_current_output_type == TEXT)
{
if (!m_text_result_decoder)
{
if (!m_text_result_charset.IsEmpty())
RETURN_IF_MEMORY_ERROR(InputConverter::CreateCharConverter(m_text_result_charset.CStr(), &m_text_result_decoder));
if (!m_text_result_decoder)
{
unsigned char first_byte = total_data_length < 1 ? 0 : (prefix_length > 0 ? prefix_buffer[0] : data[0]);
// Detect charset or delay until we have enough data to properly detect charset.
if (total_data_length == 0 || total_data_length == 1 && (first_byte == 0xfe || first_byte == 0xff))
{
// Delay decision, until FlushToResult in the worst case.
m_result_pending_len = total_data_length;
op_memcpy(m_result_pending + prefix_length, data, data_length);
return OpStatus::OK;
}
else
{
const char *charset = "utf-8";
if (total_data_length >= 2)
{
unsigned char bytes[2];
if (prefix_length > 1)
{
bytes[0] = prefix_buffer[0];
bytes[1] = prefix_buffer[1];
}
else if (prefix_length == 1)
{
bytes[0] = prefix_buffer[0];
bytes[1] = data[0];
}
else
{
bytes[0] = data[0];
bytes[1] = data[1];
}
if (bytes[0] == 0xfe && bytes[1] == 0xff || bytes[0] == 0xff && bytes[1] == 0xfe)
charset = "utf-16";
}
RETURN_IF_ERROR(InputConverter::CreateCharConverter(charset, &m_text_result_decoder));
}
}
}
OP_ASSERT(m_text_result_decoder);
while (total_data_length > 0)
{
// This assumes that the input converts 1 byte -> 1 uni_char. If it's wrong we allocate
// too much or need to do more iterations.
unsigned expected_needed_char_len = total_data_length + 1;
RETURN_IF_ERROR(tempbuf.Expand(expected_needed_char_len));
uni_char* dest = tempbuf.GetStorage();
// Leave room to insert a trailing \0.
unsigned dest_len = sizeof(uni_char)*(tempbuf.GetCapacity() - 1);
tempbuf.SetCachedLengthPolicy(TempBuffer::UNTRUSTED);
int bytes_read = 0;
int bytes_written = 0;
if (prefix_length > 0)
{
bytes_written = m_text_result_decoder->Convert(prefix_buffer, prefix_length, dest, dest_len, &bytes_read);
if (bytes_written == -1)
return OpStatus::ERR_NO_MEMORY;
}
int bytes_read_next = 0;
int bytes_written_next = m_text_result_decoder->Convert(data, data_length, dest + bytes_written, dest_len - bytes_written, &bytes_read_next);
if (bytes_written_next == -1)
return OpStatus::ERR_NO_MEMORY;
bytes_written += bytes_written_next;
bytes_read += bytes_read_next;
dest[bytes_written / sizeof(uni_char)] = '\0';
total_data_length -= bytes_read;
data += bytes_read;
if (bytes_read == 0)
{
if (total_data_length > static_cast<int>(sizeof(m_result_pending)))
{
// A decoder we can't handle.
OP_ASSERT(!"What kind of decoder did we trip on now?");
return OpStatus::ERR;
}
m_result_pending_len += data_length;
op_memcpy(m_result_pending + prefix_length, data, data_length);
data += data_length;
total_data_length -= data_length;
}
RETURN_IF_ERROR(m_binary_result.Append(reinterpret_cast<char *>(dest), bytes_written));
tempbuf.Clear();
}
}
else if (m_current_output_type == ARRAY_BUFFER || m_current_output_type == BINARY_STRING)
{
OP_ASSERT(prefix_length == 0);
return m_binary_result.Append(reinterpret_cast<const char *>(data), data_length);
}
else if (m_current_output_type == DATA_URL)
{
if (m_result.Length() == 0)
{
RETURN_IF_ERROR(m_result.Append("data:"));
OpString8 str;
RETURN_IF_ERROR(str.SetUTF8FromUTF16(m_data_url_content_type));
RETURN_IF_ERROR(m_result.Append(str.CStr()));
m_data_url_use_base64 = !(m_data_url_content_type && uni_strncmp(m_data_url_content_type, "text/", 5) == 0);
if (m_data_url_use_base64)
RETURN_IF_ERROR(m_result.Append(";base64"));
RETURN_IF_ERROR(m_result.Append(','));
}
if (m_data_url_use_base64)
{
MIME_Encode_Error base64_encoding_status;
if (total_data_length > 0)
{
int to_consume = (total_data_length / 3) * 3;
unsigned char *data_buffer = const_cast<unsigned char *>(data);
if (prefix_length > 0)
{
/* Unfortunate copying together of pieces, but will only conceivably
happen for medium-sized file input progress chunks where the read
buffer isn't filled up. */
data_buffer = OP_NEWA(unsigned char, total_data_length);
RETURN_OOM_IF_NULL(data_buffer);
op_memcpy(data_buffer, prefix_buffer, prefix_length);
op_memcpy(data_buffer + prefix_length, data, data_length);
}
char* output = NULL;
int output_len;
base64_encoding_status = MIME_Encode_SetStr(output, output_len, reinterpret_cast<const char *>(data_buffer), to_consume, NULL, GEN_BASE64_ONELINE);
if (prefix_length > 0)
{
OP_DELETEA(data_buffer);
data_buffer = NULL;
}
if (base64_encoding_status != MIME_NO_ERROR)
return OpStatus::ERR_NO_MEMORY;
OP_ASSERT(static_cast<unsigned>(output_len) == (total_data_length / 3) * 4);
/* The leftover from 'data' is what's after the bytes consumed by
the encoder (minus the bytes that were prefixed from the previous chunk.) */
data += to_consume - prefix_length;
total_data_length -= to_consume;
OP_STATUS status = m_result.Append(output, output_len);
OP_DELETEA(output);
RETURN_IF_ERROR(status);
if (total_data_length > 0)
{
// Move any remaining bytes (one or two) to our pending buffer.
OP_ASSERT(total_data_length <= 2);
m_result_pending_len = total_data_length;
m_result_pending[0] = data[0];
if (total_data_length > 1)
m_result_pending[1] = data[1];
}
}
}
else
{
OP_ASSERT(prefix_length == 0);
int data_url_escape_flags = UriEscape::NonSpaceCtrl | UriEscape::UnsafePrintable | UriEscape::URIExcluded | UriEscape::Range_80_ff;
int needed_len = UriEscape::GetEscapedLength(reinterpret_cast<const char *>(data), total_data_length, data_url_escape_flags);
RETURN_IF_ERROR(tempbuf.Expand(needed_len + 1));
uni_char* dest = tempbuf.GetStorage();
UriEscape::Escape(dest, reinterpret_cast<const char *>(data), total_data_length, data_url_escape_flags);
dest[needed_len] = '\0';
tempbuf.SetCachedLengthPolicy(TempBuffer::UNTRUSTED);
}
m_result.Append(tempbuf.GetStorage(), tempbuf.Length());
}
else
OP_ASSERT(!"We can't get here yet since we don't support this type");
return OpStatus::OK;
}
unsigned
DOM_FileReader_Base::ReadOldData(unsigned char *buf)
{
unsigned unread_bytes = m_result_pending_len;
m_result_pending_len = 0;
if (unread_bytes > 0)
op_memcpy(buf, m_result_pending, unread_bytes);
return unread_bytes;
}
void
DOM_FileReader_Base::EmptyResult()
{
m_result.FreeStorage();
OP_DELETE(m_text_result_decoder);
m_text_result_decoder = NULL;
op_free(m_data_url_content_type);
m_data_url_content_type = NULL;
m_result_pending_len = 0;
m_binary_result.FreeStorage();
m_current_output_type = NONE;
}
OP_STATUS
DOM_FileReader_Base::GetResult(DOM_Object *this_object, ES_Value* value, TempBuffer* buffer, ES_ValueString* value_string)
{
OP_ASSERT(value);
switch (m_current_output_type)
{
case TEXT:
DOM_Object::DOMSetStringWithLength(value, &(g_DOM_globalData->string_with_length_holder), reinterpret_cast<uni_char *>(m_binary_result.GetStorage()), static_cast<unsigned>(m_binary_result.Length()) / sizeof(uni_char));
break;
case DATA_URL:
DOM_Object::DOMSetString(value, &m_result);
break;
case BINARY_STRING:
{
unsigned long length = m_binary_result.Length();
RETURN_IF_ERROR(buffer->Expand(length));
const unsigned char *src = reinterpret_cast<const unsigned char *>(m_binary_result.GetStorage());
uni_char *dest = buffer->GetStorage();
for (unsigned long i = 0; i < length; i++)
dest[i] = static_cast<uni_char>(src[i]);
DOM_Object::DOMSetStringWithLength(value, value_string, dest, length);
break;
}
case ARRAY_BUFFER:
if (!m_array_buffer)
{
unsigned long length = m_binary_result.Length();
RETURN_IF_ERROR(this_object->GetRuntime()->CreateNativeArrayBufferObject(&m_array_buffer, length, reinterpret_cast<unsigned char *>(m_binary_result.GetStorage())));
m_binary_result.ReleaseStorage();
}
DOM_Object::DOMSetObject(value, m_array_buffer);
break;
default:
DOM_Object::DOMSetNull(value);
break;
}
return OpStatus::OK;
}
OP_STATUS
DOM_FileReader_Base::ReadFromBlob(OpFileLength* bytes_read)
{
unsigned char short_buf[10]; // ARRAY OK sof 2012-03-26
unsigned prefix_length = ReadOldData(short_buf);
RETURN_IF_ERROR(m_current_read_view->ReadAvailable(this, short_buf, prefix_length, bytes_read));
return OpStatus::OK;
}
void
DOM_FileReader_Base::CloseBlob()
{
if (m_current_read_view)
{
OP_DELETE(m_current_read_view);
m_current_read_view = NULL;
}
}
void
DOM_FileReader_Base::GCTrace(DOM_Runtime *runtime)
{
if (m_current_read_view)
m_current_read_view->GCTrace();
if (m_array_buffer)
runtime->GCMark(m_array_buffer);
}
void
DOM_FileReader::SendEvent(DOM_EventType type, ES_Thread* interrupt_thread, ES_Thread** created_thread /* = NULL */)
{
if (created_thread)
*created_thread = NULL;
if (m_quiet_read)
return;
if (GetEventTarget() && GetEventTarget()->HasListeners(type, NULL, ES_PHASE_AT_TARGET))
{
#ifdef PROGRESS_EVENTS_SUPPORT
DOM_ProgressEvent* read_event;
if (OpStatus::IsSuccess(DOM_ProgressEvent::Make(read_event, GetRuntime())))
{
read_event->InitProgressEvent(m_current_read_total != 0, static_cast<OpFileLength>(m_current_read_loaded), static_cast<OpFileLength>(MAX(m_current_read_loaded, m_current_read_total)));
read_event->InitEvent(type, this);
GetEnvironment()->SendEvent(read_event, interrupt_thread, created_thread);
}
#else
DOM_Event* read_event;
if (OpStatus::IsSuccess(DOMSetObjectRuntime(read_event = OP_NEW(DOM_Event, ()), GetRuntime(),
GetRuntime()->GetPrototype(DOM_Runtime::EVENT_PROTOTYPE), "ProgressEvent")))
{
read_event->InitEvent(type, this);
GetEnvironment()->SendEvent(read_event, interrupt_thread);
}
#endif // PROGRESS_EVENTS_SUPPORT
}
}
void
DOM_FileReader::SetError(DOM_FileError::ErrorCode code)
{
m_error = NULL;
if (code != DOM_FileError::WORKING_JUST_FINE)
{
DOM_FileError* new_error;
if (OpStatus::IsSuccess(DOM_FileError::Make(new_error, code, GetRuntime())))
m_error = new_error;
}
}
/* virtual */ void
DOM_FileReader::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
OP_ASSERT(static_cast<unsigned>(par1) == m_id);
OP_ASSERT(msg == MSG_DOM_READ_FILE || msg == MSG_DOM_PROGRESS_EVENT_TICK);
if (static_cast<unsigned>(par2) != m_current_read_serial)
{
// Old message, just ignore
return;
}
BOOL send_progress_event = FALSE;
if (msg == MSG_DOM_PROGRESS_EVENT_TICK)
{
send_progress_event = m_public_state != DONE;
m_delayed_progress_event_pending = FALSE;
}
if (msg == MSG_DOM_READ_FILE)
{
/* We have an open blob/file if we get here. If a file, just need to
read some, send some events and add to the result. For in-memory
blob resources, we read it all in one go. */
OpFileLength bytes_read;
OP_STATUS status = ReadFromBlob(&bytes_read);
if (OpStatus::IsSuccess(status) && bytes_read > 0)
{
m_current_read_loaded += bytes_read;
send_progress_event = TRUE;
}
if (OpStatus::IsError(status) || m_current_read_view->AtEOF())
{
GetEnvironment()->RemoveFileReader(this);
g_main_message_handler->UnsetCallBack(this, MSG_DOM_READ_FILE);
CloseBlob();
m_delayed_progress_event_pending = FALSE;
m_public_state = DONE;
DOM_FileError::ErrorCode error_code = DOM_FileError::NOT_READABLE_ERR;
if (OpStatus::IsSuccess(status))
{
status = FlushToResult();
error_code = DOM_FileError::ENCODING_ERR;
}
if (OpStatus::IsError(status))
{
SendEvent(ONERROR, NULL);
SetError(error_code);
}
else
{
#ifdef PROGRESS_EVENTS_SUPPORT
/* Issue final 'progress' before 'load' and 'loadend'. */
SendEvent(ONPROGRESS, NULL);
send_progress_event = FALSE;
#endif // PROGRESS_EVENTS_SUPPORT
SendEvent(ONLOAD, NULL);
}
#ifdef PROGRESS_EVENTS_SUPPORT
SendEvent(ONLOADEND, NULL);
#endif // PROGRESS_EVENTS_SUPPORT
}
else
g_main_message_handler->PostMessage(MSG_DOM_READ_FILE, m_id, m_current_read_serial);
}
if (send_progress_event)
{
// Send a progress message if it's not too often.
// Must not be sent more often than once every
// DOM_FILE_READ_PROGRESS_EVENT_INTERVAL milliseconds.
double current_time = g_op_time_info->GetRuntimeMS();
unsigned elapsed_time = static_cast<unsigned>(current_time - m_current_read_last_progress_msg_time);
if (elapsed_time >= DOM_FILE_READ_PROGRESS_EVENT_INTERVAL)
{
#ifdef PROGRESS_EVENTS_SUPPORT
SendEvent(ONPROGRESS, NULL);
#endif // PROGRESS_EVENTS_SUPPORT
m_current_read_last_progress_msg_time = current_time;
}
else if (!m_delayed_progress_event_pending)
{
g_main_message_handler->PostMessage(MSG_DOM_PROGRESS_EVENT_TICK, m_id, m_current_read_serial,
DOM_FILE_READ_PROGRESS_EVENT_INTERVAL - elapsed_time);
m_delayed_progress_event_pending = TRUE;
}
}
}
class DOM_FileReaderRestartObject : public DOM_Object
{
public:
ES_Object* m_abort_restart_object;
DOM_Blob* m_blob;
virtual void GCTrace() { GCMark(m_abort_restart_object); GCMark(m_blob); }
};
/* static */ int
DOM_FileReader::readBlob(DOM_Object *&reader, DOM_Blob *blob, const unsigned char *&buffer, unsigned &length, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_FileReaderSync *sync_reader;
if (blob)
{
/* Optimizations: Blob'ed ArrayBuffers are returned directly..same with
slices of them. */
if (blob->GetType() == DOM_Blob::BlobBuffer)
{
DOM_BlobBuffer *blob_buffer = static_cast<DOM_BlobBuffer *>(blob);
if (blob_buffer->IsSlice())
length = static_cast<unsigned>(blob_buffer->GetSliceLength());
else
length = static_cast<unsigned>(blob_buffer->GetSize());
unsigned start_offset = static_cast<unsigned>(blob_buffer->GetSliceStart());
buffer = blob_buffer->GetBuffer() + start_offset;
if (blob_buffer->GetArrayBufferView())
DOMSetObject(return_value, blob_buffer->GetArrayBufferView());
else
DOMSetUndefined(return_value);
return ES_VALUE;
}
else if (blob->GetType() == DOM_Blob::BlobSlice)
{
DOM_BlobSlice *blob_slice = static_cast<DOM_BlobSlice *>(blob);
if (blob_slice->GetSlicedBlob()->GetType() == DOM_Blob::BlobBuffer)
{
OP_ASSERT(blob_slice->GetSize() == static_cast<double>(blob_slice->GetSliceLength()));
length = static_cast<unsigned>(blob_slice->GetSize());
unsigned start_offset = static_cast<unsigned>(blob_slice->GetSliceStart());
DOM_BlobBuffer *blob_buffer = static_cast<DOM_BlobBuffer *>(blob_slice->GetSlicedBlob());
buffer = blob_buffer->GetBuffer() + start_offset;
if (blob_buffer->GetArrayBufferView())
DOMSetObject(return_value, blob_buffer->GetArrayBufferView());
else
DOMSetUndefined(return_value);
return ES_VALUE;
}
}
CALL_FAILED_IF_ERROR(DOM_FileReaderSync::Make(sync_reader, origining_runtime));
sync_reader->SetWithProgressEvents(FALSE);
ES_Value arg;
DOMSetObject(&arg, blob);
int result = DOM_FileReaderSync::readAs(sync_reader, &arg, 1, return_value, origining_runtime, DOM_FileReader::ARRAY_BUFFER);
if (result & ES_SUSPEND)
reader = sync_reader;
else if (result == ES_VALUE)
{
OP_ASSERT(return_value->type == VALUE_OBJECT && ES_Runtime::IsNativeArrayBufferObject(return_value->value.object));
buffer = ES_Runtime::GetArrayBufferStorage(return_value->value.object);
length = ES_Runtime::GetArrayBufferLength(return_value->value.object);
}
return result;
}
else
{
OP_ASSERT(reader && reader->IsA(DOM_TYPE_FILEREADERSYNC));
sync_reader = static_cast<DOM_FileReaderSync *>(reader);
int result = DOM_FileReaderSync::readAs(sync_reader, NULL, -1, return_value, origining_runtime, DOM_FileReader::ARRAY_BUFFER);
if (result == ES_VALUE)
{
OP_ASSERT(return_value->type == VALUE_OBJECT && ES_Runtime::IsNativeArrayBufferObject(return_value->value.object));
buffer = ES_Runtime::GetArrayBufferStorage(return_value->value.object);
length = ES_Runtime::GetArrayBufferLength(return_value->value.object);
}
return result;
}
}
/* static */ int
DOM_FileReader::readAs(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data)
{
DOM_THIS_OBJECT(reader, DOM_TYPE_FILEREADER, DOM_FileReader);
DOM_Blob* blob;
DOM_FileReaderRestartObject* restart_object = NULL;
BOOL do_abort = FALSE;
if (argc < 0)
{
OP_ASSERT(return_value->type == VALUE_OBJECT);
restart_object = static_cast<DOM_FileReaderRestartObject *>(ES_Runtime::GetHostObject(return_value->value.object));
blob = restart_object->m_blob;
if (restart_object && restart_object->m_abort_restart_object)
do_abort = TRUE;
DOMSetUndefined(return_value);
}
else
{
DOM_CHECK_ARGUMENTS("o");
DOM_ARGUMENT_OBJECT_EXISTING(blob, 0, DOM_TYPE_BLOB, DOM_Blob);
if (reader->m_public_state == LOADING)
do_abort = TRUE;
}
if (do_abort)
{
ES_Value abort_value;
int abort_argc = 0;
if (restart_object && restart_object->m_abort_restart_object)
{
DOMSetObject(&abort_value, restart_object->m_abort_restart_object);
abort_argc = -1;
}
int ret = abort(this_object, NULL, abort_argc, &abort_value, origining_runtime);
if (ret != ES_FAILED)
{
if (ret & ES_RESTART)
{
if (!restart_object)
{
CALL_FAILED_IF_ERROR(DOMSetObjectRuntime(restart_object = OP_NEW(DOM_FileReaderRestartObject, ()), origining_runtime));
restart_object->m_blob = blob;
}
restart_object->m_abort_restart_object = abort_value.value.object;
DOMSetObject(return_value, restart_object);
}
else
*return_value = abort_value;
return ret;
}
}
OpFileLength start_pos = static_cast<OpFileLength>(blob->m_sliced_start);
if (start_pos != blob->m_sliced_start) // Overflow?
return DOM_CALL_INTERNALEXCEPTION(WRONG_ARGUMENTS_ERR);
reader->EmptyResult();
reader->SetError(DOM_FileError::WORKING_JUST_FINE);
reader->m_public_state = EMPTY;
reader->m_current_read_serial++;
reader->m_public_state = LOADING;
reader->m_current_read_total = blob->GetSize();
ES_Thread* current_thread = GetCurrentThread(origining_runtime);
#ifdef PROGRESS_EVENTS_SUPPORT
reader->SendEvent(ONLOADSTART, current_thread);
#endif // PROGRESS_EVENTS_SUPPORT
reader->m_current_read_last_progress_msg_time = g_op_time_info->GetRuntimeMS() - DOM_FILE_READ_PROGRESS_EVENT_INTERVAL;
OP_ASSERT(reader->m_current_read_view == NULL);
OP_STATUS status;
if (OpStatus::IsError(status = blob->MakeReadView(reader->m_current_read_view, 0, blob->GetSliceLength())) ||
OpStatus::IsError(status = g_main_message_handler->SetCallBack(reader, MSG_DOM_READ_FILE, reader->m_id)))
{
reader->CloseBlob();
reader->SendEvent(ONERROR, current_thread);
reader->SetError(DOM_FileError::NOT_FOUND_ERR);
#ifdef PROGRESS_EVENTS_SUPPORT
reader->SendEvent(ONLOADEND, current_thread);
#endif // PROGRESS_EVENTS_SUPPORT
if (OpStatus::IsMemoryError(status))
return ES_NO_MEMORY;
return ES_FAILED;
}
// data is one of the enum OutputType values.
status = reader->InitResult(static_cast<OutputType>(data), argc, argv, blob);
if (OpStatus::IsError(status))
{
reader->CloseBlob();
reader->SendEvent(ONERROR, current_thread);
reader->Abort();
if (OpStatus::IsMemoryError(status))
{
reader->SetError(DOM_FileError::NOT_READABLE_ERR);
return ES_NO_MEMORY;
}
reader->SetError(DOM_FileError::ENCODING_ERR);
#ifdef PROGRESS_EVENTS_SUPPORT
reader->SendEvent(ONLOADEND, current_thread);
#endif // PROGRESS_EVENTS_SUPPORT
return ES_FAILED;
}
reader->GetEnvironment()->AddFileReader(reader);
g_main_message_handler->PostMessage(MSG_DOM_READ_FILE, reader->m_id, reader->m_current_read_serial);
return ES_FAILED;
}
class DOM_FileReaderAbortRestartObject : public DOM_Object
{
public:
DOM_EventType m_next_event;
};
/* static */ int
DOM_FileReader::abort(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
// This function is also used as a helper function for ::readAs()
DOM_THIS_OBJECT(reader, DOM_TYPE_FILEREADER, DOM_FileReader);
// Have to dispatch three sync event: error, abort, loadend.
DOM_EventType next_event;
DOM_FileReaderAbortRestartObject* restart_object = NULL;
if (argc < 0)
{
OP_ASSERT(return_value->type == VALUE_OBJECT);
restart_object = static_cast<DOM_FileReaderAbortRestartObject*>(ES_Runtime::GetHostObject(return_value->value.object));
DOMSetUndefined(return_value);
next_event = restart_object->m_next_event;
}
else
{
if (!reader->m_current_read_view)
return ES_FAILED;
reader->Abort();
reader->EmptyResult();
reader->SetError(DOM_FileError::ABORT_ERR);
next_event = ONERROR;
}
DOM_EventType events[] =
{
ONERROR,
ONABORT,
#ifdef PROGRESS_EVENTS_SUPPORT
ONLOADEND,
#endif // PROGRESS_EVENTS_SUPPORT
DOM_EVENT_NONE
};
for (int i = 0; events[i] != DOM_EVENT_NONE; i++)
{
if (next_event == events[i])
{
ES_Thread* event_thread;
reader->SendEvent(next_event, GetCurrentThread(origining_runtime), &event_thread);
next_event = events[i+1];
if (event_thread)
{
// Must make sure the event handler runs before we change any state (goes for
// when this is used as a helper function for readAs as well).
if (!restart_object)
CALL_FAILED_IF_ERROR(DOMSetObjectRuntime(restart_object = OP_NEW(DOM_FileReaderAbortRestartObject, ()), origining_runtime));
restart_object->m_next_event = next_event;
DOMSetObject(return_value, restart_object);
return ES_SUSPEND | ES_RESTART;
}
}
}
return ES_FAILED;
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_FileReader)
DOM_FUNCTIONS_FUNCTION(DOM_FileReader, DOM_FileReader::abort, "abort", 0)
DOM_FUNCTIONS_FUNCTION(DOM_FileReader, DOM_Node::dispatchEvent, "dispatchEvent", 0)
DOM_FUNCTIONS_END(DOM_FileReader)
DOM_FUNCTIONS_WITH_DATA_START(DOM_FileReader)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_FileReader, DOM_FileReader::readAs, DOM_FileReader::ARRAY_BUFFER, "readAsArrayBuffer", NULL)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_FileReader, DOM_FileReader::readAs, DOM_FileReader::BINARY_STRING, "readAsBinaryString", NULL)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_FileReader, DOM_FileReader::readAs, DOM_FileReader::TEXT, "readAsText", "-s-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_FileReader, DOM_FileReader::readAs, DOM_FileReader::DATA_URL, "readAsDataURL", NULL)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_FileReader, DOM_Node::accessEventListener, 0, "addEventListener", "s-b-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_FileReader, DOM_Node::accessEventListener, 1, "removeEventListener", "s-b-")
DOM_FUNCTIONS_WITH_DATA_END(DOM_FileReader)
|
#include<iostream>
#include<map>
using namespace std;
int main(){
map<int,int> mp;
mp[0]=0;
mp[1]=1;
mp[0]=10;
for(auto it=mp.begin();it!=mp.end();it++){
cout<<it->second<<" ";
}
return 0;
}
|
#include <stdio.h>
#include <errno.h>
#include <QMessageBox>
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->pushButton_burn, SIGNAL(clicked()), this, SLOT(burnMacAdr()));
connect(ui->pushButton_get, SIGNAL(clicked()), this, SLOT(getMacAdr()));
//init network
mNetManager = new QNetworkAccessManager(this);
QObject::connect(mNetManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(finishedSlot(QNetworkReply*)));
mIsFind = false;
// mCheckTimer = new QTimer(this);
// connect(mCheckTimer, SIGNAL(timeout()), this, SLOT(timerProcess()) );
// mCheckTimer->start(3000);
//autoScroll
// connect(this, SIGNAL(textChanged()), this, SLOT(autoScroll()));
}
MainWindow::~MainWindow()
{
delete ui;
delete mNetManager;
// delete mCheckTimer;
}
bool MainWindow::check_input_legal(const char *input, int maxlen)
{
int len;
bool islegal = input;
len = strlen(input);
if (len != maxlen) {
return false;
}
for (int i = 0; i < len; i++) {
// qDebug("mac: i: %d, %c", i, input[i]);
if (!isxdigit(input[i])) {
islegal = false;
break;
}
}
return islegal;
}
#if 0
bool
MainWindow::check_mac_legal(const char *mac)
{
int len;
bool islegal = true;
len = strlen(mac);
if (len != 12) {
return false;
}
for (int i = 0; i < len; i++) {
qDebug("mac: i: %d, %c", i, mac[i]);
if (!isxdigit(mac[i])) {
islegal = false;
break;
}
}
return islegal;
}
bool MainWindow::check_pid_legal(const char *pid)
{
int len = strlen(pid);
if (len == 0) {
return false;
}
return true;
}
#endif
void
MainWindow::burnMacAdr()
{
char buff[1024];
char mac_addr[18];
QString macstr, pidstr;
const char *p_mac = NULL;
const char *p_pid = NULL;
QByteArray mac_array, pid_array;
qDebug("start burn\n");
ui->textEdit->append("start burn");
Device_State state = getMacAdr();
if (state != NOT_BURNED)
return;
qDebug("count: %d\n", ui->lineEdit_mac->text().count());
qDebug("count: %d\n", ui->lineEdit_pid->text().count());
macstr = ui->lineEdit_mac->text();
mac_array = macstr.toLocal8Bit();
p_mac = mac_array.constData();
pidstr = ui->lineEdit_pid->text();
pid_array = pidstr.toLocal8Bit();
p_pid = pid_array.constData();
bool mac_legal = check_input_legal(p_mac, 12);
if (mac_legal == false) {
ui->textEdit->setTextColor(QColor(255, 0, 0));
ui->textEdit->append("error mac address");
ui->textEdit->setTextColor(QColor(0, 0, 255));
return;
}
bool pid_legal = check_input_legal(p_pid, 2);
if (pid_legal == false) {
ui->textEdit->setTextColor(QColor(255, 0, 0));
ui->textEdit->append("error pid number");
ui->textEdit->setTextColor(QColor(0, 0, 0));
return;
}
qDebug("mac_legal: %d\n", mac_legal);
for (int i = 0, j = 0; i < 12; i += 2, j+=3) {
qDebug("mac_addr: %d, %c, %c\n", i, p_mac[i], p_mac[i+1]);
mac_addr[j] = p_mac[i];
mac_addr[j + 1] = p_mac[i + 1];
if (i == 10)
continue;
mac_addr[j + 2] = ':';
}
mac_addr[17] = '\0';
qDebug("mac addr: %s\n", mac_addr);
sprintf(buff, "http://115.29.198.3:8080/szbox/service!submitMac.htm?id=%s&mac=%s", p_pid, mac_addr);
qDebug("url: %s\n", buff);
memcpy(mMacAdr, mac_addr, sizeof(mac_addr));
QUrl url(buff);
QNetworkReply* reply = mNetManager->get(QNetworkRequest(url));
}
Device_State
MainWindow::getMacAdr()
{
char buff[1024];
qDebug("get mac addr");
ui->textEdit->append("get mac");
FILE *stream = popen("CommandUSB.exe -r ETHMAC", "r");
if (NULL == stream) {
perror("popen");
} else {
memset(buff, 0, sizeof(buff));
fread(buff, sizeof(buff), 1, stream);
ui->textEdit->append(buff);
pclose(stream);
if (strstr(buff, "ETHMAC")) {
qDebug("length: %d\n", strlen(buff));
if (strlen(buff) < 19) {
ui->textEdit->append("no burn");
return NOT_BURNED;
} else {
ui->textEdit->append("already burn");
QMessageBox::about(NULL, "ERROR", "About this <font color='red'>already burn</font>");
return BURNED;
}
} else {
ui->textEdit->append("did not find device");
QMessageBox::about(NULL, "ERROR", "About this <font color='red'>did not find device</font>");
return NOT_FIND_DEVICE;
}
}
}
void
MainWindow::finishedSlot(QNetworkReply *reply)
{
char buff[1024];
char cmd[1024];
// Reading attributes of the reply
QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
// Or the target URL if it was a redirect:
QVariant redirectionTargetUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (reply->error() == QNetworkReply::NoError) {
// read data from QNetworkReply here
QByteArray bytes = reply->readAll(); // bytes
QString string = QString::fromUtf8(bytes);
if (string.contains("true")) {
ui->textEdit->setTextColor(QColor(0, 0, 255));
ui->textEdit->append("mac address start burn ...");
ui->textEdit->setTextColor(QColor(0, 0, 0));
sprintf(cmd, "CommandUSB.exe -w -s=0 ETHMAC=%s", mMacAdr);
FILE *stream = popen(cmd, "r");
if (NULL == stream) {
ui->textEdit->append(("burn error\n"));
perror("popen");
// qDebug("run cmd error: %s\n", );
} else {
memset(buff, 0, sizeof(buff));
fread(buff, sizeof(buff), 1, stream);
ui->textEdit->append(buff);
ui->textEdit->append("burn sucess\n");
pclose(stream);
mIsFind = false;
}
} else {
ui->textEdit->setTextColor(QColor(0, 255, 0));
ui->textEdit->append("mac address already used");
ui->textEdit->setTextColor(QColor(0, 0, 0));
}
qDebug("resp: %s\n", string.toLatin1().data());
} else {
// handle errors here
}
// We receive ownership of the reply object
// and therefore need to handle deletion.
reply->deleteLater();
}
void MainWindow::timerProcess()
{
qDebug("timer....\n");
char buff[1024];
if (mIsFind == true)
return;
FILE *stream = popen("CommandUSB.exe -r ETHMAC", "r");
if (NULL == stream) {
perror("popen");
mIsFind = false;
// qDebug("run cmd error: %s\n", );
} else {
if (mIsFind == false) {
memset(buff, 0, sizeof(buff));
fread(buff, sizeof(buff), 1, stream);
ui->textEdit->append(buff);
ui->textEdit->append("find a device");
pclose(stream);
mIsFind = true;
}
}
}
#if 0
void MainWindow::autoScroll()
{
qDebug("autoScroll\n");
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
/** @brief main() and associated functions for the plugin wrapper
*/
#include "core/pch.h"
#ifdef NO_CORE_COMPONENTS
#include "platforms/posix_ipc/posix_ipc_component_platform.h"
#include "platforms/unix/product/pluginwrapper/plugin_component_platform.h"
#include "platforms/unix/product/pluginwrapper/plugin_crashlog.h"
#include "modules/pi/OpThreadTools.h"
CoreComponent* g_opera = NULL;
__thread OpComponentManager* g_component_manager = NULL;
OpThreadTools* g_thread_tools = NULL;
/* For X11 debugging, from Xlib.h */
extern int _Xdebug;
int main(int argc, char** argv)
{
// Debugging: define OPERA_PLUGINWRAPPER_SLEEP to a number of seconds to sleep in main
const char* want_sleep = op_getenv("OPERA_PLUGINWRAPPER_SLEEP");
if (want_sleep)
{
unsigned seconds = op_strtoul(want_sleep, NULL, 10);
fprintf(stderr, "operapluginwrapper [%d]: sleeping for %u seconds\n", getpid(), seconds);
sleep(seconds);
}
if (op_getenv("OPERA_PLUGINWRAPPER_XSYNC"))
{
/* Make all X11 requests synchronous (slows everything down but very
* useful for debugging X11 error such as BadDrawable, BadValue etc. */
_Xdebug = 1;
}
if (argc < 5 || op_strcmp(argv[3], "-logfolder") != 0)
return -1; // Need a folder spec and either multiproc or crashlog arguments to start going
const char* logfolder = argv[4];
// Check for a crashlog argument
if (op_strcmp(argv[1], "-crashlog") == 0)
{
return OpStatus::IsSuccess(PluginCrashlog::HandleCrash(op_atoi(argv[2]), logfolder)) ? 0 : -1;
}
else if (!op_getenv("OPERA_PLUGINWRAPPER_NOCAT"))
{
PluginCrashlog::InstallHandler(argv[0], logfolder);
}
// Now return to the main case, a multiproc argument
if (op_strcmp(argv[1], "-multiproc") != 0)
return -1; // Didn't get multi-process token needed to start plugin
// Start sub-process
PosixIpcComponentPlatform* platform;
if (OpStatus::IsError((PosixIpcComponentPlatform::Create(platform, argv[2]))))
{
if (op_getenv("OPERA_PLUGINWRAPPER_CRASH_ON_ERROR"))
{
int* x = NULL;
fprintf(stderr, "operapluginwrapper [%d]: Crash %d\n", getpid(), *x);
}
fprintf(stderr, "operapluginwrapper [%d]: Error on creation of new process component\n", getpid());
return -1;
}
RETURN_VALUE_IF_ERROR(OpThreadTools::Create(&g_thread_tools), -1);
int retval = platform->Run();
OP_DELETE(g_thread_tools);
OP_DELETE(platform);
return retval;
}
PosixIpcComponentPlatform* PosixIpcComponentPlatform::CreateComponent(OpComponentType type)
{
if (type == COMPONENT_PLUGIN) // This is the only component we know how to create
return OP_NEW(PluginComponentPlatform, ());
return NULL;
}
#endif // NO_CORE_COMPONENTS
|
#ifndef HUMANB_HPP
# define HUMANB_HPP
# include <string>
# include <iostream>
# include "Weapon.hpp"
class HumanB
{
private:
const std::string name_;
const Weapon *weapon_;
HumanB();
public:
void attack(void) const;
void setWeapon(const Weapon &new_weapon);
HumanB(const std::string &name, const Weapon &weapon);
HumanB(const std::string &name);
~HumanB();
};
#endif
|
#pragma once
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct ChatRoom;
struct Person {
string name;
ChatRoom* room = nullptr;
vector<string> chat_log;
explicit Person(const string& name);
void say(const string& message) const;
void receive(const string& origin, const string& message);
void pm(const string& who, const string& message);
};
|
//Program to check if the given number is even or odd.
#include<iostream>
using namespace std;
int main()
{
int n, rem; //n-number, rem-reminder
cout<<"enter the number:\n";
cin>>n;
rem=n%2;
if(rem == 0)
{
cout<<n<<" is an even number";
}
else
{
cout<<n<<" is a odd number";
}
return 0;
}
|
#include "functionGenerator.h"
using namespace qReal;
using namespace robots::generator;
void FunctionGenerator::generateBodyWithoutNextElementCall()
{
QByteArray byteFuncCode = mNxtGen->mApi->stringProperty(mElementId, "Body").toUtf8();
byteFuncCode.replace("Сенсор1", "ecrobot_get_sonar_sensor(NXT_PORT_S1)");
byteFuncCode.replace("Сенсор2", "ecrobot_get_sonar_sensor(NXT_PORT_S2)");
byteFuncCode.replace("Сенсор3", "ecrobot_get_sonar_sensor(NXT_PORT_S3)");
byteFuncCode.replace("Сенсор4", "ecrobot_get_sonar_sensor(NXT_PORT_S4)");
variableAnalysis(byteFuncCode);
QString const funcCode = QString::fromUtf8(byteFuncCode);
foreach (QString const &str, funcCode.split(';')) {
mNxtGen->mGeneratedStrings.append(SmartLine(str.trimmed() + ";", mElementId));
}
}
void FunctionGenerator::variableAnalysis(QByteArray const &code)
{
QList<QByteArray> const funcBlocks = code.split(';');
foreach (QByteArray const &block, funcBlocks) {
//Only one possible place for first variable appear
int firstEqualSignPos = block.indexOf('=');
if (firstEqualSignPos == -1)
continue;
//must be a normal variable name
QByteArray leftPart = block.left(firstEqualSignPos);
leftPart = leftPart.trimmed();
QString forbiddenLastSimbols = "+-=*/><";
if (forbiddenLastSimbols.contains((leftPart.at(leftPart.length() - 1))))
continue;
bool isVariableExisted = false;
foreach (SmartLine const &curVariable, mNxtGen->mVariables) {
if (curVariable.text() == QString::fromUtf8(leftPart)) {
isVariableExisted = true;
break;
}
}
if (!isVariableExisted)
mNxtGen->mVariables.append(SmartLine(QString::fromUtf8(leftPart), mElementId));
}
}
|
#pragma once
#include <iostream>
#include "Game.h"
#include <exception>
int main(int argc, char *argv[])
{
Game game;
if (!game.init())
{
throw new std::exception("Erro ao inicializar o jogo");
}
game.start();
game.close();
return 0;
}
|
#include <SoftwareSerial.h>
int buzzPin = 8;
int inputPin = 4;
int pirState = LOW;
int val = 0;
int blueTx = 2;
int blueRx = 3;
SoftwareSerial mySerial(blueTx, blueRx);
String myString = "";
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
pinMode(buzzPin, OUTPUT);
pinMode(inputPin, INPUT);
}
void loop() {
while(mySerial.available()) {
char myChar = (char)mySerial.read();
myString += myChar;
delay(5);
}
if(!myString.equals("")) {
Serial.println("input value: " + myString);
if(myString =="on") {
val = digitalRead(inputPin); // 센서값 읽기
if (val == HIGH) { // 인체감지시
tone(buzzPin,500,3000); //버저 울림
if (pirState == LOW) {
// 시리얼모니터에 메시지 출력
Serial.println("Motion detected!");
pirState = HIGH;
}
} else {
noTone(buzzPin); //버저 끔
if (pirState == HIGH){
// 시리얼모니터에 메시지 출력
Serial.println("Motion ended!");
pirState = LOW;
}
}
}
else if(myString == "onoff") {
noTone(buzzPin);
myString = "";
}
else {
noTone(buzzPin);
}
}
}
|
#ifndef BITMAP_TEXT_RENDERER_HPP_
#define BITMAP_TEXT_RENDERER_HPP_
#include "TextRendererInterface.h"
#include <unordered_map>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <GL/glut.h>
class BitmapTextRenderer : public TextRendererInterface {
private:
typedef std::unordered_map<int, void *> FontContainerType;
enum {
MAX_PRINT_SIZE = 1024,
};
public:
BitmapTextRenderer() {}
~BitmapTextRenderer() {}
void Init() {
default_font_= GLUT_BITMAP_8_BY_13;
font_ = default_font_;
}
void Print(int x, int y, const char * fmt, ...) {
glRasterPos2i(x, y);
va_list args;
va_start(args, fmt);
Print(fmt, args);
va_end(args);
}
void Print(const char * format, ...) {
memset(print_buffer_, 0, MAX_PRINT_SIZE);
va_list args;
va_start(args, format);
vsnprintf(print_buffer_, MAX_PRINT_SIZE, format, args);
va_end(args);
for (unsigned int i=0; i<strlen(print_buffer_); ++i) {
glutBitmapCharacter(font_, print_buffer_[i]);
}
}
void Print(std::string message) {
for (char c : message) {
glutBitmapCharacter(font_, c);
}
}
private:
char print_buffer_[MAX_PRINT_SIZE];
void * font_;
void * default_font_;
FontContainerType fonts_;
};
#endif // BITMAP_TEXT_RENDERER_HPP_
|
#include "Test.h"
std::string Test::operator()(char c)
{
if(c >= '0' && c <= '9')
return "NUM";
}
|
// C headers
#include <cstdint>
#include <cstdlib>
#include <ctime>
// C++ headers
#include <array>
#include <iostream>
#define EIGEN_DONT_VECTORIZE
// 3rd-party library headers
#include <Eigen/Core>
// local headers
#include "compute.hpp"
/**
@brief This example is supposed to demonstrate the intended use of the
library.
*/
int main(int, char**) {
// parameters of the point cloud and the computation
using size_type = std::uint32_t;
size_type constexpr NUM_PTS = 200;
size_type constexpr DIM = 3;
size_type constexpr NUM_THREADS = 1;
// create random point cloud
using eigen_matrix = Eigen::MatrixXd;
using float_t = Eigen::MatrixXd::Scalar;
std::srand(std::time(nullptr));
eigen_matrix const point_storage = eigen_matrix::Random(DIM, NUM_PTS);
std::array<float_t const*, NUM_PTS> points;
for (size_type i = 0; i < NUM_PTS; ++i)
points[i] = point_storage.col(i).data();
// compute the flow complex
auto fc = FC::compute_flow_complex<size_type>
(points.cbegin(), points.cend(), DIM, NUM_THREADS);
if (not FC::validate(fc)) {
std::cerr << "flow complex validation failed\n";
std::exit(EXIT_FAILURE);
}
std::cout << "FC COMPUTATION SUCCESSFULLY COMPLETED\n";
std::exit(EXIT_SUCCESS);
}
|
#ifndef CHANNEL_HH
#define CHANNEL_HH
#include "task.hh"
#include <memory>
#include <queue>
#include <deque>
namespace ten {
// based on bounded_buffer example
// http://www.boost.org/doc/libs/1_41_0/libs/circular_buffer/doc/circular_buffer.html#boundedbuffer
struct channel_closed_error : std::exception {};
//! send and receive data between tasks in FIFO order
//
//! channels can be buffered or unbuffered.
//! unbuffered channels block on every send until recv
//! buffered channels only block send when the buffer is full
//! data is copied, so if you need to send large data
//! its best to allocate them on the heap and send the pointer
//! share by communicating!
//! channels are thread and task safe.
template <typename T, typename ContainerT = std::deque<T> > class channel {
private:
struct impl : boost::noncopyable {
typedef typename ContainerT::size_type size_type;
impl(size_type capacity_=0) : capacity(capacity_), unread(0),
queue(ContainerT()), closed(false) {}
// capacity is different than container.capacity()
// to avoid needing to reallocate the container
// on every send/recv for unbuffered channels
size_type capacity;
size_type unread;
std::queue<T, ContainerT> queue;
qutex qtx;
rendez not_empty;
rendez not_full;
bool closed;
bool is_empty() const { return unread == 0; }
bool is_full() const { return unread >= capacity; }
};
public:
//! create a new channel
//! \param capacity number of items to buffer. the default is 0, unbuffered.
channel(typename impl::size_type capacity=0, bool autoclose_=false)
: m(std::make_shared<impl>(capacity)), autoclose(autoclose_)
{
}
channel(const channel &other) : m(other.m), autoclose(false) {}
channel &operator = (const channel &other) {
m = other.m;
autoclose = false;
return *this;
}
~channel() {
if (autoclose) {
close();
}
}
//! send data
typename impl::size_type send(T &&p) {
std::unique_lock<qutex> l(m->qtx);
typename impl::size_type unread = m->unread;
while (m->is_full() && !m->closed) {
m->not_full.sleep(l);
}
check_closed();
m->queue.push(std::move(p));
++m->unread;
m->not_empty.wakeup();
return unread;
}
//! receive data
T recv() {
T item;
std::unique_lock<qutex> l(m->qtx);
bool unbuffered = m->capacity == 0;
if (unbuffered) {
// grow the capacity for a single item
m->capacity = 1;
// unblock sender
m->not_full.wakeup();
}
while (m->is_empty() && !m->closed) {
m->not_empty.sleep(l);
}
if (m->unread == 0) {
check_closed();
}
// we don't pop_back because the item will just get overwritten
// when the circular buffer wraps around
--m->unread;
item = std::move(m->queue.front());
m->queue.pop();
if (unbuffered) {
// shrink capacity again so sends will block
// waiting for recv
m->capacity = 0;
} else {
m->not_full.wakeup();
}
return item;
}
// TODO: rewrite this
#if 0
//! timed receive data
bool timed_recv(T &item, unsigned int ms) {
std::unique_lock<qutex> l(m->qtx);
bool unbuffered = m->capacity == 0;
if (unbuffered) {
// grow the capacity for a single item
m->capacity = 1;
// unblock sender
m->not_full.wakeup();
}
while (m->is_empty() && !m->closed) {
if (!m->not_empty.sleep_for(l, ms)) return false;
}
if (m->unread == 0) {
check_closed();
}
// we don't pop_back because the item will just get overwritten
// when the circular buffer wraps around
item = m->container[--m->unread];
if (unbuffered) {
// shrink capacity again so sends will block
// waiting for recv
m->capacity = 0;
} else {
m->not_full.wakeup();
}
return true;
}
#endif
bool empty() {
return unread() == 0;
}
//! \return number of unread items
size_t unread() {
std::unique_lock<qutex> lock(m->qtx);
return m->unread;
}
void close() {
std::unique_lock<qutex> l(m->qtx);
m->closed = true;
// wake up all users of channel
m->not_empty.wakeupall();
m->not_full.wakeupall();
}
void clear() {
std::unique_lock<qutex> l(m->qtx);
while (!m->queue.empty()) {
m->queue.pop();
}
m->unread = 0;
m->not_full.wakeupall();
}
private:
std::shared_ptr<impl> m;
bool autoclose;
void check_closed() {
// i dont like throwing an exception for this
// but i don't want to complicate the interface for send/recv
if (m->closed) throw channel_closed_error();
}
};
} // end namespace ten
#endif // CHANNEL_HH
|
#ifndef __Core__GnSQLiteQuery__
#define __Core__GnSQLiteQuery__
class sqlite3_stmt;
class GnSQLiteQuery
{
enum
{
GNSQLITE_NULL = 5,
};
private:
sqlite3_stmt* mpStatement;
bool mEof;
guint mColumnCount;
public:
GnSQLiteQuery(sqlite3_stmt* pStatement, bool bEof);
virtual ~GnSQLiteQuery();
gint GetFieldDataType(gint iNumColumn);
gint GetIntField(gint iNumColumn);
double GetFloatField(gint iNumColumn);
const gchar* GetStringField(gint iNumColumn);
gint GetFieldIndex(const gchar* szField);
const gchar* GetFieldName(gint iCol);
const gchar* GetFieldDeclType(gint iCol);
void NextRow();
void Finalize();
public:
inline void SetColumnCount(guint uiCount) {
mColumnCount = uiCount;
}
inline guint GetColumnCount() {
return mColumnCount;
}
inline void SetIsEof(bool val) {
mEof = true;
}
inline bool IsEof() {
return mEof;
}
inline bool QueryReturn() {
return ( mpStatement != NULL );
}
};
#endif
|
/*This is a user defined header file which will be included in every source code file as it cotains predefined headers,function prototypes and other statemens*/
#ifndef header_assignment2_h /*This is used to check if the statements in this header file are defined in other files where this header is included */
#define header_assignment2_h //This statement is used to define below statements
#include<iostream>
#include<string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::to_string;
int divisors(); //function prototype with return type int
bool isPerfect(unsigned int); //function prototype with return type bool
#endif/*HEADER_ASSIGNMENT2_H*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.