text
stringlengths 8
6.88M
|
|---|
#include<iostream>
using namespace std;
int board[100][100];
int row,col;
int count=0;
void initboard(int *q,int r,int c)
{
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
*(q+i*c+j)=0;
}
}
}
void display(int *q,int r,int c)
{
cout<<"---------------------------------"<<"\n";
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(*(q+i*c+j)==1)
{
cout<<"K"<<"\t";
}
else
{
cout<<"_"<<"\t";
}
}
cout<<"\n";
}
cout<<"---------------------------------";
cout<<"\n\n";
}
void attack(int *p,int ri,int cj)
{
if(*(p+ri*col+cj)==1)
{
if(ri-2>=0&&ri-2<row&&cj-1<col&&cj-1>=0)
*(p+(ri-2)*col+(cj-1))=-1;
if(ri-1>=0&&ri-1<row&&cj-2<col&&cj-2>=0)
*(p+(ri-1)*col+(cj-2))=-1;
if(ri-2>=0&&ri-2<row&&cj+1<col&&cj+1>=0)
*(p+(ri-2)*col+(cj+1))=-1;
if(ri-1>=0&&ri-1<row&&cj+2<col&&cj+2>=0)
*(p+(ri-1)*col+(cj+2))=-1;
if(ri+1>=0&&ri+1<row&&cj-2<col&&cj-2>=0)
*(p+(ri+1)*col+(cj-2))=-1;
if(ri+2>=0&&ri+2<row&&cj-1<col&&cj-1>=0)
*(p+(ri+2)*col+(cj-1))=-1;
if(ri+2>=0&&ri+2<row&&cj+1<col&&cj+1>=0)
*(p+(ri+2)*col+(cj+1))=-1;
if(ri+1>=0&&ri+1<row&&cj+2<col&&cj+2>=0)
*(p+(ri+1)*col+(cj+2))=-1;
}
}
bool canplace(int *p,int ri,int cj )
{
if( *(p+ri*col+cj)==-1||*(p+ri*col+cj)==1)
return false;
else
return true;
}
void place(int *p,int ri,int cj)
{
*(p+ri*col+cj)=1;
}
void Kknights(int *p,int sti,int stj,int k)
{
if(k==0)
{
++count;
display(p,row,col);
// cout<<count<<"\n";
return;
}
else
{
for(int i=sti;i<row;i++)
{
for(int j=stj;j<col;j++)
{
if(canplace(p,i,j)==true)
{
int newb[row][col];
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
newb[i][j]=*(p+i*col+j);
}
}
place(newb[0],i,j);
attack(newb[0],i,j);
Kknights(newb[0],i,j,k-1);
}
}
stj=0;
}
}
}
int main()
{
int kn;
cout<<"Enter the number of rows and columns"<<"\n";
cin>>row>>col;
cout<<"Enter the number of knights"<<"\n";
cin>>kn;
cout<<"No. of board configurations are:\n";
initboard(board[0],row,col);
Kknights(board[0],0,0,kn);
cout<<count<<"\n";
//display(board[0],row,col);
}
//61412928
|
#ifndef OPAUTOUPDATEPI_H
#define OPAUTOUPDATEPI_H
#ifdef AUTO_UPDATE_SUPPORT
class OpAutoUpdatePI
{
public:
virtual ~OpAutoUpdatePI() {}
static OpAutoUpdatePI* Create();
/*
* Get OS name
*
* Name of the operating system as will be passed to the auto update
* system. It should be of the form as show on the download page
* i.e. http://www.opera.com/download/index.dml?custom=yes
*
* @param os (in/out) Name of the OS
*
* Example of values: FreeBSD, Linux, MacOS, Windows
*
* @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR.
*/
virtual OP_STATUS GetOSName(OpString& os) = 0;
/*
* Get OS version (except *nix)
*
* Version of the operating system as will be passed to the auto update system
*
* @param version (in/out) Name of OS version
*
* Example of values: 10.2, 10.3, 7, 95
*
* @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR.
*/
virtual OP_STATUS GetOSVersion(OpString& version) = 0;
/*
* Get architecture
*
* @param arch (in/out) Name of architecture
*
* Example of values: i386, ppc, sparc, x86-64
*
* @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR.
*/
virtual OP_STATUS GetArchitecture(OpString& arch) = 0;
/*
* Get package type (*nix only)
*
* @param package (in/out) Name of *nix package
*
* Example of values: deb, rpm, tar.gz, tar.bz2, tar.Z, pkg.gz, pkg.bz2, pkg.Z
*
* @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR.
*
* Platforms other than *nix should set the string to empty and return OpStatus::OK.
*/
virtual OP_STATUS GetPackageType(OpString& package) = 0;
/*
* Get gcc version (*nix only)
*
* @param gcc (in/out) GCC version
*
* Example of values: gcc295, gcc3, gcc4
*
* @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR.
*
* Platforms other than *nix should set the string to empty and return OpStatus::OK.
*/
virtual OP_STATUS GetGccVersion(OpString& gcc) = 0;
/*
* Get QT version (*nix only)
*
* @param qt (in/out) QT version
*
* Example of values: qt3-shared, qt3-static, qt4-unbundled, qt4-bundled
*
* @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR.
*
* Platforms other than *nix should set the string to empty and return OpStatus::OK.
*/
virtual OP_STATUS GetQTVersion(OpString& qt) = 0;
/**
* Used on platforms that need to extract files required for
* installation from the downloaded package.
*
* @return AUF_Status.
*/
virtual OP_STATUS ExtractInstallationFiles(uni_char *package) = 0;
/**
* Return TRUE if ExtractInstallationFiles executes any long
* operation in background.
*/
virtual BOOL ExtractionInBackground() = 0;
};
#endif // AUTO_UPDATE_SUPPORT
#endif // OPAUTOUPDATEPI_H
|
#include "Game.h"
#include "DxLib.h"
#include "Peripheral.h"
#include "Scene.h"
#include "TitleScene.h"
#include <memory>
const int screen_x_size = 512;
const int screen_y_size = 480;
Game::Game()
{
screen_size.width = screen_x_size;
screen_size.height = screen_y_size;
}
void Game::operator=(const Game &) const
{
}
Game::~Game()
{
}
float Game::GetObjectScale() const
{
return 2.0f;
}
float Game::GetGravity() const
{
return 0.4f;
}
const Size Game::GetWindowSize() const
{
return screen_size;
}
void Game::Initialize()
{
DxLib::SetGraphMode(screen_x_size, screen_y_size, 32);
DxLib::SetMainWindowText("1701377_高須真樹_Ice Climber");
DxLib::ChangeWindowMode(true);
if (DxLib::DxLib_Init() == -1) {
return;
}
DxLib::SetDrawScreen(DX_SCREEN_BACK);
ChangeScene(new TitleScene());
}
void Game::Run()
{
Peripheral peripheral;
while (ProcessMessage() == 0) {
if (DxLib::CheckHitKey(KEY_INPUT_ESCAPE)) {
break;
}
DxLib::ClsDrawScreen();
//入力情報取得
peripheral.Update();
//シーン更新
_scene->Update(peripheral);
DxLib::ScreenFlip();
}
}
void Game::Terminate()
{
DxLib::DxLib_End();
}
void Game::ChangeScene(Scene * scene)
{
_scene.reset(scene);
}
|
/*
Q. Write class Sales (Salesman_Name,Product_Name,Sales_Quantity,Target).
Each salesman deals with seperate product and is assigned a target for month.
At the end of the month his monthly sales is compared with target and commission is calculated.
- If Sales_Quantity>Target
Commission is 25% of extra sales made + 10% of target
- If Sales_Quantity==Target
Commission is 10% of target
- Other
Commission is 0
Display the salesman information along with commission obtained.
*/
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
class Sales{
private:
char sname[50];
char pname[50];
int sales_quant;
int target;
public:
Sales()
{
strcpy(this->sname,"NA");
strcpy(this->pname,"NA");
this->sales_quant=0;
this->target=0;
}
Sales(char sname[50],char pname[50],int sales_quant,int target)
{
strcpy(this->sname,sname);
strcpy(this->pname,pname);
this->sales_quant = sales_quant;
this->target = target;
}
float commiCalc()
{
float comm=0;
if(this->sales_quant>this->target)
{
int extra = this->sales_quant - this->target;
comm = extra * (0.25);
comm = comm + (this->target * 0.10);
cout<<"Commission Gained::"<<comm<<endl;
}
else if(this->sales_quant==this->target)
{
comm = comm * (this->target * 0.10);
cout<<"Commission Gained::"<<comm<<endl;
}
else
{
cout<<"Commission Gained::"<<comm<<endl;
}
}
void display()
{
cout<<"Sales Man Name::"<<this->sname<<endl;
cout<<"Product Name::"<<this->pname<<endl;
cout<<"Sales Quantity::"<<this->sales_quant<<endl;
cout<<"Target::"<<this->target<<endl;
}
};
int main()
{
int ch;
while(true)
{
cout<<"-------------------------"<<endl;
cout<<"1.Check Commision"<<endl;
cout<<"2.Exit"<<endl;
cout<<"Enter the choice"<<endl;
cin>>ch;
cout<<"---------------------------"<<endl;
switch(ch)
{
case 1:
{
char sname[50],pname[50];
int sales,target;
cout<<"Enter the Sales Man Name:"<<endl;
cin>>sname;
cout<<"Enter the Product Name:"<<endl;
cin>>pname;
cout<<"Enter the Sales Quantity"<<endl;
cin>>sales;
cout<<"Enter the Target Quantity"<<endl;
cin>>target;
Sales obj (sname,pname,sales,target);
obj.display();
obj.commiCalc();
break;
}
case 2:
{
exit(0);
break;
}
default:
{
cout<<"Invalid Choice"<<endl;
}
}
}
return 0;
}
|
//
// texture.h
// Total Control
//
// Created by Parker Lawrence on 8/7/15.
// Copyright (c) 2015 Parker Lawrence. All rights reserved.
//
#ifndef __Total_Control__texture__
#define __Total_Control__texture__
#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include </usr/include/GL/glew.h>
#include "shader.h"
GLuint loadBMP_custom(const char * );
GLuint loadDDS(const char * );
#endif /* defined(__Total_Control__texture__) */
|
//$$---- Form CPP ----
//---------------------------------------------------------------------------
#include <vcl.h>
#include <process.h>
#pragma hdrstop
#include "MainForm.h"
#include "PredStart.h"
#include "ExperimentNotes.h"
#include "BuildProtocol.h"
#include "CalcParams.h"
#include "MinorChannel.h"
#include "RenamOverr.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TPStart *PStart;
IADCDevice *preS_pADC;//указатель на интерфейс драйвера
IADCUtility *preS_pUtil;//указатель на интерфейс драйвера
__int32 timeIncrement;//шаг изменения положения "опорных лини" (время в микросекундах)
float multipler;//множитель для уточнения положения линий
short typeOfExp;//тип эксперимента
//---------------------------------------------------------------------------
__fastcall TPStart::TPStart(TComponent* Owner) : TForm(Owner)
{
//модуль предварительного старта
preRecThread = new TRecordThread(true);//создаём поток эксперимента (приостановленным)
//PStart->closeWin->Tag - управляет прерыванием сбора и функцией кнопки останова-закрытия
//PStart->GetASignal->Tag - задаёт режим старта сбора: пример сигнала или сценарий
//Graphs->CrntSig->Tag - счётчик записанных сигналов (вызванных или спонтанных в режимах №1, 2 и 3)
//PStart->BackTime->Tag - счётчик спонтанных сигналов в режиме №4
//PStart->PausSpontan->Tag - флаг разрешения записи спонтанных в режиме 4
//Graphs->sigNumUpDwn->Tag - максимальное количество сигналов (зарезервировано перед стартом)
//Experiment->DiscontinWrt->Tag - дописывать данные в drr-файл или стереть старые данные
//ExpNotes->addUMark->Tag - количество заметок по ходу эксперимента (всего присутствует на графике)
//ProtoBuild->Periods->Tag - наименьший период между импульсами стимуляции
timeIncrement = 5;//шаг изменения положения "опорных лини" (время в микросекундах
multipler = 1;//множитель для уточнения положения линий
}
//---------------------------------------------------------------------------
void TPStart::PredStartWindow(IADCUtility *p0, IADCDevice *p1, short expType)
{
/*
expType - тип эксперимента
p0 - указатель на интерфейс драйвера
p1 - указатель на интерфейс драйвера
*/
__int32 i;
preS_pUtil = p0; p0 = NULL;//копии ссылок
preS_pADC = p1; p1 = NULL;//копии ссылок
//устанавливаем необходимые параметры кнопок
GetASignal->Enabled = true;//кнопка примера сигнала
StartRec->Enabled = true;//кнопка запуска сбора
ExpInfo->Enabled = true;//кнопка информации об эксперименте
CloseWin->Caption = "Закрыть";//меняем "функцию" кнопки
CloseWin->Tag = 1;//меняем функцию кнопки
//стираем все линии с графика
preTLine->Clear();
postTLine->Clear();
porogLine->Clear();
for (i = 0; i < maxChannels; i++)
exmplChannls[i]->Clear();
ExpNotes->usersNotes->Clear();//затираем записи в блокноте
typeOfExp = expType;//копируем тип эксперимента в глобальную переменную
if (typeOfExp == 1)//спонтанные сигналы
{
PStart->Caption = "Предстарт: Спонтанные";
PreTSel->Position = PreTSel->Min;
PostTSel->Position = PostTSel->Min;
}
else if (typeOfExp == 2)//вызванные (внутриклеточные)
{
PStart->Caption = "Предстарт: Вызванные-ВНУТРИклеточные";
PreTime->Text = "0";//установим в 0 линию preTime, чтобы не мешала
}
else if (typeOfExp == 3)//вызванные (внеклеточные)
PStart->Caption = "Предстарт: Вызванные-ВНЕклеточные";
else if (typeOfExp == 4)//вызванные+спонтанные
PStart->Caption = "Предстарт: Вызванные + Спонтанные";
else//ошибка типа эксперимента
{
Experiment->DevEvents->Text = "ошибка типа эксперимента";
onCloseWin(this);//окно так и не откроется, поэтому закроем все переменные
}
Graphs->Show();//делаем видимым окно графиков
PStart->Show();//открываем окно предстарта
Experiment->DevEvents->Text = "OK";
}
//---------------------------------------------------------------------------
void __fastcall TPStart::StartRecClick(TObject *Sender)
{
//задаём режим записи: 1 - примерный сигнал или 2 - запуск сценария
__int32 i,
lastPnt;//номер последней точки на графике
AnsiString theFileName,//полное имя файла
theDir,//указанная директория
anpth;//системный диск
TDateTime CurrentDateTime;//текущие дата и время
GetASignal->Tag = 2;//выбран запуск сценария
theFileName = Experiment->FilePathName->Text;//записываем новое имя из строки filePathName на главной форме
theDir = ExtractFileDir(theFileName);
//если строка пустая или директория не существует, генерируем случайное имя (по дате и времени)
if ((theFileName.IsEmpty()) || (!DirectoryExists(theDir)))
{
for (i = 0; i < 15; i++)
{
anpth = char(i + 67);//char(67) = "C" - буква системного диска
anpth += ":\\";
if (GetDriveType(anpth.c_str()) == DRIVE_FIXED)//
{
//anpth += "WINDOWS";//сохранение в папку виндоуса
if (DirectoryExists(anpth))
{
anpth.Delete(4, anpth.Length());
break;
}
}
}
CurrentDateTime = Now();//текущие дата и время
theFileName = anpth + "Signal_" + CurrentDateTime.FormatString("yyyy-mm-dd_hh-nn-ss") + "." + Experiment->defltExtPraDrr;
Experiment->FilePathName->Text = theFileName;//отображаем имя файла на главной форме
}
Graphs->SaveDlg->FileName = theFileName;//итоговое имя файла
Experiment->DiscontinWrt->Tag = 0;//указывает какой вариант выбран: 0 - создать заново или 1 - дописать
Graphs->plotFrom = 0;//продолжаем рисовать с этого момента времени
//если данный файл существует, предложим выбрать другой
if (FileExists(Graphs->SaveDlg->FileName.c_str()))
{
ChoosDlg->setsForFileChs();//настраиваем окно диалога для запроса о выборе файла
i = ChoosDlg->ShowModal();
if (i == mrOk)//выбрать другой файл
Experiment->SaveToClick(this);
else if (i == mrYes)//дописать данные в существующий файл
{
Experiment->DiscontinWrt->Tag = 1;//выбрано дописать в существующий файл
lastPnt = Graphs->sigAmpls[0]->XValues->Count() - 1;
if (lastPnt >= 0)
Graphs->plotFrom = Graphs->sigAmpls[0]->XValues->operator [](lastPnt) + 1;//продолжаем рисовать с этого момента времени
}
else if (i == mrIgnore)//сохранить с заменой
Experiment->DiscontinWrt->Tag = 0;//выбрано заменить существующий файл (графики затрутся)
//else if (i == mrCancel)//отменить запуск сценария
}
if (i != mrCancel)//если задание не было отменено
StartOfRecordThread(this);//модуль запуска параллельного потока для записи (сценарий)
}
//---------------------------------------------------------------------------
void __fastcall TPStart::GetASignalClick(TObject *Sender)
{
//задаём режим записи: 1 - примерный сигнал или 2 - запуск сценария
GetASignal->Tag = 1;//выбрано получение примера сигнала
Experiment->DiscontinWrt->Tag = 1;//графики останутся в окнах
StartOfRecordThread(this);//модуль запуска параллельного потока для записи (сценарий)
}
//---------------------------------------------------------------------------
void __fastcall TPStart::StartOfRecordThread(TObject *Sender)
{
//старт потока RecordThread
__int32 i;
AnsiString singlMark;//метка начала блока
bool mOnChn[maxChannels];//привязка меток к каналам
if (!Experiment->InitDevice())//ошибка инициализации
return;
Experiment->DevEvents->Text = "OK";
//перед началом нового эксперимента стираем данные о последнем открытом
Graphs->ClearMemor(this);//удаление всех старых данных из памяти
Graphs->csSpecPoint->Clear();//затираем спец-точки
//информация о текущем сеансе записи
ExpNotes->nmInRec = ExpNotes->addUMark->Tag;//количество меток записанных в предыдущих сеансах сбора данных (дозапись в существующий файл)
ExpNotes->npNewRec = Graphs->sigAmpls[0]->Count();//количество сигналов, записанных в предыдущих сеансах сбора данных (дозапись в существующий файл)
if ((GetASignal->Tag == 2) && (Experiment->DiscontinWrt->Tag == 1))//если выбрано дописать в существующий файл
{
//сразу ставим заметку на первый сигнал в новом блоке
singlMark = "нБ";//метка начала блока //singlMark += IntToStr(nBlocks);//номер блока
for (i = 0; i < maxChannels; i++)//привязываем метку ко всем каналам
mOnChn[i] = true;//привязываем метку ко всем каналам
ExpNotes->AddMarker(singlMark, ExpNotes->npNewRec, &mOnChn[0]);
}
preRecThread->AssignVar(typeOfExp, preS_pUtil, preS_pADC);
CloseWin->SetFocus();//наводим фокус на кнопку остановки эксперимента
preRecThread->Resume();//запускаем приостановленный поток preRecThread
}
//---------------------------------------------------------------------------
void TPStart::PlotStandardSignal(double *sData, __int32 sRecLen, float sEffDT, __int32 sIndBgn)
{
//рисуем быстро эталонный сигнал
/*
sData - массив с графиками
sRecLen - длина сигнала (отсчёты)
sEffDT - эффективное время дискретизации = discrT * chanls
sIndBgn - начальный отсчёт сигнала
*/
__int32 i,
ns1,//первый рисуемый канал
ns2;//последний рисуемый канал
ns1 = Graphs->gRF[0];//первый рисуемый канал
ns2 = Graphs->gRF[1];//последний рисуемый канал
StandardSgnl->AutoRepaint = false;//отключаем автопрорисовку для ускорения процесса рисования
for (i = 0; i < maxChannels; i++)//рисуем указанные каналы
exmplChannls[i]->Clear();//затираем старый график
for (i = ns1; i < ns2; i++)//рисуем указанные каналы
exmplChannls[i]->AddArray(&sData[sIndBgn + ((i - ns1) * sRecLen)], (sRecLen - sIndBgn) - 1);//добавляем новые точки
StandardSgnl->BottomAxis->SetMinMax(0, double((sRecLen - sIndBgn) * sEffDT) / 1000);//устанавливаем пределы горизонтальной оси
StandardSgnl->AutoRepaint = true;//возвращаем автопрорисовку, чтобы график обновился
StandardSgnl->Repaint();//Refresh();//обновляем чарт
sData = NULL;
}
//---------------------------------------------------------------------------
void __fastcall TPStart::AmpPorogSelClick(TObject *Sender, TUDBtnType Button)
{
Porog->Text = IntToStr(AmpPorogSel->Position);
}
//---------------------------------------------------------------------------
void __fastcall TPStart::PreTSelClick(TObject *Sender, TUDBtnType Button)
{
if (PreTSel->Position >= PostTSel->Position)
PreTSel->Position = PostTSel->Position - PostTSel->Increment;
PreTime->Text = IntToStr((__int32)(PreTSel->Position * multipler));
}
//---------------------------------------------------------------------------
void __fastcall TPStart::PostTSelClick(TObject *Sender, TUDBtnType Button)
{
if (PostTSel->Position <= PreTSel->Position)
PostTSel->Position = PreTSel->Position + PreTSel->Increment;
PostTime->Text = IntToStr((__int32)(PostTSel->Position * multipler));
}
//---------------------------------------------------------------------------
void __fastcall TPStart::PreTimeChange(TObject *Sender)
{
//перерисовываем ПРЕ-линию
__int32 i,
preTnow, postTnow;
float loc_max,//максимальное значение на каналах
loc_min;//минимальное значение на каналах
loc_max = exmplChannls[0]->MaxYValue();//максимальное значение на каналах
loc_min = exmplChannls[0]->MinYValue();//максимальное значение на каналах
for (i = 1; i < maxChannels; i++)
{
if (exmplChannls[i]->MaxYValue() > loc_max)
loc_max = exmplChannls[i]->MaxYValue();
if (exmplChannls[i]->MinYValue() < loc_min)
loc_min = exmplChannls[i]->MinYValue();
}
preTnow = StrToInt(PreTime->Text);
postTnow = StrToInt(PostTime->Text);
if (preTnow >= postTnow)
preTnow = postTnow - PostTSel->Increment;
PreTSel->Position = (short)(((float)preTnow) / multipler);
preTLine->Clear();
preTLine->AddXY((((float)(PreTSel->Position) * multipler) - timeOfDrawBgn) / 1000, loc_min);
preTLine->AddXY((((float)(PreTSel->Position) * multipler) - timeOfDrawBgn) / 1000, loc_max);
}
//---------------------------------------------------------------------------
void __fastcall TPStart::PostTimeChange(TObject *Sender)
{
//прерисовываем ПОСТ-линию
__int32 i,
preTnow, postTnow;
float loc_max,//максимальное значение на каналах
loc_min;//минимальное значение на каналах
loc_max = exmplChannls[0]->MaxYValue();//максимальное значение на каналах
loc_min = exmplChannls[0]->MinYValue();//максимальное значение на каналах
for (i = 1; i < maxChannels; i++)
{
if (exmplChannls[i]->MaxYValue() > loc_max)
loc_max = exmplChannls[i]->MaxYValue();
if (exmplChannls[i]->MinYValue() < loc_min)
loc_min = exmplChannls[i]->MinYValue();
}
postTnow = StrToInt(PostTime->Text);
preTnow = StrToInt(PreTime->Text);
if (postTnow <= preTnow)
postTnow = preTnow + PreTSel->Increment;
PostTSel->Position = short((float)postTnow / multipler);
postTLine->Clear();
postTLine->AddXY((((float)(PostTSel->Position) * multipler) - timeOfDrawBgn) / 1000, loc_min);
postTLine->AddXY((((float)(PostTSel->Position) * multipler) - timeOfDrawBgn) / 1000, loc_max);
}
//---------------------------------------------------------------------------
void __fastcall TPStart::PorogChange(TObject *Sender)
{
//меняем положение линии порогового напряжения согласно выставленному значению
__int32 i,
porogSet;
float loc_max,//максимальное значение на каналах
loc_min;//минимальное значение на каналах
loc_max = exmplChannls[0]->MaxYValue();//максимальное значение на каналах
loc_min = exmplChannls[0]->MinYValue();//максимальное значение на каналах
for (i = 1; i < maxChannels; i++)
{
if (exmplChannls[i]->Count() > 0)
{
if (exmplChannls[i]->MaxYValue() > loc_max)//наиден новый максимум
loc_max = exmplChannls[i]->MaxYValue();//новый максимум
if (exmplChannls[i]->MinYValue() < loc_min)//наиден новый минимум
loc_min = exmplChannls[i]->MinYValue();//новый минимум
}
}
porogSet = StrToInt(Porog->Text);//вставляем текст
if (porogSet < AmpPorogSel->Min)//сравниваем с нижним пределом
porogSet = AmpPorogSel->Min;//вставляем текст
if (porogSet > AmpPorogSel->Max)//сравниваем с верхним пределом
porogSet = AmpPorogSel->Max;//вставляем текст
AmpPorogSel->Position = porogSet;//текущее положение линии порога
porogLine->Clear();//затираем линию порога
preTLine->Clear();//затираем вертикальную линию
postTLine->Clear();//затираем вертикальную линию
porogLine->AddXY(0, (AmpPorogSel->Position));//рисуем линию порога
porogLine->AddXY(((float(PostTSel->Max) * multipler) - timeOfDrawBgn) / 1000, AmpPorogSel->Position);//рисуем линию порога
preTLine->AddXY(((float(PreTSel->Position) * multipler) - timeOfDrawBgn) / 1000, loc_min);//рисуем вертикальную линию
preTLine->AddXY(((float(PreTSel->Position) * multipler) - timeOfDrawBgn) / 1000, loc_max);//рисуем вертикальную линию
postTLine->AddXY(((float(PostTSel->Position) * multipler) - timeOfDrawBgn) / 1000, loc_min);//рисуем вертикальную линию
postTLine->AddXY(((float(PostTSel->Position) * multipler) - timeOfDrawBgn) / 1000, loc_max);//рисуем вертикальную линию
}
//---------------------------------------------------------------------------
void TPStart::RefreshLines(float rlEffDT)
{
//обновление линий, разделяющих различные фазы сигналов
/*
rlEffDT - эффективное время дискретизации = discrT * chanls
*/
__int32 i;
//множитель multipler нужен для преодоления узости интервала изменения параметра position в UpDown
PreTSel->Min = 0;
PostTSel->Min = 0;
if ((PStart->exmplChannls[0]->Count() * rlEffDT) > 32000)
{
PreTSel->Max = 32000;//в микросекундах
PostTSel->Max = 32000;//в микросекундах
multipler = (float)(PStart->exmplChannls[0]->Count() * rlEffDT) / 32000;//множитель для уточнения положения линий
}
else
{
PreTSel->Max = PStart->exmplChannls[0]->Count() * rlEffDT;//в микросекундах
PostTSel->Max = PStart->exmplChannls[0]->Count() * rlEffDT;//в микросекундах
multipler = 1;//множитель для уточнения положения линий
}
PreTSel->Increment = timeIncrement;
PostTSel->Increment = timeIncrement;
PorogChange(this);
}
//---------------------------------------------------------------------------
void __fastcall TPStart::ExpInfoClick(TObject *Sender)
{
//вызываем окно для записи информации об эксперименте
//настроим элементы окна
ExpNotes->mainLinesLbl->Caption = "Общие сведения об эксперименте";
ExpNotes->usersNotes->Visible = true;//поле для пользовательских данных
ExpNotes->addUMark->Visible = true;//поле ввода заметок по ходу эксперимента
ExpNotes->addMarkLbl->Visible = true;//заметки-лэйбл
ExpNotes->PIDates->Visible = false;//поле данных о файле
ExpNotes->Show();
}
//---------------------------------------------------------------------------
void __fastcall TPStart::SignalLenChange(TObject *Sender)
{
//проверяем можно ли принять запрашиваемую длину вызванного сигнала
__int32 sLen;//длина вызванного сигнала
sLen = StrToInt(SignalLen->Text);//длина вызванного сигнала
if (Experiment->DiscontinWrt->Checked)//выбрана прямая запись на диск
{
//ProtoBuild->Periods->Tag - наименьший период между импульсами стимуляции
if ((ProtoBuild->Periods->Tag - sLen) < minFreeTime)//слишком короткий интервал между сигналами
{
SignalLen->Text = IntToStr(sLen - 1);//уменьшаем длину сигнала
return;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TPStart::LenSpontChange(TObject *Sender)
{
//проверяем можно ли принять запрашиваемую длину спонтанного сигнала
__int32 backTimLen,//время назад для спонтанного сигнала
sLen;//полная длина записываемого сигнала (миллисекунды)
sLen = StrToInt(LenSpont->Text);//длина сигнала в миллисекундах
backTimLen = StrToInt(BackTime->Text);//время назад для спонтанного сигнала
//вводим ограничение на длину записываемого сигнала
if (sLen > limitSigLen)//длина сигнала должна быть меньше
{
LenSpont->Text = IntToStr(limitSigLen);//ограничение длины сигнала
return;
}
if (sLen < 1)//если введено нулевое или отрицательное число
{
LenSpont->Text = "1";//вставляем минимальное время
return;
}
if (sLen < backTimLen)//если длина сигнала меньше времи назад
{
LenSpont->Text = IntToStr(backTimLen + 1);//делаем длину сигнала больше времени назад
return;
}
}
//---------------------------------------------------------------------------
void __fastcall TPStart::BackTimeChange(TObject *Sender)
{
//проверяем можно ли принять запрашиваемое время назад
__int32 spntBackLen,//время назад для спонтанного сигнала
sLen;//полная длина записываемого сигнала (миллисекунды)
spntBackLen = StrToInt(BackTime->Text);
sLen = StrToInt(LenSpont->Text);//полная длина сигнала
if (spntBackLen < 1)//если введено нулевое или отрицательное число
{
BackTime->Text = "1";//вставляем минимальное время
return;
}
if (spntBackLen > sLen)//если время назад превышает длину сигнала
{
BackTime->Text = IntToStr(sLen - 1);//делаем время назад на одну миллисекунду короче длины сигнала
return;
}
}
//---------------------------------------------------------------------------
void __fastcall TPStart::InvertClick(TObject *Sender)
{
Graphs->ReplotExamplRecalc();//вызываем функцию перерисовки сигнала в инвертированном виде
}
//---------------------------------------------------------------------------
void __fastcall TPStart::OffLineInvert(TObject *Sender)
{
//инвертирование в режиме "Постобработки"
postCompInvert = 1 - (2 * (short(Invert->Checked)));//новое состояние флага инвертирования
TimeBarChange(this);//рисуем сигнал заново
}
//---------------------------------------------------------------------------
void __fastcall TPStart::ReCalClick(TObject * Sender)
{
PStart->ModalResult = mrOk;//нажата кнопка пересчёта или начала поиска сигналов
}
//---------------------------------------------------------------------------
void __fastcall TPStart::CloseWinClick(TObject *Sender)
{
if (CloseWin->Tag == 1)
PStart->Close();//закрываем окном
else
CloseWin->Tag = 1;//меняем функцию кнопки
}
//---------------------------------------------------------------------------
void __fastcall TPStart::NextBlockClick(TObject *Sender)
{
NextBlock->Tag = 1;//при нажатии на кнопку "сл. блок" происходит переход к следующему блоку протокола
}
//---------------------------------------------------------------------------
void __fastcall TPStart::onCloseWin(TObject *Sender)
{
//закрываем окно
if (preS_pUtil != NULL)
preS_pUtil = NULL;
else if (preS_pADC != NULL)
preS_pADC = NULL;
//сохраняем параметры
Experiment->progPrms[2] = StrToInt(PStart->LenSpont->Text);//2 - длина спонтанного сигнала
Experiment->progPrms[3] = StrToInt(PStart->Porog->Text);//3 - порог детекции
Experiment->progPrms[4] = StrToInt(PStart->BackTime->Text);//4 - время назад
Experiment->progPrms[5] = StrToInt(PStart->SignalLen->Text);//5 - длина сигнала
}
//---------------------------------------------------------------------------
void __fastcall TPStart::PausSpontanClick(TObject *Sender)
{
//приостановка или продолжение записи спонтанных сигналов в режиме №4
//если pausMini->Tag == 0, то продолжаем запись спонтанных сигналов
//если pausMini->Tag == 1, то приостанавливаем
if (PausSpontan->Tag == 0)
{
PausSpontan->Tag = 1;//ставим на паузу
PausSpontan->Caption = "старт спнт";
}
else//pausMini->Tag == 1
{
PausSpontan->Tag = 0;//продолжаем запись
PausSpontan->Caption = "пауза спнт";
}
}
//---------------------------------------------------------------------------
void __fastcall TPStart::StandardSgnlMouseDown(TObject *Sender, TMouseButton Button,
TShiftState Shift, int X, int Y)
{
//при нажатии правой кнопки мышки определяем, какая линия ближе к точке
//нажатия, и двигем её в эту точку
__int32 chMDexpType,//тип эксперимента
b,//х-расстояние между ПРЕ-линией и точкой щелчка
c;//х-расстояние между ПОСТ-линией и точкой щелчка
double xX;
chMDexpType = Graphs->ReCalculat->Tag;//тип эксперимента
if (Button == 1)//если нажата правая кнопка мышки
{
b = preTLine->CalcXPosValue(preTLine->XValues->operator [](0)) - X;
b = b * b;//вместо abs
c = postTLine->CalcXPosValue(postTLine->XValues->operator [](0)) - X;
c = c * c;//вместо abs
if ((b < c) && (chMDexpType == 3))
{
xX = preTLine->XScreenToValue(X);//можно взять любой Series
PreTime->Text = IntToStr((__int32)(floor(xX * 1000) + timeOfDrawBgn));
}
else
{
xX = postTLine->XScreenToValue(X);//можно взять любой Series
PostTime->Text = IntToStr((__int32)(floor(xX * 1000) + timeOfDrawBgn));
}
}
}
//---------------------------------------------------------------------------
void __fastcall TPStart::CheckForKeyPStartEdits(TObject *Sender, char &Key)
{
//проверка допустимости введения символа, соответствующего нажатой клавише
//для остальных полей ввода числовых данных
if (((Key < '0') || (Key > '9')) && (Key != '\b'))//проверим допустимость введённых символов
Key = '\0';//зануляем некорректный символ
}
//---------------------------------------------------------------------------
void __fastcall TPStart::CheckForKeyPPorogEdit(TObject *Sender, char &Key)
{
//проверка допустимости введения символа, соответствующего нажатой клавише
//для поля амплитудного порога для сигналов
if (((Key < '0') || (Key > '9')) && (Key != '\b') && (Key != '-'))//проверим допустимость введённых символов
Key = '\0';//зануляем некорректный символ
}
//---------------------------------------------------------------------------
void TPStart::SetControlVis(short expType)
{
//устанавливаем видимость контролов в зависимости от типа эксперимента
/*
expType - тип эксперимента
*/
if (expType == 1)//спонтанные сигнал
{
SignalLen->Visible = false;//выбора длины вызванного сигнала
SLenLbl1->Visible = false;//длина вызванного сигнал (лэйбл 1)
SLenLbl2->Visible = false;//длина вызванного сигнал (лэйбл 2)
SLenLbl3->Visible = false;//длина вызванного сигнал (лэйбл 3)
LenSpont->Visible = true;//выбор длины спонтанного сигнала
LenSpntLbl1->Visible = true;//длина спонтанного сигнала (лэйбл 1)
LenSpntLbl2->Visible = true;//длина спонтанного сигнала (лэйбл 2)
LenSpntLbl3->Visible = true;//длина спонтанного сигнала (лэйбл 3)
BackTime->Visible = true;//выбор времени назад
BckTmLbl1->Visible = true;//временя назад (лэйбл 1)
BckTmLbl2->Visible = true;//временя назад (лэйбл 2)
BckTmLbl3->Visible = true;//временя назад (лэйбл 3)
PreTime->Visible = false;//выбор пре-времени (эдитор)
PreTSel->Visible = false;//выбор пре-времени (кнопки)
PreTimeLbl->Visible = false;//пре-время (лэйбл)
PostTime->Visible = false;//выбор пост-времени (эдитор)
PostTSel->Visible = false;//выбор пост-времени (кнопки)
PostTimeLbl->Visible = false;//пост-времени (лэйбл)
PausSpontan->Visible = false;//кнопка паузы сбора спонтанных сигналов в режиме №4
}
else if ((expType == 2) || (expType == 3))//вызванные сигналы (внутри- или внеклеточные)
{
SignalLen->Visible = true;//выбора длины вызванного сигнала
SLenLbl1->Visible = true;//длина вызванного сигнал (лэйбл 1)
SLenLbl2->Visible = true;//длина вызванного сигнал (лэйбл 2)
SLenLbl3->Visible = true;//длина вызванного сигнал (лэйбл 3)
LenSpont->Visible = false;//выбор длины спонтанного сигнала
LenSpntLbl1->Visible = false;//длина спонтанного сигнала (лэйбл 1)
LenSpntLbl2->Visible = false;//длина спонтанного сигнала (лэйбл 2)
LenSpntLbl3->Visible = false;//длина спонтанного сигнала (лэйбл 3)
BackTime->Visible = false;//выбор времени назад
BckTmLbl1->Visible = false;//временя назад (лэйбл 1)
BckTmLbl2->Visible = false;//временя назад (лэйбл 2)
BckTmLbl3->Visible = false;//временя назад (лэйбл 3)
PreTime->Visible = (expType == 3);//выбор пре-времени (эдитор)
PreTSel->Visible = (expType == 3);//выбор пре-времени (кнопки)
PreTimeLbl->Visible = (expType == 3);//пре-время (лэйбл)
PostTime->Visible = true;//выбор пост-времени (эдитор)
PostTSel->Visible = true;//выбор пост-времени (кнопки)
PostTimeLbl->Visible = true;//пост-времени (лэйбл)
PausSpontan->Visible = false;//кнопка паузы сбора спонтанных сигналов в режиме №4
}
else if (expType == 4)//вызванные + спонтанные
{
SignalLen->Visible = true;//выбора длины вызванного сигнала
SLenLbl1->Visible = true;//длина вызванного сигнал (лэйбл 1)
SLenLbl2->Visible = true;//длина вызванного сигнал (лэйбл 2)
SLenLbl3->Visible = true;//длина вызванного сигнал (лэйбл 3)
LenSpont->Visible = true;//выбор длины спонтанного сигнала
LenSpntLbl1->Visible = true;//длина спонтанного сигнала (лэйбл 1)
LenSpntLbl2->Visible = true;//длина спонтанного сигнала (лэйбл 2)
LenSpntLbl3->Visible = true;//длина спонтанного сигнала (лэйбл 3)
BackTime->Visible = true;//выбор времени назад
BckTmLbl1->Visible = true;//временя назад (лэйбл 1)
BckTmLbl2->Visible = true;//временя назад (лэйбл 2)
BckTmLbl3->Visible = true;//временя назад (лэйбл 3)
PreTime->Visible = false;//выбор пре-времени (эдитор)
PreTSel->Visible = false;//выбор пре-времени (кнопки)
PreTimeLbl->Visible = false;//пре-время (лэйбл)
PostTime->Visible = true;//выбор пост-времени (эдитор)
PostTSel->Visible = true;//выбор пост-времени (кнопки)
PostTimeLbl->Visible = true;//пост-времени (лэйбл)
PausSpontan->Visible = true;//кнопка приостановки сбора спонтанных сигналов
}
else
Experiment->DevEvents->Text = "Ошибка типа эксперимента";//сообщение об ошибке
}
//---------------------------------------------------------------------------
__int32 TPStart::winDraw(__int32 samplPerCh)
{
//вызываем окно предстарта для рисования ранее записанного сигнала
/*
samplPerCh - количество отсчётов на один канал
*/
__int32 i;
//устанавливаем необходимые параметры кнопок
StartRec->Enabled = true;//кнопка старта
CloseWin->Caption = "Закрыть";//меняем "функцию" кнопки
CloseWin->Tag = 1;//меняем функцию кнопки
//стираем все линии с графика
preTLine->Clear();
postTLine->Clear();
porogLine->Clear();
ExpNotes->usersNotes->Clear();//затираем записи в блокноте
PStart->Caption = "Постобработка";//режим работы
SetControlVis(1);//делаем видимыми нужные органы управления и убираем ненужные
GetASignal->Visible = false;//кнопка пример сигнала
ExpInfo->Visible = false;//кнопка пример сигнала
StartRec->OnClick = ReCalClick;//меняем реакцию на нажатие
postCompInvert = 1 - (2 * (short(Invert->Checked)));//текущее состояние флага инвертирования
Invert->OnClick = OffLineInvert;//изменение реакции на смену индикатора
TimeScaleBar->Max = 5e4;//максимальная длина окна (миллисекунды)
TimeScaleBar->Min = 500;//минимальная длина окна (миллисекунды)
TimeScaleBar->PageSize = 50;//шаг изменения длины окна (миллисекунды)
TimeScaleBar->Position = 500;//начальная длина окна (миллисекунды)
TimeScaleBar->Visible = true;//делаем контрол видимым
TimeBar->Max = (samplPerCh * Graphs->effDT * 1e-3) - TimeScaleBar->Position;//максимальное начальное время рисования (миллисекунды)
TimeBar->Min = 0;//минимальное начальное время рисования (миллисекунды)
TimeBar->PageSize = 1e3;//шаг изменения длины окна (миллисекунды)
TimeBar->Position = 0;//начальное время рисования (миллисекунды)
TimeBar->Visible = true;//делаем контрол видимым
PostTSel->Max = 32000;//левый край графика
PreTSel->Position = 0;//убираем вертикальные линии
PostTSel->Position = 0;//убираем вертикальные линии
multipler = (float)(exmplChannls[0]->Count() * Graphs->effDT) / 32000;//множитель для уточнения положения линий
AmpPorogSel->Max = short(Experiment->maxADCAmp * Graphs->sampl2mV);//милливольты
AmpPorogSel->Min = (-1) * AmpPorogSel->Max;//милливольты
AmpPorogSel->Increment = (AmpPorogSel->Max / 1000) + (__int32(AmpPorogSel->Max <= 1000));//делим диапазон на 1000 шагов
TimeBarChange(this);//рисование начального участка
Graphs->Show();//делаем видимым окно графиков
i = PStart->ShowModal();//открываем окно предстарта
GetASignal->Visible = true;//кнопка пример сигнала
ExpInfo->Visible = true;//кнопка пример сигнала
StartRec->OnClick = StartRecClick;//восстанавливаем реакцию на нажатие
Invert->OnClick = NULL;//изменение реакции на смену индикатора
TimeScaleBar->Visible = false;
TimeBar->Visible = false;
return i;//возвращаем код команды ("отмена" или "принять")
}
//---------------------------------------------------------------------------
void __fastcall TPStart::TimeBarChange(TObject *Sender)
{
//реакция на изменение масштаба или времени
__int32 i, j,
startInd,//начальный отсчёт
windowLen;//длина окна рисования (отсчёты)
float eff_dt,//эффективное время дискретизации = discrT * chanls (миллисекунды)
sampl2mV;//коэффициент пересчёта отсчётов в милливольты
double *grafik;//массив с куском записи
eff_dt = Graphs->effDT * 1e-3;//эффективное время дискретизации = discrT * chanls (миллисекунды)
startInd = floor(TimeBar->Position / eff_dt);//начальный отсчёт
windowLen = floor(TimeScaleBar->Position / eff_dt);//длина окна рисоания (отсчёты)
sampl2mV = Graphs->sampl2mV;//коэффициент пересчёта отсчётов в милливольты
grafik = new double[windowLen * Graphs->chanls];//массив с куском записи
for (i = 0; i < Graphs->chanls; i++)//рисуем указанные каналы
for (j = 0; j < windowLen; j++)
grafik[(i * windowLen) + j] = (postCompInvert * continRec[i][startInd + j]) * sampl2mV;
//PlotStandardSignal(double *sData, __int32 sRecLen, float sEffDT, __int32 sIndBgn)
PlotStandardSignal(grafik, windowLen, Graphs->effDT, 0);
multipler = (float(exmplChannls[0]->Count() * Graphs->effDT)) / 32000;//множитель для уточнения положения линий
PorogChange(this);//перерисуем линии
delete[] grafik; grafik = NULL;
}
//---------------------------------------------------------------------------
void __fastcall TPStart::FormActivate(TObject *Sender)
{
//после окончания создания окна предстарта применяем файл настроек
//если существовал файл настроек SetsElph.ini, возьмём из него данные
PStart->LenSpont->Text = IntToStr(Experiment->progPrms[2]);//длина спонтанного сигнала
PStart->Porog->Text = IntToStr(Experiment->progPrms[3]);//порог
PStart->BackTime->Text = IntToStr(Experiment->progPrms[4]);//время назад
PStart->SignalLen->Text = IntToStr(Experiment->progPrms[5]);//длина вызванного сигнала
PStart->Top = Experiment->progPrms[13];//верх окна
PStart->Left = Experiment->progPrms[14];//левый край окна
PStart->OnActivate = NULL;//отключаем реагирование главной формы на "активацию"
}
//---------------------------------------------------------------------------
|
/*
* main.cpp - Terrain Scene 02564_Framework
*
* Created by J. Andreas Bærentzen on 01/02/10.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#define SOLUTION_CODE
#include <iostream>
#include <QApplication>
#include <QTimer>
#include <QTime>
#include <QDebug>
#include <QMouseEvent>
#include <CGLA/Mat4x4f.h>
#include <CGLA/Vec3f.h>
#include <CGLA/Vec2f.h>
#include <GLGraphics/GLHeader.h>
#include <GLGraphics/ShaderProgram.h>
#include <GLGraphics/ThreeDObject.h>
#include <GLGraphics/User.h>
#include "ShadowBuffer.h"
#include "auxil.h"
#include "lsys.h"
#include "Terrain.h"
#include "VoxelWorld.h"
#include "TerrainScene.h"
#include "cubemapbuffer.h"
using namespace std;
using namespace CGLA;
using namespace GLGraphics;
void TerrainScene::draw_screen_aligned_quad(ShaderProgram& shader_prog)
{
const Vec2f points[] = {Vec2f(-1,-1), Vec2f(1,-1), Vec2f(-1,1), Vec2f(1,1)};
GLuint pos_attrib = shader_prog.get_attrib_location("vertex");
static GLuint VAO = 0;
if(VAO == 0)
{
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER,4*sizeof(Vec2f),&points[0],GL_STATIC_DRAW);
glVertexAttribPointer(pos_attrib,2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(pos_attrib);
}
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLE_STRIP,0,4);
}
void TerrainScene::draw_ocean(ShaderProgram& shader_prog)
{
GLuint pos_attrib = shader_prog.get_attrib_location("vertex");
static GLuint VAO = 0;
if(VAO == 0)
{
const Vec3f points[] = {Vec3f(-1024,-1024,0) + map_center, Vec3f(1024,-1024,0) + map_center,
Vec3f(-1024,1024,0) + map_center, Vec3f(1024,1024,0) + map_center};
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER,4*sizeof(Vec3f),&points[0],GL_STATIC_DRAW);
glVertexAttribPointer(pos_attrib,3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(pos_attrib);
}
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLE_STRIP,0,4);
}
void TerrainScene::draw_objects(ShaderProgramDraw& shader_prog, const GLGraphics::HeightMap&)
{
auto f = [&](const Vec2f &map_center_offset, float height_offset)
{
Vec3f plane_pos_abs = map_center + Vec3f(map_center_offset[0],map_center_offset[1],64.0f);
return Vec3f(plane_pos_abs[0], plane_pos_abs[1], terrain.height(plane_pos_abs) + height_offset);
};
static vector<ThreeDObject> objects;
if(objects.empty())
{
objects.push_back(ThreeDObject());
objects[objects.size()-1].init(objects_path+"cottage_obj/cottage.obj");
objects.back().scale(Vec3f(1));
objects.back().translate(f(Vec2f(-16.0f, +14.0f), 0.0f));
objects.push_back(ThreeDObject());
objects[objects.size()-1].init(objects_path+"cow.obj");
objects.back().scale(Vec3f(.5));
objects.back().rotate(Vec3f(1,0,0), 90);
objects.back().translate(f(Vec2f(-6.0f, -14.0f), 1.6f));
objects.push_back(ThreeDObject());
objects[objects.size()-1].init(objects_path+"portal.obj");
objects.back().scale(Vec3f(2));
objects.back().translate(f(Vec2f(-20.0f, 0.0f), 1.0f));
}
for(int i=0;i<objects.size();++i)
objects[i].display(shader_prog);
}
/*
void TerrainScene::draw_trees(ShaderProgramDraw& shader_prog, const GLGraphics::HeightMap& terra)
{
static GLint count;
static GLuint vao = make_tree(count);
Vec3f trans(200,200,200);
trans[2] = terra.height(trans);
shader_prog.set_model_matrix(translation_Mat4x4f(trans) *scaling_Mat4x4f(Vec3f(0.010f)));
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES,0, count);
glBindVertexArray(0);
}
*/
void TerrainScene::draw_trees(ShaderProgramDraw& shader_prog, const GLGraphics::HeightMap& terra)
{
const int N = 100;
static GLint count;
static GLuint vao = make_tree(count);
static Mat4x4f M[N];
static Vec4f mat_diff[N];
static bool was_here = false;
if(!was_here) {
was_here = true;
for(int i=0;i<N;++i) {
Vec3f p(198.0 + (rand() / float(RAND_MAX))*100.0, 198.0 + rand() / (float(RAND_MAX))*100.0,rand() / (float(RAND_MAX))*100); // Set p to some random position.
p[2] = terra.height(p);
M[i] = transpose(translation_Mat4x4f(p)*scaling_Mat4x4f(Vec3f(max(0.01, (rand() / float(RAND_MAX))*0.05))));
// Multiply a random scaling and a rotation on to M[i]
mat_diff[i] = Vec4f(rand() / (float(RAND_MAX)),rand() / (float(RAND_MAX)), rand() / (float(RAND_MAX)),0); // make this guy random too.
}
}
shader_prog.set_model_matrix(identity_Mat4x4f());
glBindVertexArray(vao);
for(int i=0;i<100;++i) {
glUniformMatrix4fv(shader_prog.get_uniform_location("InstanceMatrix"), 1, GL_FALSE,(const GLfloat*) &M[i]);
glUniform4fv(shader_prog.get_uniform_location("mat_diff"),1, (const GLfloat*) &mat_diff[i]);
glDrawArrays(GL_TRIANGLE_STRIP,0, count);
}
}
void TerrainScene::set_light_and_camera(ShaderProgramDraw& shader_prog)
{
shader_prog.set_projection_matrix(perspective_Mat4x4f(55.0f, float(window_width)/window_height, 0.4f, 800));
shader_prog.set_view_matrix(user.get_view_matrix());
directional_light.set_in_shader(shader_prog);
}
void TerrainScene::render_direct(bool reload)
{
// Load shaders for terrain and general objects. The terrain color is computed
// procedurally, so we need a different shader.
static ShaderProgramDraw terrain_shader(shader_path, "terrain.vert", "", "terrain.frag");
static ShaderProgramDraw object_shader(shader_path, "object.vert", "", "object.frag");
static ShaderProgramDraw ocean_shader(shader_path, "ocean.vert", "", "ocean.frag");
static ShaderProgramDraw tree_shader(shader_path, "tree.vert", "", "tree.frag");
if(reload)
{
directional_light = default_light;
ocean_shader.reload();
terrain_shader.reload();
object_shader.reload();
tree_shader.reload();
}
glClearColor(0.4f,0.35f,0.95f,0.0f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
terrain_shader.use();
set_light_and_camera(terrain_shader);
terrain.draw(terrain_shader);
object_shader.use();
set_light_and_camera(object_shader);
draw_objects(object_shader, terrain);
tree_shader.use();
set_light_and_camera(tree_shader);
draw_trees(tree_shader, terrain);
ocean_shader.use();
set_light_and_camera(ocean_shader);
draw_ocean(ocean_shader);
}
void TerrainScene::render_direct_wireframe(bool reload)
{
// Create shader program. Note that this is the only program which has
// a geometry shader. Also there is only one shader in this function since
// all geometry is treated in the same way.
static ShaderProgramDraw wire_shader(shader_path, "wire.vert", "wire.geom", "wire.frag");
if(reload)
wire_shader.reload();
glClearColor(0.9f,0.9f,0.9f,0.0f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
wire_shader.use();
set_light_and_camera(wire_shader);
Vec2f win_scale = Vec2f(window_width/2.0, window_height/2.0);
wire_shader.set_uniform("WIN_SCALE", win_scale);
terrain.draw(wire_shader);
draw_objects(wire_shader, terrain);
draw_trees(wire_shader, terrain);
}
void TerrainScene::render_to_gbuffer(GBuffer& gbuffer, bool reload)
{
static ShaderProgramDraw objects_render_to_gbuffer(shader_path, "objects_gbuffer.vert", "", "objects_gbuffer.frag");
static ShaderProgramDraw terrain_render_to_gbuffer(shader_path, "terrain_gbuffer.vert", "", "terrain_gbuffer.frag");
if(reload)
{
objects_render_to_gbuffer.reload();
terrain_render_to_gbuffer.reload();
}
gbuffer.enable();
terrain_render_to_gbuffer.use();
set_light_and_camera(terrain_render_to_gbuffer);
terrain.draw(terrain_render_to_gbuffer);
objects_render_to_gbuffer.use();
set_light_and_camera(objects_render_to_gbuffer);
draw_objects(objects_render_to_gbuffer, terrain);
draw_trees(objects_render_to_gbuffer, terrain);
}
void TerrainScene::render_deferred_toon(bool reload)
{
// Initialize resources. Note that we have a G-Buffer here. This buffer captures eye
// space position, normal, and color for each pixel. We then do deferred shading based
// on that.
static GBuffer gbuffer(window_width, window_height);
static ShaderProgramDraw deferred_shading(shader_path, "deferred.vert", "", "deferred_toon.frag");
gbuffer.rebuild_on_resize(window_width, window_height);
if(reload)
{
directional_light = default_light;
deferred_shading.reload();
}
render_to_gbuffer(gbuffer, reload);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glDrawBuffer(GL_BACK);
glDisable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT);
deferred_shading.use();
set_light_and_camera(deferred_shading);
gbuffer.bind_textures(0, 1, 2);
deferred_shading.set_uniform("gtex", 0);
deferred_shading.set_uniform("ntex", 1);
deferred_shading.set_uniform("ctex", 2);
draw_screen_aligned_quad(deferred_shading);
glEnable(GL_DEPTH_TEST);
}
void TerrainScene::render_deferred_ssao(bool reload)
{
const int NO_DISC_POINTS = 32;
const int SHADOW_SIZE = 4096;
// Create all resources.
static GLuint ssao_tex, fbo;
static vector<Vec3f> disc_points;
static GBuffer gbuffer(window_width, window_height);
gbuffer.rebuild_on_resize(window_width, window_height);
static ShaderProgramDraw deferred_ssao(shader_path, "deferred.vert", "", "deferred_ssao.frag");
static ShaderProgramDraw deferred_combination(shader_path, "deferred.vert", "", "deferred_ssao_combination.frag");
static ShaderProgramDraw render_to_shadow_map(shader_path, "shadow.vert", "", "shadow.frag");
static ShadowBuffer shadow_buffer(SHADOW_SIZE);
const int MMW=window_width/2;
const int MMH=window_height/2;
// Reinitialize all shaders and buffers if reload = true
if(reload)
{
directional_light = default_light;
gbuffer.initialize(window_width, window_height);
deferred_ssao.reload();
deferred_combination.reload();
render_to_shadow_map.reload();
shadow_buffer.initialize();
}
// If reload=true or we are here first time, reinitialize the FBO for SSAO computation.
static bool was_here = false;
if(reload || !was_here)
{
was_here = true;
glGenTextures(1, &ssao_tex);
glBindTexture(GL_TEXTURE_RECTANGLE, ssao_tex);
glTexParameterf(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGBA16F, MMW, MMH, 0, GL_RGBA, GL_FLOAT, 0);
glGenFramebuffers(1,&fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE, ssao_tex, 0);
if(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
cout << "Something wrong with FBO" << endl;
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
// Also: Create a bunch of vectors for hemisphere sampling.
gel_srand(0);
disc_points.clear();
for(int i=0;i<NO_DISC_POINTS;++i)
{
float alpha = 2.0 * M_PI * i / float(NO_DISC_POINTS) - M_PI;
Vec3f v(cos(alpha),sin(alpha),0);
v*= gel_rand()/float(GEL_RAND_MAX);
disc_points.push_back(v);
}
}
// Enable shadow buffer and the program for drawing to shadow buffer
shadow_buffer.enable();
render_to_shadow_map.use();
// Set up a modelview matrix suitable for shadow: Maps from world coords to
// shadow buffer coords.
Vec3f v = Vec3f(directional_light.direction);
render_to_shadow_map.set_view_matrix(lookat_Mat4x4f(map_center,-v,Vec3f(0,0,1)));
render_to_shadow_map.set_model_matrix(identity_Mat4x4f());
render_to_shadow_map.set_projection_matrix(ortho_Mat4x4f(Vec3f(-300,-300,-100),Vec3f(300,300,400)));
// Switch viewport size to that of shadow buffer.
glViewport(0, 0, SHADOW_SIZE, SHADOW_SIZE);
glClearColor(0,1,0,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Draw to shadow buffer.
terrain.draw(render_to_shadow_map);
draw_objects(render_to_shadow_map, terrain);
draw_trees(render_to_shadow_map, terrain);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glDrawBuffer(GL_BACK);
// We need to reset the viewport, since the shadow buffer does not have
// the same size as the screen window.
glViewport(0, 0, window_width, window_height);
// Enable GBuffer and render to GBuffer
render_to_gbuffer(gbuffer, reload);
// Entering deferred rendering, so disable depth test
glDisable(GL_DEPTH_TEST);
// Bind the FBO that we render to in the first pass where we compute the SSAO contribution
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
// We need to change the viewport since we render SSAO to smaller buffer.
glViewport(0, 0, MMW, MMH);
glClear(GL_COLOR_BUFFER_BIT);
deferred_ssao.use();
// Bind the GBuffer, assign uniforms including the hemisphere direction vectors.
gbuffer.bind_textures(0, 1, 2);
deferred_ssao.set_uniform("gtex", 0);
deferred_ssao.set_uniform("ntex", 1);
deferred_ssao.set_uniform("ctex", 2);
glUniform3fv(deferred_ssao.get_uniform_location("disc_points"),NO_DISC_POINTS,
reinterpret_cast<float*>(&disc_points[0]));
deferred_ssao.set_uniform("NO_DISC_POINTS",NO_DISC_POINTS);
Vec2f windowDimension(window_width, window_height);
deferred_ssao.set_uniform("win_dim", windowDimension);
//Bind shadow buffer texture
shadow_buffer.bind_textures(3);
deferred_ssao.set_uniform("shadow_map", 3);
// Tricky stuff: Create an inverse of the modelview matrix to (later) be able
// to go from the GBuffer coordinates (eye space) to world coordinates. We multiply
// this inverse onto the matrix created above in order to go directly from eye space
// to shadow buffer space.
Mat4x4f mat = translation_Mat4x4f(Vec3f(0.5));
mat *= scaling_Mat4x4f(Vec3f(0.5));
mat *= render_to_shadow_map.get_projection_matrix();
mat *= render_to_shadow_map.get_view_matrix();
mat *= invert(user.get_view_matrix());
deferred_ssao.set_uniform("Mat", mat);
// Draw quad to render SSAO computation
draw_screen_aligned_quad(deferred_ssao);
// Bind regular on-screen framebuffer.
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
// Bind program for combining SSAO and other shading.
deferred_combination.use();
set_light_and_camera(deferred_combination);
// Bind texture resources, and assign uniforms
gbuffer.bind_textures(0, 1, 2);
deferred_combination.set_uniform("gtex", 0);
deferred_combination.set_uniform("ntex", 1);
deferred_combination.set_uniform("ctex", 2);
deferred_combination.use_texture(GL_TEXTURE_RECTANGLE, "ssao_tex", ssao_tex, 3);
shadow_buffer.bind_textures(4);
deferred_combination.set_uniform("shadow_map", 4);
deferred_combination.set_uniform("Mat", mat);
// Go back to right viewport size
glViewport(0, 0, window_width, window_height);
// Draw quad in order to run the program that combines
// SSAO and shading.
draw_screen_aligned_quad(deferred_combination);
// Reenable depth test
glEnable(GL_DEPTH_TEST);
}
void TerrainScene::render_deferred_ssao_sky(bool reload)
{
const int NO_DISC_POINTS = 32;
const int SHADOW_SIZE = 4096;
glClearColor(0.4f,0.35f,0.95f,0.0f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Create all resources.
static GLuint ssao_tex, fbo;
static vector<Vec3f> disc_points;
static GBuffer gbuffer(window_width, window_height);
gbuffer.rebuild_on_resize(window_width, window_height);
static ShaderProgramDraw deferred_ssao(shader_path, "deferred.vert", "", "deferred_ssao.frag");
static ShaderProgramDraw deferred_combination(shader_path, "deferred.vert", "", "deferred_ssao_combination_sky.frag");
static ShaderProgramDraw render_to_shadow_map(shader_path, "shadow.vert", "", "shadow.frag");
static ShadowBuffer shadow_buffer(SHADOW_SIZE);
const int MMW=window_width/2;
const int MMH=window_height/2;
// Reinitialize all shaders and buffers if reload = true
if(reload || recompute_sky)
directional_light = sky_model.get_directional_light(0.8f);
if(reload)
{
gbuffer.initialize(window_width, window_height);
deferred_ssao.reload();
deferred_combination.reload();
render_to_shadow_map.reload();
shadow_buffer.initialize();
}
// If reload=true or we are here first time, reinitialize the FBO for SSAO computation.
static bool was_here = false;
if(reload || !was_here)
{
was_here = true;
glGenTextures(1, &ssao_tex);
glBindTexture(GL_TEXTURE_RECTANGLE, ssao_tex);
glTexParameterf(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGBA16F, MMW, MMH, 0, GL_RGBA, GL_FLOAT, 0);
glGenFramebuffers(1,&fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE, ssao_tex, 0);
if(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
cout << "Something wrong with FBO" << endl;
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
// Also: Create a bunch of vectors for hemisphere sampling.
gel_srand(0);
disc_points.clear();
for(int i=0;i<NO_DISC_POINTS;++i)
{
float alpha = 2.0 * M_PI * i / float(NO_DISC_POINTS) - M_PI;
Vec3f v(cos(alpha),sin(alpha),0);
v*= gel_rand()/float(GEL_RAND_MAX);
disc_points.push_back(v);
}
}
// Enable shadow buffer and the program for drawing to shadow buffer
shadow_buffer.enable();
render_to_shadow_map.use();
// Set up a modelview matrix suitable for shadow: Maps from world coords to
// shadow buffer coords.
Vec3f up = (directional_light.direction[2] == 0.0f)? Vec3f(0,1,0) : Vec3f(0,0,1); // To avoid gimbal lock
Vec3f v = Vec3f(directional_light.direction);
render_to_shadow_map.set_view_matrix(lookat_Mat4x4f(map_center,-v,up));
render_to_shadow_map.set_model_matrix(identity_Mat4x4f());
render_to_shadow_map.set_projection_matrix(ortho_Mat4x4f(Vec3f(-300,-300,-100),Vec3f(300,300,400)));
// Switch viewport size to that of shadow buffer.
glViewport(0, 0, SHADOW_SIZE, SHADOW_SIZE);
glClearColor(0,1,0,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Draw to shadow buffer.
terrain.draw(render_to_shadow_map);
draw_objects(render_to_shadow_map, terrain);
draw_trees(render_to_shadow_map, terrain);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glDrawBuffer(GL_BACK);
// We need to reset the viewport, since the shadow buffer does not have
// the same size as the screen window.
glViewport(0, 0, window_width, window_height);
static ShaderProgramDraw ocean_render_to_gbuffer(shader_path, "ocean_gbuffer.vert", "", "ocean_gbuffer.frag");
// Enable GBuffer and render to GBuffer
render_to_gbuffer(gbuffer, reload);
// Adding rendering of ocean in the gbuffer
ocean_render_to_gbuffer.use();
set_light_and_camera(ocean_render_to_gbuffer);
draw_ocean(ocean_render_to_gbuffer);
// Entering deferred rendering, so disable depth test
glDisable(GL_DEPTH_TEST);
// Bind the FBO that we render to in the first pass where we compute the SSAO contribution
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
// We need to change the viewport since we render SSAO to smaller buffer.
glViewport(0, 0, MMW, MMH);
glClear(GL_COLOR_BUFFER_BIT);
deferred_ssao.use();
// Bind the GBuffer, assign uniforms including the hemisphere direction vectors.
gbuffer.bind_textures(0, 1, 2);
deferred_ssao.set_uniform("gtex", 0);
deferred_ssao.set_uniform("ntex", 1);
deferred_ssao.set_uniform("ctex", 2);
glUniform3fv(deferred_ssao.get_uniform_location("disc_points"),NO_DISC_POINTS,
reinterpret_cast<float*>(&disc_points[0]));
deferred_ssao.set_uniform("NO_DISC_POINTS",NO_DISC_POINTS);
Vec2f windowDimension(window_width, window_height);
deferred_ssao.set_uniform("win_dim", windowDimension);
//Bind shadow buffer texture
shadow_buffer.bind_textures(3);
deferred_ssao.set_uniform("shadow_map", 3);
// Tricky stuff: Create an inverse of the modelview matrix to (later) be able
// to go from the GBuffer coordinates (eye space) to world coordinates. We multiply
// this inverse onto the matrix created above in order to go directly from eye space
// to shadow buffer space.
Mat4x4f mat = translation_Mat4x4f(Vec3f(0.5));
mat *= scaling_Mat4x4f(Vec3f(0.5));
mat *= render_to_shadow_map.get_projection_matrix();
mat *= render_to_shadow_map.get_view_matrix();
mat *= invert(user.get_view_matrix());
deferred_ssao.set_uniform("Mat", mat);
// Draw quad to render SSAO computation
draw_screen_aligned_quad(deferred_ssao);
// Bind regular on-screen framebuffer.
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glViewport(0, 0, window_width, window_height);
// Draw quad in order to run the program that combines
// SSAO and shading.
GLuint sky_irradiance, sky_texture;
get_skybox_textures(reload, sky_texture, sky_irradiance);
// Bind program for combining SSAO and other shading.
deferred_combination.use();
set_light_and_camera(deferred_combination);
// Bind texture resources, and assign uniforms
gbuffer.bind_textures(0, 1, 2);
deferred_combination.set_uniform("gtex", 0);
deferred_combination.set_uniform("ntex", 1);
deferred_combination.set_uniform("ctex", 2);
deferred_combination.use_texture(GL_TEXTURE_RECTANGLE, "ssao_tex", ssao_tex, 3);
shadow_buffer.bind_textures(4);
deferred_combination.set_uniform("shadow_map", 4);
deferred_combination.use_texture(GL_TEXTURE_CUBE_MAP, "sky_irradiance", sky_irradiance, 5);
deferred_combination.use_texture(GL_TEXTURE_CUBE_MAP, "sky_texture", sky_texture, 6);
deferred_combination.set_uniform("Mat", mat);
Mat4x4f inv_V = invert(user.get_view_matrix());
deferred_combination.set_uniform("ss_view_to_world", inv_V);
Mat4x4f inv_V_3x3(Vec4f(Vec3f(inv_V[0]), 0.0f), Vec4f(Vec3f(inv_V[1]), 0.0f), Vec4f(Vec3f(inv_V[2]), 0.0f), Vec4f(0.0f));
deferred_combination.set_uniform("ss_proj_view_inv", inv_V_3x3*invert(deferred_combination.get_projection_matrix()));
deferred_combination.set_uniform("win_scale", Vec2f(1.0f/window_width, 1.0/window_height));
draw_screen_aligned_quad(deferred_combination);
// Reenable depth test
glEnable(GL_DEPTH_TEST);
}
void TerrainScene::get_skybox_textures(bool reload, GLuint& sky, GLuint& sky_integral)
{
const int SKY_RESOLUTION = 512;
const int N = 2000;
const int no_of_iters = N/5;
static GLuint cubemap = 0;
static GLuint cubemap_integrated = 0;
static CubemapBuffer buff1(SKY_RESOLUTION);
static CubemapBuffer buff2(SKY_RESOLUTION);
static ShaderProgramDraw sky_compute(shader_path, "integrator.vert","integrator.geom","integrator.frag");
static int iteration = 0;
if(recompute_sky)
{
sky_model.init();
sky_model.precomputeTexture(cubemap, SKY_RESOLUTION);
recompute_sky = false;
iteration = 0;
if(reload)
sky_compute.reload();
cout << flush << "Computing integrated skymap" << flush;
}
if(iteration < no_of_iters)
{
sky_compute.use();
glViewport(0,0,SKY_RESOLUTION,SKY_RESOLUTION);
CubemapBuffer& buff_new = iteration%2 ? buff2 : buff1;
CubemapBuffer& buff_old = iteration%2 ? buff1 : buff2;
buff_new.enable_write();
sky_compute.use_texture(GL_TEXTURE_CUBE_MAP, "sky_texture", cubemap, 0);
sky_compute.use_texture(GL_TEXTURE_CUBE_MAP, "old_texture", buff_old.get_texture(), 1);
sky_compute.set_uniform("inv_cubemap_size", Vec2f(1.0f/SKY_RESOLUTION));
sky_compute.set_uniform("N", N/no_of_iters);
sky_compute.set_uniform("iteration", iteration);
draw_screen_aligned_quad(sky_compute);
glFinish();
cubemap_integrated = buff_new.get_texture();
++iteration;
if(iteration == no_of_iters)
cout << "Done." << endl << flush;
else if(iteration%40 == 0)
cout << ".";
// Resetting values
glBindFramebuffer(GL_DRAW_FRAMEBUFFER,0);
glViewport(0, 0, window_width, window_height);
}
sky = cubemap;
sky_integral = cubemap_integrated;
}
void TerrainScene::set_time_of_day(float solar_time)
{
while(solar_time >= 24.0f)
{
solar_time -= 24.0f;
if(--day_of_the_year < 1)
day_of_the_year = 365;
}
while(solar_time < 0.0f)
{
solar_time += 24.0f;
if(++day_of_the_year > 365)
day_of_the_year = 1;
}
time_of_day = solar_time;
sky_model.setTime(day_of_the_year, time_of_day);
recompute_sky = true;
}
TerrainScene::TerrainScene( const QGLFormat& format, QWidget* parent)
: QGLWidget( new Core3_2_context(format), (QWidget*) parent),
ax(0), ay(0), dist(12),ang_x(0),ang_y(0),
user(&terrain),mouse_x0(0),mouse_y0(0)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(animate()));
timer->start(16);
}
void TerrainScene::paintGL()
{
switch(render_mode)
{
case DRAW_NORMAL:
render_direct(reload_shaders);
break;
case DRAW_WIRE:
render_direct_wireframe(reload_shaders);
break;
case DRAW_DEFERRED_TOON:
render_deferred_toon(reload_shaders);
break;
case DRAW_SSAO:
render_deferred_ssao(reload_shaders);
break;
case DRAW_SSAO_GI:
render_deferred_ssao_sky(reload_shaders);
break;
}
reload_shaders = false;
check_gl_error();
}
void TerrainScene::resizeGL(int W, int H)
{
window_width = W;
window_height = H;
glViewport(0, 0, window_width, window_height);
reload_shaders = true;
}
void TerrainScene::animate()
{
user.update_position();
repaint();
}
void TerrainScene::initializeGL()
{
setup_gl();
glClearColor( 0.7f, 0.7f, 0.7f, 0.0f );
glEnable(GL_DEPTH_TEST);
}
void TerrainScene::mousePressEvent(QMouseEvent *m)
{
mouse_x0 = m->x();
mouse_y0 = m->y();
}
void TerrainScene::mouseReleaseEvent(QMouseEvent *m)
{
float delta_ang_x = 4*M_PI*(mouse_x0-m->x())/window_width;
float delta_ang_y = M_PI*(mouse_y0-m->y())/window_height;
ang_x += delta_ang_x;
ang_y += delta_ang_y;
}
void TerrainScene::mouseMoveEvent(QMouseEvent *m)
{
float delta_ang_x = 4*M_PI*(mouse_x0-m->x())/window_width;
float delta_ang_y = M_PI*(mouse_y0-m->y())/window_height;
float ax = ang_x + delta_ang_x;
float ay = ang_y + delta_ang_y;
Vec3f dir(cos(ax)*cos(ay),sin(ax)*cos(ay),sin(ay));
user.set_dir(dir);
QWidget::repaint();
}
void TerrainScene::keyPressEvent(QKeyEvent *e)
{
static bool is_full_screen = false;
switch(e->key())
{
case Qt::Key_Escape: QApplication::quit();
case '1':
case '2':
case '3':
case '4':
case '5':
render_mode = static_cast<RenderMode>(e->key()-'1');
reload_shaders = true;
break;
case ' ':
render_mode = static_cast<RenderMode>((static_cast<int>(render_mode)+1)%5);
reload_shaders = true;
break;
case 'W': user.forward(); break;
case 'S': user.back();break;
case 'A': user.strafe_left();break;
case 'D': user.strafe_right();break;
case 'X': user.toggle_fly_mode(); break;
case 'F':
if(is_full_screen) {
showNormal();
is_full_screen = false;
}
else
{
showMaximized();
is_full_screen = true;
}
break;
case 'R':
reload_shaders = true;
break;
case 'L':
{
Vec3f v = normalize(-user.get_dir() + Vec3f(0,0,1));
directional_light.direction = v;
}
break;
case 'O':
user.set(Vec3f(-7.60765f, 14.907f, 4.37377f), Vec3f(0.333226f, -0.925571f, 0.179661f));
break;
case 'H':
{
float solar_time = get_time_of_day();
solar_time += e->modifiers() & Qt::ShiftModifier ? -0.5f : 0.5f;
set_time_of_day(solar_time);
cout << "The solar time is now: " << solar_time << endl;
}
break;
default:
QWidget::keyPressEvent(e);
break;
}
QWidget::repaint();
}
void TerrainScene::keyReleaseEvent(QKeyEvent *)
{
user.stop();
}
int main(int argc, char *argv[])
{
const int WINDOW_WIDTH = 1136;
const int WINDOW_HEIGHT = 640;
//qDebug() << argv[0] << " - " << argv[1] << endl;
QApplication a( argc, argv );
QGLFormat glFormat;
glFormat.setVersion( 3, 2 );
glFormat.setProfile( QGLFormat::CoreProfile ); // Requires >=Qt-4.8.0
glFormat.setDepthBufferSize(32);
TerrainScene w( glFormat);
w.resize(WINDOW_WIDTH, WINDOW_HEIGHT);
w.setFocusPolicy(Qt::ClickFocus);
w.show();
return a.exec();
}
|
#include "Camera.h"
void Camera::Update(DWORD dt, CGameObject* simon)
{
if (isFollowSimon && !isAuto)
{
FollowSimon(simon);
}
}
void Camera::FollowSimon(CGameObject* simon)
{
// Update camera to follow simon
float cx, cy;
simon->GetPosition(cx, cy);
cam_x = CGame::GetInstance()->getCamPos_x();
pos_max = CMap::GetInstance()->GetPos_max();
if (cx - SCREEN_WIDTH / 2.5 < 0)
{
cx = 0;
}
else if (cx + SCREEN_WIDTH / 2.5 > pos_max)
{
cx = pos_max - SCREEN_WIDTH;
}
else
{
cx -= SCREEN_WIDTH / 2.5;
}
CGame::GetInstance()->SetCamPos(cx, 0);
}
Camera* Camera::__instance = NULL;
Camera * Camera::GetInstance()
{
if (__instance == NULL) __instance = new Camera();
return __instance;
}
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct node {
int x, y, idn;
node *left;
node *right;
node *parent;
};
node *make_node(int x, int y, int id) {
auto *n = new node{};
n->x = x;
n->y = y;
n->idn = id;
n->left = nullptr;
n->right = nullptr;
n->parent = nullptr;
return n;
}
vector<node *> answer;
void print(node *el) {
answer[el->idn] = el;
if (el->left != nullptr)
print(el->left);
if (el->right != nullptr)
print(el->right);
}
bool compare(node *n1, node *n2) {
return n1->x < n2->x;
}
int id(node *el) {
if (el == nullptr)
return 0;
else return el->idn + 1;
}
int main() {
int n;
cin >> n;
vector<node *> v;
v.reserve(n);
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
v.push_back(make_node(x, y, i));
}
sort(v.begin(), v.end(), compare);
node *head = v[0];
node *last = v[0];
for (int i = 1; i < n; i++) {
node *el = v[i];
if (el->y > last->y) {
last->right = el;
el->parent = last;
} else if (el->y == last->y) {
cout << "NO";
return 0;
} else {
node *temp = last;
while (temp->y > el->y && temp->parent != nullptr) {
temp = temp->parent;
}
if (temp->y == el->y) {
cout << "NO";
return 0;
}
if (temp->y < el->y) {
el->left = temp->right;
el->left->parent = el;
temp->right = el;
el->parent = temp;
} else {
el->left = head;
head->parent = el;
head = el;
}
}
last = el;
}
answer = vector<node *>(n);
print(head);
cout << "YES" << endl;
for (node *el : answer) {
cout << id(el->parent) << " " << id(el->left) << " " << id(el->right) << endl;
}
return 0;
}
|
/**
Constructs the JSON object corresponding to a measurement
*/
aJsonObject* constructRGBCMeasurement(String R, String G, String B, String C, String ColorTemp, String lux) {
aJsonObject *root = aJson.createObject();
aJson.addStringToObject(root, "R", R.c_str());
aJson.addStringToObject(root, "G", G.c_str());
aJson.addStringToObject(root, "B", B.c_str());
aJson.addStringToObject(root, "C", C.c_str());
aJson.addStringToObject(root, "ColorTemp", ColorTemp.c_str());
aJson.addStringToObject(root, "lux", lux.c_str());
return root;
}
aJsonObject* constructElectrochemicalMeasurement(String Aluminum, String StainlessSteel, String Titanium) {
aJsonObject *root = aJson.createObject();
aJson.addStringToObject(root, "Aluminum", Aluminum.c_str());
aJson.addStringToObject(root, "StainlessSteel", StainlessSteel.c_str());
aJson.addStringToObject(root, "Titanium", Titanium.c_str());
return root;
}
|
void buzzerAlert()
{
motor(1, 50);
delay(1000);
motor(1, 0);
}
|
#ifndef MANIPULATION_OPERATION_H
#define MANIPULATION_OPERATION_H
#include "../model/image.h"
namespace manipulation {
// Encapsulates a manipulation operation that could be applied to images.
class Operation {
public:
// Applies the manipulation to a specific image.
virtual void apply(model::Image *&image) = 0;
};
}
#endif
|
//--------------------------------------------------------
// musket/include/musket/widget/label.hpp
//
// Copyright (C) 2018 LNSEAB
//
// released under the MIT License.
// https://opensource.org/licenses/MIT
//--------------------------------------------------------
#ifndef MUSKET_WIDGET_LABEL_HPP_
#define MUSKET_WIDGET_LABEL_HPP_
#include "facade.hpp"
#include "attributes.hpp"
namespace musket {
struct label_style
{
std::optional< rgba_color_t > bg_color;
std::optional< edge_property > edge;
std::optional< rgba_color_t > text_color;
};
class label;
template <>
class default_style_t< label >
{
inline static label_style style_ = {
{}, {},
rgba_color_t{ 1.0f, 1.0f, 1.0f, 1.0f },
};
inline static std::mutex mtx_;
public:
static void set(label_style const& style) noexcept
{
std::lock_guard lock{ mtx_ };
style_ = style;
}
static label_style get() noexcept
{
std::lock_guard lock{ mtx_ };
return style_;
}
};
struct label_property
{
std::optional< text_format > text_fmt;
std::optional< label_style > style;
};
class label :
public widget_facade< label >
{
std::string str_;
spirea::dwrite::text_format format_;
spirea::dwrite::text_layout text_;
style_data_t< label_style > data_;
public:
template <typename Rect>
label(
Rect const& rc,
std::string_view str,
label_property const& prop = {}
) :
widget_facade{ rc },
str_{ str.begin(), str.end() },
data_{ deref_style< label >( prop.style ) }
{
format_ = create_text_format( deref_text_format( prop.text_fmt ) );
format_->SetTextAlignment( spirea::dwrite::text_alignment::center );
format_->SetParagraphAlignment( spirea::dwrite::paragraph_alignment::center );
text_ = create_text_layout( format_, this->size(), str );
}
void set_text(std::string_view str)
{
text_ = create_text_layout( format_, size(), str );
}
template <typename Object>
void on_event(event::draw, Object& obj)
{
if( !this->is_visible() ) {
return;
}
auto const rc = spirea::rect_traits< spirea::d2d1::rect_f >::construct( this->size() );
auto const rt = obj.render_target();
data_.draw_background( rt, rc );
data_.draw_edge( rt, rc );
data_.draw_text( rt, { rc.left, rc.top }, text_ );
}
template <typename Object>
void on_event(event::recreated_target, Object& obj)
{
data_.recreated_target( obj.render_target() );
}
template <typename Object>
void on_event(event::auto_resize, Object&, spirea::rect_t< float > const& rc)
{
text_->SetMaxWidth( rc.width() );
text_->SetMaxHeight( rc.height() );
}
};
} // namespace musket
#endif // MUSKET_WIDGET_LABEL_HPP_
|
#include <iostream>
#include "Shop.h"
#include "SaleableItem.h"
#include "Book.h"
#include "CD.h"
#include "DVD.h"
#include <vector>
using namespace std;
void Shop::AddBook(const char* pTitle, unsigned int unitPricePence,
unsigned int noOfPages)
{
Book *book = new Book(pTitle, unitPricePence, noOfPages);
shared_ptr<SaleableItem> pSaleableItem(book);
saleableItems_.push_back(pSaleableItem);
}
void Shop::AddDVD(const char* pTitle, unsigned int unitPricePence,
unsigned int runningTimeMins,
DVD::DVDFormat format)
{
DVD *dvd = new DVD(pTitle, unitPricePence, runningTimeMins, format);
shared_ptr<SaleableItem> pSaleableItem(dvd);
saleableItems_.push_back(pSaleableItem);
}
void Shop::AddCD(const char* pTitle, unsigned int unitPricePence,
unsigned int runningTimeMins,
unsigned int noOfTracks)
{
CD *cd = new CD(pTitle, unitPricePence, runningTimeMins, noOfTracks);
shared_ptr<SaleableItem> pSaleableItem(cd);
saleableItems_.push_back(pSaleableItem);
}
void Shop::ShowTaxedPrices() const
{
for( auto& item : saleableItems_ )
{
cout << item->getTitle() << ": " << item->getNewPrice() <<
" pence" << endl;
}
}
|
//====================================================================================
// @Title: BATTLE STAGE
//------------------------------------------------------------------------------------
// @Location: /game/battle/include/cBattleStage.cpp
// @Author: Kevin Chen
// @Rights: Copyright(c) 2011 Visionary Games
//====================================================================================
#include "../include/cBattleStage.h"
#include "../../../prolix/framework/include/cGame.h"
//====================================================================================
// cBattleStage
//====================================================================================
cBattleStage::cBattleStage()
{
LogMgr->Write(INFO, "cBattleStage::cBattleStage >>>> Created Battle Stage");
}
void cBattleStage::Draw()
{
int y;
for (y=0; y < SCREEN_HEIGHT; y += AssetMgr->Load<Texture>("grass.png")->dim.h)
{
for (int x=0; x < SCREEN_WIDTH; x += AssetMgr->Load<Texture>("grass.png")->dim.w)
{
AssetMgr->Load<Texture>("grass.png")->Draw(Point(x,y));
}
}
y -= 32;
for (int x=0; x < SCREEN_WIDTH; x += AssetMgr->Load<Texture>("dirt.png")->dim.w)
{
AssetMgr->Load<Texture>("dirt.png")->Draw(Point(x,y));
}
}
cBattleStage::~cBattleStage()
{
}
|
#ifndef _CUDA_TIMER_
#define _CUDA_TIMER_
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
class CudaTimer {
public:
CudaTimer();
void start();
void stop();
float getTime();
private:
cudaEvent_t m_start, m_stop;
};
#endif
|
#include <iostream>
#include <pangolin/pangolin.h>
struct CustomType
{
CustomType()
: x(0), y(0.0f) {}
CustomType(int x, float y, std::string z)
: x(x), y(y), z(z) {}
int x;
float y;
std::string z;
};
std::ostream& operator<< (std::ostream& os, const CustomType& o){
os << o.x << " " << o.y << " " << o.z;
return os;
}
std::istream& operator>> (std::istream& is, CustomType& o){
is >> o.x;
is >> o.y;
is >> o.z;
return is;
}
void SampleMethod()
{
std::cout << "You typed ctrl-r or pushed reset" << std::endl;
}
int main(/*int argc, char* argv[]*/)
{
// Load configuration data
pangolin::ParseVarsFile("app.cfg");
// Create OpenGL window in single line
pangolin::CreateWindowAndBind("Main",640,480);
// 3D Mouse handler requires depth testing to be enabled
glEnable(GL_DEPTH_TEST);
// Define Camera Render Object (for view / scene browsing)
pangolin::OpenGlRenderState s_cam(
pangolin::ProjectionMatrix(640,480,420,420,320,240,0.1,1000),
pangolin::ModelViewLookAt(-0,0.5,-3, 0,0,0, pangolin::AxisY)
);
const int UI_WIDTH = 180;
// Add named OpenGL viewport to window and provide 3D Handler
pangolin::View& d_cam = pangolin::CreateDisplay()
.SetBounds(0.0, 1.0, pangolin::Attach::Pix(UI_WIDTH), 1.0, -640.0f/480.0f)
.SetHandler(new pangolin::Handler3D(s_cam));
// Add named Panel and bind to variables beginning 'ui'
// A Panel is just a View with a default layout and input handling
pangolin::CreatePanel("ui")
.SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(UI_WIDTH));
// Safe and efficient binding of named variables.
// Specialisations mean no conversions take place for exact types
// and conversions between scalar types are cheap.
pangolin::Var<bool> a_button("ui.A_Button",false,false);
pangolin::Var<double> a_double("ui.A_Double",3,0,5);
pangolin::Var<int> an_int("ui.An_Int",2,0,5);
pangolin::Var<double> a_double_log("ui.Log_scale var",3,1,1E4, true);
pangolin::Var<bool> a_checkbox("ui.A_Checkbox",false,true);
pangolin::Var<int> an_int_no_input("ui.An_Int_No_Input",2);
pangolin::Var<CustomType> any_type("ui.Some_Type", CustomType(0,1.2f,"Hello") );
pangolin::Var<bool> save_window("ui.Save_Window",false,false);
pangolin::Var<bool> save_cube("ui.Save_Cube",false,false);
pangolin::Var<bool> record_cube("ui.Record_Cube",false,false);
// std::function objects can be used for Var's too. These work great with C++11 closures.
pangolin::Var<std::function<void(void)> > reset("ui.Reset", SampleMethod);
// Demonstration of how we can register a keyboard hook to alter a Var
pangolin::RegisterKeyPressCallback(pangolin::PANGO_CTRL + 'b', pangolin::SetVarFunctor<double>("ui.A_Double", 3.5));
// Demonstration of how we can register a keyboard hook to trigger a method
pangolin::RegisterKeyPressCallback(pangolin::PANGO_CTRL + 'r', SampleMethod);
// Default hooks for exiting (Esc) and fullscreen (tab).
while( !pangolin::ShouldQuit() )
{
// Clear entire screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if( pangolin::Pushed(a_button) )
std::cout << "You Pushed a button!" << std::endl;
// Overloading of Var<T> operators allows us to treat them like
// their wrapped types, eg:
if( a_checkbox )
an_int = (int)a_double;
if( !any_type->z.compare("robot"))
any_type = CustomType(1,2.3f,"Boogie");
an_int_no_input = an_int;
if( pangolin::Pushed(save_window) )
pangolin::SaveWindowOnRender("window");
if( pangolin::Pushed(save_cube) )
d_cam.SaveOnRender("cube");
if( pangolin::Pushed(record_cube) )
pangolin::DisplayBase().RecordOnRender("ffmpeg:[fps=50,bps=8388608,unique_filename]//screencap.avi");
// Activate efficiently by object
d_cam.Activate(s_cam);
// Render some stuff
glColor3f(1.0,1.0,1.0);
pangolin::glDrawColouredCube();
// Swap frames and Process Events
pangolin::FinishFrame();
}
return 0;
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/macros.h"
#include "examples/window_manager/debug_panel_host.mojom.h"
#include "examples/window_manager/window_manager.mojom.h"
#include "mojo/application/application_runner_chromium.h"
#include "mojo/common/binding_set.h"
#include "mojo/converters/geometry/geometry_type_converters.h"
#include "mojo/converters/input_events/input_events_type_converters.h"
#include "mojo/public/c/system/main.h"
#include "mojo/public/cpp/application/application_connection.h"
#include "mojo/public/cpp/application/application_delegate.h"
#include "mojo/public/cpp/application/application_impl.h"
#include "mojo/public/cpp/application/service_provider_impl.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/services/input_events/public/interfaces/input_events.mojom.h"
#include "mojo/services/navigation/public/interfaces/navigation.mojom.h"
#include "mojo/services/view_manager/public/cpp/view.h"
#include "mojo/services/view_manager/public/cpp/view_manager.h"
#include "mojo/services/view_manager/public/cpp/view_manager_delegate.h"
#include "mojo/services/view_manager/public/cpp/view_observer.h"
#include "services/window_manager/basic_focus_rules.h"
#include "services/window_manager/view_target.h"
#include "services/window_manager/window_manager_app.h"
#include "services/window_manager/window_manager_delegate.h"
#include "services/window_manager/window_manager_root.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "url/gurl.h"
#if defined CreateWindow
#undef CreateWindow
#endif
namespace mojo {
namespace examples {
class WindowManagerController;
namespace {
const int kBorderInset = 25;
const int kControlPanelWidth = 200;
const int kTextfieldHeight = 39;
} // namespace
class WindowManagerConnection : public ::examples::IWindowManager {
public:
WindowManagerConnection(WindowManagerController* window_manager,
InterfaceRequest<::examples::IWindowManager> request)
: window_manager_(window_manager), binding_(this, request.Pass()) {}
~WindowManagerConnection() override {}
private:
// Overridden from ::examples::IWindowManager:
void CloseWindow(Id view_id) override;
WindowManagerController* window_manager_;
StrongBinding<::examples::IWindowManager> binding_;
DISALLOW_COPY_AND_ASSIGN(WindowManagerConnection);
};
class NavigatorHostImpl : public NavigatorHost {
public:
NavigatorHostImpl(WindowManagerController* window_manager, Id view_id)
: window_manager_(window_manager),
view_id_(view_id),
current_index_(-1) {}
~NavigatorHostImpl() override {}
void Bind(InterfaceRequest<NavigatorHost> request) {
bindings_.AddBinding(this, request.Pass());
}
void RecordNavigation(const std::string& url);
private:
void DidNavigateLocally(const mojo::String& url) override;
void RequestNavigate(Target target, URLRequestPtr request) override;
void RequestNavigateHistory(int32_t delta) override;
WindowManagerController* window_manager_;
Id view_id_;
std::vector<std::string> history_;
int32_t current_index_;
BindingSet<NavigatorHost> bindings_;
DISALLOW_COPY_AND_ASSIGN(NavigatorHostImpl);
};
class RootLayoutManager : public ViewObserver {
public:
RootLayoutManager(ViewManager* view_manager,
View* root,
Id content_view_id,
Id launcher_ui_view_id,
Id control_panel_view_id)
: root_(root),
view_manager_(view_manager),
content_view_id_(content_view_id),
launcher_ui_view_id_(launcher_ui_view_id),
control_panel_view_id_(control_panel_view_id) {}
~RootLayoutManager() override {
if (root_)
root_->RemoveObserver(this);
}
private:
// Overridden from ViewObserver:
void OnViewBoundsChanged(View* view,
const Rect& old_bounds,
const Rect& new_bounds) override {
DCHECK_EQ(view, root_);
View* content_view = view_manager_->GetViewById(content_view_id_);
content_view->SetBounds(new_bounds);
int delta_width = new_bounds.width - old_bounds.width;
int delta_height = new_bounds.height - old_bounds.height;
View* launcher_ui_view = view_manager_->GetViewById(launcher_ui_view_id_);
Rect launcher_ui_bounds(launcher_ui_view->bounds());
launcher_ui_bounds.width += delta_width;
launcher_ui_view->SetBounds(launcher_ui_bounds);
View* control_panel_view =
view_manager_->GetViewById(control_panel_view_id_);
Rect control_panel_bounds(control_panel_view->bounds());
control_panel_bounds.x += delta_width;
control_panel_view->SetBounds(control_panel_bounds);
const View::Children& content_views = content_view->children();
View::Children::const_iterator iter = content_views.begin();
for (; iter != content_views.end(); ++iter) {
View* view = *iter;
if (view->id() == control_panel_view->id() ||
view->id() == launcher_ui_view->id())
continue;
Rect view_bounds(view->bounds());
view_bounds.width += delta_width;
view_bounds.height += delta_height;
view->SetBounds(view_bounds);
}
}
void OnViewDestroyed(View* view) override {
DCHECK_EQ(view, root_);
root_->RemoveObserver(this);
root_ = NULL;
}
View* root_;
ViewManager* view_manager_;
const Id content_view_id_;
const Id launcher_ui_view_id_;
const Id control_panel_view_id_;
DISALLOW_COPY_AND_ASSIGN(RootLayoutManager);
};
class Window : public InterfaceFactory<NavigatorHost> {
public:
Window(WindowManagerController* window_manager, View* view)
: window_manager_(window_manager),
view_(view),
navigator_host_(window_manager_, view_->id()) {
exposed_services_impl_.AddService<NavigatorHost>(this);
}
~Window() override {}
View* view() const { return view_; }
NavigatorHost* navigator_host() { return &navigator_host_; }
void Embed(const std::string& url) {
// TODO: Support embedding multiple times?
ServiceProviderPtr exposed_services;
exposed_services_impl_.Bind(GetProxy(&exposed_services));
view_->Embed(url, nullptr, exposed_services.Pass());
navigator_host_.RecordNavigation(url);
}
private:
// InterfaceFactory<NavigatorHost>
void Create(ApplicationConnection* connection,
InterfaceRequest<NavigatorHost> request) override {
navigator_host_.Bind(request.Pass());
}
WindowManagerController* window_manager_;
View* view_;
ServiceProviderImpl exposed_services_impl_;
NavigatorHostImpl navigator_host_;
};
class WindowManagerController
: public examples::DebugPanelHost,
public window_manager::WindowManagerController,
public ui::EventHandler,
public ui::AcceleratorTarget,
public mojo::InterfaceFactory<examples::DebugPanelHost>,
public InterfaceFactory<::examples::IWindowManager> {
public:
WindowManagerController(Shell* shell,
ApplicationImpl* app,
ApplicationConnection* connection,
window_manager::WindowManagerRoot* wm_root)
: shell_(shell),
launcher_ui_(NULL),
view_manager_(NULL),
window_manager_root_(wm_root),
navigation_target_(Target::DEFAULT),
app_(app),
binding_(this) {
connection->AddService<::examples::IWindowManager>(this);
}
~WindowManagerController() override {
// host() may be destroyed by the time we get here.
// TODO: figure out a way to always cleanly remove handler.
// TODO(erg): In the aura version, we removed ourselves from the
// PreTargetHandler list here. We may need to do something analogous when
// we get event handling without aura working.
}
void CloseWindow(Id view_id) {
WindowVector::iterator iter = GetWindowByViewId(view_id);
DCHECK(iter != windows_.end());
Window* window = *iter;
windows_.erase(iter);
window->view()->Destroy();
}
void DidNavigateLocally(uint32 source_view_id, const mojo::String& url) {
LOG(ERROR) << "DidNavigateLocally: source_view_id: " << source_view_id
<< " url: " << url.To<std::string>();
}
void RequestNavigate(uint32 source_view_id,
Target target,
const mojo::String& url) {
OnLaunch(source_view_id, target, url);
}
// Overridden from mojo::DebugPanelHost:
void CloseTopWindow() override {
if (!windows_.empty())
CloseWindow(windows_.back()->view()->id());
}
void NavigateTo(const String& url) override {
OnLaunch(control_panel_id_, Target::NEW_NODE, url);
}
void SetNavigationTarget(Target t) override { navigation_target_ = t; }
// mojo::InterfaceFactory<examples::DebugPanelHost> implementation.
void Create(
mojo::ApplicationConnection* connection,
mojo::InterfaceRequest<examples::DebugPanelHost> request) override {
binding_.Bind(request.Pass());
}
// mojo::InterfaceFactory<::examples::IWindowManager> implementation.
void Create(
mojo::ApplicationConnection* connection,
mojo::InterfaceRequest<::examples::IWindowManager> request) override {
new WindowManagerConnection(this, request.Pass());
}
private:
typedef std::vector<Window*> WindowVector;
// Overridden from ViewManagerDelegate:
void OnEmbed(View* root,
InterfaceRequest<ServiceProvider> services,
ServiceProviderPtr exposed_services) override {
DCHECK(!view_manager_);
view_manager_ = root->view_manager();
View* view = view_manager_->CreateView();
root->AddChild(view);
Rect rect;
rect.width = root->bounds().width;
rect.height = root->bounds().height;
view->SetBounds(rect);
view->SetVisible(true);
content_view_id_ = view->id();
Id launcher_ui_id = CreateLauncherUI();
control_panel_id_ = CreateControlPanel(view);
root_layout_manager_.reset(
new RootLayoutManager(view_manager_, root, content_view_id_,
launcher_ui_id, control_panel_id_));
root->AddObserver(root_layout_manager_.get());
// TODO(erg): In the aura version, we explicitly added ourselves as a
// PreTargetHandler to the window() here. We probably have to do something
// analogous here.
window_manager_root_->InitFocus(
make_scoped_ptr(new window_manager::BasicFocusRules(root)));
window_manager_root_->accelerator_manager()->Register(
ui::Accelerator(ui::VKEY_BROWSER_BACK, 0),
ui::AcceleratorManager::kNormalPriority, this);
}
void OnViewManagerDisconnected(ViewManager* view_manager) override {
DCHECK_EQ(view_manager_, view_manager);
view_manager_ = NULL;
base::MessageLoop::current()->Quit();
}
// Overridden from WindowManagerDelegate:
void Embed(const String& url,
InterfaceRequest<ServiceProvider> services,
ServiceProviderPtr exposed_services) override {
const Id kInvalidSourceViewId = 0;
OnLaunch(kInvalidSourceViewId, Target::DEFAULT, url);
}
// Overridden from ui::EventHandler:
void OnEvent(ui::Event* event) override {
View* view =
static_cast<window_manager::ViewTarget*>(event->target())->view();
if (event->type() == ui::ET_MOUSE_PRESSED)
view->SetFocus();
}
// Overriden from ui::AcceleratorTarget:
bool AcceleratorPressed(const ui::Accelerator& accelerator,
mojo::View* view) override {
if (accelerator.key_code() != ui::VKEY_BROWSER_BACK)
return false;
WindowVector::iterator iter = GetWindowByViewId(view->id());
DCHECK(iter != windows_.end());
Window* window = *iter;
window->navigator_host()->RequestNavigateHistory(-1);
return true;
}
// Overriden from ui::AcceleratorTarget:
bool CanHandleAccelerators() const override { return true; }
void OnLaunch(uint32 source_view_id,
Target requested_target,
const mojo::String& url) {
Target target = navigation_target_;
if (target == Target::DEFAULT) {
if (requested_target != Target::DEFAULT) {
target = requested_target;
} else {
// TODO(aa): Should be Target::NEW_NODE if source origin and dest origin
// are different?
target = Target::SOURCE_NODE;
}
}
Window* dest_view = NULL;
if (target == Target::SOURCE_NODE) {
WindowVector::iterator source_view = GetWindowByViewId(source_view_id);
bool app_initiated = source_view != windows_.end();
if (app_initiated)
dest_view = *source_view;
else if (!windows_.empty())
dest_view = windows_.back();
}
if (!dest_view) {
dest_view = CreateWindow();
windows_.push_back(dest_view);
}
dest_view->Embed(url);
}
// TODO(beng): proper layout manager!!
Id CreateLauncherUI() {
View* view = view_manager_->GetViewById(content_view_id_);
Rect bounds = view->bounds();
bounds.x += kBorderInset;
bounds.y += kBorderInset;
bounds.width -= 2 * kBorderInset;
bounds.height = kTextfieldHeight;
launcher_ui_ = CreateWindow(bounds);
launcher_ui_->Embed("mojo:browser");
return launcher_ui_->view()->id();
}
Window* CreateWindow() {
View* view = view_manager_->GetViewById(content_view_id_);
Rect bounds;
bounds.x = kBorderInset;
bounds.y = 2 * kBorderInset + kTextfieldHeight;
bounds.width = view->bounds().width - 3 * kBorderInset - kControlPanelWidth;
bounds.height =
view->bounds().height - (3 * kBorderInset + kTextfieldHeight);
if (!windows_.empty()) {
bounds.x = windows_.back()->view()->bounds().x + 35;
bounds.y = windows_.back()->view()->bounds().y + 35;
}
return CreateWindow(bounds);
}
Window* CreateWindow(const Rect& bounds) {
View* content = view_manager_->GetViewById(content_view_id_);
View* view = view_manager_->CreateView();
content->AddChild(view);
view->SetBounds(bounds);
view->SetVisible(true);
view->SetFocus();
return new Window(this, view);
}
Id CreateControlPanel(View* root) {
View* view = view_manager_->CreateView();
root->AddChild(view);
Rect bounds;
bounds.x = root->bounds().width - kControlPanelWidth - kBorderInset;
bounds.y = kBorderInset * 2 + kTextfieldHeight;
bounds.width = kControlPanelWidth;
bounds.height = root->bounds().height - kBorderInset * 3 - kTextfieldHeight;
view->SetBounds(bounds);
view->SetVisible(true);
ServiceProviderPtr exposed_services;
control_panel_exposed_services_impl_.Bind(GetProxy(&exposed_services));
control_panel_exposed_services_impl_.AddService<::examples::IWindowManager>(
this);
GURL frame_url = url_.Resolve("/examples/window_manager/debug_panel.sky");
view->Embed(frame_url.spec(), nullptr, exposed_services.Pass());
return view->id();
}
WindowVector::iterator GetWindowByViewId(Id view_id) {
for (std::vector<Window*>::iterator iter = windows_.begin();
iter != windows_.end(); ++iter) {
if ((*iter)->view()->id() == view_id) {
return iter;
}
}
return windows_.end();
}
Shell* shell_;
Window* launcher_ui_;
WindowVector windows_;
ViewManager* view_manager_;
scoped_ptr<RootLayoutManager> root_layout_manager_;
ServiceProviderImpl control_panel_exposed_services_impl_;
window_manager::WindowManagerRoot* window_manager_root_;
// Id of the view most content is added to.
Id content_view_id_;
// Id of the debug panel.
Id control_panel_id_;
GURL url_;
Target navigation_target_;
ApplicationImpl* app_;
mojo::Binding<examples::DebugPanelHost> binding_;
DISALLOW_COPY_AND_ASSIGN(WindowManagerController);
};
class WindowManager : public ApplicationDelegate,
public window_manager::WindowManagerControllerFactory {
public:
WindowManager()
: window_manager_app_(new window_manager::WindowManagerApp(this)) {}
scoped_ptr<window_manager::WindowManagerController>
CreateWindowManagerController(
ApplicationConnection* connection,
window_manager::WindowManagerRoot* wm_root) override {
return scoped_ptr<WindowManagerController>(
new WindowManagerController(shell_, app_, connection, wm_root));
}
private:
// Overridden from ApplicationDelegate:
void Initialize(ApplicationImpl* app) override {
window_manager_app_.reset(new window_manager::WindowManagerApp(this));
shell_ = app->shell();
app_ = app;
// FIXME: Mojo applications don't know their URLs yet:
// https://docs.google.com/a/chromium.org/document/d/1AQ2y6ekzvbdaMF5WrUQmneyXJnke-MnYYL4Gz1AKDos
url_ = GURL(app->args()[1]);
window_manager_app_->Initialize(app);
}
bool ConfigureIncomingConnection(ApplicationConnection* connection) override {
window_manager_app_->ConfigureIncomingConnection(connection);
return true;
}
ApplicationImpl* app_;
Shell* shell_;
GURL url_;
scoped_ptr<window_manager::WindowManagerApp> window_manager_app_;
DISALLOW_COPY_AND_ASSIGN(WindowManager);
};
void WindowManagerConnection::CloseWindow(Id view_id) {
window_manager_->CloseWindow(view_id);
}
void NavigatorHostImpl::DidNavigateLocally(const mojo::String& url) {
window_manager_->DidNavigateLocally(view_id_, url);
RecordNavigation(url);
}
void NavigatorHostImpl::RequestNavigate(Target target, URLRequestPtr request) {
window_manager_->RequestNavigate(view_id_, target, request->url);
}
void NavigatorHostImpl::RequestNavigateHistory(int32_t delta) {
if (history_.empty())
return;
current_index_ =
std::max(0, std::min(current_index_ + delta,
static_cast<int32_t>(history_.size()) - 1));
window_manager_->RequestNavigate(view_id_, Target::SOURCE_NODE,
history_[current_index_]);
}
void NavigatorHostImpl::RecordNavigation(const std::string& url) {
if (current_index_ >= 0 && history_[current_index_] == url) {
// This is a navigation to the current entry, ignore.
return;
}
history_.erase(history_.begin() + (current_index_ + 1), history_.end());
history_.push_back(url);
++current_index_;
}
} // namespace examples
} // namespace mojo
MojoResult MojoMain(MojoHandle application_request) {
mojo::ApplicationRunnerChromium runner(new mojo::examples::WindowManager);
return runner.Run(application_request);
}
|
// Created on: 1992-04-06
// Created by: Christian CAILLET
// Copyright (c) 1992-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 _IGESData_IGESType_HeaderFile
#define _IGESData_IGESType_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
//! taken from directory part of an entity (from file or model),
//! gives "type" and "form" data, used to recognize entity's type
class IGESData_IGESType
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT IGESData_IGESType();
Standard_EXPORT IGESData_IGESType(const Standard_Integer atype, const Standard_Integer aform);
//! returns "type" data
Standard_EXPORT Standard_Integer Type() const;
//! returns "form" data
Standard_EXPORT Standard_Integer Form() const;
//! compares two IGESTypes, avoiding comparing their fields
Standard_EXPORT Standard_Boolean IsEqual (const IGESData_IGESType& another) const;
Standard_Boolean operator == (const IGESData_IGESType& another) const
{
return IsEqual(another);
}
//! resets fields (useful when an IGESType is stored as mask)
Standard_EXPORT void Nullify();
protected:
private:
Standard_Integer thetype;
Standard_Integer theform;
};
#endif // _IGESData_IGESType_HeaderFile
|
#pragma once
#include <memory> // std::unique_ptr
#include "GlobalHeader.h" // fa::OStream
#include <utility> // std::move
#include <type_traits> // std::is_same
#include "NoteImpl.h" // fa::NoteImpl
namespace fa {
class DailyPlanImpl;
} // END of namespace fa
namespace fa {
class PlanEntryInterface {
public:
using this_type = PlanEntryInterface;
using SmartPointer = std::unique_ptr<this_type>;
virtual ~PlanEntryInterface();
virtual SmartPointer copy_() = 0;
virtual OStream &printOn(OStream &) const = 0;
virtual bool isNote() const = 0;
virtual bool isFood() const = 0;
virtual bool equals(PlanEntryInterface const &) const = 0;
virtual String getText() const = 0;
}; // END of class PlanEntryInterface
OStream &operator<<(OStream &, PlanEntryInterface const &);
template <class Target>
class PlanEntryDynamicDelegator : public PlanEntryInterface {
public:
friend class DailyPlanImpl;
using this_type = PlanEntryDynamicDelegator;
using value_type = Target;
explicit PlanEntryDynamicDelegator(value_type value) noexcept
: val_{ std::move(value) } { }
virtual ~PlanEntryDynamicDelegator() = default;
virtual SmartPointer copy_() override {
return std::make_unique<this_type>(*this);
}
virtual OStream &printOn(OStream &ostr) const override {
return ostr << val_;
}
virtual bool isNote() const override {
return std::is_same<value_type, NoteImpl>::value;
}
virtual bool isFood() const override {
return !isNote();
}
virtual bool equals(PlanEntryInterface const &other) const override {
auto ptr = &other;
auto downcasted = dynamic_cast<this_type const *>(ptr);
if (downcasted == nullptr) {
return false;
}
return val_ == downcasted->val_;
}
virtual String getText() const override {
return val_.getText();
}
private:
value_type val_;
}; // END of class PlanEntryDynamicDelegator
} // END of namespace fa
|
#include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
#define inf 100000
/*
* Complete the 'findCapitalCity' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER robber_distance
* 2. WEIGHTED_INTEGER_GRAPH city
*/
/*
* For the weighted graph, <name>:
*
* 1. The number of nodes is <name>_nodes.
* 2. The number of edges is <name>_edges.
* 3. An edge exists between <name>_from[i] and <name>_to[i]. The weight of the edge is <name>_weight[i].
*
*/
int findCapitalCity(int robber_distance, int city_nodes, vector<int> city_from, vector<int> city_to, vector<int> city_weight) {
int dist[1001][1001], capital, leastRobbers, curRobbers;
//initialize all distance as inf
for(int i = 0; i < 1001; i++)
for(int j = 0; j < 1001; j++)
dist[i][j] = inf;
//update the distance as given in input
for(int i = 0; i < city_from.size(); i++ ){
dist[city_from[i]][city_to[i]] = city_weight[i];
dist[city_to[i]][city_from[i]] = city_weight[i];
}
//apply floyds algo
for(int k = 1; k <= city_nodes; k++)
for(int i = 1; i <= city_nodes; i++)
for(int j = 1; j <= city_nodes; j++)
if(dist[i][j] > dist[i][k] + dist[k][j])
dist[i][j] = dist[i][k] + dist[k][j];
//find robber
capital = 1;
leastRobbers = 9999;
for(int i = 1; i <= city_nodes; i++)
{
curRobbers = 0;
for(int j = 1;j <= city_nodes; j++)
if(dist[i][j] <= robber_distance)
curRobbers++;
cout << curRobbers << " " << i << endl;
if(leastRobbers >= curRobbers)
{
leastRobbers = curRobbers;
capital = i;
}
}
// cout << capital << endl;
return capital;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string robber_distance_temp;
getline(cin, robber_distance_temp);
int robber_distance = stoi(ltrim(rtrim(robber_distance_temp)));
string city_nodes_edges_temp;
getline(cin, city_nodes_edges_temp);
vector<string> city_nodes_edges = split(rtrim(city_nodes_edges_temp));
int city_nodes = stoi(city_nodes_edges[0]);
int city_edges = stoi(city_nodes_edges[1]);
vector<int> city_from(city_edges);
vector<int> city_to(city_edges);
vector<int> city_weight(city_edges);
for (int i = 0; i < city_edges; i++) {
string city_from_to_weight_temp;
getline(cin, city_from_to_weight_temp);
vector<string> city_from_to_weight = split(rtrim(city_from_to_weight_temp));
int city_from_temp = stoi(city_from_to_weight[0]);
int city_to_temp = stoi(city_from_to_weight[1]);
int city_weight_temp = stoi(city_from_to_weight[2]);
city_from[i] = city_from_temp;
city_to[i] = city_to_temp;
city_weight[i] = city_weight_temp;
}
int result = findCapitalCity(robber_distance, city_nodes, city_from, city_to, city_weight);
fout << result << "\n";
fout.close();
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
vector<string> split(const string &str) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
|
#pragma once
#include "common_def.h"
#include "proto_buf.h"
namespace fgs
{
bool Init(const char * config_file);
bool Update();
bool Close();
bool Send2Client(unid_t sid, PB::proto_buf& pb);
template < class PBTYPE >
bool Send2Client(unid_t sid, PBTYPE& pb)
{
PB2STR(pb, data_str, return false)
PB::proto_buf send_pb;
send_pb.set_pb_type(pb.type());
send_pb.set_pb_data(data_str);
return Send2Client(sid, send_pb);
}
}
|
#include <iostream>
using namespace std;
int doStuff() {
return 2 + 3;
}
int count_of_function_calls = 0;
void fun() {
count_of_function_calls++;
}
int main() {
fun();
fun();
fun();
cout << "Function fun was called: " << count_of_function_calls << " times.";
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 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"
#ifdef PI_CAMERA
// no need to update any project file
#pragma comment(lib, "vfw32.lib")
#include <Vfw.h>
#include <dbt.h>
#define OUR_GUID_ENTRY(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
EXTERN_C const GUID DECLSPEC_SELECTANY name \
= { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } };
//Just like DEFINE_GUID with INITGUID defined
//Needed for IAMPluginControl calls
#include <uuids.h>
#undef OUR_GUID_ENTRY
#include "WindowsOpCamera.h"
#include "adjunct/desktop_util/string/i18n.h"
#include "platforms/windows/pi/WindowsOpCamera_DirectShow.h"
#include "modules/console/opconsoleengine.h"
#include "modules/img/src/imagedecoderjpg.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/locale/locale-enum.h"
#include "modules/pi/OpBitmap.h"
#ifdef WINDOWS_CAMERA_GRAPH_TEST
#include "platforms/windows/prefs/PrefsCollectionMSWIN.h"
#endif
//why Vega #defines/#undefs this in every .cpp is beyond me...
//when the owner of Vega moves this to header, remove this and corresponding
//#undef and use the one gfx people maintain.
#define VEGA_CLAMP_U8(v) (((v) <= 255) ? (((v) >= 0) ? (v) : 0) : 255)
/* static */
OP_STATUS OpCameraManager::Create(OpCameraManager** new_camera_manager)
{
OP_ASSERT(new_camera_manager != NULL);
*new_camera_manager = OP_NEW(WindowsOpCameraManager, ());
if(*new_camera_manager == NULL)
return OpStatus::ERR_NO_MEMORY;
return OpStatus::OK;
}
extern HINSTANCE hInst; //from opera.cpp, this process HINSTANCE
// Error code translation for moving through adapter
static OP_CAMERA_STATUS HR2CAM(HRESULT hr)
{
if (hr == E_OUTOFMEMORY)
return OpCameraStatus::ERR_NO_MEMORY;
if (hr == VFW_E_CANNOT_CONNECT)
return OpCameraStatus::ERR_NOT_AVAILABLE;
if (FAILED(hr))
return OpCameraStatus::ERR;
return OpCameraStatus::OK;
};
static OP_CAMERA_STATUS CAM2HR(OP_CAMERA_STATUS status)
{
if (status == OpCameraStatus::ERR_NO_MEMORY)
return E_OUTOFMEMORY;
if (status == OpCameraStatus::ERR_NOT_AVAILABLE)
return VFW_E_CANNOT_CONNECT;
if (OpStatus::IsError(status))
return E_FAIL;
return S_OK;
};
#define METHOD_CALL //OutputDebugStringA( __FUNCTION__ "\n" )
WindowsOpCameraManager::WindowsOpCameraManager()
: m_notify_sink(NULL)
, m_pnp_notify(NULL)
, m_device_listener(NULL)
{
static ATOM notify_class = 0;
if (!notify_class)
{
WNDCLASS wc = {};
wc.lpfnWndProc = NotifyProc;
wc.hInstance = hInst;
wc.lpszClassName = L"CameraNotifyCallback";
notify_class = RegisterClass(&wc);
}
m_notify_sink = CreateWindowEx(0, MAKEINTATOM(notify_class), L"Opera", WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, NULL, NULL, hInst, NULL);
}
WindowsOpCameraManager::~WindowsOpCameraManager()
{
if (IsWindow(m_notify_sink))
SendMessage(m_notify_sink, WM_CLOSE, 0, 0);
}
OP_STATUS WindowsOpCameraManager::GetCameraDevices(OpVector<OpCamera>* camera_devices)
{
UINT32 count = m_cameras.GetCount();
for (UINT32 i = 0; i < count; ++i)
{
WindowsOpCamera* cam = m_cameras.Get(i);
if (cam && cam->IsConnected())
camera_devices->Add(cam);
}
return OpStatus::OK;
}
void WindowsOpCameraManager::_InitializePnP(HWND hWnd)
{
UpdatePnPList(m_cameras);
OP_ASSERT(m_pnp_notify == NULL);
DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) );
NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
m_pnp_notify =
RegisterDeviceNotification(hWnd, &NotificationFilter,
DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
#ifdef WINDOWS_CAMERA_GRAPH_TEST
if (g_pcmswin->GetIntegerPref(PrefsCollectionMSWIN::BanDefaultDirectShowRenderers) != FALSE)
#else
//Always disable the renderers
#endif
{
// Ban all the system-provided renderers. If we don't do this
// then the "magical" and "intelligent" IGraphBuilder::Render
// used inside OpDirectShowCamera::CreateGraph will create,
// in some bizzare filters configurations[1], a graph with
// Opera Sink not connected, and VMR (or similar) present
// and connected. This in turn will create separate window
// (HWND) with the output, as a result of IGraphBuilder::Run call.
//
// There is a problem here, as this calls are proccess-wide
// and can produce unexpected results in some other parts of
// the code.
//
// On the other hand, we render the video with gstream and here
// we need the video from camera rendered onto OpBitmap and not
// DirectX surface. Assumption here is, if we ever wanted
// DirectShow again, we would use our own sink anyway.
//
// [1] Here, "bizzare" configuration is one, where cross section
// of filter set on output pin of camera and filter set on input
// ping of Opera Sink is empty.
OpComPtr<IAMPluginControl> control;
HRESULT hr = control.CoCreateInstance(CLSID_DirectShowPluginControl);
if (SUCCEEDED(hr))
{
control->SetDisabled(CLSID_VideoMixingRenderer, TRUE);
control->SetDisabled(CLSID_VideoMixingRenderer9, TRUE);
control->SetDisabled(CLSID_VideoRendererDefault, TRUE);
control->SetDisabled(CLSID_EnhancedVideoRenderer, TRUE);
control->SetDisabled(CLSID_VideoRenderer, TRUE);
}
}
}
void WindowsOpCameraManager::_UninitializePnP()
{
if (m_pnp_notify)
UnregisterDeviceNotification(m_pnp_notify);
m_pnp_notify = NULL;
}
void WindowsOpCameraManager::_OnDeviceChange(WPARAM wParam, LPARAM lParam)
{
// Note to the future maintainer:
//
// Half of the notifications use DEV_BROADCAST_HEADER structure;
// the other half has the lParam set to zero. If you ever expand
// the switch to inlude something like DBT_QUERYCHANGECONFIG, be
// sure to reflect that on the condition below: either change it,
// or move the dev_iface test into the switch.
PDEV_BROADCAST_DEVICEINTERFACE dev_iface = reinterpret_cast<PDEV_BROADCAST_DEVICEINTERFACE>(lParam);
if (!dev_iface || dev_iface->dbcc_devicetype != DBT_DEVTYP_DEVICEINTERFACE)
return;
WindowsOpCamera* cam = NULL;
switch (wParam)
{
case DBT_DEVICEARRIVAL:
case DBT_DEVICEREMOVECOMPLETE:
UpdatePnPList(m_cameras);
cam = FindPnPCamera(dev_iface->dbcc_name, m_cameras);
if (cam)
{
if (wParam == DBT_DEVICEARRIVAL && cam->IsConnected())
OnCameraAdded(cam);
else if (!cam->IsConnected())
OnCameraRemoved(cam);
}
return;
};
}
void WindowsOpCameraManager::OnCameraAdded(WindowsOpCamera* nfo)
{
#if 0
// Used rarely, not even in the debug, but will be handy,
// once Core supports camera hotplugging. After that can be removed
UINT32 count = m_cameras.GetCount();
for (UINT32 i = 0; i < count; ++i)
{
WindowsOpCamera* cam = m_cameras.Get(i);
wchar_t buffer[1024] = L"";
if (cam)
{
wchar_t c = L' ';
if (nfo && *cam == *nfo) c = L'>';
if (cam->GetPath().CStr())
swprintf_s(buffer, L"%c %6d %s [%s]\n", c, cam->GetDevice(), cam->GetName().CStr(), cam->GetPath().CStr());
else
swprintf_s(buffer, L"%c %6d %s [-]\n", c, cam->GetDevice(), cam->GetName().CStr());
}
else swprintf_s(buffer, L" ------ -\n");
OutputDebugString(buffer);
}
#endif
if (nfo && m_device_listener)
{
m_device_listener->OnCameraAttached(nfo);
}
}
void WindowsOpCameraManager::OnCameraRemoved(WindowsOpCamera* nfo)
{
#if 0
// Used rarely, not even in the debug, but will be handy,
// once Core supports camera hotplugging. After that can be removed
UINT32 count = m_cameras.GetCount();
for (UINT32 i = 0; i < count; ++i)
{
WindowsOpCamera* cam = m_cameras.Get(i);
wchar_t buffer[1024] = L"";
if (cam)
{
wchar_t c = L' ';
if (nfo && *cam == *nfo) c = L'<';
if (cam->GetPath().CStr())
swprintf_s(buffer, L"%c %6d %s [%s]\n", c, cam->GetDevice(), cam->GetName().CStr(), cam->GetPath().CStr());
else
swprintf_s(buffer, L"%c %6d %s [-]\n", c, cam->GetDevice(), cam->GetName().CStr());
}
else swprintf_s(buffer, L" ------ -\n");
OutputDebugString(buffer);
}
#endif
if (nfo && m_device_listener)
{
m_device_listener->OnCameraDetached(nfo);
}
}
// The compare function below is enhanced to favour USB devices
// over other types of devices. Once we have an infrastucture
// allowing users to knowingly choose a device, those enhancements
// should be removed and the function should back down to device id
// comparison.
// --- ENHANCEMENT ----
static bool CameraIsUSBDevice(const WindowsOpCamera* cam)
{
static const uni_char usb_path[] = L"\\\\?\\USB#";
return cam->GetPath().Compare(usb_path, ARRAY_SIZE(usb_path)-1) == 0;
}
// --- /ENHANCEMENT ----
static int CameraOrder(const WindowsOpCamera** left, const WindowsOpCamera** right)
{
if (!left)
return right ? -1 : 0;
if (!right)
return 1;
if (!*left)
return *right ? -1 : 0;
if (!*right)
return 1;
const WindowsOpCamera* _left = *left;
const WindowsOpCamera* _right = *right;
// --- ENHANCEMENT ----
// if one (and only one) camera is an USB device
// then it wins compared to any PCI and otherwise
// attached device
bool _left_is_usb = CameraIsUSBDevice(_left);
bool _right_is_usb = CameraIsUSBDevice(_right);
if (_left_is_usb != _right_is_usb)
{
//non-USB is greater than USB, so that USB is sorted at the begining
return _left_is_usb ? -1 : 1;
}
// --- /ENHANCEMENT ----
return _left->GetDevice() - _right->GetDevice();
}
void WindowsOpCameraManager::UpdatePnPList(OpVector<WindowsOpCamera>& cams)
{
DWORD device = 0;
UINT32 count = cams.GetCount();
for (UINT32 i = 0; i < count; ++i)
{
WindowsOpCamera* cam = cams.Get(i);
if (cam)
cam->InvalidateDevice();
}
OpComPtr<ICreateDevEnum> cde;
if (SUCCEEDED(cde.CoCreateInstance(CLSID_SystemDeviceEnum)))
{
OpComPtr<IEnumMoniker> mons;
OpComPtr<IMoniker> mon;
if (SUCCEEDED(cde->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &mons, 0)) && mons)
{
mons->Reset();
ULONG fetched;
HRESULT hr;
while(hr = mons->Next(1, &mon, &fetched), hr==S_OK && fetched == 1)
{
OpComPtr<IPropertyBag> bag;
if (FAILED(mon->BindToStorage(NULL, NULL, IID_IPropertyBag, (void **)&bag)))
{
mon = NULL;
device++;
continue;
}
bool use_name = false;
OpString data;
OpComVariant var;
hr = bag->Read(L"DevicePath", &var, NULL);
if (FAILED(hr))
{
hr = bag->Read(L"FriendlyName", &var, NULL);
use_name = true;
}
if (SUCCEEDED(hr))
hr = var.ChangeType(VT_BSTR);
if (SUCCEEDED(hr))
{
OpStatus::Ignore(data.Set(V_BSTR(&var)));
if (!use_name)
data.MakeUpper();
var.Clear();
}
WindowsOpCamera* found = NULL;
if (use_name)
{
for (UINT32 i = 0; i < count; ++i)
{
WindowsOpCamera* cam = cams.Get(i);
if (cam &&
cam->GetPath().Compare(OpStringC()) == 0 &&
cam->GetName().Compare(data) == 0)
{
found = cam;
break;
}
}
}
else
{
for (UINT32 i = 0; i < count; ++i)
{
WindowsOpCamera* cam = cams.Get(i);
if (cam && cam->GetPath().Compare(data) == 0)
{
found = cam;
break;
}
}
}
if (found)
{
found->ValidateDevice(device);
mon = NULL;
device++;
continue;
}
OpAutoPtr<WindowsOpCamera> cam = OP_NEW(WindowsOpCamera, (bag, device));
if (OpStatus::IsSuccess(cams.Add(cam.get())))
cam.release();
mon = NULL;
device++;
}
}
}
// Sort cameras based on m_device
// As a side effect, objects with camera device id
// 0xFFFFFFFF (representing devices once seen, but
// now detached) will be sorted at the end
cams.QSort(CameraOrder);
}
inline WindowsOpCamera* WindowsOpCameraManager::FindPnPCamera(const wchar_t* path, const OpVector<WindowsOpCamera>& cams)
{
OpString key;
if (OpStatus::IsError(key.Set(path)))
return NULL;
key.MakeUpper();
UINT32 count = cams.GetCount();
for (UINT32 i = 0; i < count; i++)
{
WindowsOpCamera* cam = cams.Get(i);
if (cam && cam->GetPath().Compare(key) == 0)
return cam;
}
return NULL;
}
LRESULT CALLBACK WindowsOpCameraManager::NotifyProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CREATE:
// g_op_camera_manager is still NULL here
PostMessage(hWnd, DirectShow::WMU_PNP_INIT, 0, 0);
return 0;
case DirectShow::WMU_PNP_INIT:
WindowsOpCameraManager::InitializePnP(hWnd);
return 0;
case DirectShow::WMU_UPDATE:
WindowsOpCamera::OnCameraUpdateFrame(lParam);
return 0;
case DirectShow::WMU_RESIZE:
WindowsOpCamera::OnCameraFrameResize(lParam);
return 0;
case DirectShow::WMU_MEDIA_EVENT:
WindowsOpCamera::OnMediaEvent(lParam);
return 0;
case WM_DESTROY:
WindowsOpCameraManager::UninitializePnP();
return 0;
case WM_DEVICECHANGE:
WindowsOpCameraManager::OnDeviceChange(wParam, lParam);
return DefWindowProc(hWnd, uMsg, wParam, lParam);
};
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
void WindowsOpCamera::GetProperty(IPropertyBag* bag, LPCWSTR propname, OpString& prop)
{
prop.Empty();
OpComVariant var;
if (FAILED(bag->Read(propname, &var, NULL)))
return;
if (FAILED(var.ChangeType(VT_BSTR)))
return;
prop.Append(V_BSTR(&var));
}
WindowsOpCamera::WindowsOpCamera(IPropertyBag* bag, DWORD device)
: m_preview_listener(NULL)
, m_device(device)
{
GetProperty(bag, L"FriendlyName", m_name);
GetProperty(bag, L"Description", m_descr);
GetProperty(bag, L"DevicePath", m_path);
m_path.MakeUpper();
}
WindowsOpCamera::~WindowsOpCamera()
{
}
void WindowsOpCamera::_OnMediaEvent()
{
long code = 0;
LONG_PTR p1 = 0, p2 = 0;
if (!m_event)
return;
while (SUCCEEDED(m_event->GetEvent(&code, &p1, &p2, 0)))
{
#if 0
// Used rarely, not even in the debug, but will be handy,
// once Core supports camera hotplugging. After that we might
// consider removing media event support entirely.
char buffer[1024];
switch (code)
{
case EC_CLOCK_CHANGED:
strcpy_s(buffer, "WMU_MEDIA_EVENT: EC_CLOCK_CHANGED\n");
break;
case EC_DEVICE_LOST:
{
IUnknown* unk = reinterpret_cast<IUnknown*>(p1);
OpComQIPtr<IBaseFilter> filter(unk);
if (filter)
{
FILTER_INFO info = {};
if (SUCCEEDED(filter->QueryFilterInfo(&info)))
{
if (info.pGraph)
info.pGraph->Release();
sprintf_s(buffer, "WMU_MEDIA_EVENT: EC_DEVICE_LOST, 0x%016x '%S' %s\n", p1, info.achName, p2 ? "available" : "removed");
break;
}
}
sprintf_s(buffer, "WMU_MEDIA_EVENT: EC_DEVICE_LOST, 0x%016x %s\n", p1, p2 ? "available" : "removed");
}
break;
default:
sprintf_s(buffer, "WMU_MEDIA_EVENT: 0x%08x, 0x%016x 0x%016x\n", code, p1, p2);
};
OutputDebugStringA(buffer);
#endif
m_event->FreeEventParams(code, p1, p2);
}
}
// OpCamera
OP_CAMERA_STATUS WindowsOpCamera::Enable(OpCameraPreviewListener* preview_listener)
{
METHOD_CALL;
if (!IsConnected())
return OpCameraStatus::ERR_NOT_AVAILABLE;
if (IsEnabled())
Disable();
//WindowsOpCameraManager::SetListener(this);
#ifdef OPERA_CONSOLE
Str::LocaleString string_id = m_name.IsEmpty() ? Str::S_STARTED_UNNAMED_CAMERA : Str::S_STARTED_CAMERA;
OpConsoleEngine::Message msg(OpConsoleEngine::Internal, OpConsoleEngine::Information);
OP_STATUS status = I18n::Format(msg.context, string_id, m_name.CStr());
if (OpStatus::IsSuccess(status))
{
TRAPD(rc, g_console->PostMessageL(&msg));
}
#endif
m_preview_listener = preview_listener;
OpComPtr<DirectShow::ICamera> camera;
HRESULT hr = OpComObject<DirectShow::impl::OpDirectShowCamera>::Create(&camera);
if (FAILED(hr))
return HR2CAM(hr);
hr = camera->CreateGraph(this, m_device, &m_control);
if (FAILED(hr))
return HR2CAM(hr);
if (!m_control)
return OpCameraStatus::ERR;
hr = m_control->QueryInterface(&m_event);
if (FAILED(hr))
return HR2CAM(hr);
if (!m_event)
return OpCameraStatus::ERR;
m_event->SetNotifyWindow(
reinterpret_cast<OAHWND>(WindowsOpCameraManager::GetSyncWindow()),
DirectShow::WMU_MEDIA_EVENT,
reinterpret_cast<LONG_PTR>(this)
);
long flags = 0;
if (SUCCEEDED(m_event->GetNotifyFlags(&flags)) && (flags & AM_MEDIAEVENT_NONOTIFY))
m_event->SetNotifyFlags(flags & ~AM_MEDIAEVENT_NONOTIFY);
m_camera = camera;
//dump the graph
#ifdef DEBUG_DSHOW_GRAPH_DUMP
OpComPtr<IGraphBuilder> gb;
OLE(m_control.QueryInterface(&gb));
OLE(DirectShow::debug::DumpGraph(gb));
#endif
hr = m_control->Run();
if (FAILED(hr))
{
Disable();
return HR2CAM(hr);
}
return OpCameraStatus::OK;
}
void WindowsOpCamera::Disable()
{
METHOD_CALL;
m_preview_listener = NULL;
m_camera = NULL;
if (m_control)
m_control->Stop();
m_control = NULL;
if (m_event)
m_event->SetNotifyWindow(0, 0, 0);
m_event = NULL;
}
OP_CAMERA_STATUS WindowsOpCamera::GetCurrentPreviewFrame(OpBitmap** frame)
{
if (!IsConnected())
return OpCameraStatus::ERR_NOT_AVAILABLE;
if (!IsEnabled())
return OpCameraStatus::ERR_DISABLED;
return HR2CAM(m_camera->GetCurrentPreviewFrame(frame));
}
OP_CAMERA_STATUS WindowsOpCamera::GetPreviewDimensions(Resolution* dimensions)
{
if (!IsEnabled())
return OpCameraStatus::ERR_DISABLED;
return HR2CAM(m_camera->GetPreviewDimensions(dimensions));
}
namespace DirectShow
{
const GUID MEDIASUBTYPE_4CC_I420 = { 0x30323449, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 };
namespace trans
{
//3 bytes per pixel, 1 pixel per sample
class OpTransformRGB24: public OpTransform< OpTransformRGB24 >
{
public:
static long Stride(long width) { return BitmapStride(width * 3); }
static size_t LineOffset(long height, long y, long stride) { return (height - y - 1) * stride; }
static void TransformLine(long width, unsigned char * dst, const unsigned char * src)
{
for (long x = 0; x < width; ++x)
{
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = 0xFF;
}
}
static bool Supported(REFIID mediasubtype)
{
return mediasubtype == MEDIASUBTYPE_RGB24 || 0; //there was a performance warning of int->bool conversion
}
};
//4 bytes per pixel, 1 pixel per sample
class OpTransformRGB32: public OpTransform< OpTransformRGB32 >
{
public:
static long Stride(long width) { return BitmapStride(width * 4); }
static size_t LineOffset(long height, long y, long stride) { return (height - y - 1) * stride; }
static void TransformLine(long width, unsigned char * dst, const unsigned char * src)
{
op_memcpy(dst, src, width * 4);
}
static bool Supported(REFIID mediasubtype)
{
return mediasubtype == MEDIASUBTYPE_RGB32 || 0;
}
};
// 2 bytes per pixel, 2 pixels per sample
class OpTransformYUY2: public OpTransform< OpTransformYUY2 >
{
public:
static long Stride(long width) { return BitmapStride(width * 2); }
static size_t LineOffset(long, long y, long stride) { return y * stride; }
static void TransformLine(long width, unsigned char * dst, const unsigned char * src)
{
for (int x = 0; x < width; x += 2)
{
int Y1, U, Y2, V, UV;
Y1 = *src++;
U = *src++;
Y2 = *src++;
V = *src++;
Y1 -= 16;
Y2 -= 16;
U -= 128;
V -= 128;
Y1 = 1164 * Y1;
Y2 = 1164 * Y2;
UV = 391 * U + 813 * V;
V = 1596 * V;
U = 2018 * U;
*dst++ = VEGA_CLAMP_U8((Y1 + U)/1000);
*dst++ = VEGA_CLAMP_U8((Y1 - UV)/1000);
*dst++ = VEGA_CLAMP_U8((Y1 + V)/1000);
*dst++ = 0xFF;
*dst++ = VEGA_CLAMP_U8((Y2 + U)/1000);
*dst++ = VEGA_CLAMP_U8((Y2 - UV)/1000);
*dst++ = VEGA_CLAMP_U8((Y2 + V)/1000);
*dst++ = 0xFF;
}
}
static bool Supported(REFIID mediasubtype)
{
return mediasubtype == MEDIASUBTYPE_YUY2 ||
mediasubtype == MEDIASUBTYPE_YUYV;
}
};
//planar, Y plane followed by U and V planes, Y size is width x height, U and V size quarter that
class OpTransformI420
{
public:
static long BitmapStride(long raw_bytes_per_line) { return ((raw_bytes_per_line + 3) >> 2) << 2; }
static void TransformLine(long width, unsigned char * dst, const unsigned char * luma, const unsigned char* chroma_u, const unsigned char* chroma_v)
{
for (int x = 0; x < width; x += 2)
{
int Y1, U, Y2, V, UV;
Y1 = *luma++;
Y2 = *luma++;
U = *chroma_u++;
V = *chroma_v++;
Y1 -= 16;
Y2 -= 16;
U -= 128;
V -= 128;
Y1 = 1164 * Y1;
Y2 = 1164 * Y2;
UV = 391 * U + 813 * V;
V = 1596 * V;
U = 2018 * U;
*dst++ = VEGA_CLAMP_U8((Y1 + U)/1000);
*dst++ = VEGA_CLAMP_U8((Y1 - UV)/1000);
*dst++ = VEGA_CLAMP_U8((Y1 + V)/1000);
*dst++ = 0xFF;
*dst++ = VEGA_CLAMP_U8((Y2 + U)/1000);
*dst++ = VEGA_CLAMP_U8((Y2 - UV)/1000);
*dst++ = VEGA_CLAMP_U8((Y2 + V)/1000);
*dst++ = 0xFF;
}
}
static HRESULT Transform(const unsigned char* src_data, long /* src_bytes */, OpBitmap *frame, long width, long height)
{
//This function will be called only, if OpBitmap supports pointers.
//If current implementation of OpBitmap does not support pointers,
//the OpDirectShowCamera::SetMediaType will start asserting and
//OpDirectShowCamera::Receive will not call any transforms...
unsigned char * dst_data = reinterpret_cast<unsigned char*>(frame->GetPointer());
unsigned long dst_stride = width * 4; // ABGR32
long luma_stride = width;
long chroma_stride = width / 2;
const unsigned char* src_chroma_u = src_data + luma_stride * height;
const unsigned char* src_chroma_v = src_chroma_u + chroma_stride * height/2;
for (long y = 0; y < height; ++y)
{
unsigned char * dst = dst_data + y * dst_stride;
const unsigned char * luma = src_data + y * luma_stride;
//this will take every chroma line twice, once for y mod 2 == 0, second for y mod 2 == 1
//which is exactly, what is needed for this planar sampling
const unsigned char * chroma_u = src_chroma_u + (y/2) * chroma_stride;
const unsigned char * chroma_v = src_chroma_v + (y/2) * chroma_stride;
TransformLine(width, dst, luma, chroma_u, chroma_v);
}
frame->ReleasePointer();
return S_OK;
}
static bool Supported(REFIID mediasubtype)
{
return mediasubtype == MEDIASUBTYPE_4CC_I420 ||
mediasubtype == MEDIASUBTYPE_IYUV;
}
};
//intra-jpeg encoding, using core
class OpTransformJPEG
{
class JpegTransform: public ImageDecoderListener
{
OpBitmap *m_frame;
unsigned char * dst_data;
long m_width;
long m_height;
long m_outwidth;
public:
JpegTransform(OpBitmap *frame, long width, long height)
: m_frame(frame)
, m_width(width)
, m_height(height)
, m_outwidth(width)
, dst_data(NULL)
{
//here, only OpBitmaps supporting pointers are allowed
dst_data = reinterpret_cast<unsigned char*>(m_frame->GetPointer());
}
~JpegTransform()
{
if (dst_data)
m_frame->ReleasePointer();
}
void OnLineDecoded(void* data, INT32 line, INT32 lineHeight)
{
if (!dst_data)
return;
op_memcpy(dst_data + line * m_width * 4, data, m_outwidth * 4);
}
BOOL OnInitMainFrame(INT32 width, INT32 height)
{
BOOL ret = width == m_width && height == m_height;
if (m_outwidth > width)
m_outwidth = width;
return ret;
}
void OnNewFrame(const ImageFrameData& image_frame_data) {}
void OnAnimationInfo(INT32 nrOfRepeats) {}
void OnDecodingFinished() {}
void OnMetaData(ImageMetaData, const char*) {}
virtual void OnICCProfileData(const UINT8* data, unsigned datalen) {}
};
public:
static HRESULT Transform(const unsigned char* src_data, long src_bytes, OpBitmap *frame, long width, long height)
{
int resend_bytes = 0;
ImageDecoderJpg jpgdecoder;
JpegTransform listener(frame, width, height);
jpgdecoder.SetImageDecoderListener(&listener);
return CAM2HR(jpgdecoder.DecodeData(src_data, src_bytes, FALSE, resend_bytes));
}
static bool Supported(REFIID mediasubtype)
{
return mediasubtype == MEDIASUBTYPE_MJPG || 0;
}
};
//contents must be in sync with coll::OpInputMediaTypes::formats below
static FormVtbl _forms[] = {
{ OpTransformRGB24::Supported, OpTransformRGB24::Transform },
{ OpTransformRGB32::Supported, OpTransformRGB32::Transform },
{ OpTransformYUY2::Supported, OpTransformYUY2::Transform },
{ OpTransformJPEG::Supported, OpTransformJPEG::Transform },
{ OpTransformI420::Supported, OpTransformI420::Transform }
};
const FormVtbl* forms = _forms;
const size_t form_count = ARRAY_SIZE(_forms);
}
namespace coll
{
// contents must be in sync with contents of trans::_forms above
// notable difference: YUYV missing here, while it is supported by OpXFormYUY2
// this happens, because the documentation for YUY2 and YUYV
// says they are the same, but I couldn't find any camera
// with YUYV to actually check it.
//
// Exactly the same goes for I420 and IYUV.
const MediaFormat OpInputMediaTypes::formats[] =
{
MediaFormat( MEDIASUBTYPE_RGB24, 24 ),
MediaFormat( MEDIASUBTYPE_RGB32, 32 ),
MediaFormat( MEDIASUBTYPE_YUY2, 16, 0x32595559 ),
MediaFormat( MEDIASUBTYPE_MJPG, 24, 0x47504a4d ),
MediaFormat( MEDIASUBTYPE_4CC_I420, 12, 0x30323449 ), //media subtype not defined in uuids.h
};
const size_t OpInputMediaTypes::format_count = ARRAY_SIZE(OpInputMediaTypes::formats);
ULONG OpInputMediaTypes::CollectionSize() const
{
#ifdef WINDOWS_CAMERA_GRAPH_TEST
if (m_prefs_forced_format)
return sizes.GetCount();
#endif
return sizes.GetCount() * format_count;
}
HRESULT OpInputMediaTypes::CopyItem(ULONG pos, AM_MEDIA_TYPE** ppOut)
{
size_t s_count = sizes.GetCount();
#ifdef WINDOWS_CAMERA_GRAPH_TEST
const MediaFormat& fmt = m_prefs_forced_format ? *m_prefs_forced_format : formats[pos / s_count];
#else
const MediaFormat& fmt = formats[pos / s_count];
#endif
const FrameSize* ref = sizes.Get(pos % s_count);
ULONG linesize = (((ref->width * fmt.bitcount / 8) + 3) >> 2) << 2;
AM_MEDIA_TYPE stencil = {};
VIDEOINFOHEADER header = {};
stencil.pbFormat = reinterpret_cast<BYTE*>(&header);
stencil.cbFormat = sizeof(header);
header.bmiHeader.biSize = sizeof(header.bmiHeader);
fmt.FillMediaType(stencil, header);
ref->FillMediaType(stencil, header, ref->height * linesize);
*ppOut = mtype::CreateMediaType(&stencil);
if (!*ppOut)
return E_OUTOFMEMORY;
return S_OK;
}
HRESULT OpInputMediaTypes::FinalCreate()
{
#ifdef WINDOWS_CAMERA_GRAPH_TEST
GUID subtype = impl::OpDirectShowCamera::OverridenCameraFormat();
if (subtype != GUID_NULL)
{
for (size_t i = 0; i < trans::form_count; i++)
{
const MediaFormat* format = formats + i;
if (format->subtype == subtype)
{
m_prefs_forced_format = format;
break;
}
}
}
#endif
return S_OK;
}
};
namespace impl
{
namespace
{
wchar_t vendor_name[] = L"Opera Software ASA";
wchar_t pin_name[] = L"Input0"; //must not exceed MAX_PIN_NAME
enum
{
PIN_NAME_SIZE = sizeof(pin_name),
VENDOR_NAME_SIZE = sizeof(vendor_name)
};
};
OpDirectShowCamera::~OpDirectShowCamera()
{
mtype::DeleteMediaType(media_type);
media_type = NULL;
OP_DELETE(frame);
OP_DELETE(backbuffer);
}
HRESULT OpDirectShowCamera::FinalCreate()
{
return CAM2HR(camera_mutex.Init());
}
HRESULT OpDirectShowCamera::SetMediaType(const AM_MEDIA_TYPE* pmt, bool notify)
{
METHOD_CALL;
if (media_type)
{
mtype::DeleteMediaType(media_type);
media_type = NULL;
}
OpCamera::Resolution res;
curr_xform = NULL;
#ifdef WINDOWS_CAMERA_GRAPH_TEST
{
GUID subtype = OverridenCameraFormat();
if (subtype != GUID_NULL && subtype != pmt->subtype)
return VFW_E_INVALID_MEDIA_TYPE;
}
#endif
for (size_t i = 0; i < trans::form_count; i++)
{
const trans::FormVtbl* transform = trans::forms + i;
if (transform->Supported(pmt->subtype))
{
curr_xform = transform;
break;
}
}
if (!curr_xform) // now, someone called SetMediaType on media type not vetted by QueryAccept....
return VFW_E_INVALID_MEDIA_TYPE;
media_type = mtype::CreateMediaType(pmt);
if (!media_type)
return E_OUTOFMEMORY;
if (media_type->formattype == FORMAT_VideoInfo)
{
VIDEOINFOHEADER* header = reinterpret_cast<VIDEOINFOHEADER*>(media_type->pbFormat);
res.x = header->bmiHeader.biWidth;
res.y = header->bmiHeader.biHeight;
}
else if (media_type->formattype == FORMAT_VideoInfo2)
{
VIDEOINFOHEADER2* header = reinterpret_cast<VIDEOINFOHEADER2*>(media_type->pbFormat);
res.x = header->bmiHeader.biWidth;
res.y = header->bmiHeader.biHeight;
}
if (res.x == 0 || res.y == 0)
return E_FAIL;
if (res.x != frame_res.x || res.y != frame_res.y || !frame)
{
DesktopMutexLock on(camera_mutex);
frame_res = res;
OP_DELETE(frame);
frame = NULL;
OP_CAMERA_STATUS tmp = OpBitmap::Create(&frame, res.x, res.y);
if (OpStatus::IsError(tmp))
{
if (backbuffer_status == BACKBUFFER_FRESH)
{
OP_DELETE(backbuffer);
backbuffer = NULL;
}
else
backbuffer_status = BACKBUFFER_STALE;
return CAM2HR(tmp);
}
OP_ASSERT(frame->Supports(OpBitmap::SUPPORTS_POINTER) && "Bitmaps without SUPPORTS_POINTER are rather pointless here...");
if (!frame->Supports(OpBitmap::SUPPORTS_POINTER))
{
if (backbuffer_status == BACKBUFFER_FRESH)
{
OP_DELETE(backbuffer);
backbuffer = NULL;
}
else
backbuffer_status = BACKBUFFER_STALE;
OP_DELETE(frame);
frame = NULL;
return E_FAIL;
}
if (backbuffer_status == BACKBUFFER_FRESH)
{
OP_DELETE(backbuffer);
backbuffer = NULL;
tmp = OpBitmap::Create(&backbuffer, res.x, res.y);
if (OpStatus::IsError(tmp))
return CAM2HR(tmp);
OP_ASSERT(backbuffer->Supports(OpBitmap::SUPPORTS_POINTER) && "Bitmaps without SUPPORTS_POINTER are rather pointless here...");
if (!backbuffer->Supports(OpBitmap::SUPPORTS_POINTER))
{
OP_DELETE(frame);
OP_DELETE(backbuffer);
frame = NULL;
backbuffer = NULL;
return E_FAIL;
}
}
else
backbuffer_status = BACKBUFFER_STALE;
}
if (parent && notify)
parent->OnCameraFrameResize();
return S_OK;
}
HRESULT OpDirectShowCamera::EnsureInputPinPresent()
{
if (in_pin)
return S_OK;
METHOD_CALL;
return OpComObjectEx<OpDirectShowCameraPin>::Create(this, &in_pin);
}
HRESULT OpDirectShowCamera::ReadSupportedSizes(IPin* pin)
{
METHOD_CALL;
HRESULT hr = S_OK;
ULONG fetched = 0;
OpComPtr<IEnumMediaTypes> types;
OLE(pin->EnumMediaTypes(&types));
AM_MEDIA_TYPE* type = NULL;
sizes.DeleteAll();
while(hr = types->Next(1, &type, &fetched), hr==S_OK && fetched == 1)
{
OpAutoPtr<coll::FrameSize> size = OP_NEW(coll::FrameSize, ());
if (type->majortype == MEDIATYPE_Video && type->cbFormat && type->pbFormat)
{
if (type->formattype == FORMAT_VideoInfo)
{
VIDEOINFOHEADER* pvi = reinterpret_cast<VIDEOINFOHEADER*>(type->pbFormat);
size->CopyFromFormat(pvi);
}
else if (type->formattype == FORMAT_VideoInfo2)
{
VIDEOINFOHEADER2* pvi = reinterpret_cast<VIDEOINFOHEADER2*>(type->pbFormat);
size->CopyFromFormat(pvi);
}
}
mtype::DeleteMediaType(type);
type = NULL;
if (size->width == 0 || size->height == 0)
continue;
UINT32 i = 0, len = sizes.GetCount();
for (; i < len; ++i)
{
const coll::FrameSize* ref = sizes.Get(i);
if (!ref)
continue;
if (*ref == *size)
break;
}
if (i == len)
{
if (OpStatus::IsError(sizes.Add(size.get())))
continue;
size.release();
}
}
return S_OK;
}
static inline HRESULT GetBaseFilter(DWORD device, IBaseFilter** ppOut)
{
HRESULT hr = S_OK;
ULONG fetched = 0;
OpComPtr<ICreateDevEnum> cde;
OpComPtr<IEnumMoniker> mons;
OpComPtr<IMoniker> mon;
OLE(cde.CoCreateInstance(CLSID_SystemDeviceEnum));
OLE(cde->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &mons, 0));
OLE(mons->Reset());
if (device)
hr = mons->Skip(device); //skip the #[device] monikers from the begining
hr = mons->Next(1, &mon, &fetched);
if (hr!=S_OK || fetched != 1)
return SUCCEEDED(hr) ? E_FAIL : hr;
return mon->BindToObject(NULL, NULL, IID_IBaseFilter, (void**)ppOut);
}
STDMETHODIMP OpDirectShowCamera::CreateGraph(WindowsOpCamera* parent, DWORD device, IMediaControl** ppmc)
{
METHOD_CALL;
HRESULT hr = S_OK;
this->parent = NULL;
#if defined WINDOWS_CAMERA_GRAPH_TEST && defined OPERA_CONSOLE
{
GUID subtype = OverridenCameraFormat();
if (subtype != GUID_NULL)
{
OpConsoleEngine::Message msg(OpConsoleEngine::Internal, OpConsoleEngine::Information);
msg.context.Set(L"Overriding camera format");
msg.message.Append(g_pcmswin->GetStringPref(PrefsCollectionMSWIN::SupportedCameraFormat));
TRAPD(rc, g_console->PostMessageL(&msg));
}
}
#endif
OpComPtr<IGraphBuilder> gb;
OpComPtr<IBaseFilter> opera, cam;
OpComPtr<IPin> cam_out;
OLE(EnsureInputPinPresent());
OLE(GetBaseFilter(device, &cam));
OLE(GetBaseObject()->QueryInterface(&opera));
OLE(gb.CoCreateInstance(CLSID_FilterGraph));
OLE(gb->AddFilter(cam, L"Camera Source"));
OLE(gb->AddFilter(opera, L"Opera Sink"));
{
OpComPtr<ICaptureGraphBuilder2> cgb;
OLE(cgb.CoCreateInstance(CLSID_CaptureGraphBuilder2));
OLE(cgb->SetFiltergraph(gb));
OLE(cgb->FindPin(cam, PINDIR_OUTPUT, &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, TRUE, 0, &cam_out));
}
OLE(ReadSupportedSizes(cam_out));
OLE(gb->Render(cam_out));
OLE(gb.QueryInterface(ppmc));
this->parent = parent;
return S_OK;
}
STDMETHODIMP OpDirectShowCamera::GetCurrentPreviewFrame(OpBitmap** ppFrame)
{
DesktopMutexLock on(camera_mutex);
if (frame_dirty)
{
/*
if the frame is dirty, we are going to check if it is also
stale and recreate the bitmap here.
this code is inside the dirty check, because if it wouldn't and
the stale buffer would not be dirty at the same time, then we
are going to show, for split of a second, a black rectangle
(or multicolored rainbow of uninitailized bitmap buffer)
instead of perfectly valid last frame from the cam from before
it changed it's size...
*/
if (backbuffer_status == BACKBUFFER_STALE)
{
OP_DELETE(backbuffer);
backbuffer = NULL;
//we might have failed in the SetMediaType
//due to the error with frame creation
if (!frame)
return E_FAIL;
OP_STATUS tmp = OpBitmap::Create(&backbuffer, frame_res.x, frame_res.y);
if (OpStatus::IsError(tmp))
return CAM2HR(tmp);
OP_ASSERT(backbuffer->Supports(OpBitmap::SUPPORTS_POINTER) && "Bitmaps without SUPPORTS_POINTER are rather pointless here...");
if (!backbuffer->Supports(OpBitmap::SUPPORTS_POINTER))
{
OP_DELETE(frame);
OP_DELETE(backbuffer);
frame = NULL;
backbuffer = NULL;
return E_FAIL;
}
}
//after refreshing the buffer (think low quality chain store fish dept. here)
//we are changing the status to ACCESSED, so that it will not be meddled with
//in the SetMediaType
backbuffer_status = BACKBUFFER_ACCESSED;
OpBitmap* tmp = backbuffer;
backbuffer = frame;
frame = tmp;
frame_dirty = false;
}
else
{
//we want to retain the STALE status for next frame_dirty, but change to ACCESS otherwise
if (backbuffer_status != BACKBUFFER_STALE)
backbuffer_status = BACKBUFFER_ACCESSED;
}
*ppFrame = backbuffer;
return S_OK;
}
STDMETHODIMP OpDirectShowCamera::GetPreviewDimensions(OpCamera::Resolution* dimensions)
{
if (!dimensions)
return E_POINTER;
DesktopMutexLock on(camera_mutex);
*dimensions = frame_res;
return S_OK;
}
STDMETHODIMP OpDirectShowCamera::Stop()
{
METHOD_CALL;
is_playing = false;
return S_OK;
}
STDMETHODIMP OpDirectShowCamera::Pause()
{
METHOD_CALL;
return S_OK;
}
STDMETHODIMP OpDirectShowCamera::Run(REFERENCE_TIME tStart)
{
METHOD_CALL;
is_playing = true;
return S_OK;
}
STDMETHODIMP OpDirectShowCamera::GetState(DWORD dwMilliSecsTimeout, FILTER_STATE *State)
{
METHOD_CALL;
return E_NOTIMPL;
}
STDMETHODIMP OpDirectShowCamera::EnumPins(IEnumPins **ppEnum)
{
METHOD_CALL;
return OpComObjectEx< coll::OpSinglePinEnum >::Create(in_pin, ppEnum);
}
STDMETHODIMP OpDirectShowCamera::FindPin(LPCWSTR Id, IPin **ppPin)
{
METHOD_CALL;
if (wcscmp(Id, pin_name) == 0)
return in_pin.CopyTo(ppPin);
return VFW_E_NOT_FOUND;
}
STDMETHODIMP OpDirectShowCamera::QueryFilterInfo(FILTER_INFO *pInfo)
{
METHOD_CALL;
if (!pInfo)
return E_POINTER;
pInfo->pGraph = graph;
if (pInfo->pGraph)
pInfo->pGraph->AddRef();
if (name.IsEmpty())
pInfo->achName[0] = 0;
else
{
wcsncpy(pInfo->achName, name.CStr(), ARRAY_SIZE(pInfo->achName));
pInfo->achName[ARRAY_SIZE(pInfo->achName)-1] = 0;
}
return S_OK;
}
STDMETHODIMP OpDirectShowCamera::JoinFilterGraph(IFilterGraph *pGraph, LPCWSTR pName)
{
METHOD_CALL;
//this does not addrefs the graph; if we would addref it here,
//it would never go down to zero (in which case it would never
//call JoinFilterGraph(NULL, NULL) on this, nor release the last
//reference to this, or to the cam source filter)
graph = pGraph;
name.Empty();
if (pName)
name.Append(pName);
return S_OK;
}
STDMETHODIMP OpDirectShowCamera::QueryVendorInfo(LPWSTR *pVendorInfo)
{
METHOD_CALL;
if (!pVendorInfo)
return E_POINTER;
*pVendorInfo = (LPWSTR)CoTaskMemAlloc(VENDOR_NAME_SIZE);
if (!*pVendorInfo)
return E_OUTOFMEMORY;
op_memcpy(*pVendorInfo, vendor_name, VENDOR_NAME_SIZE);
return S_OK;
}
HRESULT OpDirectShowCamera::Connect(IPin* pin, const AM_MEDIA_TYPE* pmt)
{
METHOD_CALL;
return SetMediaType(pmt, false);
}
HRESULT OpDirectShowCamera::Disconnect()
{
METHOD_CALL;
mtype::DeleteMediaType(media_type);
media_type = NULL;
return S_OK;
}
HRESULT OpDirectShowCamera::Receive(IMediaSample* pSample, const AM_SAMPLE2_PROPERTIES& sampleProps)
{
HRESULT hr = S_OK;
if (sampleProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED)
{
OLE(SetMediaType(sampleProps.pMediaType));
}
if (!parent)
return S_OK;
if (!curr_xform)
return VFW_E_INVALID_MEDIA_TYPE;
if (!frame)
return E_FAIL;
DesktopMutexLock critSection(camera_mutex);
OLE(trans::Form(*curr_xform, pSample, frame, frame_res.x, frame_res.y));
frame_dirty = true;
OpStatus::Ignore(critSection.Release()); //as in lock's d.tor
parent->OnCameraUpdateFrame();
return S_OK;
}
HRESULT OpDirectShowCamera::QueryMediaType(AM_MEDIA_TYPE* pmt)
{
METHOD_CALL;
return mtype::CopyMediaType(pmt, media_type);
}
#ifdef WINDOWS_CAMERA_GRAPH_TEST
GUID OpDirectShowCamera::OverridenCameraFormat()
{
OpStringC format = g_pcmswin->GetStringPref(PrefsCollectionMSWIN::SupportedCameraFormat);
if (format.HasContent())
{
if (format.CompareI("RGB24") == 0)
return MEDIASUBTYPE_RGB24;
else if (format.CompareI("RGB32") == 0)
return MEDIASUBTYPE_RGB32;
else if (format.CompareI("YUY2") == 0)
return MEDIASUBTYPE_YUY2;
else if (format.CompareI("MJPG") == 0)
return MEDIASUBTYPE_MJPG;
else if (format.CompareI("I420") == 0)
return MEDIASUBTYPE_4CC_I420;
}
return GUID_NULL;
}
#endif
STDMETHODIMP OpDirectShowCameraPin::Connect(IPin *pReceivePin, const AM_MEDIA_TYPE *pmt)
{
METHOD_CALL;
return E_FAIL; // method for output pins only, anyone calling it on a PINDIR_INPUT pin is (gravely) mistaken
}
STDMETHODIMP OpDirectShowCameraPin::ReceiveConnection(IPin *pConnector, const AM_MEDIA_TYPE *pmt)
{
METHOD_CALL;
if (QueryAccept(pmt) == S_FALSE)
return VFW_E_TYPE_NOT_ACCEPTED;
if (IsConnected())
return VFW_E_ALREADY_CONNECTED;
if (IsStarted())
return VFW_E_NOT_STOPPED;
OLE_(m_parent->Connect(pConnector, pmt));
m_connection = pConnector;
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::Disconnect()
{
METHOD_CALL;
if (IsStarted())
return VFW_E_NOT_STOPPED;
m_connection = NULL;
m_allocator = NULL;
return m_parent->Disconnect();
}
STDMETHODIMP OpDirectShowCameraPin::ConnectedTo(IPin **pPin)
{
METHOD_CALL;
if (!IsConnected())
return VFW_E_NOT_CONNECTED;
return m_connection.CopyTo(pPin);
}
STDMETHODIMP OpDirectShowCameraPin::ConnectionMediaType(AM_MEDIA_TYPE *pmt)
{
METHOD_CALL;
if (!IsConnected())
{
op_memset(pmt, 0, sizeof(AM_MEDIA_TYPE));
return VFW_E_NOT_CONNECTED;
}
if (!pmt)
return E_POINTER;
return m_parent->QueryMediaType(pmt);
}
STDMETHODIMP OpDirectShowCameraPin::QueryPinInfo(PIN_INFO *pInfo)
{
METHOD_CALL;
if (!pInfo)
return E_POINTER;
OLE_(m_parent->GetBaseObject()->QueryInterface(&pInfo->pFilter));
pInfo->dir = PINDIR_INPUT;
uni_strncpy(pInfo->achName, pin_name, ARRAY_SIZE(pInfo->achName));
pInfo->achName[ARRAY_SIZE(pInfo->achName)-1] = 0;
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::QueryDirection(PIN_DIRECTION *pPinDir)
{
METHOD_CALL;
if (!pPinDir)
return E_POINTER;
*pPinDir = PINDIR_INPUT;
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::QueryId(LPWSTR *Id)
{
METHOD_CALL;
if (!Id)
return E_POINTER;
*Id = (LPWSTR)CoTaskMemAlloc(PIN_NAME_SIZE);
if (!*Id)
return E_OUTOFMEMORY;
op_memcpy(*Id, pin_name, PIN_NAME_SIZE);
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::QueryAccept(const AM_MEDIA_TYPE *pmt)
{
METHOD_CALL;
if (pmt->majortype == MEDIATYPE_Video)
{
if (pmt->formattype == FORMAT_VideoInfo ||
pmt->formattype == FORMAT_VideoInfo2)
{
#ifdef WINDOWS_CAMERA_GRAPH_TEST
GUID subtype = OpDirectShowCamera::OverridenCameraFormat();
if (subtype != GUID_NULL && subtype != pmt->subtype)
return S_FALSE;
#endif
for (size_t i = 0; i < trans::form_count; i++)
{
if (trans::forms[i].Supported(pmt->subtype))
return S_OK;
}
}
}
return S_FALSE;
}
STDMETHODIMP OpDirectShowCameraPin::EnumMediaTypes(IEnumMediaTypes **ppEnum)
{
METHOD_CALL;
return OpComObjectEx< coll::OpInputMediaTypesEnum >::Create(m_parent->sizes, ppEnum);
}
STDMETHODIMP OpDirectShowCameraPin::QueryInternalConnections(IPin **apPin, ULONG *nPin)
{
METHOD_CALL;
if (!nPin)
return E_POINTER;
*nPin = 0;
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::EndOfStream()
{
METHOD_CALL;
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::BeginFlush()
{
METHOD_CALL;
m_flushing = true;
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::EndFlush()
{
METHOD_CALL;
m_flushing = false;
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::NewSegment(REFERENCE_TIME, REFERENCE_TIME, double)
{
METHOD_CALL;
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::GetAllocator(IMemAllocator **ppAllocator)
{
METHOD_CALL;
if (!m_allocator)
OLE_(m_allocator.CoCreateInstance(CLSID_MemoryAllocator));
return m_allocator.CopyTo(ppAllocator);
}
STDMETHODIMP OpDirectShowCameraPin::NotifyAllocator(IMemAllocator *pAllocator, BOOL)
{
METHOD_CALL;
m_allocator = pAllocator;
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::GetAllocatorRequirements(ALLOCATOR_PROPERTIES *pProps)
{
METHOD_CALL;
return E_NOTIMPL;
}
HRESULT OpDirectShowCameraPin::GetSampleProps(IMediaSample* pSample, AM_SAMPLE2_PROPERTIES& sampleProps)
{
/* Check for IMediaSample2 */
OpComPtr<IMediaSample2> pSample2;
if (SUCCEEDED(pSample->QueryInterface(&pSample2)))
{
OLE_(pSample2->GetProperties(sizeof(sampleProps), (PBYTE)&sampleProps));
pSample2 = NULL;
}
else
{
/* Get the properties the hard way */
sampleProps.cbData = sizeof(sampleProps);
sampleProps.dwTypeSpecificFlags = 0;
sampleProps.dwStreamId = AM_STREAM_MEDIA;
sampleProps.dwSampleFlags = 0;
if (S_OK == pSample->IsDiscontinuity())
sampleProps.dwSampleFlags |= AM_SAMPLE_DATADISCONTINUITY;
if (S_OK == pSample->IsPreroll())
sampleProps.dwSampleFlags |= AM_SAMPLE_PREROLL;
if (S_OK == pSample->IsSyncPoint())
sampleProps.dwSampleFlags |= AM_SAMPLE_SPLICEPOINT;
if (SUCCEEDED(pSample->GetTime(&sampleProps.tStart, &sampleProps.tStop)))
sampleProps.dwSampleFlags |= AM_SAMPLE_TIMEVALID | AM_SAMPLE_STOPVALID;
if (S_OK == pSample->GetMediaType(&sampleProps.pMediaType))
sampleProps.dwSampleFlags |= AM_SAMPLE_TYPECHANGED;
pSample->GetPointer(&sampleProps.pbBuffer);
sampleProps.lActual = pSample->GetActualDataLength();
sampleProps.cbBuffer = pSample->GetSize();
}
/* Has the format changed in this sample */
if (sampleProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED)
{
if (QueryAccept(sampleProps.pMediaType) == S_FALSE)
{
return VFW_E_INVALIDMEDIATYPE;
}
}
return S_OK;
}
STDMETHODIMP OpDirectShowCameraPin::Receive(IMediaSample *pSample)
{
if (!IsConnected() || !IsStarted())
return VFW_E_WRONG_STATE;
if (IsFlushing())
return S_FALSE;
AM_SAMPLE2_PROPERTIES sampleProps = {};
OLE_(GetSampleProps(pSample, sampleProps));
return m_parent->Receive(pSample, sampleProps);
}
STDMETHODIMP OpDirectShowCameraPin::ReceiveMultiple(IMediaSample **pSamples, long nSamples, long *nSamplesProcessed)
{
if (!pSamples)
return E_POINTER;
HRESULT hr = S_OK;
*nSamplesProcessed = 0;
while (nSamples-- > 0)
{
hr = Receive(pSamples[*nSamplesProcessed]);
/* S_FALSE means don't send any more */
if (hr != S_OK)
break;
(*nSamplesProcessed)++;
}
return hr;
}
STDMETHODIMP OpDirectShowCameraPin::ReceiveCanBlock()
{
METHOD_CALL;
return S_OK;
}
}
#ifdef DEBUG_DSHOW_GRAPH_DUMP
namespace debug
{
typedef struct {
CHAR *szName;
GUID guid;
} GUIDSTRINGENTRY;
#define OUR_GUID_ENTRY(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) { #name, { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } },
GUIDSTRINGENTRY g_GuidNames[] = {
#include <uuids.h>
};
#undef OUR_GUID_ENTRY
const size_t g_cGuidNames = ARRAY_SIZE(g_GuidNames);
static inline char *FindGuidName(const GUID &guid)
{
if (guid == GUID_NULL) {
return "GUID_NULL";
}
for (size_t i = 0; i < g_cGuidNames; i++)
{
if (g_GuidNames[i].guid == guid)
{
return g_GuidNames[i].szName;
}
}
GUID copy = guid;
copy.Data1 = 0;
static const GUID FCC = {0x00000000, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71};
if (copy == FCC)
{
static char buffer[100];
strcpy_s(buffer, "MEDIASUBTYPE_XXXX (Four CC)");
const char* ccguid = (const char*)&guid;
buffer[13] = ccguid[0];
buffer[14] = ccguid[1];
buffer[15] = ccguid[2];
buffer[16] = ccguid[3];
return buffer;
}
static char buffer[100];
sprintf_s(buffer, "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1],
guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
return buffer;
}
static inline void DumpMediaType(const AM_MEDIA_TYPE& media, OpString& msg)
{
char * guid;
guid = FindGuidName(media.majortype); if (op_strncmp(guid, "MEDIATYPE_", 10) == 0) guid += 10; msg.Append(guid); msg.Append("/");
guid = FindGuidName(media.subtype); if (op_strncmp(guid, "MEDIASUBTYPE_", 13) == 0) guid += 13; msg.Append(guid); msg.Append(" ");
guid = FindGuidName(media.formattype); if (op_strncmp(guid, "FORMAT_", 7) == 0) guid += 7; msg.Append(guid);
if (media.bFixedSizeSamples)
{
msg.AppendFormat(" [%d]", media.lSampleSize);
}
long width = -1, height = -1;
ULONG bps = 0;
REFERENCE_TIME tpf = 1;
if (media.formattype == FORMAT_VideoInfo)
{
VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)media.pbFormat;
height = vih->bmiHeader.biHeight;
width = vih->bmiHeader.biWidth;
bps = vih->dwBitRate;
tpf = vih->AvgTimePerFrame;
}
else if (media.formattype == FORMAT_VideoInfo2)
{
VIDEOINFOHEADER2* vih = (VIDEOINFOHEADER2*)media.pbFormat;
height = vih->bmiHeader.biHeight;
width = vih->bmiHeader.biWidth;
bps = vih->dwBitRate;
tpf = vih->AvgTimePerFrame;
}
if (width != -1)
{
const wchar_t* size = L"B/s";
float majorbps = (float)bps;
majorbps /= 8;
if (majorbps > 1024)
{
size = L"kiB/s"; majorbps /= 1024;
if (majorbps > 1024)
{
size = L"MiB/s"; majorbps /= 1024;
if (majorbps > 1024)
{
size = L"GiB/s"; majorbps /= 1024;
}
}
}
static const REFERENCE_TIME second = 10000000;
float fps = second;
fps /= tpf;
msg.AppendFormat(" %dx%d", width, height);
msg.AppendFormat(" %.1f %s", majorbps, size);
msg.AppendFormat(" %.1f fps", fps);
}
}
static inline void DumpPin(ULONG pinid, ULONG& id, IPin* pin, OpString& msg)
{
++id;
PIN_INFO pinfo = {};
if (FAILED(pin->QueryPinInfo(&pinfo)))
{
pinfo.dir = PINDIR_INPUT;
wcscpy_s(pinfo.achName, L"<unknown>");
}
if (pinfo.pFilter)
pinfo.pFilter->Release();
OpComPtr<IPin> pin2;
if (FAILED(pin->ConnectedTo(&pin2)) || !pin2)
{
msg.AppendFormat(L" %d.%d. %s [%s] (not connected)\n", pinid, id, pinfo.dir == PINDIR_INPUT ? L"Input " : L"Output", pinfo.achName);
return;
}
FILTER_INFO finfo = {};
PIN_INFO pinfo2 = {};
if (FAILED(pin2->QueryPinInfo(&pinfo2)))
{
pinfo.dir = PINDIR_INPUT;
wcscpy_s(finfo.achName, L"<unknown pin>");
}
if (!pinfo2.pFilter || FAILED(pinfo2.pFilter->QueryFilterInfo(&finfo)))
wcscpy_s(finfo.achName, L"<unknown filter>");
if (pinfo2.pFilter)
pinfo2.pFilter->Release();
if (finfo.pGraph)
finfo.pGraph->Release();
msg.AppendFormat(L" %d.%d. %s [%s] connected to %s [%s] of [%s]", pinid, id, pinfo.dir == PINDIR_INPUT ? L"Input " : L"Output",
pinfo.achName, pinfo2.dir == PINDIR_INPUT ? L"input" : L"output", pinfo2.achName, finfo.achName);
if (pinfo.dir == PINDIR_INPUT)
{
AM_MEDIA_TYPE media = {};
if (SUCCEEDED(pin->ConnectionMediaType(&media)))
{
msg.Append(L" with ");
DumpMediaType(media, msg);
}
mtype::FreeMediaType(media);
}
msg.Append(L"\n");
}
static inline void DumpFilter(ULONG& pinid, IBaseFilter* filter, OpString& msg)
{
HRESULT hr = S_OK;
FILTER_INFO finfo = {};
++pinid;
if (FAILED(filter->QueryFilterInfo(&finfo)))
wcscpy_s(finfo.achName, L"<unknown>");
if (finfo.pGraph)
finfo.pGraph->Release();
//swprintf_s(buffer, L"%d. [%s]\n", pinid, finfo.achName);
GUID guid;
if (SUCCEEDED(filter->GetClassID(&guid)))
{
// If the filter successfully presented its class id,
// print it as well, so debugging of the issues such as
// filter ban is easier. We do not use functions like
// StringFromCLSID (as they require addtional memory).
// Instead, we'll print it directly as a bracketed 8-4-4-4-12 UUID[1]
//
// [1] http://en.wikipedia.org/wiki/Universally_unique_identifier
msg.AppendFormat(L"%d. [%s] {%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n",
pinid, finfo.achName,
guid.Data1, //8 digits
guid.Data2, //4 digits
guid.Data3, //4 digits
guid.Data4[0], guid.Data4[1], //4 digits
guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7] //12 digits
);
}
else
{
msg.AppendFormat(L"%d. [%s]\n", pinid, finfo.achName);
}
OpComPtr<IEnumPins> pins;
OpComPtr<IPin> pin;
if (SUCCEEDED(filter->EnumPins(&pins)))
{
ULONG fetched = 0;
ULONG id = 0;
while (hr = pins->Next(1, &pin, &fetched), hr == S_OK && fetched == 1)
{
DumpPin(pinid, id, pin, msg);
pin = NULL;
}
}
}
static inline HRESULT DumpGraph(IGraphBuilder* gb)
{
#ifdef OPERA_CONSOLE
HRESULT hr = S_OK;
if (!g_console || !gb)
return S_OK;
// FIXME: Severity?
OpConsoleEngine::Message msg(OpConsoleEngine::Internal, OpConsoleEngine::Information);
msg.context.Set(L"DirectShow graph dump");
OpComPtr<IEnumFilters> fenum;
OpComPtr<IBaseFilter> filter;
OLE_(gb->EnumFilters(&fenum));
ULONG fetched = 0;
ULONG pinid = 0;
while (hr = fenum->Next(1, &filter, &fetched), hr == S_OK && fetched == 1)
{
DumpFilter(pinid, filter, msg.message);
filter = NULL;
}
TRAPD(rc, g_console->PostMessageL(&msg));
#endif
return S_OK;
}
}
#endif //DEBUG_DSHOW_GRAPH_DUMP
};
#undef METHOD_CALL
#undef VEGA_CLAMP_U8
#endif // PI_CAMERA
|
//
// ItemManage.h
// GetFish
//
// Created by zhusu on 15/7/28.
//
//
#ifndef __GetFish__ItemManage__
#define __GetFish__ItemManage__
#include "cocos2d.h"
#include "Item.h"
#include "ActorManage.h"
USING_NS_CC;
class ItemManage : public ActorManage
{
public:
CREATE_FUNC(ItemManage);
ItemManage();
virtual bool init();
virtual ~ItemManage();
void addItem(const char* name,CCPoint pos,int type,int v,int time);
};
#endif /* defined(__GetFish__ItemManage__) */
|
// Created on: 2019-07-08
// Copyright (c) 2019 OPEN CASCADE SAS
// Created by: Oleg AGASHIN
//
// 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 _BRepMesh_ConstrainedBaseMeshAlgo_HeaderFile
#define _BRepMesh_ConstrainedBaseMeshAlgo_HeaderFile
#include <BRepMesh_BaseMeshAlgo.hxx>
class BRepMesh_Delaun;
//! Class provides base functionality to build face triangulation using Dealunay approach.
//! Performs generation of mesh using raw data from model.
class BRepMesh_ConstrainedBaseMeshAlgo : public BRepMesh_BaseMeshAlgo
{
public:
//! Constructor.
BRepMesh_ConstrainedBaseMeshAlgo ()
{
}
//! Destructor.
virtual ~BRepMesh_ConstrainedBaseMeshAlgo ()
{
}
DEFINE_STANDARD_RTTIEXT(BRepMesh_ConstrainedBaseMeshAlgo, BRepMesh_BaseMeshAlgo)
protected:
//! Returns size of cell to be used by acceleration circles grid structure.
virtual std::pair<Standard_Integer, Standard_Integer> getCellsCount (const Standard_Integer /*theVerticesNb*/)
{
return std::pair<Standard_Integer, Standard_Integer> (-1, -1);
}
//! Performs processing of generated mesh.
//! By default does nothing.
//! Expected to be called from method generateMesh() in successor classes.
virtual void postProcessMesh (BRepMesh_Delaun& /*theMesher*/,
const Message_ProgressRange& /*theRange*/)
{
}
};
#endif
|
#include <iostream>
#include <vector>
#include <climits>
#include <unordered_set>
using namespace std;
#define N 1500
#define FASTIO \
ios_base::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0);
int nums[N];
int n;
int sum3(int a, int sum, int in)
{
unordered_set<int> s;
int total = sum - a;
for (int i = 0; i < n; i++)
{
if (i == in)
{
continue;
}
if (s.find(total - nums[i]) == s.end())
{
s.insert(nums[i]);
}
else
{
return nums[i] * (total - nums[i]) * a;
}
}
return 0;
}
int main()
{
FASTIO;
int i = 0;
int num;
while (cin >> num)
{
nums[i] = num;
i++;
}
n = i;
// part 2: 3 sum
for (int j = 0; j < n; j++)
{
int x = sum3(nums[j], 2020, j);
if (x > 0)
{
cout << x << endl;
break;
}
}
return 0;
}
|
/**
* “Experience is the name everyone gives to their mistakes.” – Oscar Wilde
*
* Prodip Datta
* Dept. Of Computer Science & Engineering
* Session: 2014-15
* email : prodipdatta7@gmail.com
* Bangabandhu Sheikh Mujibur Rahman Science & Technology University, Gopalganj-8100.
*
* created : Sunday 30-May, 2021 09:50:46 PM
**/
//#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <deque>
#include <iterator>
#include <bitset>
#include <assert.h>
#include <new>
#include <sstream>
#include <time.h>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
// #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2,fma")
// #pragma GCC optimize("unroll-loops")
using namespace std ;
using namespace __gnu_pbds ;
#define ll long long
#define ld long double
#define ull unsigned long long
#define pii pair< int, int >
#define pll pair< ll, ll >
#define vi vector< int >
#define vll vector< ll >
#define vvi vector< vector< int > >
#define vvii vector< vector< pii > >
#define debug(x) cerr << #x << " = " << x << '\n' ;
#define rep(i,b,e) for(__typeof(e) i = (b) ; i != (e + 1) - 2 * ((b) > (e)) ; i += 1 - 2 * ((b) > (e)))
#define all(x) x.begin() , x.end()
#define rall(x) x.rbegin() , x.rend()
#define sz(x) (int)x.size()
#define ff first
#define ss second
#define pb push_back
#define eb emplace_back
#define mem(a) memset(a , 0 ,sizeof a)
#define memn(a) memset(a , -1 ,sizeof a)
#define fread freopen("input.txt","r",stdin)
#define fwrite freopen("output.txt","w",stdout)
#define TN typename
#define FastIO ios_base::sync_with_stdio(false) ; cin.tie(NULL) ; cout.tie(NULL) ;
typedef tree <pii, null_type, less< pii >, rb_tree_tag, tree_order_statistics_node_update > ordered_set;
typedef tree <pii, null_type, less_equal< pii >, rb_tree_tag, tree_order_statistics_node_update > ordered_multiset;
/*
Note : There is a problem with erase() function in ordered_multiset (for less_equal<int> tag).
lower_bound() works as upper_bound() and vice-versa.
Be careful to use.
i) find_by_order(k) : kth smallest element counting from 0 .
ii) order_of_key(k) : number of elements strictly smaller than k.
*/
/*###############-> Input Section <-###############*/
template <TN T> inline void Int(T &a) {
bool minus = false; a = 0; char ch = getchar();
while (true) { if (ch == '-' or (ch >= '0' && ch <= '9')) break; ch = getchar(); }
if (ch == '-') minus = true; else a = ch - '0';
while (true) { ch = getchar(); if (ch < '0' || ch > '9') break; a = a * 10 + (ch - '0'); }
if (minus)a *= -1 ;
}
template < TN T, TN T1 > inline void Int(T &a, T1 &b) {Int(a), Int(b) ;}
template < TN T, TN T1, TN T2 > inline void Int(T &a, T1 &b, T2 &c) {Int(a, b), Int(c) ;}
template < TN T, TN T1, TN T2, TN T3 > inline void Int(T &a, T1 &b, T2 &c, T3 &d) {Int(a, b), Int(c, d) ;}
template < TN T, TN T1, TN T2, TN T3, TN T4> inline void Int(T &a, T1 &b, T2 &c, T3 &d, T4 &e) {Int(a, b), Int(c, d, e) ;}
template<typename T, typename U> inline void cmin(T &x, U y) { if (y < x) x = y; }
template<typename T, typename U> inline void cmax(T &x, U y) { if (x < y) x = y; }
/*###############-> Debugger <-###############*/
#ifdef LOCAL
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {cout << endl ;}
template<TN T, TN... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << ' ' ;
err(++it, args...);
}
#else
#define error(args...)
#endif
template<class ValueType>
void unstable_remove(
typename std::vector<ValueType>& container,
typename std::vector<ValueType>::iterator it
) {
auto lastEl = container.end() - 1;
if (it != lastEl) {
*it = std::move(*lastEl);
}
container.pop_back();
}
/******************************************
#Rows are numbered from top to bottom.
#Columns are numbered from left to right.
Moves : L, U, R, D, LU, RU, RD, LD.
******************************************/
int dx[8] = {0, -1, 0, 1, -1, -1, 1, 1} ;
int dy[8] = { -1, 0, 1, 0, -1, 1, 1, -1} ;
/*###############-> Constraints <-###############*/
const int N = (int)2e5 + 5 ;
const int maxN = (int)1e6 + 6 ;
const ll Mod = (ll)1e9 + 7 ;
const int inf = (int)2e9 ;
const ll Inf = (ll)1e18 ;
const int mod = (int)1e9 + 7 ;
const double EPS = (double)1e-9 ;
const double PI = (double)acos(-1.0) ;
inline int add(int a, int b, int mod) {a += b ; return a >= mod ? a - mod : a ;}
inline int sub(int a, int b, int mod) {a -= b ; return a < 0 ? a + mod : a ;}
inline int mul(int a, int b, int mod) {return (ll)a * b % mod ;}
/*...... ! Code starts from here ! ......*/
vector < vector < pii > > g, rg ;
int n, m, s, t, p;
void dijkstra(int s, vector < ll > &d, vector < vector < pii > > &g) {
d.assign(n + 1, Inf) ;
d[s] = 0 ;
priority_queue < pair < ll, int>, vector < pair < ll, int> > , greater< pair < ll, int> > > pq ;
pq.push({0, s}) ;
while (!pq.empty()) {
int v = pq.top().ss ;
ll dv = pq.top().ff ;
pq.pop() ;
if (dv != d[v])continue ;
for (auto i : g[v]) {
int to = i.ff ;
int len = i.ss ;
if (d[v] + len < d[to]) {
d[to] = d[v] + len ;
pq.push({d[to], to}) ;
}
}
}
}
int main() {
#ifdef LOCAL
clock_t tStart = clock();
//freopen("input.txt", "r", stdin) ;
//freopen("output.txt", "w", stdout) ;
#endif
int test = 1 , tc = 0 ;
Int(test) ;
while (test--) {
Int(n, m, s, t, p) ;
g.assign(n + 1, vector < pii > ()) ;
rg.assign(n + 1, vector < pii > ()) ;
vector < pair< pii, int > > edges ;
for (int i = 1 ; i <= m ; ++i) {
int x, y, z ; Int(x, y, z) ;
g[x].emplace_back(y, z) ;
rg[y].emplace_back(x, z) ;
edges.push_back({{x, y}, z}) ;
}
vector < ll > dl, dr ;
dijkstra(s, dl, g) ;
dijkstra(t, dr, rg) ;
int res = -1 ;
for (auto i : edges) {
ll cost = dl[i.ff.ff] + dr[i.ff.ss] + i.ss ;
if (cost <= 1LL * p) {
cmax(res, i.ss) ;
}
}
cout << res << '\n' ;
}
#ifdef LOCAL
fprintf(stderr, "\nRuntime: %.10fs\n", (double) (clock() - tStart) / CLOCKS_PER_SEC);
#endif
return 0 ;
}
|
#include <ros.h>
#include <Stepper.h>
#include <math.h>
#include <geometry_msgs/Point.h> // type of message
//change this to the number of steps on your motor
#define STEPS 200
#define STEPS1 513
float theta1;
float theta2;
float X ;
float Y ;
double L2 = 76.2; // length of the link arms
double L1 = 177.8; // in mm
Stepper stepper(STEPS, 4, 5, 6, 7); // defining motor phases pins
Stepper stepper2(STEPS2, 8, 10, 9, 11);
ros::NodeHandle nh;
void messageCb( const geometry_msgs::Point& toggle_msg){
X = toggle_msg.x;
Y = toggle_msg.y;
theta2 = 2*atan(sqrt(((L1+L2)*(L1+L2)-((X*X)+(Y*Y)))/(((X*X)+(Y*Y))-((L1-L2)*(L1-L2)))));
theta1 = atan2(Y,X)+atan2(L2*sin(theta2),(L1+(L2*cos(theta2)))); // get theta in radians
STEPS = (theta1*200)/(2*3.14159); //convert theta1 (radians) to steps
STEPS2 = (theta2*513)/(2*3.14159); //convert theta2 (radians) to steps
stepper.step(STEPS);
stepper2.step(STEPS2);
delay(5000);
stepper.step(-STEPS);
stepper2.step(-STEPS2);
delay(5000);
}
ros::Subscriber<std_msgs::Empty> sub("vision_node", &messageCb);// name of the topic to suscribe to
void setup()
{
stepper.setSpeed(10);
stepper2.setSpeed(30);
nh.initNode();
nh.subscribe(sub);
}
void loop()
{
nh.spinOnce(); // may need to be changed to spin for continuous listening
delay(1);
}
|
#include<iostream>
#include<ctime>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define N 301
#define eps 1e-5
using namespace std;
static unsigned long rand_seed;
void mysrand(unsigned long seed) {
rand_seed = seed;
}
unsigned long myrand() {
rand_seed = (rand_seed * 16807L) % ((1 << 31) - 1);
return rand_seed;
}
struct point {
double x,y;
} p[N],Ans,now;
int n;
double dist(point a,point b) {
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
double calc(point A) {
double res=0;
for(int i=1; i<=n; i++)
res+=dist(A,p[i]);
return res;
}
void init() {
for(int i=1; i<=n; i++)
scanf("%lf%lf",&p[i].x,&p[i].y);
}
void solve() {
double X,Y,T=10000,preD,nextD;
Ans.x=0;
Ans.y=0;
for(int i=1; i<=n; i++)
Ans.x+=p[i].x,Ans.y+=p[i].y;
Ans.x/=n;
Ans.y/=n;
while(T>eps) {
preD=calc(Ans);
X=0;
Y=0;
for(int i=1; i<=n; i++) {
X+=(p[i].x-Ans.x)/dist(p[i],Ans);
Y+=(p[i].y-Ans.y)/dist(p[i],Ans);
}
now.x=Ans.x+X*T;
now.y=Ans.y+Y*T;
nextD=calc(now);
if(nextD<preD) Ans=now;
else {
double K=(double)(myrand()%10001)/10000.00;
if(exp((preD-nextD)/T)>K)
Ans=now;
}
T*=0.95;
}
printf("%.0f\n",calc(Ans));
}
int main() {
mysrand(51219);
while(scanf("%d",&n)!=EOF) {
init();
solve();
}
return 0;
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
LL a[1010],b[1010];
bool cmp(LL a,LL b) {
return a > b;
}
int main()
{
int n,ca = 0;
while (scanf("%d",&n) != EOF) {
LL ans = 0;
for (int i = 0;i < n; i++) scanf("%lld",&a[i]);
sort(a,a+n);
for (int i = 0;i < n; i++) scanf("%lld",&b[i]);
sort(b,b+n,cmp);
for (int i = 0;i < n; i++)
ans += a[i]*b[i];
printf("Case #%d:\n%lld\n",++ca,ans);
}
return 0;
}
|
// http://blog.csdn.net/q1204265228/article/details/42915067
//http://blog.csdn.net/x920405451x/article/details/39753305
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<vector>
#include<bitset>
using namespace std;
#define MAX 111
int m, ok, j, order[MAX], flag[MAX][MAX];
bitset<MAX> digit[MAX];//存放每个城市能到达的所有城市,能到达不是两城市间必须有路
vector<int> u[MAX];//存放每个城市有路连接的所有城市
void canReach(int a, int v)
{
digit[a][a] = 1;
for (int i = 0; i < u[a].size(); i++)
{
int b = u[a][i];
if (b == v)
continue;
canReach(b, a);
digit[a] |= digit[b];
}
}
void dfs(int a, int v)
{
if (a == order[j])
j++;
if (j == m)
{
ok = 1;
return;
}
while (j < m)
{
int p = j, c = order[j];
for (int i = 0; i < u[a].size(); i++)
{
int b = u[a][i];
if (b == v)
continue;
if (digit[b][c] && flag[a][b])//如果b能到达c并且a、b之间有路
{
flag[a][b] = 0;
dfs(b, a);
break;
}
}
if (p == j)
break;//表示以该节点为根的子树不存在目标点,跳出循环,(然后返回递归上一层)
}
}
int main(void)
{
freopen("../test.txt", "r", stdin);
int a, b, i, t, n;
scanf("%d", &t);
while (t--)
{
ok = j = 0;
memset(flag, 0, sizeof flag);
for (i = 0; i < MAX; i++)
{
digit[i].reset();
u[i].clear();
}
scanf("%d", &n);
for (i = 1; i < n; i++)
{
scanf("%d%d", &a, &b);
u[a].push_back(b);
u[b].push_back(a);
flag[a][b] = flag[b][a] = 1;
}
scanf("%d", &m);
for (i = 0; i < m; i++)
scanf("%d", &order[i]);
canReach(1, -1);
dfs(1, -1);
if (ok)
printf("YES\n");
else
printf("NO\n");
}
}
|
/*
** InventoryModel.hpp for cpp_indie_studio in /home/jabbar_y/rendu/cpp_indie_studio/InventoryModel.hpp
**
** Made by Yassir Jabbari
** Login <yassir.jabbari@epitech.eu>
**
** Started on Wed Jun 14 16:41:35 2017 Yassir Jabbari
** Last update Wed Jun 14 16:41:35 2017 Yassir Jabbari
*/
#ifndef CPP_INDIE_STUDIO_INVENTORYMODEL_HPP
#define CPP_INDIE_STUDIO_INVENTORYMODEL_HPP
#include <Events/EventReceiver.hpp>
#include "Events/EventStatus.hpp"
class InventoryModel
{
public:
enum class weaponsId : uint16_t
{
UZI = 0,
SHOTGUN = 1,
SURRENDER = 2
};
private:
irr::IrrlichtDevice *_device;
irr::video::IVideoDriver *_driver;
irr::gui::IGUIEnvironment *_guienv;
irr::gui::IGUITabControl *tabctrl;
irr::core::dimension2du screenSize;
irr::gui::IGUISpriteBank *spriteBank;
irr::core::dimension2d<irr::u32> cursorSize;
EventReceiver &eventReceiver;
EventStatus eventStatus;
irr::core::dimension2d<irr::u32> backgroundSize;
weaponsId *id;
public:
InventoryModel(irr::IrrlichtDevice *device, irr::video::IVideoDriver *driver,
EventReceiver &eventReceiver);
virtual ~InventoryModel();
virtual void setModelProperties();
virtual EventStatus launchModel();
virtual void showTabCtrl();
virtual void hideTabCtrl();
};
#endif //CPP_INDIE_STUDIO_INVENTORYMODEL_HPP
|
#include "testMacros.h"
#include "Group.h"
#include "Clan.h"
#include "exceptions.h"
using namespace mtm;
bool constractorClan() {
Clan beta("Beta");
ASSERT_EXCEPTION(Clan(""), ClanEmptyName);
Clan copy(beta);
ASSERT_TRUE(copy.isFriend(copy));
ASSERT_TRUE(copy.getSize() == 0);
return 1;
}
bool addGetGroupClan() {
Group Nana("Nana", "Tea", 0, 0, 40, 50, 80);
Group Luiza("Luiza", "Tea", 10, 5, 20, 10, 90);
Group Shiba("Shiba", "", 10, 10, 40, 50, 60);
Group copy_luiza("Luiza", "Tea", 10, 5, 20, 10, 90);
Clan Tea("Tea");
ASSERT_EXCEPTION(Tea.addGroup(Nana), ClanGroupIsEmpty);
ASSERT_NO_EXCEPTION(Tea.addGroup(Luiza));
ASSERT_NO_EXCEPTION(Tea.addGroup(Shiba));
ASSERT_EXCEPTION(Tea.addGroup(copy_luiza), ClanGroupNameAlreadyTaken);
ASSERT_TRUE(Tea.getGroup("Shiba")->getClan() == "Tea");
ASSERT_TRUE(Tea.getSize() == 35);
ostringstream os;
os << *(Tea.getGroup(Luiza.getName())) << *(Tea.getGroup(Shiba.getName()));
ASSERT_TRUE(VerifyOutput(os, "Group's name: Luiza\n"
"Group's clan: Tea\n"
"Group's children: 10\n"
"Group's adults: 5\n"
"Group's tools: 20\n"
"Group's food: 10\n"
"Group's morale: 90\n"
"Group's name: Shiba\n"
"Group's clan: Tea\n"
"Group's children: 10\n"
"Group's adults: 10\n"
"Group's tools: 40\n"
"Group's food: 50\n"
"Group's morale: 66\n"));
return true;
}
bool GetSizeClan() {
Group Luiza("Luiza", "Tea", 10, 90, 20, 10, 90);
Group Shiba("Shiba", "", 10, 10, 40, 50, 60);
Clan Tea("Tea");
ASSERT_TRUE(Tea.getSize() == 0);
ASSERT_NO_EXCEPTION(Tea.addGroup(Luiza));
ASSERT_TRUE(Tea.getSize() == 100);
ASSERT_NO_EXCEPTION(Tea.addGroup(Shiba));
ASSERT_TRUE(Tea.getSize() == 120);
return true;
}
bool IsMakeFriendClan() {
Group Luiza("Luiza", "Tea", 10, 90, 20, 10, 90);
Group Shiba("Shiba", "", 10, 10, 40, 50, 60);
Clan Tea("Tea");
ASSERT_TRUE(Tea.isFriend(Tea));
ASSERT_NO_EXCEPTION(Tea.addGroup(Luiza));
ASSERT_NO_EXCEPTION(Tea.addGroup(Shiba));
Clan Tree("Tree");
ASSERT_NO_EXCEPTION(Tea.makeFriend(Tree));
ASSERT_TRUE(Tea.isFriend(Tree));
return 1;
}
bool UnitClan() {
Group Nana("Nana", "Tea", 10, 10, 41, 51, 90);
Group Copy("Nana", "Tea", 10, 10, 41, 51, 90);
Group Luiza("Luiza", "Tea", 80, 20, 40, 50, 80);
Group Shiba("Shiba", "Tea", 10, 10, 40, 40, 60);
Group Ginger("Ginger", "Tea", 10, 30, 61, 51, 90);
Clan Tea("Tea");
ASSERT_NO_EXCEPTION(Tea.addGroup(Nana));
ASSERT_NO_EXCEPTION(Tea.addGroup(Luiza));
ASSERT_NO_EXCEPTION(Tea.addGroup(Shiba));
Clan Tree("Tree");
ASSERT_NO_EXCEPTION(Tree.addGroup(Shiba));
ASSERT_NO_EXCEPTION(Tree.addGroup(Ginger));
Clan Apple("Apple");
ASSERT_NO_EXCEPTION(Apple.addGroup(Ginger));
ASSERT_NO_EXCEPTION(Apple.makeFriend(Tree));
ASSERT_EXCEPTION(Tea.unite(Tree,"new"),ClanCantUnite);
ASSERT_EXCEPTION(Tea.unite(Apple,""),ClanEmptyName);
ASSERT_NO_EXCEPTION(Tea.unite(Apple,"Banana"));
ASSERT_TRUE(Tea.getSize()==180);
ASSERT_TRUE(Apple.getSize()==0);
ASSERT_TRUE(Tea.getGroup("Ginger")->getClan() == "Banana");
ASSERT_TRUE(Tea.doesContain("Ginger"));
ASSERT_TRUE(Tea.isFriend(Tree));
ASSERT_FALSE(Tea.isFriend(Apple));
ASSERT_TRUE(Tea.isFriend(Tea));
ostringstream os;
ASSERT_NO_EXCEPTION(os << Tea);
ASSERT_TRUE(VerifyOutput(os, "Clan's name: Banana\n"
"Clan's groups:\n"
"Ginger\n"
"Luiza\n"
"Nana\n"
"Shiba\n"));
return true;
}
int main() {
RUN_TEST(constractorClan);
RUN_TEST(addGetGroupClan);
RUN_TEST(GetSizeClan);
RUN_TEST(IsMakeFriendClan);
RUN_TEST(UnitClan);
return 0;
}
|
#ifndef __CURSES_LIBS_HPP_INCLUDED__
#define __CURSES_LIBS_HPP_INCLUDED__
#ifdef CURSES_HAS_PRAGMA_ONCE
#pragma once
#endif
#include "containers.hpp"
#include "noncopyable.hpp"
#endif // __CURSES_LIBS_HPP_INCLUDED__
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head || !head->next) return head;
ListNode *newHead = new ListNode(-1);
newHead->next = head;
ListNode *pre = newHead;
while(pre->next && pre->next->next){
ListNode *nNode = pre->next;
ListNode *nnNode = nNode->next;
nNode->next = nnNode->next;
pre->next = nnNode;
nnNode->next = nNode;
pre = nNode;
}
return newHead->next;
}
};
|
/*
* ConstExpr.cpp
*
* Created on: May 12, 2016
* Author: bakhvalo
*/
#include "gtest/gtest.h"
#include <type_traits>
#include <array>
// constexpr is a part of functions signature
TEST(ConstExprUnitTest, constexpr_produces_const_objects)
{
constexpr int a = 0;
(void) a;
// a = 1; won't compile
}
TEST(ConstExprUnitTest, constexpr_can_be_used_as_compileTime_constant)
{
constexpr int a = 0;
std::array<int, a> arr;
(void) arr;
}
constexpr int constexpr_foo(int val)
{
return val * 2;
}
TEST(ConstExprUnitTest, constexpr_function_can_be_invoked_in_compileTime)
{
static_assert( 4 == constexpr_foo(2), "error" );
constexpr int a = 1;
int x = constexpr_foo(a); // constexpr_foo(a) is computed in compile-time
ASSERT_EQ(2, x);
}
TEST(ConstExprUnitTest, constexpr_function_can_be_invoked_in_runTime)
{
int a = 1;
int x = constexpr_foo(a); // constexpr_foo(a) is computed in run-time
ASSERT_EQ(2, x);
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <queue>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <cstdio>
#include <cmath>
#define INT_MIN (1<<31)
#define INT_MAX (~INT_MIN)
#define UNREACHABLE (INT_MAX>>2)
#define INF (1e300)
#define eps (1e-9)
using namespace std;
ifstream fin("1111_input.txt");
#define cin fin
struct Line {
Line(long long x1, long long y1, long long x2, long long y2) {
this->A = y1 - y2;
this->B = x2 - x1;
this->C = x1 * (y2 - y1) - y1 * (x2 - x1);
denominator = sqrt((double)A * A + B * B);
}
double distToPoint(long long x, long long y) {
double numerator = abs((double)A * x + B * y + C);
return numerator / denominator;
}
long long getPointDir(long long x, long long y) {
return A * x + B * y + C;
}
long long A, B, C;
double denominator;
};
int main()
{
int n;
int case_count = 0;
cin >> n;
while (n != 0) {
vector<long long> x(n, 0), y(n, 0);
for (int i = 0; i < n; i++) {
cin >> x[i] >> y[i];
}
double result = INF;
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++) {
Line l = Line(x[i], y[i], x[j], y[j]);
vector<long long> v(n, 0);
for (int k = 0; k < n; k++) {
v[k] = l.getPointDir(x[k], y[k]);
}
int positive, negative;
positive = negative = 0;
for (int k = 0; k < n; k++)
if (v[k] != 0) {
if (v[k] > 0) positive++;
else negative++;
}
if (positive > 0 && negative > 0) continue;
double tmp_max = 0;
for (int k = 0; k < n; k++) {
double tmp = l.distToPoint(x[k], y[k]);
tmp_max = max(tmp_max, tmp);
}
result = min(tmp_max, result);
}
case_count++;
// result = ceil(100 * result) / 100;
printf("Case %d: %.2f\n", case_count, result);
cin >> n;
}
}
|
#include <AFMotor.h>
#include "LedControl.h"
#include "DFRobotDFPlayerMini.h"
// define of pins
#define PHASE_PIN 22
#define LASER_PIN_L 52
#define LASER_PIN_R 53
// dfplayer
#define BUSY_PIN 21
// led matrix
#define DATA_PIN 38
#define CS_PIN 40
#define CLK_PIN 42
// define for intensity of the eyes
#define INTENSITY 1
// define for movement
#define MOT_R 3
#define MOT_L 4
#define V 140
#define T_back 1400
// define for messages exchanged between arduino and ESP
#define ARD_READY "1"
#define ESP_READY "2"
#define PHASE_1 "3"
#define PHASE_2 "4"
#define MOV_1 "5"
#define END_MOV_1 "6"
#define RES_POS_1 "7"
#define END_RES_POS_1 "8"
#define SPEAK_1 "9"
#define END_SPEAK_1 "10"
#define STOP_SPEAK_1 "11"
#define ROCK_INT "12"
#define END_ROCK_INT "13"
#define MOV_2 "14"
#define END_MOV_2 "15"
#define SPEAK_2 "16"
#define END_SPEAK_2 "17"
#define STOP_SPEAK_2 "18"
#define RES_POS_2 "19"
#define END_RES_POS_2 "20"
#define START_GAME "21"
#define START_GAME_YES "22"
#define START_GAME_NO "23"
#define END_GAME "24"
#define CORRECT_ANSWER "25"
#define WRONG_ANSWER "26"
// enum of the tracks on SD card
enum Track { A, GREETINGS, ADVERTISE, QRCODE, BYE_GREETINGS, SADNESS, GAME_PROPOSAL, GAME_START_INSTRUCTION, INTRODUCTION_PHRASE,
CORRECT_PHRASE, WRONG_PHRASE, FACTS_1, FACTS_2, FACTS_3, FACTS_4, FACTS_5,
LETS_SEE, VERY_BAD, BAD, GOOD, VERY_GOOD, PERFECT, ROCK_SONG
};
// variable for timers
unsigned long t;
// variable for phase
int phase;
DFRobotDFPlayerMini dfplayer;
// used for the eyes
LedControl lc = LedControl(DATA_PIN, CLK_PIN, CS_PIN, 2);
void setup() {
Serial1.begin(115200);
Serial1.setTimeout(1);
Serial.begin(115200);
serial_write_debug("START");
// wait for message from esp
while (serial_read() != ESP_READY) {
}
serial_write_debug("ESP READY");
// initialization of arduino
sensor_setup();
motor_setup();
eyes_setup();
dfplayer_setup();
// Inizializza Laser
pinMode(LASER_PIN_L, OUTPUT);
digitalWrite(LASER_PIN_L, LOW);
pinMode(LASER_PIN_R, OUTPUT);
digitalWrite(LASER_PIN_R, LOW);
// Inizializza Switch Phase
pinMode(PHASE_PIN, INPUT_PULLUP);
// comunicate to ESP that initialization has finished
serial_write(ARD_READY);
delay(10);
serial_write_debug("ARDUINO READY");
// read current phase
phase = digitalRead(PHASE_PIN);
if (phase == 1)
serial_write(PHASE_1);
if (phase == 0)
serial_write(PHASE_2);
// random for phase 2
randomSeed(analogRead(31));
// ready to start
draw_openclose();
delay(500);
}
void loop() {
if (phase == 1) {
phase1();
}
else {
phase2();
}
}
|
#pragma once
#include "PokemonObject.h"
#include <vector>
class Factory
{
public:
static Factory& GetInstance()
{
static Factory instance;
return instance;
}
Factory();
int ChoiceNumToPokeNum(int choice);
int RandNumToPokeNum(int choice);
pokemonObject CreatePokemon(int choose);
void checkPokeStatisticsOrCont();
void printPokemonList();
std::vector<int> pokemonNumber = {1,3,4,95,125,130,159,217};
~Factory();
};
|
//自行构造和解密数字信封(非PKCS#7)
#include <iostream>
#include "getopt.h"
#include <openssl\evp.h>
#include <openssl\err.h>
#include <openssl\rsa.h>
#include <openssl\pem.h>
#include <fstream>
#include <string>
/*e/--encrypt 数字信封加密(对称算法使用AES128-CBC)
-d/--decrypt 数字信封解密
-k/--key 公钥或私钥文件(在加密时使用公钥,解密时使用私钥)
-i/--input 输入文件
-o/--output 输出文件
-h/--help 显示使用帮助*/
using uchar = unsigned char;
void showHelpInfo()
{
std::cout << "-e/--encrypt 数字信封加密(对称算法使用AES128-CBC)" << std::endl;
std::cout << "-d/--decrypt 数字信封解密" << std::endl;
std::cout << "-k/--key 公钥或私钥文件(在加密时使用公钥,解密时使用私钥)" << std::endl;
std::cout << "-i/--input 输入文件" << std::endl;
std::cout << "-o/--output 输出文件" << std::endl;
std::cout << "-h/--help 显示使用帮助" << std::endl;
}
struct option arg_options[] =
{
{"encrypt", 0, 0, 'e'},
{"decrypt", 0, 0, 'd'},
{"key", 1, 0, 'k'},
{"input", 1, 0, 'i'},
{"output", 0, 0, 'o'},
{"help", 0, 0, 'h'},
{0, 0, 0, 0}
};
int main(int argc, char* argv[])
{
OpenSSL_add_all_algorithms();
uchar mes[1024] = { 0 };//明文
auto mes_len = 0;
uchar out[1024] = { 0 };//密文
auto outlen = 0;
uchar* cipher_key[2] = { 0 };//对称加密的密钥
cipher_key[0] = (uchar*)malloc(500);
cipher_key[1] = (uchar*)malloc(500);
int cipher_key_len[2] = { 0 };
uchar iv[1024] = { 0 };//初始化向量
auto encr_or_decr = 1;//1加密0解密
EVP_PKEY* pkey[2] = { nullptr, nullptr };
RSA* rsa = nullptr;
EVP_CIPHER_CTX ctx;
auto option_index = 0;
auto c = 0;
while ((c = getopt_long(argc, argv, "hedk:i:o", arg_options, &option_index)) != -1)
{
switch (c)
{
case 'h':
{
showHelpInfo();
}
break;
case 'e':
{
encr_or_decr = 1;
}
break;
case 'd':
{
encr_or_decr = 0;
}
break;
case 'k':
{
BIO* bio = BIO_new_file(optarg, "r");
rsa = RSA_new();
pkey[0] = EVP_PKEY_new();
rsa = PEM_read_bio_RSAPrivateKey(bio, &rsa, nullptr, nullptr);
EVP_PKEY_assign_RSA(pkey[0], rsa);
BIO_free(bio);
}
break;
case 'i':
{
//加密
if (1 == encr_or_decr)
{
std::ifstream readFile(optarg);
readFile.seekg(0, std::ios::end);
auto len = readFile.tellg();
readFile.seekg(0, std::ios::beg);
readFile.read((char*)mes, len);
readFile.close();
mes_len = len;
}
else
{
std::ifstream readFile(optarg, std::ios::binary);
if (!readFile.is_open())
{
std::cout << std::endl;
}
auto len = 0;
readFile >> len;
readFile.read((char*)mes, len);
mes_len = len;
readFile >> len;
readFile.read((char*)cipher_key[0], len);
cipher_key_len[0] = len;
readFile >> len;
readFile.read((char*)iv, len);
readFile.close();
}
}
break;
case 'o':
{
//加密
if (1 == encr_or_decr)
{
auto total = 0;
EVP_CIPHER_CTX_init(&ctx);
EVP_SealInit(&ctx, EVP_aes_128_cbc(), cipher_key, cipher_key_len, iv, pkey, 1);
EVP_SealUpdate(&ctx, out, &outlen, mes, strlen((char*)mes));
total += outlen;
EVP_SealFinal(&ctx, out + outlen, &outlen);
total += outlen;
std::ofstream writeFile("out.txt", std::ios::binary);
EVP_CIPHER_CTX_free(&ctx);
writeFile << outlen;
writeFile.write((char*)out, outlen);
writeFile << cipher_key_len[0];
writeFile.write((char*)cipher_key[0], cipher_key_len[0]);
writeFile << 16;
writeFile.write((char*)iv, 16);
writeFile.close();
}
//解密
else
{
auto total = 0;
auto outl = 0;
EVP_CIPHER_CTX_init(&ctx);
EVP_OpenInit(&ctx, EVP_aes_128_cbc(), cipher_key[0], cipher_key_len[0], iv, pkey[0]);
EVP_OpenUpdate(&ctx, out, &outl, mes, mes_len);
total += outl;
EVP_OpenFinal(&ctx, out + outl, &outl);
total += outl;
out[total] = 0;
std::ofstream writeFile("decry.txt");
writeFile.write((char*)out, total);
writeFile.close();
EVP_CIPHER_CTX_cleanup(&ctx);
}
}
break;
default:
break;
}
}
RSA_free(rsa);
system("pause");
return 0;
}
|
// Created on: 1993-11-17
// Created by: Jean Yves LEBEY
// Copyright (c) 1993-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 _TopOpeBRep_VPointInterClassifier_HeaderFile
#define _TopOpeBRep_VPointInterClassifier_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <BRepClass_FaceClassifier.hxx>
#include <TopAbs_State.hxx>
#include <TopoDS_Shape.hxx>
#include <Standard_Integer.hxx>
class TopOpeBRep_VPointInter;
class TopOpeBRep_PointClassifier;
class TopOpeBRep_VPointInterClassifier
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT TopOpeBRep_VPointInterClassifier();
//! compute position of VPoint <VP> regarding with face <F>.
//! <ShapeIndex> (= 1,2) indicates which (u,v) point of <VP> is used.
//! when state is ON, set VP.EdgeON() with the edge containing <VP>
//! and associated parameter.
//! returns state of VP on ShapeIndex.
Standard_EXPORT TopAbs_State VPointPosition (const TopoDS_Shape& F, TopOpeBRep_VPointInter& VP, const Standard_Integer ShapeIndex, TopOpeBRep_PointClassifier& PC, const Standard_Boolean AssumeINON, const Standard_Real Tol);
//! returns the edge containing the VPoint <VP> used in the
//! last VPointPosition() call. Edge is defined if the state previously
//! computed is ON, else Edge is a null shape.
Standard_EXPORT const TopoDS_Shape& Edge() const;
//! returns the parameter of the VPoint <VP> on Edge()
Standard_EXPORT Standard_Real EdgeParameter() const;
protected:
private:
BRepClass_FaceClassifier mySlowFaceClassifier;
TopAbs_State myState;
TopoDS_Shape myNullShape;
};
#endif // _TopOpeBRep_VPointInterClassifier_HeaderFile
|
#include <arba/evnt/version.hpp>
#include <gtest/gtest.h>
#include <cstdlib>
TEST(project_version_tests, test_version_macros)
{
ASSERT_EQ(ARBA_EVNT_VERSION_MAJOR, 0);
ASSERT_EQ(ARBA_EVNT_VERSION_MINOR, 3);
ASSERT_EQ(ARBA_EVNT_VERSION_PATCH, 0);
ASSERT_STREQ(ARBA_EVNT_VERSION, "0.3.0");
}
|
#include "core/pch.h"
//Core header files
#include "modules/widgets/OpWidget.h"
//Platform header files
#include "adjunct/quick/managers/TipsManager.h"
//Global objects and constant definations
TipsManager::TipsManager()
: m_tips_token(FALSE)
{
}
TipsManager::~TipsManager()
{
TipsConfigManager::Destroy(m_tips_config_mgr);
}
OP_STATUS
TipsManager::Init()
{
RETURN_OOM_IF_NULL(m_tips_config_mgr = TipsConfigManager::GetInstance());
OpStatus::Ignore(m_tips_config_mgr->LoadConfiguration());
m_timer_tips_token.SetTimerListener(this);
return OpStatus::OK;
}
OP_STATUS
TipsManager::GetTipsConfigData(const OpStringC16& tip_name, TipsConfigGeneralInfo &tip_info)
{
return m_tips_config_mgr->GetTipsConfigData(tip_name, tip_info);
}
BOOL
TipsManager::CanTipBeDisplayed(const OpStringC16& tip_name, TipsConfigGeneralInfo &tip_info)
{
if (m_tips_config_mgr->IsTipsNeverOff())
{
OP_STATUS status = GetTipsConfigData(tip_name , tip_info);
return OpStatus::IsSuccess(status) ? TRUE : FALSE;
}
if (!IsTipsSystemEnabled())
return FALSE;
if (m_tips_token) //If m_tips_token is not FALSE, it means someone has displayed a tip.
return FALSE;
if (OpStatus::IsError(GetTipsConfigData(tip_name , tip_info)))
return FALSE;
if (!tip_info.CanTipBeDisplayed())
return FALSE;
return TRUE;
}
OP_STATUS
TipsManager::GrabTipsToken(TipsConfigGeneralInfo &tip_info)
{
if (m_tips_config_mgr->IsTipsNeverOff())
return OpStatus::OK;
if (m_tips_token == TRUE) //If m_tips_token is not FALSE, it means someone has displayed a tip.
return OpStatus::ERR;
RETURN_IF_ERROR(MarkTipShown(tip_info));
m_tips_token = TRUE;
m_timer_tips_token.Start(m_tips_config_mgr->GetTipsDisplayInterval());
return OpStatus::OK;
}
OP_STATUS
TipsManager::MarkTipShown(TipsConfigGeneralInfo &tip_info)
{
return m_tips_config_mgr->UpdateTipsLastDisplayedInfo(tip_info);
}
void
TipsManager::OnTimeOut(OpTimer* timer)
{
if (timer == &m_timer_tips_token)
{
m_tips_token = FALSE;
}
}
|
#ifndef VnaChannel_H
#define VnaChannel_H
// RsaToolbox
#include "Definitions.h"
#include "BalancedPort.h"
#include "VnaArbitraryFrequency.h"
#include "VnaLinearSweep.h"
#include "VnaLogSweep.h"
#include "VnaSegmentedSweep.h"
#include "VnaPowerSweep.h"
#include "VnaCwSweep.h"
#include "VnaTimeSweep.h"
#include "VnaUserDefinedPort.h"
#include "VnaPortSettings.h"
#include "VnaGeneratorSettings.h"
#include "VnaAveraging.h"
#include "VnaIntermod.h"
#include "VnaCalibrate.h"
#include "VnaExtensionUnit.h"
#include "VnaPulseGenerator.h"
#include "VnaSyncGenerator.h"
#include "VnaTrigger.h"
#include "vnausercontrol.h"
// This should probably be rolled into
// VnaCorrections.h (a lot of the same
// commands apply here).
#include "VnaPowerCorrections.h"
// * #include "VnaCorrections.h"
// * See note at end of file
// Qt
#include <QMap>
#include <QObject>
#include <QScopedPointer>
#include <QString>
#include <QStringList>
#include <QVector>
namespace RsaToolbox {
class Vna;
class VnaCorrections;
class VnaChannel : public QObject
{
Q_OBJECT
public:
enum /*class*/ SweepType {
Linear,
Log,
Segmented,
Power,
Cw,
Time
};
enum /*class*/ IfSelectivity {
Normal,
High
};
explicit VnaChannel(QObject *parent = 0);
VnaChannel(const VnaChannel &other);
VnaChannel(Vna *_vna, uint index, QObject *parent = 0);
~VnaChannel();
uint index();
QString name();
void setName(QString name);
void select();
QVector<uint> diagrams();
QStringList traces();
// Sweep control
void startSweep();
bool isSweepOn();
bool isSweepOff();
void sweepOn(bool isOn = true);
void sweepOff(bool isOff = true);
bool isContinuousSweep();
bool isManualSweep();
void continuousSweepOn(bool isOn = true);
void manualSweepOn(bool isOn = true);
uint sweepCount();
void setSweepCount(uint count = 1);
// Timing
uint sweepTime_ms();
uint totalSweepTime_ms();
// IF Selectivity
IfSelectivity ifSelectivity();
void setIfSelectivity(IfSelectivity s);
// Sweep type
bool isFrequencySweep();
bool isLinearSweep();
bool isLogarithmicSweep();
bool isSegmentedSweep();
bool isPowerSweep();
bool isCwSweep();
bool isTimeSweep();
SweepType sweepType();
void setSweepType(SweepType sweepType);
void setFrequencies(QRowVector values, SiPrefix prefix = SiPrefix::None);
VnaLinearSweep &linearSweep();
VnaLinearSweep *takeLinearSweep();
VnaLogSweep &logSweep();
VnaLogSweep *takeLogSweep();
VnaSegmentedSweep &segmentedSweep();
VnaSegmentedSweep *takeSegmentedSweep();
VnaPowerSweep &powerSweep();
VnaPowerSweep *takePowerSweep();
VnaCwSweep &cwSweep();
VnaCwSweep *takeCwSweep();
VnaTimeSweep &timeSweep();
VnaTimeSweep *takeTimeSweep();
// Attenuation
double sourceAttenuation_dB(uint port);
void setSourceAttenuation(double attenuation_dB, uint port);
void setSourceAttenuations(double attenuation_dB);
double receiverAttenuation_dB(uint port);
void setReceiverAttenuation(double attenuation_dB, uint port);
void setReceiverAttenuations(double attenuation_dB);
// Balanced ports
uint numberOfLogicalPorts();
bool isSingleEndedPort(uint logicalPort);
uint testPort(uint logicalPort);
bool isBalancedPort(uint logicalPort);
void testPorts(uint logicalPort, uint &testPort1, uint &testPort2);
void createSingleEndedPort(uint logicalPort, uint testPort);
void createBalancedPort(uint logicalPort, uint testPort1, uint testPort2);
void deleteBalancedPort(uint logicalPort);
void deleteBalancedPorts();
QMap<uint, uint> testToLogicalPortMap();
QVector<uint> logicalPorts(QVector<uint> testPorts);
// User-defined ports
bool isUserDefinedPort(uint testPort);
bool isNotUserDefinedPort(uint testPort);
VnaUserDefinedPort userDefinedPort(uint testPort);
void setUserDefinedPort(uint testPort, VnaUserDefinedPort userDefinedPort);
void deleteUserDefinedPort(uint testPort);
void deleteUserDefinedPorts();
// Port settings
VnaPortSettings& port(uint testPort);
// Receiver Arbitrary Frequency
// - Applies to all ports -
// Note: ZVA only
bool isArbitraryReceiverFrequencyOn();
VnaArbitraryFrequency arbitraryReceiverFrequency();
void setArbitraryReceiverFrequency(const VnaArbitraryFrequency &arbitraryFreq);
void arbitraryReceiverFrequencyOff();
// External Generators
VnaGeneratorSettings& externalGenerator(uint i);
// Averaging
VnaAveraging &averaging();
// Delay Offsets
double delayOffset_s(uint port);
QRowVector delayOffsets_s();
void setDelayOffset(uint port, double delay, SiPrefix prefix = SiPrefix::None);
void setDelayOffsets(QRowVector delays, SiPrefix prefix = SiPrefix::None);
void clearDelayOffset(uint port);
void clearDelayOffsets();
VnaIntermod &intermod();
VnaIntermod *takeIntermod();
// Corrections
bool isCalibrated();
bool isCalGroup();
void saveCalibration(QString calGroup);
void setCalGroup(QString calGroup);
QString calGroup();
QString calGroupFile();
void dissolveCalGroupLink();
VnaCorrections &corrections();
VnaCalibrate &calibrate();
VnaCalibrate *takeCalibrate();
// Power corrections
// bool isPowerCalibrated();
VnaPowerCorrections &powerCorrections();
// VnaPowerCalibrate &powerCalibrate();
// Pulse Modulator
VnaExtensionUnit &extensionUnit();
// Pulse Generators
VnaPulseGenerator &pulseGenerator();
VnaSyncGenerator &syncGenerator();
// Trigger
VnaTrigger &trigger();
// User control
VnaUserControl &userControl();
void operator=(const VnaChannel &other);
private:
Vna *_vna;
QScopedPointer<Vna> placeholder;
uint _index;
QScopedPointer<VnaLinearSweep> _frequencySweep;
QScopedPointer<VnaLogSweep> _logSweep;
QScopedPointer<VnaSegmentedSweep> _segmentedSweep;
QScopedPointer<VnaPowerSweep> _powerSweep;
QScopedPointer<VnaCwSweep> _cwSweep;
QScopedPointer<VnaTimeSweep> _timeSweep;
QScopedPointer<VnaPortSettings> _portSettings;
QScopedPointer<VnaGeneratorSettings> _generatorSettings;
QScopedPointer<VnaAveraging> _averaging;
QScopedPointer<VnaIntermod> _intermod;
QScopedPointer<VnaCorrections> _corrections;
QScopedPointer<VnaPowerCorrections> _powerCorrections;
QScopedPointer<VnaCalibrate> _calibrate;
QScopedPointer<VnaExtensionUnit> _extensionUnit;
QScopedPointer<VnaPulseGenerator> _pulseGenerator;
QScopedPointer<VnaSyncGenerator> _syncGenerator;
QScopedPointer<VnaTrigger> _trigger;
QScopedPointer<VnaUserControl> _userControl;
bool isFullyInitialized() const;
QStringList zvaTraces();
// Balanced Ports
QVector<uint> testPorts(uint logicalPort);
// User-defined ports
bool isUserDefinedPortOn(uint testPort);
bool isUserDefinedPortOff(uint testPort);
void userDefinedPortOn(uint testPort);
void userDefinedPortOff(uint testPort);
};
} // RsaToolbox
Q_DECLARE_METATYPE(RsaToolbox::VnaChannel::SweepType)
// Classes that depend
// on VnaChannel::SweepType :
// Cannot forward declare class,
// Must provide definition first.
// This unusual include placement
// allows reference in
// child classes and header
// inclusion in parent.
#include "VnaCorrections.h"
#endif // VnaChannel_H
|
#include "MemoryManager.h"
#include <cassert>
namespace keng::memory
{
MemoryManager::MemoryManager() {
m_pools.emplace_back( 8, 10, 100000);
m_pools.emplace_back(16, 10, 100000);
m_pools.emplace_back(24, 10, 100000);
m_pools.emplace_back(32, 10, 100000);
m_pools.emplace_back(40, 10, 100000);
m_pools.emplace_back(48, 10, 100000);
m_pools.emplace_back(56, 10, 100000);
m_pools.emplace_back(64, 10, 100000);
m_sortedBySize.reserve(m_pools.size());
m_sortedByStartAddress.reserve(m_pools.size());
for (auto& pool : m_pools) {
m_sortedBySize.push_back(&pool);
m_sortedByStartAddress.push_back(&pool);
m_biggestPoolSize = std::max(pool.GetElementSize(), m_biggestPoolSize);
}
std::sort(m_sortedBySize.begin(), m_sortedBySize.end(), [](VirtualPool* a, VirtualPool* b) {
return a->GetElementSize() < b->GetElementSize();
});
std::sort(m_sortedByStartAddress.begin(), m_sortedByStartAddress.end(), [](VirtualPool* a, VirtualPool* b) {
return a->GetBeginAddress() < b->GetBeginAddress();
});
}
MemoryManager::~MemoryManager()
{
}
void* MemoryManager::Allocate(size_t size) {
if(size <= m_biggestPoolSize) {
auto it = std::lower_bound(
m_sortedBySize.begin(), m_sortedBySize.end(), size,
[](VirtualPool* b, size_t val) {
return b->GetElementSize() < val;
});
if (m_sortedBySize.end() != it) {
assert((*it)->GetElementSize() >= size);
if(auto result = (*it)->Allocate()) {
return result;
}
}
}
return malloc(size);
}
void MemoryManager::Deallocate(void* pointer) {
assert(pointer != nullptr);
auto address = (size_t)pointer;
auto it = std::upper_bound(
m_sortedByStartAddress.rbegin(), m_sortedByStartAddress.rend(), address,
[](size_t address, VirtualPool* b) {
return address >= b->GetBeginAddress();
});
if (it != m_sortedByStartAddress.rend()) {
auto& pool = **it;
assert(pool.GetBeginAddress() <= address);
if (pool.GetEndAddress() > address) {
pool.Deallocate(pointer);
return;
}
}
free(pointer);
}
MemoryManager& MemoryManager::Instance() {
static MemoryManager instance;
return instance;
}
}
|
#pragma once
#include <string>
using namespace std;
namespace nora {
namespace net {
namespace websocket {
const string ws_magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) Opera Software ASA 2006 - 2008
*
* Web server implementation
*/
#ifndef WEBSERVER_ROBOTS_H_
#define WEBSERVER_ROBOTS_H_
#if defined(WEBSERVER_SUPPORT)
#include "modules/webserver/webserver_resources.h"
#include "modules/webserver/webresource_base.h"
class WebServerConnection;
class WebServer;
/**
This class provide a robots.txt file for blocking Search Engines
*/
class WebResource_Robots : public WebResource_Administrative_Standard
{
private:
static OP_STATUS ManageSubServer(ByteBuffer &buf, WebSubServer *sub_server);
public:
/* Create the resource */
static OP_STATUS Make(WebResource *&webresource, WebServerConnection *service, const OpStringC16 &subServerRequestString, WebserverRequest *requestObject, WebserverResourceDescriptor_Base *resource, WebServerFailure *result);
WebResource_Robots(WebServerConnection *service, WebserverRequest *requestObject): WebResource_Administrative_Standard(service, requestObject) { }
};
#endif // defined(WEBSERVER_SUPPORT)
#endif /*WEBSERVER_FILE_H_*/
|
#include "stdafx.h"
#include "Material.h"
Jaraffe::Material Jaraffe::Material::m_pDefalutMaterial;
Jaraffe::Material::Material()
{
m_Material.Ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_Material.Diffuse = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_Material.Specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_Material.Reflect = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
}
Jaraffe::Material::~Material()
{
}
Jaraffe::Material* Jaraffe::Material::GetDefalutMaterial()
{
return &m_pDefalutMaterial;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 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 OP_PROTOBUF_OUTPUT_H
#define OP_PROTOBUF_OUTPUT_H
#ifdef PROTOBUF_SUPPORT
#include "modules/util/adt/opvector.h"
#include "modules/protobuf/src/protobuf_wireformat.h"
#ifdef PROTOBUF_JSON_SUPPORT
#include "modules/protobuf/src/json_tools.h"
#endif // PROTOBUF_JSON_SUPPORT
#if defined(PROTOBUF_JSON_SUPPORT) || defined(PROTOBUF_XML_SUPPORT)
class ByteBuffer;
class TempBuffer;
class OpScopeFormatter;
#endif // defined(PROTOBUF_JSON_SUPPORT) || defined(PROTOBUF_XML_SUPPORT)
class OpProtobufInstanceProxy;
class OpProtobufField;
class OpProtobufDataOutputRange;
class OpProtobufBasicOutputStream
{
public:
OpProtobufBasicOutputStream(OpProtobufDataOutputRange *out_range);
const OpProtobufDataOutputRange *OutputRange() const { return out_range; }
OP_STATUS WriteFieldHeader(OpProtobufWireFormat::WireType wire_type, int number);
OP_STATUS WriteVarInt32(INT32 num);
OP_STATUS WriteVarInt64(INT64 num);
OP_STATUS WriteUint32(UINT32 num);
OP_STATUS WriteUint64(UINT64 num);
OP_STATUS WriteFloat(float num);
OP_STATUS WriteDouble(double num);
OP_STATUS WriteBool(BOOL v);
OP_STATUS WriteString(OpProtobufStringChunkRange range);
OP_STATUS WriteBytes(const OpProtobufDataChunkRange &range);
private:
OpProtobufDataOutputRange *out_range;
};
class OpProtobufOutputStream : public OpProtobufBasicOutputStream
{
public:
OpProtobufOutputStream(OpProtobufDataOutputRange *out_range);
OP_STATUS Write(const OpProtobufInstanceProxy &instance);
private:
OP_STATUS WriteMessage(const OpProtobufInstanceProxy &instance);
OP_STATUS WriteField(const OpProtobufInstanceProxy &instance, int field_idx, const OpProtobufField &field);
int CalculateMessageSize(const OpProtobufInstanceProxy &instance) const;
int CalculateFieldSize(const OpProtobufInstanceProxy &instance, int field_idx, const OpProtobufField &field) const;
int level;
};
#ifdef PROTOBUF_JSON_SUPPORT
class OpJSONOutputStream
{
public:
OpJSONOutputStream(ByteBuffer &out);
OP_STATUS Write(const OpProtobufInstanceProxy &instance);
private:
OP_STATUS WriteMessage(const OpProtobufInstanceProxy &instance, BOOL first = TRUE);
OP_STATUS WriteField(const OpProtobufInstanceProxy &instance, int field_idx, const OpProtobufField &field, BOOL embed = FALSE, BOOL first = TRUE);
ByteBuffer &out;
};
#endif // PROTOBUF_JSON_SUPPORT
#ifdef PROTOBUF_XML_SUPPORT
class OpXMLOutputStream
{
public:
OpXMLOutputStream(ByteBuffer &out);
OP_STATUS Write(const OpProtobufInstanceProxy &instance);
private:
OP_STATUS WriteMessage(const OpProtobufInstanceProxy &instance);
OP_STATUS WriteField(const OpProtobufInstanceProxy &instance, int field_idx, const OpProtobufField &field);
OP_STATUS WriteDouble(double value);
OP_STATUS WriteSignedLong(long value);
OP_STATUS WriteUnsignedLong(long value);
OP_STATUS WriteString(OpProtobufStringChunkRange range);
OP_STATUS WriteCString(const char *str, int len = -1);
OP_STATUS WriteBytes(OpProtobufDataChunkRange range);
ByteBuffer &out;
};
#endif // PROTOBUF_XML_SUPPORT
#endif // PROTOBUF_SUPPORT
#endif // OP_PROTOBUF_OUTPUT_H
|
#include "Component.hpp"
Elysium::Data::Model::Component::~Component()
{
}
Elysium::Data::Model::Component::Component(Elysium::Data::Description::ComponentDescriptor* ComponentDescriptor)
: Object(),
_ComponentDescriptor(ComponentDescriptor)
{
}
|
/*
===============================================================================
AAS_Find.cpp
This file has all aas search classes.
===============================================================================
*/
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../Game_local.h"
#include "AI.h"
#include "AI_Manager.h"
#include "AI_Util.h"
#include "AAS_Find.h"
/*
===============================================================================
rvAASFindGoalForHide
===============================================================================
*/
/*
============
rvAASFindGoalForHide::rvAASFindGoalForHide
============
*/
rvAASFindGoalForHide::rvAASFindGoalForHide( const idVec3 &hideFromPos ) {
int numPVSAreas;
idBounds bounds( hideFromPos - idVec3( 16, 16, 0 ), hideFromPos + idVec3( 16, 16, 64 ) );
// setup PVS
numPVSAreas = gameLocal.pvs.GetPVSAreas( bounds, PVSAreas, idEntity::MAX_PVS_AREAS );
hidePVS = gameLocal.pvs.SetupCurrentPVS( PVSAreas, numPVSAreas );
}
/*
============
rvAASFindGoalForHide::~rvAASFindGoalForHide
============
*/
rvAASFindGoalForHide::~rvAASFindGoalForHide() {
gameLocal.pvs.FreeCurrentPVS( hidePVS );
}
/*
rvAASFindGoalForHide
rvAASFindHide::TestArea
============
*/
bool rvAASFindGoalForHide::TestArea( class idAAS *aas, int areaNum, const aasArea_t& area ) {
int numPVSAreas;
int PVSAreas[ idEntity::MAX_PVS_AREAS ];
numPVSAreas = gameLocal.pvs.GetPVSAreas( idBounds( area.center ).Expand( 16.0f ).TranslateSelf(idVec3(0,0,1)), PVSAreas, idEntity::MAX_PVS_AREAS );
if ( !gameLocal.pvs.InCurrentPVS( hidePVS, PVSAreas, numPVSAreas ) ) {
return true;
}
return false;
}
/*
===============================================================================
rvAASFindGoalOutOfRange
===============================================================================
*/
/*
============
rvAASFindGoalOutOfRange::rvAASFindGoalOutOfRange
============
*/
rvAASFindGoalOutOfRange::rvAASFindGoalOutOfRange( idAI* _owner ) {
owner = _owner;
}
/*
============
rvAASFindAreaOutOfRange::TestArea
============
*/
bool rvAASFindGoalOutOfRange::TestPoint ( idAAS* aas, const idVec3& pos, const float zAllow ) {
return aiManager.ValidateDestination ( owner, pos );
}
/*
===============================================================================
rvAASFindGoalForAttack
Find a position to move to that allows the ai to at their target
===============================================================================
*/
/*
============
rvAASFindGoalForAttack::rvAASFindGoalForAttack
============
*/
rvAASFindGoalForAttack::rvAASFindGoalForAttack( idAI* _owner ) {
owner = _owner;
cachedIndex = 0;
}
/*
============
rvAASFindGoalForAttack::~rvAASFindGoalForAttack
============
*/
rvAASFindGoalForAttack::~rvAASFindGoalForAttack ( void ) {
}
/*
============
rvAASFindGoalForAttack::Init
============
*/
void rvAASFindGoalForAttack::Init ( void ) {
// setup PVS
int numPVSAreas;
numPVSAreas = gameLocal.pvs.GetPVSAreas( owner->enemy.ent->GetPhysics()->GetAbsBounds(), PVSAreas, idEntity::MAX_PVS_AREAS );
targetPVS = gameLocal.pvs.SetupCurrentPVS( PVSAreas, numPVSAreas );
cachedGoals.SetGranularity ( 1024 );
}
/*
============
rvAASFindGoalForAttack::Finish
============
*/
void rvAASFindGoalForAttack::Finish ( void ) {
gameLocal.pvs.FreeCurrentPVS( targetPVS );
}
/*
============
rvAASFindGoalForAttack::TestArea
============
*/
bool rvAASFindGoalForAttack::TestArea( class idAAS *aas, int areaNum, const aasArea_t& area ) {
int numPVSAreas;
int PVSAreas[ idEntity::MAX_PVS_AREAS ];
cachedAreaNum = areaNum;
// If the whole area is out of range then skip it
float range;
range = area.bounds.ShortestDistance ( owner->enemy.lastKnownPosition );
if ( range > owner->combat.attackRange[1] ) {
return false;
}
// Out of pvs?
numPVSAreas = gameLocal.pvs.GetPVSAreas( idBounds( area.center ).Expand( 16.0f ), PVSAreas, idEntity::MAX_PVS_AREAS );
return gameLocal.pvs.InCurrentPVS( targetPVS, PVSAreas, numPVSAreas );
}
/*
============
rvAASFindGoalForAttack::TestPoint
============
*/
bool rvAASFindGoalForAttack::TestPoint ( class idAAS *aas, const idVec3& point, const float zAllow ) {
float dist;
idVec3 localPoint = point;
float bestZ = owner->enemy.ent->GetPhysics()->GetOrigin().z;
if ( bestZ > localPoint.z ) {
if ( bestZ > zAllow ) {
localPoint.z = zAllow;
} else {
localPoint.z = bestZ;
}
}
// Out of attack range?
dist = (localPoint - owner->enemy.ent->GetPhysics()->GetOrigin ( )).LengthFast ( );
if ( dist < owner->combat.attackRange[0] || dist > owner->combat.attackRange[1] ) {
return false;
}
// If tethered make sure the point is within the tether range
if ( owner->tether ) {
idVec3 localPoint = point;
float bestZ = owner->tether.GetEntity()->GetPhysics()->GetOrigin().z;
if ( bestZ > localPoint.z ) {
if ( bestZ > zAllow ) {
localPoint.z = zAllow;
} else {
localPoint.z = bestZ;
}
}
if ( !owner->tether->ValidateDestination ( owner, localPoint ) ) {
return false;
}
}
aasGoal_t& goal = cachedGoals.Alloc ( );
goal.areaNum = cachedAreaNum;
goal.origin = localPoint;
return false;
}
/*
============
rvAASFindGoalForAttack::TestCachedGoal
============
*/
bool rvAASFindGoalForAttack::TestCachedGoal ( int index ) {
const aasGoal_t& goal = cachedGoals[index];
// Out of attack range?
float dist = (goal.origin - owner->enemy.ent->GetPhysics()->GetOrigin ( ) ).LengthFast ( );
if ( dist < owner->combat.attackRange[0] || dist > owner->combat.attackRange[1] ) {
return false;
}
// Someone already there?
if ( !aiManager.ValidateDestination ( owner, goal.origin, true ) ) {
return false;
}
// Can we see the enemy from this position?
if ( !owner->CanSeeFrom ( goal.origin - owner->GetPhysics()->GetGravityNormal ( ) * owner->combat.visStandHeight, owner->GetEnemy(), false ) ) {
return false;
}
return true;
}
/*
============
rvAASFindGoalForAttack::TestCachedPoints
============
*/
bool rvAASFindGoalForAttack::TestCachedGoals ( int count, aasGoal_t& goal ) {
int i;
goal.areaNum = 0;
// Test as many points as we are allowed to test
for ( i = 0; i < count && cachedIndex < cachedGoals.Num(); cachedIndex ++, i ++ ) {
// Retest simple checks
if ( TestCachedGoal( cachedIndex ) ) {
goal = cachedGoals[cachedIndex];
return true;
}
}
return !(cachedIndex >= cachedGoals.Num());
}
/*
===============================================================================
rvAASFindGoalForTether
Find a goal to move to that is within the given tether.
===============================================================================
*/
/*
============
rvAASFindGoalForTether::rvAASFindGoalForTether
============
*/
rvAASFindGoalForTether::rvAASFindGoalForTether( idAI* _owner, rvAITether* _tether ) {
owner = _owner;
tether = _tether;
}
/*
============
rvAASFindGoalForTether::rvAASFindGoalForTether
============
*/
rvAASFindGoalForTether::~rvAASFindGoalForTether( void ) {
}
/*
============
rvAASFindGoalForTether::TestArea
============
*/
bool rvAASFindGoalForTether::TestArea( class idAAS *aas, int areaNum, const aasArea_t& area ) {
// Test super class first
if ( !idAASCallback::TestArea ( aas, areaNum, area ) ) {
return false;
}
// Make sure the area bounds is remotely valid for the tether
idBounds tempBounds = area.bounds;
tempBounds[1].z = area.ceiling;
if ( !tether->ValidateBounds ( tempBounds ) ) {
return false;
}
return true;
}
/*
============
rvAASFindGoalForTether::TestPoint
============
*/
bool rvAASFindGoalForTether::TestPoint ( class idAAS* aas, const idVec3& point, const float zAllow ) {
if ( !tether ) {
return false;
}
idVec3 localPoint = point;
float bestZ = tether->GetPhysics()->GetOrigin().z;
if ( bestZ > localPoint.z ) {
if ( bestZ > zAllow ) {
localPoint.z = zAllow;
} else {
localPoint.z = bestZ;
}
}
if ( !tether->ValidateDestination ( owner, localPoint ) ) {
return false;
}
if ( !aiManager.ValidateDestination ( owner, localPoint ) ) {
return false;
}
return true;
}
|
#include "G_Particles_IO.h"
#include <omp.h>
#define ATT_LENGTH 20;
g_particles_io::g_particles_io()
{
name ="fuck ok";
}
g_particles_io::~g_particles_io()
{
}
// int method settings
void g_particles_io::GIO_setINTAttributeList( int arr[],int arraySize )
{
per_int_attList.clear();
per_int_attList.resize(arraySize);
#pragma omp parallel for
for(int i=0;i<arraySize;i++)
{
per_int_attList[i]=arr[i];
}
}
void g_particles_io::GIO_setINTAttributeList( vector <int> &intAttList )
{
per_int_attList.clear();
per_int_attList=intAttList;
}
void g_particles_io::GIO_setINTAttributeList( int value )
{
per_int_attList.clear();
per_int_attList.push_back(value);
}
// float settings
void g_particles_io::GIO_setFLTAttributeList( float arr[],int arraySize )
{
per_float_attList.clear();
per_float_attList.resize(arraySize);
#pragma omp parallel for
for(int i=0;i<arraySize;i++)
{
per_float_attList[i]=arr[i];
}
}
void g_particles_io::GIO_setFLTAttributeList( vector <float> &intAttList )
{
per_float_attList.clear();
per_float_attList=intAttList;
}
void g_particles_io::GIO_setFLTAttributeList( float value )
{
per_float_attList.clear();
per_float_attList.push_back(value);
}
void g_particles_io::GIO_setINTVecAttributeList( int x,int y,int z )
{
per_int_vector per_int;
per_int.g_x=x;
per_int.g_y=y;
per_int.g_z=z;
per_int_vec_attList.push_back(per_int);
}
void g_particles_io::GIO_setINTVecAttributeList( vector<per_int_vector> intVecAttList )
{
per_int_vec_attList.clear();
int arraySize= intVecAttList.size();
per_int_vec_attList.resize(arraySize);
#pragma omp parallel for
for(int i=0;i<arraySize;i++)
{
per_int_vec_attList[i]=intVecAttList[i];
}
}
void g_particles_io::GIO_setINTVecAttributeList( per_int_vector arr[],int arraySize )
{
per_int_vec_attList.clear();
per_int_vec_attList.resize(arraySize);
#pragma omp parallel for
for(int i=0;i<arraySize;i++)
{
per_int_vec_attList[i]=arr[i];
}
}
// float vector settings
void g_particles_io::GIO_setFLTVecAttributeList( float x,float y,float z )
{
per_float_vector per_flt;
per_flt.g_x=x;
per_flt.g_y=y;
per_flt.g_z=z;
per_float_vec_attList.push_back(per_flt);
}
void g_particles_io::GIO_setFLTVecAttributeList( vector<per_float_vector> fltVecAttList )
{
per_float_vec_attList.clear();
int arraySize= fltVecAttList.size();
per_float_vec_attList.resize(arraySize);
#pragma omp parallel for
for(int i=0;i<arraySize;i++)
{
per_float_vec_attList[i]=fltVecAttList[i];
}
}
void g_particles_io::GIO_setFLTVecAttributeList( per_float_vector arr[],int arraySize )
{
per_float_vec_attList.clear();
per_float_vec_attList.resize(arraySize);
#pragma omp parallel for
for(int i=0;i<arraySize;i++)
{
per_float_vec_attList[i]=arr[i];
}
}
void g_particles_io::saveData( ofstream &fout )
{
//save type and save size
//save size into the fork funcion
//save data
//save name
fout.write((char*)&type,sizeof(type)); // write type
switch (type)
{
case attType::INT_TYPE:
//cout<<"writing the int type attribute\n";
writeINT_AttListData(fout);
break;
case attType::FLT_TYPE:
//cout<<"writing the flt type attribute\n";
writeFLT_AttListData(fout);
break;
case attType::INT_VEC_TYPE:
//cout<<"writing the INT_VEC_TYPE type attribute\n";
writeINT_VecAttListData(fout);
break;
case attType::FLT_VEC_TYPE:
//cout<<"writing the FLT_VEC_TYPE type attribute\n";
writeFLT_VecAttListData(fout);
break;
default:
break;
}
// next to save name
// and save the text length
//1->save text length ,2->save the attribute name
char w_name[40]; //sizeof(w_name) load the 40 ,very important
strcpy(w_name,name.c_str());
int text_length = strlen(w_name); // str length for read used
//std::cout<<"->->->->->write the attribute "<<w_name<<" length is "<<text_length<<std::endl;
fout.write((char*)&text_length,sizeof(int));// write the attribute name length to disk
fout.write((char*)&w_name,sizeof(w_name)); // write the attribute name to disk
}
void g_particles_io::loadData( ifstream &fin )
{
//read type
//std::cout<<"enter the g_particles_io class io loading ......\n";0
attType data_type;
fin.read((char*)&data_type,sizeof(data_type));
type=data_type;
///read size and read data
//std::cout<<"the type id is : "<<data_type<<std::endl;
switch (data_type)
{
case attType::INT_TYPE:
//std::cout<<"loading the g_particles_io class INT ......\n";
loadINT_AttListData(fin);
break;
case attType::FLT_TYPE:
//std::cout<<"loading the g_particles_io class FLT ......\n";
loadFLT_AttListData(fin);
break;
case attType::INT_VEC_TYPE:
//std::cout<<"loading the g_particles_io class INT_VEC_TYPE ......\n";
loadINT_VecAttListData(fin);
break;
case attType::FLT_VEC_TYPE:
//std::cout<<"loading the g_particles_io class FLT_VEC_TYPE ......\n";
loadFLT_VecAttListData(fin);
break;
default:
break;
}
//read the text length
int text_length;
fin.read((char*)&text_length,sizeof(int));
//std::cout<<"read the attribute "<<" length is "<<text_length<<std::endl;
char attName[50]={"\0"};
fin.read((char*)&attName,text_length);
name = string(attName);
//std::cout<<"read the attribute name is"<<name<<std::endl;
//std::cout<<"enter the g_particles_io class io loading ending ......\n";
}
void g_particles_io::writeINT_AttListData( ofstream &fout )
{
int size=per_int_attList.size();
fout.write((char*)&size,sizeof(int));
for(int i=0;i<size;i++)
{
fout.write((char*)&per_int_attList[i],sizeof(per_int_attList[i]));
}
}
void g_particles_io::writeFLT_AttListData( ofstream &fout )
{
int size=per_float_attList.size();
fout.write((char*)&size,sizeof(int));
for(int i=0;i<size;i++)
{
fout.write((char*)&per_float_attList[i],sizeof(per_float_attList[i]));
}
}
void g_particles_io::writeINT_VecAttListData( ofstream &fout )
{
int size=per_int_vec_attList.size();
fout.write((char*)&size,sizeof(int));
for(int i=0;i<size;i++)
{
fout.write((char*)&per_int_vec_attList[i],sizeof(per_int_vec_attList[i]));
}
}
void g_particles_io::writeFLT_VecAttListData( ofstream &fout )
{
int size=per_float_vec_attList.size();
fout.write((char*)&size,sizeof(int));
for(int i=0;i<size;i++)
{
//std::cout<<"every pt num is"<<per_float_vec_attList[i].g_x<<" "<<per_float_vec_attList[i].g_y<<" "<<per_float_vec_attList[i].g_z<<std::endl;
per_float_vector pt=per_float_vec_attList[i];
fout.write((char*)&pt,sizeof(pt));
}
}
void g_particles_io::loadINT_AttListData( ifstream &fin )
{
int size;
fin.read((char*)&size,sizeof(int));
per_int_attList.clear();
per_int_attList.resize(size);
//create temp stack
vector <int> temp_per_int_attList;
for(int i=0;i<size;i++)
{
int value;
fin.read((char*)&value,sizeof(value));
temp_per_int_attList.push_back(value);
}
GIO_setINTAttributeList(temp_per_int_attList);
}
void g_particles_io::loadFLT_AttListData( ifstream &fin )
{
int size;
fin.read((char*)&size,sizeof(int));
per_float_attList.clear();
per_float_attList.resize(size);
//create temp stack
vector <float> temp_per_int_attList;
for(int i=0;i<size;i++)
{
float value;
fin.read((char*)&value,sizeof(value));
temp_per_int_attList.push_back(value);
}
GIO_setFLTAttributeList(temp_per_int_attList);
}
void g_particles_io::loadINT_VecAttListData( ifstream &fin )
{
int size;
fin.read((char*)&size,sizeof(int));
per_int_vec_attList.clear();
per_int_vec_attList.resize(size);
//create temp stack
vector <per_int_vector> temp_per_int_vec_attList;
for(int i=0;i<size;i++)
{
per_int_vector pt_int;
fin.read((char*)&pt_int,sizeof(pt_int));
temp_per_int_vec_attList.push_back(pt_int);
}
GIO_setINTVecAttributeList(temp_per_int_vec_attList);
}
void g_particles_io::loadFLT_VecAttListData( ifstream &fin )
{
int size;
fin.read((char*)&size,sizeof(int));
per_int_vec_attList.clear();
per_int_vec_attList.resize(size);
//create temp stack
vector <per_float_vector> temp_per_flt_vec_attList;
for(int i=0;i<size;i++)
{
per_float_vector pt_int;
fin.read((char*)&pt_int,sizeof(pt_int));
//std::cout<<"get x y z"<<pt_int.g_x<<" "<<pt_int.g_y<<" "<<pt_int.g_z<<std::endl;
temp_per_flt_vec_attList.push_back(pt_int);
}
GIO_setFLTVecAttributeList(temp_per_flt_vec_attList);
}
|
#pragma once
// Node
template <class T>
class Node
{
private:
int id;
public:
T* next;
};
typedef struct _Node
{
struct _Node* next;
} Node;
|
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node *Next;
};
struct Node *head = NULL;
//Insert Function
void insert(int no)
{
if (head == NULL)
{
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
new_node->data = no;
new_node->Next = NULL;
cout << "first node added" << endl;
head = new_node;
}
else
{
struct Node *temp;
temp = head;
//traverse to last node of list
while (temp->Next != NULL)
{
temp = temp->Next;
}
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
new_node->data = no;
new_node->Next = NULL;
temp->Next = new_node;
cout << "first node added" << endl;
}
}
void SearchNum(int no)
{
if (head == NULL)
{
cout << "list is empty" << endl;
}
else
{
struct Node *temp;
temp = head;
while (temp != NULL)
{
if (temp->data == no)
{
cout << "no found in list" << endl;
break;
}
temp = temp->Next;
}
}
}
void deleteFront()
{
if (head == NULL)
{
cout << "list is empty" << endl;
return;
}
else
{
struct Node *temp;
temp = head;
cout << temp->data << " Deleted from list" << endl;
head = temp->Next;
}
}
//display Function
void display()
{
if (head == NULL)
{
cout << "list is empty" << endl;
return;
}
else
{
struct Node *temp;
temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->Next;
}
}
cout << "" << endl;
}
int main()
{
int ch, no;
bool Var = true;
do
{
cout << endl;
cout << "*****************" << endl;
cout << "1.insert" << endl;
cout << "2.display" << endl;
cout << "3.search" << endl;
cout << "4.delete" << endl;
cout << "5.exit" << endl;
cin >> ch;
switch (ch)
{
case 1:
cout << "Enter the Number" << endl;
cin >> no;
insert(no);
break;
case 2:
cout << "Linked List Elements are" << endl;
display();
break;
case 3:
display();
cout << endl;
cout << "Enter The Number To Search From List" << endl;
cin >> no;
SearchNum(no);
break;
case 4:
deleteFront();
break;
case 5:
exit(0);
Var = false;
break;
default:
break;
}
} while (Var);
return 0;
}
|
#pragma once
#include "menu/scrolling_menu_screen.hpp"
#include "menu/main_menu_screen.hpp"
#include <Thor/Input.hpp>
class KeysMenuScreen : public ScrollingMenuScreen {
private:
bool selecting_key;
string to_upper(string s);
void add_opt(float xcor, string s, sf::Color color=sf::Color::White);
public:
KeysMenuScreen(TextLoader &a_text_loader, ResourceManager &a_resource_manager,
InputManager &an_input_manager);
unique_ptr<Screen> next_screen() override;
void handle_event(sf::Event &evt) override;
void update(float s_elapsed) override;
};
|
#pragma once
#include <vector>
#include <QString>
using DevHandle = void*;
enum RimDevType:unsigned {RimUnknown = 0, RimMouse, RimKeyboard, RimHid};
std::size_t getDevicesNumber();
QString getDeviceName(DevHandle);
bool registerID(void*);
struct devinfo{
QString name;
QString typeName;
DevHandle handle;
RimDevType rimType;
};
typedef std::vector<devinfo> devinfo_vec;
devinfo_vec getAllDevices();
enum ButtonState:unsigned char {KeyUp, KeyDown, KeyNeutral};
enum MouseButtons:unsigned char {LeftKey, MiddleKey, RightKey, Key1, Key2, Key3, Key4, Key5, UnknownKey};
enum WheelState:signed char {ForwardWheel=-120,NeutralWheel=0,BackwardWheel=120};
typedef ButtonState ButtonStates[UnknownKey];
typedef std::function<void(DevHandle, unsigned short vk, bool pressed)> OnKeyboardProc;
typedef std::function<void(DevHandle, const ButtonStates&, WheelState)> OnMouseProc;
typedef std::function<void(DevHandle, bool arrival)> OnDevPlug;
bool processRawInput(void * message, long * result,
OnKeyboardProc, OnMouseProc, OnDevPlug);
|
//: C10:OverridingAmbiguity.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
#include "NamespaceMath.h"
#include "NamespaceOverriding2.h"
void s() {
using namespace Math;
using namespace Calculation;
// Wszystko jest w porzadku, az do instrukcji:
//! divide(1, 2); // Dwuznacznosc
}
int main() {} ///:~
|
#include<bits/stdc++.h>
using namespace std;
int bc(int n)
{
int cnt=0;
while(n){
if(n & 1 == 1)
cnt++;
n = n >> 1;
}
return cnt;
}
int func(int n1,int n2)
{
int c1 = bc(n1);
int c2 = bc(n2);
if(c1<=c2)
return 0;
return 1;
}
int main()
{
int n, a[30];
cout<<"Enter the number of elements in the array : ";
cin>>n;
cout<<"Enter the elements : ";
for(int i=0; i<n; i++){
cin>>a[i];
}
sort(a,a+n,func);
cout<<"Sorted array elements in descending order : ";
for(int i=0; i<n; i++){
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
|
// -------------------------------------------
// Line
// -------------------------------------------
#include "Line.h"
Line::Line(const string& line)
{
// Hint: some of string's member functions might come in handy here
// for extracting words.
string line_copy=line;
vector<Word> words_of_line;
string delimiter = " ";
seperateString(words_of_line, delimiter, line_copy);
}
bool Line::contains(const Word& search_word) const
{
if (_line.empty())
return false;
for (int i=0; i<_line.size();i++)
{
if (search_word.isQueryable() && _line[i]==search_word)
{
return true;
}
}
return false;
}
void Line::seperateString(vector<Word>& words_of_line, const string& delimiter, string& line_copy)
{
int counter=0;
size_t pos=0;
if (!line_copy.empty())
{
while ((pos = line_copy.find(delimiter)) != string::npos)
{
auto individual_word=line_copy.substr(0,pos);
line_copy.erase(0, pos+delimiter.length());
words_of_line.push_back(individual_word);
counter++;
}
words_of_line.push_back(line_copy);
_line=words_of_line;
}
else
_line.clear();
}
|
#include "ApplicationManager.h"
#include "Actions\AddSmplAssign.h"
#include "Actions\AddVarAssign.h"
#include "Actions\AddSOAssign.h"
#include "Actions\AddStart.h"
#include "Actions\AddEnd.h"
#include "Actions\AddRead.h"
#include "Actions\AddWrite.h"
#include "Actions\AddCondition.h"
#include "Actions\AddConnector.h"
#include "Actions\EditConnector.h"
#include "Actions\EditStatement.h"
#include "Actions\AddComment.h"
#include "Actions\Copy.h"
#include "Actions\Cut.h"
#include "Actions\Paste.h"
#include "Actions\Delete.h"
#include "Actions\Select.h"
#include "Actions\Load.h"
#include "Actions\Save.h"
#include "Actions\Move.h"
#include "Actions\Resize.h"
#include "Actions\Run.h"
#include "Actions\Step.h"
#include "Actions\Generate.h"
#include "Actions\Zoom.h"
#include "GUI\Input.h"
#include "GUI\Output.h"
//Constructor
ApplicationManager::ApplicationManager()
{
//Create Input and output
pOut = new Output;
pIn = pOut->CreateInput();
StatID=1;
StatCount = 0;
ConnCount = 0;
VarCount=0;
pSelectedStat = NULL; //no Statement is selected yet
pSelectedConn=NULL;
pCopied=NULL;
editedDesign=false;
//Create an array of Statement pointers and set them to NULL
for(int i=0; i<MaxCount; i++)
{
StatList[i] = NULL;
ConnList[i] = NULL;
VarList[i] = NULL;
}
for(int j=0;j<10000;j++)
{
SaveArr[j]="U"+to_string(long double(j+1));
SaveArr[j]=SaveArr[j]+".txt";
string s="Undo\\"+SaveArr[j];
remove(s.c_str());
}
GL=0,plus=0;
}
//==================================================================================//
// Actions Related Functions //
//==================================================================================//
ActionType ApplicationManager::GetUserAction()
{
//Ask the input to get the action from the user.
return pIn->GetUserAction(P);
}
////////////////////////////////////////////////////////////////////////////////////
//Creates an action and executes it
void ApplicationManager::ExecuteAction(ActionType ActType)
{
Action* pAct = NULL;
//According to ActioType, create the corresponding action object
switch (ActType)
{
case ADD_START :
pAct= new AddStart(this);
break;
case ADD_END :
pAct=new AddEnd(this);
break;
case ADD_SMPL_ASSIGN:
pAct = new AddSmplAssign(this);
break;
case ADD_VAR_ASSIGN :
pAct=new AddVarAssign(this);
break;
case ADD_SINGLE_OPERATOR_ASSIGN :
pAct=new AddSOAssign(this);
break;
case ADD_CONDITION:
pAct= new AddCondition(this);
break;
case ADD_READ_STAT :
pAct= new AddRead(this);
break;
case ADD_WRITE_STAT :
pAct= new AddWrite(this);
break;
case ADD_CONNECTOR:
pAct= new AddConnector(this);
break;
case EDIT_CONNECTOR :
pAct= new EditConnector(this);
break;
case EDIT_STAT :
pAct= new EditStatement(this);
break;
case COMMENT :
pAct=new AddComment(this);
break;
case SIM_MODE:
SwitchToSim();
break;
case COPY:
pAct=new Copy(this);
break;
case CUT:
pAct=new Cut(this);
break;
case PASTE:
pAct=new Paste(this);
break;
case MOVE:
pAct=new Move(this);
break;
case ZOOMIN :
pAct= new Zoom(this,'+');
break;
case ZOOMOUT :
pAct= new Zoom(this,'-');
break;
case DEL:
pAct=new Delete(this);
break;
case RESIZE:
pAct=new Resize(this);
break;
case SAVE:
pAct= new Save(this);
break;
case LOAD:
pAct=new Load(this);
break;
case NEW:
while(GetStatList(0))
DeleteStat(GetStatList(0));
UndoRedo();
break;
case UNDO:
UndoRedo(1);
break;
case REDO:
UndoRedo(2);
break;
case RUN:
pAct=new Run(this);
break;
case STEP:
pAct=new Step(this);
break;
case GENERATE:
pAct=new Generate(this);
break;
case SELECT:
pAct=new Select(this);
break;
case STATUS:
UnSelect();
return;
case DSN_TOOL:
UnSelect();
break;
case SIM_TOOL:
UnSelect();
break;
case DSN_MODE:
pOut->PrintMessage("Design Mode");
pOut->CreateDesignToolBar();
break;
case EXIT:
onExit();
break;
}
//Execute the created action
if(pAct != NULL)
{
pAct->Execute();//Execute
delete pAct; //Action is not needed any more ==> delete it
}
}
//==================================================================================//
// Statements Management Functions //
//==================================================================================//
int ApplicationManager::GetStatCount()
{
return StatCount;
}
int ApplicationManager::GetConnCount()
{
return ConnCount;
}
int ApplicationManager::GetVarCount()
{
return VarCount;
}
//Add a statement to the list of statements
void ApplicationManager::AddStatement(Statement *pStat)
{
if(pStat->GetStatType()=="STRT" || pStat->GetStatType()=="END")
for(int i=0; i<StatCount; i++)
if(StatList[i]->GetStatType()==pStat->GetStatType())
{
pOut->PrintMessage("Action in not accessible:"+pStat->GetStatType()+" Statement already exists");
return;
}
if(StatCount < MaxCount)
{
StatList[StatCount++] = pStat;
if(pStat->GetID()==0)
StatList[StatCount-1]->SetID(StatID++);
}
}
////////////////////////////////////////////////////////////////////////////////////
Statement *ApplicationManager::GetStatement(Point P) const
{
for(int i=0;i<StatCount;i++)
if(StatList[i]->IsOnStat(P))
return StatList[i];
return NULL;
}
void ApplicationManager::DeleteStat (Statement* Stat)
{if(Stat!=NULL)
{
int ID = Stat->GetID();
//********************* Deleting Out-Connectors *************************//
//If Stat has 1 out-connector (The statement is not END or COND)
if(Stat->GetStatType()=="VAR"||Stat->GetStatType()=="SNGLOP"||Stat->GetStatType()=="COND")
{
deleteVariable(Stat->getVar(0));
deleteVariable(Stat->getVar(1));
}
else deleteVariable(Stat->getVar(0));
if(Stat->GetStatType() != "END" && Stat->GetStatType() != "COND") DeleteConn (Stat->getStatConnector(0));
//If Stat is COND (has 2 out-connectors)
else if(Stat->GetStatType() == "COND"){
DeleteConn (Stat->getStatConnector(1));
DeleteConn (Stat->getStatConnector(2));
}
//----------------------------------------------------------------------//
//********************* Deleting In-Connectors **************************//
int count=0;
for (int i = 0 ; i< ConnCount ; i++)
if (ConnList[i]->getDstID() == ID) count++;
while(count!=0)
for (int i = 0 ; i< ConnCount ; i++)
if (ConnList[i]->getDstID() == ID) {DeleteConn (ConnList[i]); count--;}
int i;
for (i = 0 ; i < StatCount ; i++) if (StatList[i] == Stat) break; //Get its order in link
for (i ; i < StatCount ; i++) StatList [i] = StatList [i+1];
StatList [StatCount-1] = NULL;
StatCount--;
}
//---------------------------------------------------------------------//
}
void ApplicationManager::SetConnector(Connector *pConn)
{
if(ConnCount < MaxCount)
ConnList[ConnCount++] = pConn;
}
////////////////////////////////////////////////////////////////////////////////////
Connector *ApplicationManager::GetConnector(Point P) const
{
for(int i=0;i<ConnCount;i++)
if(ConnList[i]->IsOnConnect(P))
return ConnList[i];
return NULL;
}
////////////////////////////////////////////////////////////////////////////////////
void ApplicationManager::EditConnectors(Statement *Stat)
{
for (int i = 0 ; i< ConnCount ; i++)
if (ConnList[i]->getDstID() ==Stat->GetID())
{
ConnList[i]->setEndPoint(Stat->GetConnPoint(2));
}
}
void ApplicationManager::DeleteConn (Connector* Conn)
{
if (Conn != NULL){ //If statement has this connector
Conn->getSrcStat()->setStatConnector(NULL,Conn->getConnType()); //Set pointer of connector's tail statement to NULL
int i;
for (i = 0 ; i < ConnCount ; i++) if (ConnList[i] == Conn) break; //Get its order in link
// int i = Conn - ConnList[i]
//Shift connector list backwards from i to the end (deleting the desired connector)
for (i ; i < ConnCount ; i++) ConnList [i] = ConnList [i+1];
ConnList [ConnCount-1] = NULL;
ConnCount--;
}
}
Variable* ApplicationManager::AddVariable(Variable *V)
{
if(V->name=="")
return NULL;
for(int i=0;i<VarCount;i++)
if(VarList[i]->name==V->name)
{ VarList[i]->repeat++; return VarList[i];}
VarList[VarCount++]=V;
return NULL;
}
Variable *ApplicationManager::GetVariable(int j) const
{
return VarList[j];
}
void ApplicationManager::deleteVariable(Variable *V)
{if(VarCount==0)
return;
int i;
for(i=0;i<VarCount;i++)
if(VarList[i]==V) break;
if(i==VarCount)
return;
if(VarList[i]->repeat==1)
{
for(i;i<VarCount;i++)
VarList[i]=VarList[i+1];
VarList[VarCount-1]=NULL;
VarCount--;
}
}
void ApplicationManager::InitializeVar()
{
for(int i=0;i<VarCount;i++)
VarList[i]->value=0;
}
//Returns the selected statement
Statement *ApplicationManager::GetSelectedStatement() const
{ return pSelectedStat; }
////////////////////////////////////////////////////////////////////////////////////
//Set the statement selected by the user
void ApplicationManager::SetSelectedStatement(Statement *pStat)
{ pSelectedStat = pStat; }
Connector *ApplicationManager::GetSelectedSConnector() const
{return pSelectedConn;}
void ApplicationManager::SetSelectedConnector(Connector *pConn)
{pSelectedConn=pConn;}
Statement* ApplicationManager::GetStatList(int j)
{
return StatList[j];
}
Connector* ApplicationManager::GetConnList(int j)
{
return ConnList[j];
}
void ApplicationManager::SetCopied(Statement* P)
{
pCopied=P;
}
Statement* ApplicationManager::GetCopied()
{
return pCopied;
}
void ApplicationManager::SetCopyType(int x)
{
CopyType=x;
}
int ApplicationManager::GetCopyType()
{
return CopyType;
}
void ApplicationManager::UnSelect()
{if(GetSelectedStatement()!=NULL)
{
GetSelectedStatement()->SetSelected(false);
SetSelectedStatement(NULL);
}
else if(GetSelectedSConnector()!=NULL)
{
GetSelectedSConnector()->SetSelected(false);
SetSelectedConnector(NULL);
}
UpdateInterface();
}
Point ApplicationManager::getPoint()
{
return P;
}
bool ApplicationManager::onBars(Point P)
{
if(P.x>=0&&P.x<=UI.width)
if(P.y>=0&&P.y<=UI.TlBrWdth)
return true;
if(P.x>=0&&P.x<=UI.MnItWdth)
if(P.y>=UI.TlBrWdth&&P.y<=(UI.height-UI.StBrWdth))
return true;
return false;
}
bool ApplicationManager::onObject(Point P)
{
if(GetStatement(P)!=NULL)
return true;
if(GetConnector(P)!=NULL)
return true;
return false;
}
void ApplicationManager::setEditedDesign(bool E)
{
editedDesign=E;
}
bool ApplicationManager::getEditedDesign()
{
return editedDesign;
}
void ApplicationManager::onExit()
{
if(getEditedDesign())
{
pOut->DrawExitMsg();
Point Position;
while(1)
{
pIn->GetPointClicked(Position);
if(Position.x>=(UI.width/2-150)+49.28&&Position.x<=(UI.width/2-150)+133.72&&Position.y>=(UI.height/2-75)+74.66&&Position.y<=(UI.height/2-75)+104.32) //yes button
{Action* pAct=new Save(this); pAct->Execute(); break;}
else if(Position.x>=(UI.width/2-150)+169.66&&Position.x<=(UI.width/2-150)+253.38&&Position.y>=(UI.height/2-75)+74.38&&Position.y<=(UI.height/2-75)+103.63) //no button
{
while(GetStatList(0))
DeleteStat(GetStatList(0));
break;
}
}
}
}
void ApplicationManager::UndoRedo(int n)
{
Statement *Stat=NULL;
Connector *Conn=NULL;
Variable *V;
int l=0;
if(n==0)
{
ofstream ufile;
if(GL==0)
{
ufile.open("Undo\\"+SaveArr[GL]);
ufile<<""<<endl;
ufile.close();
GL++;
}
plus=GL;
ufile.open("Undo\\"+SaveArr[GL]);
ufile<<GetVarCount()<<endl;
for(int i=0;i<GetVarCount();i++)
ufile<<GetVariable(i)->name<<" ";
ufile<<endl<<GetStatCount()<<endl;
for(int i=0;i<GetStatCount();i++)
{
Stat=GetStatList(i);
Stat->Save(ufile);
}
ufile<<GetConnCount()<<endl;
for(int i=0;i<GetConnCount();i++)
{
Conn=GetConnList(i);
Conn->Save(ufile);
}
GL++;
ufile.close();
}
else
{
if(n==1)
l=plus-1;
else l=plus+1;
if(n==1 && l<0)
{
return;
}
else if(n==2 && l==GL )
{
return;
}
string line,S;
int x,y,z;
Point P; P.x=200; P.y=200;
while(GetStatList(0))
DeleteStat(GetStatList(0));
ifstream ifile("Undo\\"+SaveArr[l]);
if (ifile.is_open())
{
ifile>>x;
for(int i=0;i<x;i++)
{
V=new Variable;
ifile>>V->name;
AddVariable(V);
}
ifile>>y;
for(int j=0;j<y;j++)
{
ifile>>line;
if(line=="STRT")
{
Stat=new Start(P);
}
else if(line=="COND")
{
Stat=new Condition(P);
}
else if(line=="END")
{
Stat=new End(P);
}
else if(line=="SMPL")
{
Stat=new SmplAssign(P);
}
else if(line=="READ")
{
Stat=new Read(P);
}
else if(line=="WRITE")
{
Stat=new Write(P);
}
else if(line=="SNGLOP")
{
Stat=new SOAssign(P);
}
else if(line=="VAR")
{
Stat=new VarAssign(P);
}
Stat->Load(ifile);
AddStatement(Stat);
}
ifile>>z;
for(int i=0;i<z;i++)
{
Conn=new Connector(NULL,NULL);
Conn->Load(ifile);
SetConnector(Conn);
}
LoadModify();
if(n==1)
{
plus--;
}
else
{
plus++;
}
ifile.close();
}
}
}
void ApplicationManager::LoadModify()
{
for(int i=0;i<ConnCount;i++)
{
for(int j=0;j<StatCount;j++)
{
if(ConnList[i]->getSrsID()==StatList[j]->GetID())
{
StatList[j]->setStatConnector(ConnList[i],ConnList[i]->getConnType());
ConnList[i]->setStartPoint(StatList[j]->GetConnPoint(1,ConnList[i]->getConnType()));
ConnList[i]->setSrcStat(StatList[j]);
}
if(ConnList[i]->getDstID()==StatList[j]->GetID())
{
ConnList[i]->setEndPoint(StatList[j]->GetConnPoint(2,ConnList[i]->getConnType()));
ConnList[i]->setDstStat(StatList[j]);
}
}
}
int ID; bool right=false;
if(StatList[0])
{
ID=StatList[0]->GetID();
right=true;
}
for(int i=1;i<StatCount;i++)
if(StatList[i]->GetID()>ID)
ID=StatList[i]->GetID();
if(right)
StatID=ID+1;
for(int i=0;i<VarCount;i++)
{
for(int j=0;j<StatCount;j++)
{
if(StatList[j]->getVar(0)->name==VarList[i]->name)
StatList[j]->setVar(VarList[i],0);
if(StatList[j]->GetStatType()=="COND"||StatList[j]->GetStatType()=="VAR"||StatList[j]->GetStatType()=="SNGLOP")
if(StatList[j]->getVar(1)->name==VarList[i]->name)
StatList[j]->setVar(VarList[i],1);
}
}
}
void ApplicationManager::SwitchToSim()
{int count=0;
for(int i=0;i<StatCount;i++)
if(StatList[i]->GetStatType()=="STRT"||StatList[i]->GetStatType()=="END")
count++;
if(count!=2)
{pOut->PrintMessage("the design is incomplete the program can't switch to simulation mode"); return;}
pOut->PrintMessage("Simulation mode");
pOut->CreateSimulationToolBar();
UnSelect();
}
//==================================================================================//
// Interface Management Functions //
//==================================================================================//
//Draw all figures on the user interface
void ApplicationManager::UpdateInterface() const
{ pOut->ClearDrawArea();
//Draw all connections
for(int i=0; i<ConnCount; i++)
ConnList[i]->Draw(pOut);
//Draw all statements
for(int i=0; i<StatCount; i++)
StatList[i]->Draw(pOut);
if(UI.AppMode==DESIGN)
pOut->CreateDesignToolBar();
else if(UI.AppMode==SIMULATION)
pOut->CreateSimulationToolBar();
}
////////////////////////////////////////////////////////////////////////////////////
//Return a pointer to the input
Input *ApplicationManager::GetInput() const
{ return pIn; }
//Return a pointer to the output
Output *ApplicationManager::GetOutput() const
{ return pOut; }
////////////////////////////////////////////////////////////////////////////////////
//Destructor
ApplicationManager::~ApplicationManager()
{
for(int i=0; i<StatCount; i++)
delete StatList[i];
for(int i=0; i<StatCount; i++)
delete ConnList[i];
for(int i=0; i<VarCount; i++)
delete VarList[i];
delete pIn;
delete pOut;
}
|
#include "objectValue.h"
namespace json {
std::size_t ObjectValue::size() const
{
return curSize;
}
const IValue * ObjectValue::itemAtIndex(std::size_t index) const
{
if (index < curSize) return (const IValue *)((*this)[index]);
return getUndefined();
}
bool ObjectValue::enumItems(const IEnumFn &fn) const
{
for (auto &&x : *this) {
if (!fn(x)) return false;
}
return true;
}
const IValue * ObjectValue::member(const StringView<char>& name) const {
const IValue *r = findSorted(name);
if (r == nullptr) return getUndefined();
else return r;
}
const IValue *ObjectValue::findSorted(const StringView<char> &name) const
{
std::size_t l = 0;
std::size_t r = size();
while (l < r) {
std::size_t m = (l + r) / 2;
int c = name.compare(operator[](m)->getMemberName());
if (c > 0) {
l = m + 1;
}
else if (c < 0) {
r = m;
}
else {
return operator[](m);
}
}
return nullptr;
}
void ObjectValue::sort() {
std::stable_sort(begin(),end(),[](const PValue &left, const PValue &right) {
return left->getMemberName().compare(right->getMemberName()) < 0;
});
StrViewA lastKey;
std::size_t wrpos = 0;
for (const PValue &v: *this) {
StrViewA k = v->getMemberName();
if (k == lastKey && wrpos) {
wrpos--;
}
operator[](wrpos) = v;
wrpos++;
lastKey = k;
}
while (curSize > wrpos)
pop_back();
}
RefCntPtr<ObjectValue> ObjectValue::create(std::size_t capacity) {
AllocInfo nfo(capacity);
return new(nfo) ObjectValue(nfo);
}
RefCntPtr<ObjectValue> ObjectValue::clone() const {
RefCntPtr<ObjectValue> cp = create(size());
*cp = *this;
return cp;
}
ObjectValue& ObjectValue::operator =(const ObjectValue& other) {
Container<PValue>::operator =(other);
isDiff = other.isDiff;
return *this;
}
}
|
#include <Arduino.h>
#include <unity.h>
#include <BintrayClient.h>
#include <WiFi.h>
const BintrayClient bintray(BINTRAY_USER, BINTRAY_REPO, BINTRAY_PACKAGE);
// void setUp(void) {
// }
// void tearDown(void) {
// // clean stuff up here
// }
void test_wifi_connection(void) {
const int RESPONSE_TIMEOUT_MS = 5000;
unsigned long timeout = millis();
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
if (millis() - timeout > RESPONSE_TIMEOUT_MS) {
TEST_FAIL_MESSAGE("WiFi connection timeout. Please check your settings!");
}
delay(500);
}
TEST_ASSERT_TRUE(WiFi.isConnected());
}
void test_bintray_client_credentials(void) {
TEST_ASSERT_EQUAL_STRING(BINTRAY_USER, bintray.getUser().c_str());
TEST_ASSERT_EQUAL_STRING(BINTRAY_REPO, bintray.getRepository().c_str());
TEST_ASSERT_EQUAL_STRING(BINTRAY_PACKAGE, bintray.getPackage().c_str());
}
void test_bintray_latest_version_is_not_empty(void) {
const String version = bintray.getLatestVersion();
TEST_ASSERT_TRUE(version.length() > 0);
TEST_ASSERT_TRUE(atoi(version.c_str()) != 0);
}
void test_bintray_binary_path_is_valid(void) {
const String binaryPath = bintray.getBinaryPath(bintray.getLatestVersion());
TEST_ASSERT_TRUE(binaryPath.length() > 0);
TEST_ASSERT_TRUE(binaryPath.endsWith(".bin"));
TEST_ASSERT_TRUE(binaryPath.indexOf(BINTRAY_USER) > 0);
}
void setup() {
delay(2000);
UNITY_BEGIN();
RUN_TEST(test_bintray_client_credentials);
RUN_TEST(test_wifi_connection);
RUN_TEST(test_bintray_latest_version_is_not_empty);
RUN_TEST(test_bintray_binary_path_is_valid);
UNITY_END();
}
void loop() {}
|
#include "Task.h"
#ifndef __TIMER__H__
#define __TIMER__H__
class Timer : public Task
{
public:
Timer(void);
~Timer(void);
void run();
float fps;
float frameScalar; // scale vectors by this value to acheive frame-rate independant movement.
float lastFrame;
float frameDifference;
float time;
private:
int priority;
};
#endif
|
#include "snake.h"
#include "../client/engine.h"
game::Snake::Snake(sf::RenderWindow *window, sf::Color snake_color){
color = snake_color;
alive = true;
screen = window;
int x = rand.getRandomInt(window->getSize().x / 4, window->getSize().x * 3 / 4);
int y = rand.getRandomInt(window->getSize().y / 4, window->getSize().y * 3 / 4);
body.push_back( CreateRectangle( sf::Vector2f( x, y ), color));
}
void game::Snake::drawSnake() {
for(const sf::RectangleShape &body_part:body){
screen->draw(body_part);
}
}
bool game::Snake::ateFood(Food *fd) {
return false;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef DOM_DOMSTRINGLIST
#define DOM_DOMSTRINGLIST
#include "modules/dom/src/domobj.h"
class DOM_DOMStringList
: public DOM_Object
{
public:
class Generator
{
public:
virtual unsigned StringList_length() = 0;
virtual OP_STATUS StringList_item(int index, const uni_char *&name) = 0;
virtual BOOL StringList_contains(const uni_char *string) = 0;
protected:
virtual ~Generator() {}
/* This destructor is only here because some compilers
complain if it isn't, not because it is in any way
needed. */
};
static OP_STATUS Make(DOM_DOMStringList *&stringlist, DOM_Object *base, Generator *generator, DOM_Runtime *runtime);
/**< Create a new DOM_StringList.
@param [out] stringlist The result object.
@param base The object that must remain alive for the items
of the string list to be computed. Can be NULL if this
list doesn't have any such dependent objects.
@param generator The generator/producer object for this list,
@see DOM_StringList::Generator. If NULL, the string list will be empty.
@param runtime The runtime to create this list in.
@return OpStatus::OK if succesful, OpStatus::ERR_NO_MEMORY on OOM. */
virtual ES_GetState GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime);
virtual ES_GetState GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime);
virtual ES_PutState PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime);
virtual ES_PutState PutIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime);
virtual BOOL IsA(int type) { return type == DOM_TYPE_DOMSTRINGLIST || DOM_Object::IsA(type); }
virtual void GCTrace();
virtual ES_GetState GetIndexedPropertiesLength(unsigned &count, ES_Runtime *origining_runtime);
DOM_DECLARE_FUNCTION(item);
DOM_DECLARE_FUNCTION(contains);
enum { FUNCTIONS_ARRAY_SIZE = 3 };
protected:
DOM_DOMStringList(DOM_Object *base, Generator *generator);
DOM_Object *base;
Generator *generator;
};
#endif // DOM_DOMSTRINGLIST
|
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <GL/glew.h>
#include <GL/gl.h>
#include "Cube.hpp"
#include "ShaderAttributes.hpp"
////////////////////////////////////////////////////////////////////////////////
static std::vector<glm::vec3> generate_vertices(glm::vec3 pos, float x_len, float y_len, float z_len);
static std::vector<GLuint> generate_indices();
static void cube_generate_vertex_buffers(Cube* cube);
////////////////////////////////////////////////////////////////////////////////
Cube cube_create(float x, float y, float z, glm::vec3 color, float x_len, float y_len, float z_len) {
Cube cube;
cube.model_matrix = glm::mat4(1.0f);
cube.length = glm::vec3(x_len, y_len, z_len);
cube.pos = glm::vec3(x, y, z);
cube.model_matrix = glm::translate(cube.model_matrix, cube.pos);
cube.color = color;
cube_generate_vertex_buffers(&cube);
std::vector<GLuint> indices = generate_indices();
std::vector<glm::vec3> vertices = generate_vertices(cube.pos, x_len, y_len, z_len);
cube.n_indices = indices.size();
glBindVertexArray(cube.vao);
glBindBuffer(GL_ARRAY_BUFFER, cube.vbo);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3),
&vertices[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*) 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cube.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBindVertexArray(0);
cube.shader = new Shader("src/shaders/cube",
ShaderAttributes::CUBE_ATTRIBUTES);
return cube;
}
////////////////////////////////////////////////////////////////////////////////
static std::vector<glm::vec3> generate_vertices(glm::vec3 pos, float x_len, float y_len, float z_len) {
float min_x = 0.0f;
float min_y = 0.0f;
float min_z = 0.0f;
float max_x = min_x + x_len;
float max_y = min_y + y_len;
float max_z = min_z + z_len;
float x0 = min_x;
float y0 = min_y;
float z0 = min_z;
float x1 = max_x;
float y1 = max_y;
float z1 = max_z;
std::vector<glm::vec3> vertices {
glm::vec3(x0, y0, z0),
glm::vec3(x1, y0, z0),
glm::vec3(x1, y1, z0),
glm::vec3(x0, y1, z0),
glm::vec3(x0, y0, z1),
glm::vec3(x1, y0, z1),
glm::vec3(x1, y1, z1),
glm::vec3(x0, y1, z1)
};
return vertices;
}
////////////////////////////////////////////////////////////////////////////////
static std::vector<GLuint> generate_indices() {
return std::vector<GLuint> {
0, 1, 1, 2, 2, 3, 3, 0, 0, 4, 4, 7, 7, 3,
3, 0, 4, 5, 5, 6, 6, 7, 1, 5, 1, 2, 2, 6
};
}
////////////////////////////////////////////////////////////////////////////////
static void cube_generate_vertex_buffers(Cube* cube) {
glGenVertexArrays(1, &cube->vao);
glGenBuffers(1, &cube->vbo);
glGenBuffers(1, &cube->ebo);
}
////////////////////////////////////////////////////////////////////////////////
void cube_render(void* ventity, RenderInfo* renderinfo) {
Cube* cube = (Cube*) ventity;
cube->shader->Bind();
glm::mat4 mvp = renderinfo->view_proj * cube->model_matrix;
glUniformMatrix4fv(glGetUniformLocation(cube->shader->Id(), "mvp"), 1,
GL_FALSE, &mvp[0][0]);
glUniform3f(glGetUniformLocation(cube->shader->Id(), "color"),
cube->color.r, cube->color.g, cube->color.b);
glBindVertexArray(cube->vao);
glDrawElements(GL_LINES, cube->n_indices, GL_UNSIGNED_INT, NULL);
glBindVertexArray(0);
cube->shader->Unbind();
}
////////////////////////////////////////////////////////////////////////////////
void cube_overlap_dist(Cube* c1, Cube* c2, float* x, float* y, float* z) {
glm::vec3 near1 = c1->pos;
glm::vec3 near2 = c2->pos;
glm::vec3 far1 = c1->pos + c1->length;
glm::vec3 far2 = c2->pos + c2->length;
if (glm::all(glm::lessThanEqual(far1, near2)) ||
glm::all(glm::lessThanEqual(far2, near2))) {
*x = 0.0f;
*y = 0.0f;
*z = 0.0f;
return;
}
// Get smallest distance to far corner
float min_far_x = fminf(far1.x, far2.x);
float min_far_y = fminf(far1.y, far2.y);
float min_far_z = fminf(far1.z, far2.z);
// Get greatest distance to near corner
float max_near_x = fmaxf(near1.x, near2.x);
float max_near_y = fmaxf(near1.y, near2.y);
float max_near_z = fmaxf(near1.z, near2.z);
*x = min_far_x - max_near_x;
*y = min_far_y - max_near_y;
*z = min_far_z - max_near_z;
}
////////////////////////////////////////////////////////////////////////////////
void cube_overlap(Cube* c1, Cube* c2, float* x, float* y, float* z) {
float x_overlap_21, y_overlap_21, z_overlap_21;
cube_overlap_dist(c1, c2, &x_overlap_21, &y_overlap_21, &z_overlap_21);
glm::vec3 abs_len1 = glm::abs(c1->length);
x_overlap_21 /= (abs_len1.x) > 0.0f ? abs_len1.x : 1.0f;
y_overlap_21 /= (abs_len1.y) > 0.0f ? abs_len1.y : 1.0f;
z_overlap_21 /= (abs_len1.z) > 0.0f ? abs_len1.z : 1.0f;
float x_overlap_12, y_overlap_12, z_overlap_12;
cube_overlap_dist(c2, c1, &x_overlap_12, &y_overlap_12, &z_overlap_12);
glm::vec3 abs_len2 = glm::abs(c2->length);
x_overlap_12 /= (abs_len2.x) > 0.0f ? abs_len2.x : 1.0f;
y_overlap_12 /= (abs_len2.y) > 0.0f ? abs_len2.y : 1.0f;
z_overlap_12 /= (abs_len2.z) > 0.0f ? abs_len2.z : 1.0f;
*x = (x_overlap_21 + x_overlap_12) / 2.0f;
*y = (y_overlap_21 + y_overlap_12) / 2.0f;
*z = (z_overlap_21 + z_overlap_12) / 2.0f;
}
////////////////////////////////////////////////////////////////////////////////
Cube cube_merge(Cube* c1, Cube* c2) {
glm::vec3 near1 = c1->pos;
glm::vec3 near2 = c2->pos;
glm::vec3 far1 = c1->pos + c1->length;
glm::vec3 far2 = c2->pos + c2->length;
glm::vec3 min = near1;
glm::vec3 max = far1;
for (uint8_t l = 0; l < 3; l++) {
min[l] = fminf(min[l], near2[l]);
max[l] = fmaxf(max[l], far2[l]);
}
glm::vec3 len = max - min;
Cube merged = cube_create(min[0], min[1], min[2], glm::vec3(0.8f, 0.8f, 0.0f), len[0], len[1], len[2]);
return merged;
}
/// @file
|
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define FOR(a, b, c) for (int a = b; a <= c; ++a)
#define FORW(a, b, c) for(int a = b; a >= c; --a)
#define pb push_back
#define SZ(a) ((int)a.size())
#define int long long
const int N = 4e6;
const int oo = 1e9;
const int mod = 1e9 + 7;
typedef pair<int, int> ii;
int n;
int f[N], g[N], pos[N], root[N];
vector<int> tmp;
ii val[N];
map<int, int> mp;
vector<ii> in[N];
signed main(){
freopen("timber_input.txt", "r", stdin);
freopen("timber.out", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t; cin >> t;
FOR(cases, 1, t) {
cin >> n;
int ans = 0;
tmp.clear();
mp.clear();
FOR(i, 1, n) {
cin >> val[i].fi >> val[i].se;
tmp.pb(val[i].fi);
tmp.pb(val[i].fi + val[i].se);
tmp.pb(val[i].fi - val[i].se);
}
sort(tmp.begin(), tmp.end());
int cnt = 0;
FOR(i, 0, SZ(tmp) - 1) if(i == SZ(tmp) - 1 || tmp[i] != tmp[i + 1])
mp[tmp[i]] = ++cnt, pos[cnt] = tmp[i];
FOR(i, 0, cnt + 1) f[i] = g[i] = 0, root[i] = -1, in[i].clear();
FOR(i, 1, n) {
root[ mp[val[i].fi] ] = val[i].se;
in[ mp[ val[i].fi + val[i].se] ].pb({mp[val[i].fi], val[i].se});
}
FOR(i, 1, cnt) {
for(auto x: in[i]) f[i] = max(f[i], f[x.fi] + x.se);
g[i] = f[i];
if(root[i] != -1) {
int last = mp[ pos[i] - root[i]];
g[i] = max(g[i], g[last] + root[i]);
}
ans = max(ans, g[i]);
}
cout << "Case #" << cases << ": " << ans << '\n';
}
}
|
// Copyright (c) 2020 ETH Zurich
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/execution/algorithms/execute.hpp>
#include <pika/testing.hpp>
#include <cstddef>
#include <exception>
#include <type_traits>
static std::size_t friend_tag_invoke_schedule_calls = 0;
static std::size_t tag_invoke_execute_calls = 0;
template <typename Scheduler>
struct sender
{
template <template <class...> class Tuple, template <class...> class Variant>
using value_types = Variant<Tuple<>>;
template <template <class...> class Variant>
using error_types = Variant<std::exception_ptr>;
static constexpr bool sends_done = false;
using completion_signatures = pika::execution::experimental::completion_signatures<
pika::execution::experimental::set_value_t()>;
struct operation_state
{
friend void tag_invoke(
pika::execution::experimental::start_t, operation_state&) noexcept {};
};
template <typename R>
friend operation_state
tag_invoke(pika::execution::experimental::connect_t, sender&&, R&&) noexcept
{
return {};
}
struct env
{
friend Scheduler tag_invoke(pika::execution::experimental::get_completion_scheduler_t<
pika::execution::experimental::set_value_t>,
env const&) noexcept
{
return {};
}
};
friend env tag_invoke(pika::execution::experimental::get_env_t, sender const&) noexcept
{
return {};
}
};
struct scheduler_1
{
friend sender<scheduler_1> tag_invoke(pika::execution::experimental::schedule_t, scheduler_1)
{
++friend_tag_invoke_schedule_calls;
return {};
}
bool operator==(scheduler_1 const&) const noexcept { return true; }
bool operator!=(scheduler_1 const&) const noexcept { return false; }
};
struct scheduler_2
{
friend sender<scheduler_2> tag_invoke(pika::execution::experimental::schedule_t, scheduler_2)
{
PIKA_TEST(false);
return {};
}
bool operator==(scheduler_2 const&) const noexcept { return true; }
bool operator!=(scheduler_2 const&) const noexcept { return false; }
};
template <typename F>
void tag_invoke(pika::execution::experimental::execute_t, scheduler_2, F&&)
{
++tag_invoke_execute_calls;
}
struct f_struct_1
{
void operator()() noexcept {};
};
struct f_struct_2
{
void operator()(int = 42){};
};
void f_fun_1() {}
void f_fun_2(int) {}
int main()
{
{
scheduler_1 s1;
pika::execution::experimental::execute(s1, f_struct_1{});
pika::execution::experimental::execute(s1, f_struct_2{});
pika::execution::experimental::execute(s1, &f_fun_1);
PIKA_TEST_EQ(friend_tag_invoke_schedule_calls, std::size_t(3));
PIKA_TEST_EQ(tag_invoke_execute_calls, std::size_t(0));
}
{
scheduler_2 s2;
pika::execution::experimental::execute(s2, f_struct_1{});
pika::execution::experimental::execute(s2, f_struct_2{});
pika::execution::experimental::execute(s2, &f_fun_1);
PIKA_TEST_EQ(friend_tag_invoke_schedule_calls, std::size_t(3));
PIKA_TEST_EQ(tag_invoke_execute_calls, std::size_t(3));
}
return 0;
}
|
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include "RelOp.h"
#include "Record.h"
#include "Errors.h"
#include "HeapFile.h"
#define FOREACH_INPIPE(rec, in) \
Record rec; \
while (in->Remove(&rec))
#define FOREACH_INFILE(rec, f) \
f.MoveFirst(); \
Record rec; \
while (f.GetNext(rec))
#ifndef END_FOREACH
#define END_FOREACH }
#endif
void SelectFile::Run (DBFile& inFile, Pipe& outPipe, CNF& selOp, Record& literal) {
PACK_ARGS4(param, &inFile, &outPipe, &selOp, &literal);
FATALIF(create_joinable_thread(&worker, work, param), "Error creating worker thread.");
}
void* SelectFile::work(void* param) {
UNPACK_ARGS4(Args, param, in, out, sel, lit);
Record next;
in->MoveFirst();
while (in->GetNext(next, *sel, *lit)) out->Insert(&next);
out->ShutDown();
}
void SelectPipe::Run (Pipe& inPipe, Pipe& outPipe, CNF& selOp, Record& literal) {
PACK_ARGS4(param, &inPipe, &outPipe, &selOp, &literal);
FATALIF(create_joinable_thread(&worker, work, param), "Error creating worker thread.");
}
void* SelectPipe::work(void* param) {
UNPACK_ARGS4(Args, param, in, out, sel, lit);
ComparisonEngine cmp;
FOREACH_INPIPE(rec, in) if(cmp.Compare(&rec, lit, sel)) out->Insert(&rec);
out->ShutDown();
}
void Project::Run(Pipe& inPipe, Pipe& outPipe, int* keepMe, int numAttsInput, int numAttsOutput) {
PACK_ARGS5(param, &inPipe, &outPipe, keepMe, numAttsInput, numAttsOutput);
FATALIF(create_joinable_thread(&worker, work, param), "Error creating worker thread.");
}
void* Project::work(void* param) {
UNPACK_ARGS5(Args, param, in, out, keepMe, numAttsIn, numAttsOut);
FOREACH_INPIPE(rec, in) {
rec.Project(keepMe, numAttsOut, numAttsIn);
out->Insert(&rec);
}
out->ShutDown();
}
void Sum::Run (Pipe& inPipe, Pipe& outPipe, Function& computeMe) {
PACK_ARGS3(param, &inPipe, &outPipe, &computeMe);
FATALIF(create_joinable_thread(&worker, work, param), "Error creating worker thread.");
}
void* Sum::work(void* param) {
UNPACK_ARGS3(Args, param, in, out, func);
if (func->resultType() == Int) doSum<int>(in, out, func);
else doSum<double>(in, out, func);
out->ShutDown();
}
void Join::Run(Pipe& inPipeL, Pipe& inPipeR, Pipe& outPipe, CNF& selOp, Record& literal) {
PACK_ARGS6(param, &inPipeL, &inPipeR, &outPipe, &selOp, &literal, runLength);
FATALIF(create_joinable_thread(&worker, work, param), "Error creating worker thread.");
}
void* Join::work(void* param) {
UNPACK_ARGS6(Args, param, pleft, pright, pout, sel, lit, runLen);
OrderMaker orderLeft, orderRight;
if (sel->GetSortOrders(orderLeft, orderRight))
sortMergeJoin(pleft, &orderLeft, pright, &orderRight, pout, sel, lit, runLen);
else nestedLoopJoin(pleft, pright, pout, sel, lit, runLen);
pout->ShutDown();
}
void Join::sortMergeJoin(Pipe* pleft, OrderMaker* orderLeft, Pipe* pright, OrderMaker* orderRight, Pipe* pout,
CNF* sel, Record* literal, size_t runLen) {
ComparisonEngine cmp;
Pipe sortedLeft(PIPE_SIZE), sortedRight(PIPE_SIZE);
BigQ qLeft(*pleft, sortedLeft, *orderLeft, runLen), qRight(*pright, sortedRight, *orderRight, runLen);
Record fromLeft, fromRight, merged, previous;
JoinBuffer buffer(runLen);
for (bool moreLeft = sortedLeft.Remove(&fromLeft), moreRight = sortedRight.Remove(&fromRight); moreLeft && moreRight; ) {
int result = cmp.Compare(&fromLeft, orderLeft, &fromRight, orderRight);
if (result<0) moreLeft = sortedLeft.Remove(&fromLeft);
else if (result>0) moreRight = sortedRight.Remove(&fromRight);
else {
buffer.clear();
for(previous.Consume(&fromLeft);
(moreLeft=sortedLeft.Remove(&fromLeft)) && cmp.Compare(&previous, &fromLeft, orderLeft)==0; previous.Consume(&fromLeft))
FATALIF(!buffer.add(previous), "Join buffer exhausted.");
FATALIF(!buffer.add(previous), "Join buffer exhausted.");
do {
FOREACH(rec, buffer.buffer, buffer.nrecords)
if (cmp.Compare(&rec, &fromRight, literal, sel)) {
merged.CrossProduct(&rec, &fromRight);
pout->Insert(&merged);
}
END_FOREACH
} while ((moreRight=sortedRight.Remove(&fromRight)) && cmp.Compare(buffer.buffer, orderLeft, &fromRight, orderRight)==0); // read all records from right pipe with equal value
}
}
}
void Join::nestedLoopJoin(Pipe* pleft, Pipe* pright, Pipe* pout, CNF* sel, Record* literal, size_t runLen) {
DBFile rightFile;
dumpFile(*pright, rightFile);
JoinBuffer leftBuffer(runLen);
FOREACH_INPIPE(rec, pleft)
if (!leftBuffer.add(rec)) {
joinBuf(leftBuffer, rightFile, *pout, *literal, *sel);
leftBuffer.clear();
leftBuffer.add(rec);
}
joinBuf(leftBuffer, rightFile, *pout, *literal, *sel);
rightFile.Close();
}
void Join::joinBuf(JoinBuffer& buffer, DBFile& file, Pipe& out, Record& literal, CNF& selOp) {
ComparisonEngine cmp;
Record merged;
FOREACH_INFILE(fromFile, file) {
FOREACH(fromBuffer, buffer.buffer, buffer.nrecords)
if (cmp.Compare(&fromBuffer, &fromFile, &literal, &selOp)) {
merged.CrossProduct(&fromBuffer, &fromFile);
out.Insert(&merged);
}
END_FOREACH
}
}
void Join::dumpFile(Pipe& in, DBFile& out) {
const int RLEN = 10;
char rstr[RLEN];
Rstring::gen(rstr, RLEN);
std::string tmpName("join");
tmpName = tmpName + rstr + ".tmp";
out.Create((char*)tmpName.c_str(), heap, NULL);
Record rec;
while (in.Remove(&rec)) out.Add(rec);
}
void DuplicateRemoval::Run (Pipe& inPipe, Pipe& outPipe, Schema& mySchema) {
PACK_ARGS4(param, &inPipe, &outPipe, &mySchema, runLength);
FATALIF(create_joinable_thread(&worker, work, param), "Error creating worker thread.");
}
void* DuplicateRemoval::work(void* param) {
UNPACK_ARGS4(Args, param, in, out, myschema, runLen);
OrderMaker sortOrder(myschema);
Pipe sorted(PIPE_SIZE);
BigQ biq(*in, sorted, sortOrder, (int)runLen);
Record cur, next;
ComparisonEngine cmp;
if(sorted.Remove(&cur)) {
while(sorted.Remove(&next))
if(cmp.Compare(&cur, &next, &sortOrder)) {
out->Insert(&cur);
cur.Consume(&next);
}
out->Insert(&cur);
}
out->ShutDown();
}
void GroupBy::Run(Pipe &inPipe, Pipe &outPipe, OrderMaker &groupAtts, Function &computeMe) {
PACK_ARGS5(param, &inPipe, &outPipe, &groupAtts, &computeMe, runLength);
FATALIF(create_joinable_thread(&worker, work, param), "Error creating worker thread.");
}
void* GroupBy::work(void* param) {
UNPACK_ARGS5(Args, param, in, out, order, func, runLen);
if (func->resultType() == Int) doGroup<int>(in, out, order, func, runLen);
else doGroup<double>(in, out, order, func, runLen);
out->ShutDown();
}
void WriteOut::Run (Pipe &inPipe, FILE *outFile, Schema &mySchema) {
PACK_ARGS3(param, &inPipe, outFile, &mySchema);
FATALIF(create_joinable_thread(&worker, work, param), "Error creating worker thread.");
}
void* WriteOut::work(void* param) {
UNPACK_ARGS3(Args, param, in, out, myschema);
FOREACH_INPIPE(rec, in) rec.Write(out, myschema);
}
void RelationalOp::WaitUntilDone() {
FATALIF(pthread_join (worker, NULL), "joining threads failed.");
}
int RelationalOp::create_joinable_thread(pthread_t *thread, void *(*start_routine) (void *), void *arg) {
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int rc = pthread_create(thread, &attr, start_routine, arg);
pthread_attr_destroy(&attr);
return rc;
}
JoinBuffer::JoinBuffer(size_t npages): size(0), capacity(PAGE_SIZE*npages), nrecords(0) {
buffer = (Record*)malloc(PAGE_SIZE*npages);
}
JoinBuffer::~JoinBuffer() { free(buffer); }
bool JoinBuffer::add (Record& addme) {
if((size+=addme.getLength())>capacity) return 0;
buffer[nrecords++].Consume(&addme);
return 1;
}
|
/*
TouchKeys: multi-touch musical keyboard control software
Copyright (c) 2013 Andrew McPherson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=====================================================================
MainApplicationController.h: contains the overall glue that holds
together the various parts of the TouchKeys code. It works together
with the user interface to let the user configure the hardware and
manage the mappings, but it is kept separate from any particular user
interface configuration.
*/
#ifndef __TouchKeys__MainApplicationController__
#define __TouchKeys__MainApplicationController__
#undef TOUCHKEY_ENTROPY_GENERATOR_ENABLE
#include <iostream>
#include <vector>
#include "TouchKeys/Osc.h"
#include "TouchKeys/MidiInputController.h"
#include "TouchKeys/MidiKeyboardSegment.h"
#include "TouchKeys/MidiOutputController.h"
#include "TouchKeys/TouchkeyDevice.h"
#include "TouchKeys/PianoKeyInfo.h"
//#include "TouchkeyOscEmulator.h"
#include "Mappings/Vibrato/TouchkeyVibratoMappingFactory.h"
#include "Mappings/PitchBend/TouchkeyPitchBendMappingFactory.h"
#include "Mappings/Control/TouchkeyControlMappingFactory.h"
#include "Mappings/ReleaseAngle/TouchkeyReleaseAngleMappingFactory.h"
#include "Mappings/OnsetAngle/TouchkeyOnsetAngleMappingFactory.h"
#include "Mappings/MultiFingerTrigger/TouchkeyMultiFingerTriggerMappingFactory.h"
//#include "Mappings/KeyDivision/TouchkeyKeyDivisionMappingFactory.h"
#include "Mappings/MappingFactorySplitter.h"
//#include "TouchKeys/LogPlayback.h"
//#include "../JuceLibraryCode/JuceHeader.h"
#ifdef TOUCHKEY_ENTROPY_GENERATOR_ENABLE
#include "TouchKeys/TouchkeyEntropyGenerator.h"
#endif
#ifndef TOUCHKEYS_NO_GUI
#include "GUI/GraphicsDisplayWindow.h"
#include "GUI/PreferencesWindow.h"
class KeyboardTesterDisplay;
#endif
const char kDefaultOscTransmitHost[] = "127.0.0.1";
const char kDefaultOscTransmitPort[] = "8000";
const int kDefaultOscReceivePort = 8001;
class MainApplicationOSCController;
class MainApplicationController : public OscHandler {
friend class MainApplicationOSCController;
public:
// *** Constructor ***
MainApplicationController();
// *** Destructor ***
~MainApplicationController();
// *** Startup actions ***
void initialise();
// *** TouchKeys device methods ***
// Return the path prefix of the TouchKeys device
std::string touchkeyDevicePrefix();
// Return a list of paths to all available touchkey devices
std::vector<std::string> availableTouchkeyDevices();
// Run the main startup sequence: open device, check its presence,
// start data collection, all in one method. Returns true if successful.
// Will set the error message string if not
bool touchkeyDeviceStartupSequence(const char * path);
void touchkeyDeviceClearErrorMessage();
// Check whether a given touchkey device exists
bool touchkeyDeviceExists(const char * path);
// Select a particular touchkey device
bool openTouchkeyDevice(const char * path);
void closeTouchkeyDevice();
// Check for device present
bool touchkeyDeviceCheckForPresence(int waitMilliseconds = 250, int tries = 10);
void startCalibration(int secondsToCalibrate);
void finishCalibration();
void updateQuiescent();
bool saveCalibration(std::string const& filename);
bool loadCalibration(std::string const& filename);
// Start/stop the TouchKeys data collection
bool startTouchkeyDevice();
void stopTouchkeyDevice();
// Status queries on TouchKeys
// Returns true if device has been opened
bool touchkeyDeviceIsOpen();
// Return true if device is collecting data
bool touchkeyDeviceIsRunning();
// Returns true if an error has occurred
bool touchkeyDeviceErrorOccurred();
// Return the error message if one occurred
std::string touchkeyDeviceErrorMessage();
// How many octaves on the current device
int touchkeyDeviceNumberOfOctaves();
// Return the lowest MIDI note
int touchkeyDeviceLowestMidiNote();
// Set the lowest MIDI note for the TouchKeys
void touchkeyDeviceSetLowestMidiNote(int note);
// Attempt to autodetect the correct TouchKey octave from MIDI data
void touchkeyDeviceAutodetectLowestMidiNote();
void touchkeyDeviceStopAutodetecting();
bool touchkeyDeviceIsAutodetecting();
void touchkeyDeviceSetVerbosity(int verbose);
// *** MIDI device methods ***
// // Return a list of IDs and paths to all available MIDI devices
std::vector<std::pair<int, std::string> > availableMIDIInputDevices() {
return midiInputController_.availableMidiDevices();
}
std::vector<std::pair<int, std::string> > availableMIDIOutputDevices() {
return midiOutputController_.availableMidiDevices();
}
// Return the number of keyboard segments
int midiSegmentsCount() {
return midiInputController_.numSegments();
}
// Return the pointer to a specific segment
MidiKeyboardSegment* midiSegment(int index) {
return midiInputController_.segment(index);
}
// Return a unique signature of segment configuration which
// tells any listeners whether an update has happened
int midiSegmentUniqueIdentifier() {
return midiInputController_.segmentUniqueIdentifier();
}
// Add a new segment, returning the result. Segments are
// stored
MidiKeyboardSegment* midiSegmentAdd();
// Remove a segment
void midiSegmentRemove(MidiKeyboardSegment *segment);
void midiSegmentSetMode(MidiKeyboardSegment *segment, int mode);
void midiSegmentSetMidiOutputController(MidiKeyboardSegment *segment, MidiOutputController *controller);
void midiSegmentsSetMode(int mode);
void midiSegmentsSetMidiOutputController(MidiOutputController *controller);
void midiSegmentsSetMidiOutputController();
// Select MIDI input/output devices
void enableMIDIInputPort(int portNumber, bool isPrimary);
void enableAllMIDIInputPorts(int primaryPortNumber);
void disableMIDIInputPort(int portNumber);
void disablePrimaryMIDIInputPort();
void disableAllMIDIInputPorts(bool auxiliaryOnly);
void enableMIDIOutputPort(int identifier, int deviceNumber);
#ifndef JUCE_WINDOWS
void enableMIDIOutputVirtualPort(int identifier, const char *name);
#endif
void disableMIDIOutputPort(int identifier);
void disableAllMIDIOutputPorts();
// Get selected MIDI input/output devices by ID
int selectedMIDIPrimaryInputPort() {
return midiInputController_.primaryActivePort();
}
std::vector<int> selectedMIDIAuxInputPorts() {
return midiInputController_.auxiliaryActivePorts();
}
int selectedMIDIOutputPort(int identifier) {
return midiOutputController_.enabledPort(identifier);
}
void midiTouchkeysStandaloneModeEnable();
void midiTouchkeysStandaloneModeDisable();
bool midiTouchkeysStandaloneModeIsEnabled() { return touchkeyStandaloneModeEnabled_; }
// *** Update sync methods ***
// The controller maintains a variable that tells when the devices should be updated
// by the control window component. Whenever it changes value, the devices should be rescanned.
int devicesShouldUpdate() { return deviceUpdateCounter_; }
void tellDevicesToUpdate() { deviceUpdateCounter_++; }
// *** OSC device methods ***
bool oscTransmitEnabled();
void oscTransmitSetEnabled(bool enable);
bool oscTransmitRawDataEnabled();
void oscTransmitSetRawDataEnabled(bool enable);
std::vector<lo_address> oscTransmitAddresses();
int oscTransmitAddAddress(const char * host, const char * port, int proto = LO_UDP);
void oscTransmitRemoveAddress(int index);
void oscTransmitClearAddresses();
// OSC Input (receiver) methods
// Enable or disable on the OSC receive, and report is status
bool oscReceiveEnabled();
// Enable method returns true on success (false only if it was
// unable to set the port)
bool oscReceiveSetEnabled(bool enable);
// Whether the OSC server is running (false means couldn't open port)
bool oscReceiveRunning();
// Get the current OSC receive port
int oscReceivePort();
// Set the current OSC receive port (returns true on success)
bool oscReceiveSetPort(int port);
// *** Display methods ***
// KeyboardDisplay& keyboardDisplay() { return keyboardDisplay_; }
#ifndef TOUCHKEYS_NO_GUI
void setKeyboardDisplayWindow(DocumentWindow *window) { keyboardDisplayWindow_ = window; }
void showKeyboardDisplayWindow() {
if(keyboardDisplayWindow_ != 0) {
keyboardDisplayWindow_->addToDesktop(keyboardDisplayWindow_->getDesktopWindowStyleFlags()
| ComponentPeer::windowHasCloseButton);
keyboardDisplayWindow_->setVisible(true);
keyboardDisplayWindow_->toFront(true);
}
}
void setPreferencesWindow(PreferencesWindow *window) { preferencesWindow_ = window; }
void showPreferencesWindow() {
if(preferencesWindow_ != 0) {
preferencesWindow_->addToDesktop(preferencesWindow_->getDesktopWindowStyleFlags()
| ComponentPeer::windowHasCloseButton);
preferencesWindow_->setVisible(true);
preferencesWindow_->toFront(true);
}
}
#endif
// *** Logging methods ***
// Logging methods which record TouchKeys and MIDI data to files for
// later analysis/playback
void startLogging();
void stopLogging();
bool isLogging() { return loggingActive_; }
void setLoggingDirectory(const char *directory);
// Playback methods for log files
void playLogWithDialog();
void stopPlayingLog();
bool isPlayingLog() { return isPlayingLog_; }
// *** OSC handler method (different from OSC device selection) ***
bool oscHandlerMethod(const char *path, const char *types, int numValues, lo_arg **values, void *data);
// *** Mapping methods ***
// Whether experimental (not totally finished/tested) mappings are available
bool experimentalMappingsEnabled() { return experimentalMappingsEnabled_; }
void setExperimentalMappingsEnabled(bool enable) { experimentalMappingsEnabled_ = enable; }
// *** Preset Save/Load ***
// These methods save the current settings to file or load settings
// from a file. They return true on success.
bool savePresetToFile(const char *filename);
bool loadPresetFromFile(const char *filename);
#ifndef TOUCHKEYS_NO_GUI
bool savePresetWithDialog();
bool loadPresetWithDialog();
#endif
// Clears the current preset and restores default settings to zones/mappings
void clearPreset();
// *** Preferences ***
// Whether to automatically start the TouchKeys on startup
bool getPrefsAutoStartTouchKeys();
void setPrefsAutoStartTouchKeys(bool autoStart);
// Whether to automatically detect the TouchKeys octave when they start
bool getPrefsAutodetectOctave();
void setPrefsAutodetectOctave(bool autoDetect);
// Which preset (if any) to load at startup
void setPrefsStartupPresetNone();
bool getPrefsStartupPresetNone();
void setPrefsStartupPresetLastSaved();
bool getPrefsStartupPresetLastSaved();
void setPrefsStartupPresetVibratoPitchBend();
bool getPrefsStartupPresetVibratoPitchBend();
void setPrefsStartupPreset(std::string const& path);
std::string getPrefsStartupPreset();
// Reset all preferences
void resetPreferences();
// Load global preferences from file
void loadApplicationPreferences();
// Load a MIDI output device from preexisting application preferences
void loadMIDIOutputFromApplicationPreferences(int zone);
#ifdef ENABLE_TOUCHKEYS_SENSOR_TEST
// *** TouchKeys sensor testing methods ***
// Start testing the TouchKeys sensors
bool touchkeySensorTestStart(const char *path, int firstKey);
// Stop testing the TouchKeys sensors
void touchkeySensorTestStop();
// Is the sensor test running?
bool touchkeySensorTestIsRunning();
// Set the current key that is begin tested
void touchkeySensorTestSetKey(int key);
// Reset the testing state to all sensors off
void touchkeySensorTestResetState();
#endif
#ifdef ENABLE_TOUCHKEYS_FIRMWARE_UPDATE
// Put TouchKeys controller board into bootloader mode
bool touchkeyJumpToBootloader(const char *path);
#endif
// *** Static utility methods ***
static std::string midiNoteName(int noteNumber);
static int midiNoteNumberForName(std::string const& name);
private:
// bool savePresetHelper(File& outputFile);
// bool loadPresetHelper(File const& inputFile);
// Application properties: for managing preferences
// ApplicationProperties applicationProperties_;
// TouchKeys objects
MainApplicationOSCController *mainOscController_;
PianoKeyboard keyboardController_;
MidiInputController midiInputController_;
MidiOutputController midiOutputController_;
OscTransmitter oscTransmitter_;
OscReceiver oscReceiver_;
TouchkeyDevice touchkeyController_;
// TouchkeyOscEmulator touchkeyEmulator_;
// LogPlayback *logPlayback_;
#ifdef TOUCHKEY_ENTROPY_GENERATOR_ENABLE
TouchkeyEntropyGenerator touchkeyEntropyGenerator_;
bool entropyGeneratorSelected_;
#endif
bool touchkeyErrorOccurred_;
std::string touchkeyErrorMessage_;
bool touchkeyAutodetecting_;
bool touchkeyStandaloneModeEnabled_;
int deviceUpdateCounter_; // Unique number that increments every time devices should
// be rescanned
// OSC information
bool oscReceiveEnabled_;
int oscReceivePort_;
// Mapping objects
bool experimentalMappingsEnabled_;
// Display objects
// KeyboardDisplay keyboardDisplay_;
#ifndef TOUCHKEYS_NO_GUI
DocumentWindow *keyboardDisplayWindow_;
KeyboardTesterDisplay *keyboardTesterDisplay_;
GraphicsDisplayWindow *keyboardTesterWindow_;
PreferencesWindow *preferencesWindow_;
#endif
// Segment info
int segmentCounter_;
// Logging info
bool loggingActive_, isPlayingLog_;
std::string loggingDirectory_;
PianoKeyInfo pianoKeyInfo_ = PianoKeyInfo(touchkeyController_, keyboardController_);
};
// Separate class for handling external OSC control messages since
// one class cannot have two receivers. This one is for all external
// OSC messages which OscHandler on MainApplicationController is for
// internally-generated messages via the PianoKeyboard class.
class MainApplicationOSCController : public OscHandler {
public:
MainApplicationOSCController(MainApplicationController& controller,
OscMessageSource& source) :
controller_(controller), source_(source) {
setOscController(&source_);
addOscListener("/control*");
}
// *** OSC handler method (different from OSC device selection) ***
bool oscHandlerMethod(const char *path, const char *types, int numValues, lo_arg **values, void *data);
private:
// Reply to OSC messages with a status
void oscControlTransmitResult(int result);
MainApplicationController& controller_;
OscMessageSource& source_;
};
#endif /* defined(__TouchKeys__MainApplicationController__) */
|
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2016 RDK Management
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <string.h>
#include <exception>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "frontPanelConfig.hpp"
#include "frontPanelTextDisplay.hpp"
#include "videoOutputPort.hpp"
#include "videoOutputPortType.hpp"
#include "videoResolution.hpp"
#include "host.hpp"
#include "manager.hpp"
#include "dsUtl.h"
#include "dsError.h"
#include "list.hpp"
#include "libIBus.h"
#include "unsupportedOperationException.hpp"
#define SIZEOF_ARR(arr) (sizeof((arr))/sizeof((arr)[0]))
const char* validParams[] = {"--hdcpTvPwrState","--setTimeFormat"};
const int numberOfParams = SIZEOF_ARR(validParams) ;
const int RX_SENSE_UNSUPPORTED = 4 ;
void displayHelp() {
printf("Usage : QueryDSState [CMD] \n");
printf("CMDs are \n" );
printf("%5s -> %s \n","--help", "print this help.");
printf("%5s -> %s \n","--hdcpTvPwrState", "Get HDCP Power State");
printf("%16s -> %s \n"," Output :", "ON(1), OFF(2), Unknown(3), NOT Supported(4)");
printf("%5s -> %s \n","--setTimeFormat <TimeFormat>", "Set Time Format");
printf("%16s -> %s \n"," Params :", "12_HR(0), 24_HR(1),NOT Supported(2)");
}
/**
Return the index of parameter to be retrived if valid.
If not valid return -1 and display the help screen
**/
int validateParams(const char* param) {
int paramIndex = -1 ;
if (param != NULL)
{
for ( int i=0; i < numberOfParams; i++ ) {
if (strcmp(param, validParams[i]) == 0 ) {
paramIndex = i ;
break ;
}
}
}
return paramIndex;
}
void getHDCPTvPowerState() {
FILE fp_old = *stdout; // preserve the original stdout
// redirect stdout to null to avoid printing debug prints from other modules
*stdout = *fopen("/dev/null","w");
/*Unknown needs to be displayed if Component out is active*/
int hdcpStatus = 3;
bool isHDMIConnected = false;
bool isHDMIActive = false;
IARM_Bus_Init("DsUtility");
IARM_Bus_Connect();
try {
device::Manager::Initialize();
device::VideoOutputPort vPort = device::Host::getInstance().getVideoOutputPort(std::string("HDMI0"));
isHDMIConnected = vPort.isDisplayConnected();
if ( isHDMIConnected == true ) {
try {
isHDMIActive = vPort.isActive();
if ( isHDMIActive == true ) {
hdcpStatus = 1; // ON
} else {
hdcpStatus = 2; // OFF
}
} catch (device::UnsupportedOperationException &e) { // This happens for pltforms where SoC doesn't support RxSense
hdcpStatus = RX_SENSE_UNSUPPORTED ;
}
} else {
hdcpStatus = 3 ; // Unknown
}
device::Manager::DeInitialize();
}
catch (...) {
printf("Exception Caught during [%s]\r\n",__func__);
}
IARM_Bus_Disconnect();
IARM_Bus_Term();
*stdout=fp_old; // restore stdout
printf("%d\r\n", hdcpStatus );
}
void setFPTimeFormat(int timeformat) {
IARM_Bus_Init("DsUtility");
IARM_Bus_Connect();
try {
device::Manager::Initialize();
device::FrontPanelConfig::getInstance().getTextDisplay("Text").setTimeFormat(timeformat);
printf("Time Format change to %s \r\n",timeformat == dsFPD_TIME_12_HOUR ?"12_HR":"24_HR");
device::Manager::DeInitialize();
}
catch (...) {
printf("Exception Caught during [%s]\r\n",__func__);
}
IARM_Bus_Disconnect();
IARM_Bus_Term();
}
int main(int argc, char *argv[])
{
int paramIndex = 0;
int paramArg = 0;
if (argc > 3) {
displayHelp();
return -1;
}
paramIndex = validateParams(argv[1]);
if( paramIndex == -1 ){
displayHelp();
return -1;
}
switch(paramIndex) {
/*Check for validParams array for parameter name mapping*/
case 0 :
getHDCPTvPowerState();
break;
case 1 :
if(argc == 3)
{
paramArg = atoi((const char *)argv[2]);
setFPTimeFormat(paramArg);
}
else
{
displayHelp();
}
break;
default :
displayHelp();
break;
}
return 0;
}
|
#include <Servo.h>
#include "Timer.h" //http://github.com/JChristensen/Timer
Servo servo; // create servo object to control a servo
Timer t;
class KeySequence {
static const int LENGTH = 4;
static const int TIMEOUT = 3000;
int sequence[LENGTH];
int i;
unsigned long last_click;
public:
KeySequence() {
i = 0;
}
// Returns sequence as number if succesful, 0 otherwise
int write(int key) {
unsigned long mil = millis();
if (mil - last_click > TIMEOUT) {
i = 0;
}
last_click = mil;
sequence[i] = key;
++i;
if (i == LENGTH) {
if (valid()) {
i = 0;
int result = 0;
for (int j = 0; j < KeySequence::LENGTH / 2; ++j) {
result *= 10;
result += sequence[j*2];
}
return result;
} else {
return i = 0;
}
}
return 0;
}
protected:
boolean valid() {
boolean result = true;
for (int j = 0; j < LENGTH; ++j) {
if ((j % 2) == 0) {
result &= (sequence[j] > 0);
} else {
result &= (sequence[j] == -1);
}
}
return result;
}
};
KeySequence sequence;
//ADKeyboard Module
int adc_key_val[5] ={50, 200, 400, 600, 800 };
int NUM_KEYS = 5;
int adc_key_in;
int key=-1;
int oldkey=-1;
const int LED = 17;
const int SERVO_PIN = 9;
const int KEYPAD_PIN = 0;
const int START = 120;
const int END = 62;
const int MNM_PERIOD = 250;
const byte ADDR1 = '1';
const byte ADDR2 = '2';
boolean led2state = false;
void led2on() {
TXLED1;
}
void led2off() {
TXLED0;
}
void led2() {
led2on();
t.after(100, led2off);
t.after(200, led2on);
t.after(250, led2off);
}
void handle_keypad() {
adc_key_in = analogRead(0); // read the value from the sensor
key = get_key(adc_key_in); // convert into key press
if (key != oldkey) { // if keypress is detected {
t.after(10, handle_key_pressed);
}
}
void transmit(int addr) {
byte dest[5] = {'z', 'a', 'p', '0' + addr / 10, '0' + addr % 10};
Mirf.setTADDR(dest);
byte data = '\0';
Mirf.send(&data);
while(Mirf.isSending()){
}
}
void handle_key_pressed() {
adc_key_in = analogRead(KEYPAD_PIN); // read the value from the sensor
key = get_key(adc_key_in); // convert into key press
if (key != oldkey) {
oldkey = key;
int seq = sequence.write(key);
if (seq == (ADDR1 - '0') * 10 + (ADDR2 - '0')) {
dispense_mnm();
}
}
}
void mnm_open() {
servo.write(END);
}
void mnm_close() {
servo.write(START);
}
void dispense_mnm() {
mnm_open();
t.after(MNM_PERIOD, mnm_close);
}
// Convert ADC value to key number
int get_key(unsigned int input) {
int k;
/*
5
3 1
4 2
*/
int translate[5] = {5, 3, 4, 2, 1};
for (k = 0; k < NUM_KEYS; k++) {
if (input < adc_key_val[k]) {
return translate[k];
}
}
if (k >= NUM_KEYS) k = -1; // No valid key pressed
return k;
}
void setup() {
servo.attach(SERVO_PIN);
servo.write(START);
Serial.begin(9600); // 9600 bps
led2();
t.every(2000, led2);
t.every(100, handle_keypad);
}
void loop() {
t.update();
}
|
#include "stdafx.h"
#include "Rect.h"
namespace cvfn {
Rect::Rect( int x, int y, int width, int height )
:X(x), Y(y), Width(width), Height(height)
{
}
Rect::~Rect(void)
{
}
}
|
#include"Vec3.hpp"
#include"Vec2.hpp"
namespace GPEngine
{
namespace GPMath
{
Vec3::Vec3()
: x(0.0f), y(0.0f), z(0.0f)
{
}
Vec3::Vec3(
float _x,
float _y,
float _z
)
: x(_x),y(_y),z(_z)
{
}
Vec3::Vec3(float scalar)
: x(scalar), y(scalar) ,z(scalar)
{
}
Vec3::~Vec3()
{
}
Vec3::Vec3(const Vec3 &other)
:x(other.x),y(other.y),z(other.z)
{
}
Vec3& Vec3::operator = (const Vec3 &other)
{
if(this==&other)
return *this;
this->x = other.x;
this->y = other.y;
this->z = other.z;
return *this;
}
Vec3 Vec3::operator + (const Vec3 &other) const
{
return Vec3(x + other.x , y + other.y , z + other.z);
}
Vec3 Vec3::operator - (const Vec3 &other)const
{
return Vec3(x - other.x , y - other.y ,z - other.z);
}
Vec3 Vec3::normalize()const
{
float len = length();
return Vec3(x/len , y/len, z/len);
}
float Vec3::length() const
{
return sqrt(x*x + y*y + z*z);
}
float Vec3::dot(const Vec3 &other)const
{
return (x*other.x + y*other.y + z*other.z);
}
Vec3 Vec3::cross(const Vec3 &other) const
{
return Vec3( (y*other.z - other.y*z) , (z*other.x - other.z*x) , (x*other.y - other.x*y) );
}
}
}
|
/*
* File: checker.h
*
* Description: This file contains the public function declarations for the
* semantic checker for Simple C.
*/
# ifndef CHECKER_H
# define CHECKER_H
# include "Scope.h"
Scope *openScope();
Scope *closeScope();
Symbol *defineFunction(const std::string &name, const Type &type);
Symbol *declareFunction(const std::string &name, const Type &type);
Symbol *declareVariable(const std::string &name, const Type &type);
Symbol *checkIdentifier(const std::string &name);
Symbol *checkFunction(const std::string &name);
// Phase 4 functions
Type checkFunctionType(const Symbol& sym, Parameters* arguments);
Type checkIdentifierType(const Type& left, bool& lvalue);
Type checkIndex(const Type& left, const Type& right);
Type checkNot(const Type& left);
Type checkNegate(const Type& left);
Type checkDereference(const Type& left);
Type checkAddress(const Type& left, bool& lvalue);
Type checkSizeOf(const Type& left);
Type checkTypeCast(const Type& left, int typespec, unsigned indirection);
Type checkMultiply(const Type& left, const Type& right);
Type checkDivide(const Type& left, const Type& right);
Type checkModulo(const Type& left, const Type& right);
Type checkAdd(const Type& left, const Type& right);
Type checkSub(const Type& left, const Type& right);
Type checkLessThan(const Type& left, const Type& right);
Type checkGreaterThan(const Type& left, const Type& right);
Type checkLessThanEqual(const Type& left, const Type& right);
Type checkGreaterThanEqual(const Type& left, const Type& right);
Type checkEqualityExpression(const Type& left, const Type& right);
Type checkNotEquals(const Type& left, const Type& right);
Type checkEquals(const Type& left, const Type& right);
Type checkLogicalAnd(const Type& left, const Type& right);
Type checkLogicalOr(const Type& left, const Type& right);
Type checkReturnType(const Type& left, Symbol& function);
Type checkWhile(const Type& left);
Type checkIf(const Type& left);
Type checkAssignment(const Type& left, const Type& right, bool& left_lvalue);
# endif /* CHECKER_H */
|
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <iomanip>
#include <set>
#include <climits>
#include <ctime>
#include <complex>
#include <cmath>
#include <string>
#include <cctype>
#include <cstring>
#include <algorithm>
using namespace std;
#define endl '\n'
typedef pair<int,int> pii;
typedef long long ll;
typedef pair<ll,ll> pll;
typedef long double ld;
typedef unsigned int uint;
typedef unsigned long long ull;
const int MAXN=200005;
const int INF=0x3f3f3f3f;
const double pi=acos(-1.0);
const double eps=1e-9;
inline int sgn(double a){return a<-eps? -1:a>eps;}
struct node{
ll pos;
ll len;
ll sum;
int id;
bool operator < (node b)const{
return pos<b.pos;
}
}frog[MAXN];
int n,m;
int pos[MAXN];
pll mos[MAXN];
template<class T>struct Segtree {
#define ls (o<<1)
#define rs (o<<1)|1
T data[MAXN<<2];
void pushup(int o) {
data[o]=max(data[ls],data[rs]);
}
void build(int o,int l,int r) {
if(l==r) {
data[o]=frog[l].sum;
return;
}
int mid=(l+r)>>1;
build(ls,l,mid);
build(rs,mid+1,r);
pushup(o);
}
void updateone(int o,int l,int r,int index,T v) {
if(l==r) {
data[o]+=v;
return;
}
int mid=(l+r)>>1;
if(index<=mid) updateone(ls,l,mid,index,v);
else updateone(rs,mid+1,r,index,v);
pushup(o);
}
T query(int o,int l,int r,int x,int y) {
if(l>=x && r<=y) {
return data[o];
}
ll t=-1;
int mid=(l+r)>>1;
if(x<=mid) t=max(t,query(ls,l,mid,x,y));
if(y>=mid+1) t=max(t,query(rs,mid+1,r,x,y));
return t;
}
};
Segtree<ll> tree;
pll ans[MAXN];
int gao(int x){
int l=1;
int r=upper_bound(pos+1,pos+1+n,x)-pos;
r--;
// cout<<"r= "<<r<<endl;
// cout<<"query= "<<tree.query(1,1,n,1,r)<<endl;
if(r==0||tree.query(1,1,n,1,r)<x)
return -1;
int res=-1;
while(l<=r){
int mid=(l+r)/2;
// cout<<tree.query(1,1,n,1,mid)<<" query\n";
if(tree.query(1,1,n,1,mid)>=x){
// cout<<r<<endl;
r=mid-1;
res=mid;
}else
l=mid+1;
}
return res;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>frog[i].pos>>frog[i].len;
frog[i].id=i;
}
for(int i=1;i<=m;i++){
cin>>mos[i].first>>mos[i].second;
}
sort(frog+1,frog+n+1);
for(int i=1;i<=n;i++){
frog[i].sum=frog[i].pos+frog[i].len;
pos[i]=frog[i].pos;
}
tree.build(1,1,n);
multiset<pll> mset;
for(int i=1;i<=m;i++){
int p=gao(mos[i].first);
// cout<<p<<endl;
if(p!=-1){
ans[frog[p].id].first++;
// cout<<frog[p].id<<endl;
frog[p].len+=mos[i].second;
tree.updateone(1,1,n,p,mos[i].second);
frog[p].sum=frog[p].pos+frog[p].len;
while(!mset.empty()){
auto it=mset.lower_bound(make_pair(frog[p].pos,0));
if(it==mset.end()||frog[p].sum<it->first)
break;
frog[p].len+=it->second;
frog[p].sum+=it->second;
ans[frog[p].id].first++;
tree.updateone(1,1,n,p,it->second);
mset.erase(it);
}
}else
mset.insert(mos[i]);
}
for(int i=1;i<=n;i++){
ans[frog[i].id].second=frog[i].len;
}
for(int i=1;i<=n;i++){
cout<<ans[i].first<<' '<<ans[i].second<<endl;
}
return 0;
}
|
/****************************************************************
* TianGong RenderLab *
* Copyright (c) Gaiyitp9. All rights reserved. *
* This code is licensed under the MIT License (MIT). *
*****************************************************************/
#pragma once
#include "Graphics/Core.hpp"
#include "Graphics/Direct3D11/FactoryD3D11.hpp"
namespace TG::Graphics
{
class GraphicsLayer
{
public:
GraphicsLayer(Window const* window)
{
factory = std::make_unique<FactoryD3D11>();
CreateInfoD3D11 info;
info.adapterIndex = 0;
info.hwnd = window->Hwnd();
IRenderDevice* pDevice = nullptr;
IDeviceContext* pContext = nullptr;
factory->CreateDeviceAndContext(&info, &pDevice, &pContext);
device.reset(pDevice);
context.reset(pContext);
SwapChainDesc desc;
desc.format = TextureFormat::R8G8B8A8_UNORM;
desc.bufferCount = 2;
desc.sampleCount = 4;
desc.width = window->Width();
desc.height = window->Height();
ISwapChain* pSwapChain = nullptr;
factory->CreateSwapChain(pDevice, window->Hwnd(), desc, &pSwapChain);
swapChain.reset(pSwapChain);
}
void Update()
{
swapChain->Present(1);
}
void ClearBackground(const Math::Color& color)
{
DeviceContextD3D11* c = static_cast<DeviceContextD3D11*>(context.get());
SwapChainD3D11* s = static_cast<SwapChainD3D11*>(swapChain.get());
c->m_context->ClearRenderTargetView(s->GetCurrentBackBufferRTV(), color.RGBA());
}
public:
#ifdef _DEBUG
std::unique_ptr<DebugInfo<DeviceType::DirectX11>> dbgInfo;
#endif
std::unique_ptr<IFactory> factory;
std::unique_ptr<IRenderDevice> device;
std::unique_ptr<IDeviceContext> context;
std::unique_ptr<ISwapChain> swapChain;
};
}
|
/**
* created: 2013-4-6 22:47
* filename: FKCheckNameSvr
* author: FreeKnight
* Copyright (C):
* purpose:
*/
//------------------------------------------------------------------------
#pragma once
//------------------------------------------------------------------------
#include "../FKSvr3Common/FKCommonInclude.h"
#include "../FKSvr3Common/Include/BaseProtocol/BaseServerCmd.h"
#include "FKSubsvrSession.h"
//------------------------------------------------------------------------
class CCheckNameTcpServices : public CMIocpTcpAccepters
{
public:
CCheckNameTcpServices()
: CMIocpTcpAccepters("")
{
};
virtual CLD_IocpClientSocket* CreateIocpClient(CMIocpTcpAccepters::CSubAccepter* pAccepter, SOCKET s);
virtual void OnIocpClientConnect(CLD_Socket* Socket);
virtual void OnClientDisconnect(CLD_Socket* Socket);
virtual void OnClientError(CLD_Socket* Socket, CLD_TErrorEvent ErrEvent, OUT int& nErrCode, char* sErrMsg);
};
//------------------------------------------------------------------------
#define _SVR_PARAM_DBHASHCODE_ 0
//------------------------------------------------------------------------
#ifdef _WX1_PRJ_
#define _MAX_ONLYID_ 0xFFFFFFFE
#else
#define _MAX_ONLYID_ 0xFFFFFFFE
#endif
#define _MIN_ONLYID_ 40000
//------------------------------------------------------------------------
#define MAKEBIGINT(h,l) ( ( ( (ULONGLONG)(h) ) << 32 ) | (l) )
#ifdef _WX1_PRJ_
#define MAKE_ONLYID(id,tid) (id)
#else
#define MAKE_ONLYID(id,tid) ( (((id) & 0x3FFFFFF)<<6) | ((tid) & 0x3F) )
#define MAKE_PLAYER_ONLYID( PlatFormID, ZoneID, UserID ) MAKEBIGINT( ( ( ( PlatFormID ) << 8 ) | ZoneID ), UserID )
#endif // _WX1_PRJ_
//------------------------------------------------------------------------
class CCheckNameService : public Singleton< CCheckNameService>,public CWndBase
{
public:
void EnableCtrl( bool bEnableStart );
bool CreateToolbar();
virtual void OnStartService();
virtual void OnStopService();
virtual void OnConfiguration();
virtual void OnQueryClose(bool& boClose);
virtual bool OnInit();
virtual void OnUninit();
virtual long OnTimer( int nTimerID );
virtual long OnCommand( int nCmdID );
virtual bool OnCommand( char* szCmd );
virtual bool Init( HINSTANCE hInstance );
virtual void OnClearLog();
virtual void OnIdle();
public:
static const WORD m_svrtype=_CHECKNAMESVR_TYPE;
public:
CLD_IocpHandle m_iocp; // 完成端口对象
CCheckNameTcpServices m_TcpServices; // tcp服务器管理器
CMIocpTcpConnters m_TcpConnters;
bool m_boStartService;
WORD m_svridx;
char m_szsvrcfgdburl[MAX_PATH];
char m_szgamesvrparamdburl[MAX_PATH]; //游戏服务器数据库地址
char m_szSvrName[MAX_PATH];
bool m_boAutoStart;
int m_niocpworkthreadcount;
char m_szmanageip[_MAX_IP_LEN_]; //游戏管理服务器IP
WORD m_manageport; //游戏管理服务器端口
bool m_boConnectManage; //是否连接游戏管理服务器
char m_szLocalIp[_MAX_IP_LEN_];
char m_szZoneName[_MAX_NAME_LEN_];
int m_nZoneid;
WORD m_subsvrport;
int m_nTradeid;
bool m_boshutdown;
time_t m_timeshutdown;
bool m_forceclose;
CIntLock cfg_lock;
svrinfomap m_svrlistmap;
int m_dwUserOnlyId;
int m_dwAccountOnlyId;
int m_dwStrOnlyId;
stSvr2SvrLoginCmd m_Svr2SvrLoginCmd;
HashDBPool m_datadb;
HashDBPool m_svrdatadb;
CSyncSet< CSubSvrSession* > m_gamesvrsession;
typedef LimitStrCaseHash<void*> checkstrmap;
checkstrmap m_accountmap;
checkstrmap m_namemap;
LimitStrCaseHash<checkstrmap*> m_checkstrmap;
public:
CCheckNameService();
~CCheckNameService();
void StartService();
void RefSvrRunInfo();
void ShutDown();
void StopService();
static void RecycleThreadCallBackProxy(void* pobj)
{
((CCheckNameService *) pobj)->RecycleThreadCallBack();
}
virtual void RecycleThreadCallBack();
bool LoadLocalConfig();
bool LoadSvrConfig(CSqlClientHandle* sqlc);
bool LoadSysParam(CSqlClientHandle* sqlc);
bool LoadServerParam();
bool SaveServerParam(int naddtime,int nadditemid);
CLD_ThreadBase* m_msgProcessThread;
CLD_ThreadBase* m_LogicProcessThread;
unsigned int __stdcall SimpleMsgProcessThread(CLD_ThreadBase* pthread,void* param);
unsigned int __stdcall LogicProcessThread(CLD_ThreadBase* pthread,void* param);
};
//------------------------------------------------------------------------
|
#include <iostream>
using namespace std;
struct node{ // Declararea listei dublu inlantuite
int value;
node *next, *prev;
};
void display_info() // Functie care afiseaza meniul problemei
{
cout<<"\n1) Adaugare la inceputul listei";
cout<<"\n2) Adaugare la sfarsitul listei";
cout<<"\n3) Adaugare in interiorul listei";
cout<<"\n4) Afisarea in ordine";
cout<<"\n5) Afisarea in ordine inversa";
cout<<"\n6) Stergere (numar de ordine)";
cout<<"\n7) Stergere (valoare)";
cout<<"\n\n0) Iesire";
}
void read_number_of_elements(int &number_of_elements)
{
cout<<"Introduceti numarul elementelor din lista: ";
cin>>number_of_elements;
}
void create_list(node* &first_node, node* &last_node, int number_of_elements) // Functie care creaza o lista dublu inlantuita
{
first_node = new node; // Cream primul nod al listei
cout<<"\nPrimul element al listei este: ";
cin>>first_node->value; // Citim informatia din primul nod al listei
first_node->next = NULL; // Legam primul nod de nul in partea dreapta
first_node->prev = NULL; // Legam primul nod de nul in partea stanga
node* aux_first_node = first_node; // Pointer in care retinem valoarea din primul nod
for (int index = 1; index < number_of_elements; index++) // Citim restul elementelor
{
node* new_node = new node; // Cream un nou nod
cout<<"Urmatorul element al listei este: ";
cin>>new_node->value; // Citim informatia din noul nod creat
first_node->next = new_node; // Legam nodul anterior de noul nod in partea dreapta
new_node->next = NULL; // Legam noul nod de nul la dreapta
new_node->prev = first_node; // Legam noul nod de cel precedent la stanga
first_node = new_node; // Reinitializam nodul precedent cu valoarea noului nod adaugat
}
last_node = first_node; // Pointerul first_node se va afla pe ultimul nod al listei la finalul ciclului
first_node = aux_first_node; // Reinitializam pointerul first_node cu primul nod al listei
}
void print_list(node* given_node, int type_of_navigation) // Functie care afiseaza lista dublu inlantuita in functie de modul de parcurgere ales
{
node* current_node = given_node; // Pointer catre nodul curent al listei
cout<<'\n';
while(current_node) // Parcurgem lista
{
cout<<current_node->value<<" "; // Afisam informatia din nodul curent
current_node = type_of_navigation == 1 ? current_node->next : current_node->prev; // Pointerul curent va avansa spre stanga sau dreapta
// in functie de tipul de parcurgere ales
// 1 - parcurgere obisnuita
// altfel - parcurgere inversa
}
}
void add_beginning(node* &first_node, int node_info) // Functie care adauga un element la inceputul listei
{
node* new_node = new node; // Cream noul nod
new_node->value = node_info; // Initializam informatia din noul nod
new_node->next = first_node; // Legam noul nod de anteriorul prim nod la dreapta
new_node->prev = NULL; // In stanga il legam la nul
first_node->prev = new_node; // Legam anteriorul prim nod la stanga cu noul nod
first_node = new_node; // Reinitializam primul nod al listei cu noul nod adaugat
}
void add_end(node* &last_node, int node_info) // Functie care adauga un element la finalul listei
{
node* new_node = new node; // Cream noul nod
new_node->value = node_info; // Initializam informatia din noul nod
new_node->next = NULL; // Legam noul nod de nul la dreapta
new_node->prev = last_node; // si de prcedentul ultim element la stanga
last_node->next = new_node; // Legam precedentul ultim nod de noul nod la dreapta
last_node = new_node; // Reinitializam ultimul nod cu noul nod adaugat
}
void add_middle(node* &first_node, int node_info, int position) // Functie care adauga un elementul in interiorul listei in functie de pozitie
{
int index = 1; // Variabila care contorizeaza pozitia curenta din lista
node* new_node = new node; // Cream noul nod
new_node->value = node_info; // Initializam informatia din noul nod
node* current_left_node; // Pointer care va retine elementul din stanga pozitiei unde trebuie adaugat noul nod
node* current_right_node = first_node; // Pointer care va retine elementul din dreapta pozitiei unde trebuie adaugat noul nod
while (current_right_node && index != position) // Parcurgem lista pana cand ajungem pe pozitia furnizata ca parametru sau terminam lista
{
index++; // Incrementam variabila care contorizeaza pozitia curenta
current_right_node = current_right_node->next; // Trecem pe urmatorul element din dreapta
}
// Daca lista data este: 1 2 3 5
// pozitita pe care vrem sa adaugam este: 4
// elementul este: 4
// dupa iesirea din while, current_right_node va pointa pe 5
// current_left_node este pointat pe 3
// elementul 4 trebuie adaugat intre 3 si 5
// in stanga lui 5 il legam pe 4 (4 <-- 5)
// in dreapta lui 3 il legam pe 4 (3 --> 4)
// lista arata la final: 1 2 3 4 5
if (current_right_node) // Daca am gasit pozitia in lista
{
current_left_node = current_right_node->prev; // Retinem nodul din stanga
current_left_node->next = new_node; // Legam nodul din stanga de noul nod
new_node->prev = current_left_node; // Legam noul nod de nodul din stanga
current_right_node->prev = new_node; // Legam nodul din dreapta de noul nod
new_node->next = current_right_node; // Legam noul nod de nodul din dreapta
return; // Oprim executarea functiei
}
cout<<"\nPozitia introdusa nu este una valida"; // Afisam mesajul in cazul in care pointerul e nul, adica nu am gasit pozitia in lista
}
void erase_element_position(node* &first_node, int position) // Functie care sterge un element din lista in functie de pozitie
{
int index = 1; // Variabila care contorizeaza pozitia curenta din lista
node* current_element = first_node; // Pointer catre elementul curent din lista
while (current_element && index != position) // Parcurgem lista pana cand gasim pozitia furnizata ca parametru sau terminam elementele listei
{
index++; // Incrementam variabila care retine pozitia curenta din lista
current_element = current_element->next; // Trecem pe urmatorul element din dreapta
}
// Daca lista arata asa: 1 2 3 4 5
// si vrem sa stergem elementul de pe pozitia 4
// la finalul while-ului pointerul currrent_element se va afla exact pe pozitia 4
// atunci declaram alti 2 pointeri
// left_element --> 3
// right_element --> 5
// stergem elementul 4 si refacem legaturile dintre vecinii sai
// left_element->next = right_element (3 --> 5)
// right_element->prev = left_element (3 <-- 5)
// lista finala va arata asa: 1 2 3 5
if (current_element) // Daca am gasit pozitia
{
node* left_element = current_element->prev; // Elementul din stanga celui care urmeaza sa fie sters
node* right_element = current_element->next; // Elementul din dreapta celui care urmeaza sa fie sters
delete current_element; // Stergem elementul curent
left_element->next = right_element; // Legam elementul din stanga de cel din dreapta
right_element->prev = left_element; // Legam elementul din dreapta de cel din stanga
return; // Oprim executia functiei
}
cout<<"\nPozitia introdusa nu este valida"; // Afisam mesajul in cazul in care pointerul e nul, adica nu am gasit pozitia in lista
}
void erase_element_value(node* &first_node, int node_info) // Functie care sterge un element al listei in functie de informatia din interiorul sau
{
node* current_element = first_node; // Pointer catre elementul curent al listei
while(current_element && current_element->value != node_info) // Parcurgem de la stanga la dreapta elementele listei pana cand gasim valoarea cautata sau terminam elementele
{
current_element = current_element->next; // Trecem pe urmatorul element din dreapta
}
if (current_element) // Daca am gasit valoarea cautata in lista
{
node* left_element = current_element->prev; // Pointer catre elementul din stanga celui care urmeaza sa fie sters
node* right_element = current_element->next; // Pointer catre elementul din dreapta celui care urmeaza sa fie sters
delete current_element; // Stergem elementul curent
left_element->next = right_element; // Legam elementul din stanga de cel din dreapta
right_element->prev = left_element; // Legam elementul din dreapta de cel din stanga
return; // Oprim executia functiei
}
cout<<"\nValoarea introdusa nu se afla in lista"; // Afisam mesajul in cazul in care pointerul e nul, adica nu am gasit elementul in lista
}
int main()
{
int number_of_elements; // Numarul de elemente al listei
int type; // Optiunea din meniu introdusa de la tastatura
int x, position; // Variabile care vor fi folosite in interiorul instructiunii switch
node* first_node; // Pointer catre primul nod al listei
node* last_node; // Pointer catre ultimul nod al listei
display_info(); // Afisam meniul
cout<<"\nIntroduceti numarul problemei alese: ";
cin>>type; // Citim optiunea aleasa
read_number_of_elements(number_of_elements); // Citim numarul de elemente al listei
create_list(first_node, last_node, number_of_elements); // Cream lista prin salvarea primei si ultimei valori din lista
while (type) // Cat timp optiunea introdusa diferita de 0
{
switch (type) // Instructiune switch in functie de optiunea introdusa
{
case 1: // Adaugarea unui element la inceputul listei
cout<<"\nIntroduceti elementul care urmeaza sa fie adaugat in lista: ";
cin>>x; // Citim elementul care urmeaza sa fie adaugat in lista
add_beginning(first_node, x); // Apelam functia de adaugare care salveaza modificarile facute in pointerul first_node
print_list(first_node, 1); // Afisam lista utilizand parcurgerea de tip 1, adica de la stanga la dreapta
break; // Oprim executarea instructiunii switch
case 2: // Adaugarea unui element la sfarsitul listei
cout<<"\nIntroduceti elementul care urmeaza sa fie adaugat in lista: ";
cin>>x; // Citim elementul care urmeaza sa fie adaugat in lista
add_end(last_node, x); // Apelam functie de adaugare care salveaza modificarile facute in pointerul last_node
print_list(first_node, 1); // Afisam lista utilizand parcurgerea de tip 1, adica de la stanga la dreapta
break; // Oprim executarea instructiunii switch
case 3: // Adaugarea unui element in interiorul listei in functie de pozitie
cout<<"\nIntroduceti elementul care urmeaza sa fie adaugat in lista: ";
cin>>x; // Citim elementul care urmeaza sa fie adaugat in lista
cout<<"Introduceti pozitia pe care urmeaza sa fie inserat elementul: ";
cin>>position; // Citim pozitia pe care urmeaza sa fie inserat elementul citit
add_middle(first_node, x, position); // Apelam functia care salveaza modificarile facute in pointerul first_node
print_list(first_node, 1); // Afisam lista utilizand parcurgerea de tip 1, adica de la stanga la dreapta
break; // Oprim executarea instructiunii switch
case 4: // Afisarea listei de la stanga la dreapta
print_list(first_node, 1); // Afisam lista utilizand parcurgerea de tip 1, adica de la stanga la dreapta
break; // Oprim executarea instructiunii switch
case 5: // Afisarea listei de la dreapta la stanga
print_list(last_node, 0); // Afisam lista utilizand parcurgerea de tip 0, adica de la dreapta la stanga
break; // Oprim executarea instructiunii switch
case 6: // Stergerea unui element in functie de pozitie
cout<<"Introduceti pozitia de pe care urmeaza sa fie sters elementul: ";
cin>>position; // Citim pozitia pe care se afla elementul care urmeaza sa fie sters
erase_element_position(first_node, position); // Apelam functia care salveaza modificarile facute in pointerul first_node
print_list(first_node, 1); // Afisam lista utilizand parcurgerea de tip 1, adica de la stanga la dreapta
break; // Oprim executarea instructiunii switch
case 7: // Stergerea unui element in functie de valoare
cout<<"\nIntroduceti elementul care urmeaza sa fie sters din lista: ";
cin>>x; // Citim informatia elementului care urmeaza sa fie sters din lista
erase_element_value(first_node, x); // Apelam functia care salveaza modificarile facute in pointerul first_node
print_list(first_node, 1); // Afisam lista utilizand parcurgerea de tip 1, adica de la stanga la dreapta
break; // Oprim executarea instructiunii switch
}
display_info(); // Afisam din nou meniul
cout<<"\nIntroduceti numarul problemei alese: ";
cin>>type; // Citim optiunea introdusa de la tastatura
}
}
|
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <thread>
#include "BigLexer.h"
#include "SmallLexer.h"
#include "DataReaderServer.h"
#include "LineParser.h"
#include "SymbolTable.h"
#include "BlockParser.h"
#include "DataSender.h"
#include <fstream>
using namespace std;
// create mutex lock.
mutex mutex1;
void shared_print(string toPrint) {
mutex1.lock();
cout << toPrint << endl;
mutex1.unlock();
}
void *pthreadFunc(void *arg) {
int *idPtr = (int *) arg;
int id = *idPtr;
for (int i = 0; i < 1000; i++) {
if (id == 1) {
shared_print("hello, this is the NUMBER ONE thread");
} else {
shared_print("i am not the number one...");
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
pthread_exit(nullptr); // the thread which runs this func finishes.
}
/**
* Shared memory try.
* @param toPrint
*/
//void sharedMemory(map<string, double> *mapy, double id, string toPut) {
//
//// mutex1.lock();
// mapy->insert(pair<string, double>("this", id));
// cout << to_string(mapy->at("this")) + "\n";
//// mutex1.unlock();
//}
//
//void *pthreadFunc2(void *arg) {
// map<string, double> mapy;
// int *idPtr = (int *) arg;
// double id = *idPtr;
// mutex1.lock();
// for (int i = 0; i < 100; i++) {
// if (id == 1) {
// sharedMemory(&mapy, 1);
// } else {
// sharedMemory(&mapy, 2);
// }
// }
// mutex1.unlock();
//
//
// pthread_exit(nullptr); // the thread which runs this func finishes.
//}
int main(int argc, char *argv[]) {
/**
* Pthread try:
* this try is using mutex in order to lock data usage from other threads.
*/
// // create 1st thread
// pthread_t threadID;
// pthread_attr_t attr;
// pthread_attr_init(&attr);
// int valueForFunc = 1;
// pthread_create(&threadID, &attr, pthreadFunc2, &valueForFunc);
//
// // create 2nd thread
// pthread_t thread2ID;
// pthread_attr_t attr2;
// pthread_attr_init(&attr2);
// int secondValue = 2;
// pthread_create(&thread2ID, &attr2, pthreadFunc2, &secondValue);
//
// pthread_join(threadID, nullptr); // wait for thread to join.
// pthread_join(thread2ID, nullptr); // wait for thread to join.
/**
* 2nd Pthread try:
* this try is trying to use thread on a class method.
*/
// DataReaderServer dataReaderServer;
// dataReaderServer.threadListen();
/**
* Lexer try:
*/
// BigLexer lexer1;
// string str;
// vector<string> vec;
// while (true) {
// getline(cin, str); // client input will be sent to lexer function to receive string array.
// vec = lexer1.lexer(str);
// for (int i = 0; i < vec.size(); i++) {
// cout << vec.at(i) << "\n";
// }
// }
// SmallLexer lexer1;
// string str;
// vector<string> vec;
// while (true) {
// getline(cin, str); // client input will be sent to lexer function to receive string array.
// vec = lexer1.lexer(str);
// for (int i = 0; i < vec.size(); i++) {
// cout << vec.at(i) << "\n";
// }
// }
/**
* "REAL" main for sending commands.
* this main simulates the real main used for the flight simulator.
*/
// SymbolTable st;
// LineParser lineParser(&st); // parser gets a pointer to the shared symbol table.
// BlockParser blockParser(&st); // block parser gets a pointer to the shared symbol table.
// BigLexer bl;
// string userInput;
// vector<string> stringVector;
//
// while (true) {
// getline(cin, userInput);
// stringVector = bl.lexer(userInput);
//
// // if the user wants to exit the process.
// if (userInput == "exit") {
// break;
// }
// // if command is block command.
// else if (stringVector.at(0) == "while" || stringVector.at(0) == "if") {
// string blockString = userInput.substr(0, userInput.length() - 2); // exclude curly bracket.
// // get all of the user input until the end of the if/while statement.
// int openedBrackets = 1;
// while (openedBrackets != 0) {
// getline(cin, userInput);
// if (userInput.back() == '}') {
// openedBrackets -= 1;
// continue;
// } else if (userInput.back() == '{') {
// openedBrackets += 1;
// }
// blockString += userInput;
// }
//
// stringVector = bl.lexer(blockString);
// blockParser.parse(stringVector);
// }
// // command was a line command.
// else {
// lineParser.parse(bl.lexer(userInput), 0);
// }
// }
/**
* "REAL" main for sending command - WITH FILEEE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* this main simulates the real main used for the flight simulator.
*/
SymbolTable st;
DataReaderServer dataReaderServer;
DataSender dataSender;
LineParser lineParser(&st, &dataReaderServer, &dataSender); // parser gets a pointer to the shared symbol table and DRS
BlockParser blockParser(&st, &dataReaderServer, &dataSender); // block parser gets pointers to the shared symbol table and DRS
BigLexer bl;
string userInput;
vector<string> stringVector;
bool fromFile = false;
string line;
ifstream myFile(argv[1]);
if (argc == 2) {
// ifstream myFile(argv[1]);
if (myFile.is_open()) {
fromFile = true;
}
}
while (true) {
if (fromFile) {
if (getline(myFile, line)) {
userInput = line;
} else {
break;
}
}
if (!fromFile) {
getline(cin, userInput);
}
stringVector = bl.lexer(userInput);
// if the user wants to exit the process.
if (userInput == "exit") {
break;
}
// if command is block command.
else if (stringVector.at(0) == "while" || stringVector.at(0) == "if") {
string blockString = userInput.substr(0, userInput.length() - 2); // exclude curly bracket.
// get all of the user input until the end of the if/while statement.
int openedBrackets = 1;
while (openedBrackets != 0) {
if (fromFile) {
if (getline(myFile, line)) {
userInput = line;
} else {
break;
}
}
if (!fromFile) {
getline(cin, userInput);
}
if (userInput.back() == '}') {
openedBrackets -= 1;
continue;
} else if (userInput.back() == '{') {
openedBrackets += 1;
}
blockString += " " + userInput;
}
vector<string> lexedVec1 = bl.lexer(blockString);
stringVector = bl.lexer(blockString);
blockParser.parse(stringVector);
}
// command was a line command.
else {
cout << "user *Line Command input* is :" << userInput << endl;
vector<string> lexedVec = bl.lexer(userInput);
lineParser.parse(bl.lexer(userInput), 0);
}
}
if (fromFile) {
myFile.close();
}
/**
* Test with Ido (worked open server).
*
* And now also the client can connect to the flight simulator with it's own pthread.
* After it connects it can send commands to the simulator.
*/
// DataReaderServer dataReaderServer;
// pthread_t t1ID;
// pthread_create(&t1ID, NULL, &DataReaderServer::runOpen, &dataReaderServer);
//
// dataReaderServer.set("5402", "10");
//
// // unconnected print...
// cout << "parallel activity" << endl;
//
// DataSender dataSender;
// pthread_t t2ID;
// pthread_create(&t2ID, NULL, &DataReaderServer::runOpen, &dataSender);
//
// sleep(18);
//
// dataSender.set("127.0.0.1", "5401");
// dataSender.openPipe();
//
// sleep(18);
// dataSender.sendCommand("ls");
//
// // unconnected print...
// cout << "parallel activity" << endl;
//
// pthread_join(t1ID, nullptr); // wait for thread to join.
// pthread_join(t2ID, nullptr); // wait for thread to join.
return 0;
}
|
#include <fstream>
#include "jacobi2d_unrolled_2_opt.h"
int main() {
ofstream in_pix("input_pixels_regression_result_jacobi2d_unrolled_2_opt.txt");
ofstream fout("regression_result_jacobi2d_unrolled_2_opt.txt");
HWStream<hw_uint<64> > t1_update_0_read;
HWStream<hw_uint<64> > jacobi2d_unrolled_2_update_0_write;
// Loading input data
// cmap : { t1_update_0[root = 0, t1_0, t1_1] -> t1_arg[0, 0] : -1 <= t1_0 <= 8 and -1 <= t1_1 <= 16 }
// read map: { t1_arg[0, 0] -> t1_update_0[root = 0, t1_0, t1_1] : -1 <= t1_0 <= 8 and -1 <= t1_1 <= 16 }
// rng : { t1_update_0[root = 0, t1_0, t1_1] : -1 <= t1_0 <= 8 and -1 <= t1_1 <= 16 }
for (int i = 0; i < 180; i++) {
hw_uint<64> in_val;
set_at<0*32, 64, 32>(in_val, 2*i + 0);
in_pix << in_val << endl;
set_at<1*32, 64, 32>(in_val, 2*i + 1);
in_pix << in_val << endl;
t1_update_0_read.write(in_val);
}
jacobi2d_unrolled_2_opt(t1_update_0_read, jacobi2d_unrolled_2_update_0_write);
for (int i = 0; i < 128; i++) {
hw_uint<64> actual = jacobi2d_unrolled_2_update_0_write.read();
auto actual_lane_0 = actual.extract<0*32, 31>();
fout << actual_lane_0 << endl;
auto actual_lane_1 = actual.extract<1*32, 63>();
fout << actual_lane_1 << endl;
}
in_pix.close();
fout.close();
return 0;
}
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
int main()
{
freopen("labiec7.inp","r",stdin);
freopen("labiec7.out","w",stdout);
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
for(int j=0;j<n*2;j++)
if (j>=n-i-1 && j<=n+i-1)
printf("*");
else
printf(" ");
printf("\n");
}
return 0;
}
|
#include "../include/evaluator.hpp"
//#define DEBUG 1 //usar junto com debug da main.cpp
evaluator::evaluator (cv::String file_name, float a, float b){
this->index = 0;
std::ifstream myfile(file_name.c_str());
std::string linex, liney, linefps;
int x, y;
std::getline(myfile, linefps);
std::istringstream(linefps) >> this->fps;
//this->fps = stoi(linefps, 0, 10);
while(std::getline(myfile, linex) && std::getline(myfile, liney)){
std::istringstream(linex) >> x;
std::istringstream(liney) >> y;
/*
x = stoi(linex, 0, 10);
y = stoi(liney, 0, 10);
*/
cv::Point coordinates(x, y);
this->ballPos.push_back(coordinates);
}
myfile.close();
this->a = a;
this->b = b;
}
int evaluator::test(cv::Point p, cv::Mat frame){
int range = (int) (this->a * (float) ballPos[index].y + this->b);
range += 10;
//std::cout << "ballPos: " << ballPos[index] << endl;
//std::cout << "range: " << range << endl;
dbg_circle(frame, ballPos[index], range, 2); //amarelo raio de acerto
if(this->ballPos[index].x != -1){
if(p.x != -1){
if(std::abs(this->ballPos[index].x - p.x) < range && std::abs(this->ballPos[index].y - p.y) < range){
dbg_circle(frame, p, range, 1); //acerto em verde
return 1;
}else{
dbg_circle(frame, p, range, 0); //erro em vermelho
return 0;
}
}else{
//marcador falso negativo
return 0;
}
}else{
if(p.x != -1){
dbg_circle(frame, p, range, 0); //erro em vermelho
return 0;
}else{
//marcador verdadeiro negativo
//nao conta na calibração
return 0;
}
}
}
void evaluator::add(bool data){
this->score.push_back(data);
this->index += 1;
}
float evaluator::evaluate(){
float accumulator = 0;
for (std::vector<bool>::iterator it = this->score.begin(); it != this->score.end() ; it++)
{
if(*it == true)
accumulator++;
}
return accumulator/this->score.size();
}
int dbg_circle(cv::Mat frame, cv::Point center, int radius, int color){
#ifdef DEBUG
if(color == 0) circle( frame, center, radius, cv::Scalar(0,0,255), 3, 8, 0 );
else if(color == 1) circle( frame, center, radius, cv::Scalar(0,255,0), 3, 8, 0 );
else if(color == 2) circle( frame, center, radius, cv::Scalar(0,255,255), 3, 8, 0 );
#endif
return 0;
}
|
#include "MinMaxHierarchy.h"
#include <cmath>
#include <thread>
#include <functional>
// Under this threshold stop processing in parallel
#define PARALLEL_THRESHOLD 256
MinMaxHierarchy::MinMaxHierarchy(const ImageF& orig)
: m_root(orig)
{
assert(orig.getWidth() == orig.getHeight());
const size_t size = orig.getWidth();
assert(isPowerOfTwo(size));
// num of levels (without root)
const size_t numLevels = std::ceil(log2(size));
m_levels.reserve(numLevels);
ImageF level1 = constructLevelFromRoot(orig);
m_levels.push_back(std::move(level1));
for (size_t i = 0; i < numLevels - 1; ++i) {
ImageF newLevel = constructLevel(m_levels[i]);
m_levels.push_back(std::move(newLevel));
}
}
inline float find(float a, float b, float c, float d, std::function<float(float, float)> pred) {
float abRes = pred(a, b);
float cdRes = pred(c, d);
return pred(abRes, cdRes);
}
void setRow(const ImageF& in, ImageF& out, size_t row, size_t channel, size_t outChannel, std::function<float(float, float)> pred) {
for (int x = 0; x < in.getWidth(); x += 2) {
float val = find(in.get(x, row, channel), in.get(x + 1, row, channel),
in.get(x, row + 1, channel), in.get(x + 1, row + 1, channel), pred);
out.set(x / 2, row / 2, outChannel, val);
}
}
inline void constructRange(const ImageF& in, ImageF& out, size_t begin, size_t end, size_t minInChannel, size_t maxInChannel) {
for (int y = begin; y < end; y += 2) {
setRow(in, out, y, minInChannel, 0, std::min<float>);
setRow(in, out, y, maxInChannel, 1, std::max<float>);
}
}
ImageF MinMaxHierarchy::constructLevel(const ImageF& in) const {
const size_t inSize = in.getWidth();
const size_t newSize = inSize / 2;
ImageF res(newSize, newSize, 2);
if (inSize >= PARALLEL_THRESHOLD) {
const size_t perThreadWork = inSize / 4;
assert(perThreadWork >= 2);
std::thread task1{constructRange, std::cref(in), std::ref(res), 0, perThreadWork, MIN_CH, MAX_CH};
std::thread task2{constructRange, std::cref(in), std::ref(res), perThreadWork, 2 * perThreadWork, MIN_CH, MAX_CH};
std::thread task3{constructRange, std::cref(in), std::ref(res), 2 * perThreadWork, 3 * perThreadWork, MIN_CH, MAX_CH};
constructRange(in, res, 3 * perThreadWork, inSize, MIN_CH, MAX_CH);
task1.join();
task2.join();
task3.join();
} else {
constructRange(in, res, 0, inSize, MIN_CH, MAX_CH);
}
return res;
}
ImageF MinMaxHierarchy::constructLevelFromRoot(const ImageF& in) const {
const size_t inSize = in.getWidth();
const size_t newSize = inSize / 2;
ImageF res(newSize, newSize, 2);
if (inSize >= PARALLEL_THRESHOLD) {
const size_t perThreadWork = inSize / 4;
assert(perThreadWork >= 2);
std::thread task1{constructRange, std::cref(in), std::ref(res), 0, perThreadWork, 0, 0};
std::thread task2{constructRange, std::cref(in), std::ref(res), perThreadWork, 2 * perThreadWork, 0, 0};
std::thread task3{constructRange, std::cref(in), std::ref(res), 2 * perThreadWork, 3 * perThreadWork, 0,0};
constructRange(in, res, 3 * perThreadWork, inSize, 0, 0);
task1.join();
task2.join();
task3.join();
} else {
constructRange(in, res, 0, inSize, 0, 0);
}
return res;
}
|
#ifndef __residlerProcessor__
#define __residlerProcessor__
#include "BaseProcessor.h"
#include "residlerParameterFormat.h"
#include "sid_wrapper.h"
namespace Steinberg {
namespace Vst {
namespace residler {
//-----------------------------------------------------------------------------
class residlerProcessor : public BaseProcessor
{
public:
residlerProcessor ();
~residlerProcessor ();
tresult PLUGIN_API initialize (FUnknown* context);
tresult PLUGIN_API terminate ();
tresult PLUGIN_API setActive (TBool state);
void doProcessing (ProcessData& data);
//-----------------------------------------------------------------------------
static FUnknown* createInstance (void*) { return (IAudioProcessor*)new residlerProcessor; }
static FUID uid;
//-----------------------------------------------------------------------------
protected:
void recalculate ();
void noteOn(int16 note, float velocity, int32 sampleOffset);
void noteOff(int16 note, int32 sampleOffset);
private:
void event_test (IEventList* events);
bool parameter_test (IParameterChanges* changes);
private:
residlerParameterFormat paramFormat;
// this 65536 because 65536 is nice, big and round
int last_update_times[residlerParameterFormat::knumParameters];
sid_wrapper *sid;
};
}}} // namespaces
#endif
|
#ifndef BOARD_COM_H
#define BOARD_COM_H
#include "FreeRTOS.h"
#include "PID.h"
#include <main.h>
#include "drv_can.h"
#include "referee.h"
//#include "Infantry_Config.h"
extern CAN_HandleTypeDef hcan1;
extern referee_Classdef Referee;
class C_BoardCom
{
public:
void Update(
uint8_t sourcePowerMax,
uint8_t shooterSpeedLimit,
uint16_t coolingRate,
uint16_t coolingLimit,
uint16_t shooterHeat,
float bullet_speed);
void Send();
uint8_t data[8];
uint8_t dataFloat[8];
};
#endif
|
#pragma once
////////////////////////////////////////////////////////////////////////////////
#include <cellogram/common.h>
#include <vector>
#include <string>
////////////////////////////////////////////////////////////////////////////////
namespace cellogram {
namespace StringUtils {
int cellogram_mkdir(const std::string &path);
// Split a string into tokens
std::vector<std::string> split(const std::string &str, const std::string &delimiters = " ");
// Skip comments in a stream
std::istream &skip(std::istream &in, char x = '#');
// Tests whether a string starts with a given prefix
bool startswith(const std::string &str, const std::string &prefix);
// Tests whether a string ends with a given suffix
bool endswidth(const std::string &str, const std::string &suffix);
}
} // namespace cellogram
|
// Created on: 1996-12-05
// Created by: Flore Lantheaume/Odile Olivier
// Copyright (c) 1996-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 _PrsDim_FixRelation_HeaderFile
#define _PrsDim_FixRelation_HeaderFile
#include <gp_Circ.hxx>
#include <TopoDS_Wire.hxx>
#include <PrsDim_Relation.hxx>
class Geom_Plane;
DEFINE_STANDARD_HANDLE(PrsDim_FixRelation, PrsDim_Relation)
//! Constructs and manages a constraint by a fixed
//! relation between two or more interactive datums. This
//! constraint is represented by a wire from a shape -
//! point, vertex, or edge - in the first datum and a
//! corresponding shape in the second.
//! Warning: This relation is not bound with any kind of parametric
//! constraint : it represents the "status" of an parametric
//! object.
class PrsDim_FixRelation : public PrsDim_Relation
{
DEFINE_STANDARD_RTTIEXT(PrsDim_FixRelation, PrsDim_Relation)
public:
//! initializes the vertex aShape, the
//! plane aPlane and the wire aWire, which connects
//! the two vertices in a fixed relation.
Standard_EXPORT PrsDim_FixRelation(const TopoDS_Shape& aShape, const Handle(Geom_Plane)& aPlane, const TopoDS_Wire& aWire);
//! initializes the vertex aShape, the
//! plane aPlane and the wire aWire, the position
//! aPosition, the arrow size anArrowSize and the
//! wire aWire, which connects the two vertices in a fixed relation.
Standard_EXPORT PrsDim_FixRelation(const TopoDS_Shape& aShape, const Handle(Geom_Plane)& aPlane, const TopoDS_Wire& aWire, const gp_Pnt& aPosition, const Standard_Real anArrowSize = 0.01);
//! initializes the edge aShape and the plane aPlane.
Standard_EXPORT PrsDim_FixRelation(const TopoDS_Shape& aShape, const Handle(Geom_Plane)& aPlane);
//! initializes the edge aShape, the
//! plane aPlane, the position aPosition and the arrow
//! size anArrowSize.
Standard_EXPORT PrsDim_FixRelation(const TopoDS_Shape& aShape, const Handle(Geom_Plane)& aPlane, const gp_Pnt& aPosition, const Standard_Real anArrowSize = 0.01);
//! Returns the wire which connects vertices in a fixed relation.
const TopoDS_Wire& Wire() { return myWire; }
//! Constructs the wire aWire. This connects vertices
//! which are in a fixed relation.
void SetWire (const TopoDS_Wire& aWire) { myWire = aWire; }
//! Returns true if the Interactive Objects in the relation
//! are movable.
virtual Standard_Boolean IsMovable() const Standard_OVERRIDE { return Standard_True; }
private:
Standard_EXPORT virtual void Compute (const Handle(PrsMgr_PresentationManager)& thePrsMgr,
const Handle(Prs3d_Presentation)& thePrs,
const Standard_Integer theMode) Standard_OVERRIDE;
Standard_EXPORT virtual void ComputeSelection (const Handle(SelectMgr_Selection)& theSel,
const Standard_Integer theMode) Standard_OVERRIDE;
//! computes the presentation for <myFixShape> if it's a vertex.
Standard_EXPORT void ComputeVertex (const TopoDS_Vertex& FixVertex, gp_Pnt& curpos);
Standard_EXPORT gp_Pnt ComputePosition (const Handle(Geom_Curve)& curv1, const Handle(Geom_Curve)& curv2, const gp_Pnt& firstp1, const gp_Pnt& lastp1, const gp_Pnt& firstp2, const gp_Pnt& lastp2) const;
Standard_EXPORT gp_Pnt ComputePosition (const Handle(Geom_Curve)& curv, const gp_Pnt& firstp, const gp_Pnt& lastp) const;
//! computes the presentation for <myFixShape> if it's a
//! edge.
Standard_EXPORT void ComputeEdge (const TopoDS_Edge& FixEdge, gp_Pnt& curpos);
Standard_EXPORT void ComputeLinePosition (const gp_Lin& glin, gp_Pnt& pos, Standard_Real& pfirst, Standard_Real& plast);
Standard_EXPORT void ComputeCirclePosition (const gp_Circ& gcirc, gp_Pnt& pos, Standard_Real& pfirst, Standard_Real& plast);
Standard_EXPORT static Standard_Boolean ConnectedEdges (const TopoDS_Wire& aWire, const TopoDS_Vertex& aVertex, TopoDS_Edge& Edge1, TopoDS_Edge& Edge2);
private:
TopoDS_Wire myWire;
gp_Pnt myPntAttach;
};
#endif // _PrsDim_FixRelation_HeaderFile
|
#include<iostream>
#define FOR0(i,n) for(i=0;i<n;i++)
#define FOR(i,j,n) for(i=j;i<n;i++)
#define FORD(i,j) for(i=j;i>=0;i--)
#define MAX(a,b) (a)>(b)?(a):(b)
using namespace std;
int main()
{
int H[2002],W[2002],Mi[2002],Md[2002],i,testcases,n,curri,currd,maxi,maxd,j,k;
scanf("%d",&testcases);
FOR0(k,testcases)
{
cin>>n;
FOR0(i,n)
scanf("%d",&H[i]);
FOR0(i,n)
{scanf("%d",&W[i]);Mi[i]=W[i];Md[i]=W[i];}
//LIS && LDS
maxi=Mi[0];maxd=Md[0];
FOR0(i,n)
{
curri=0;currd=0;
FOR0(j,i)
{
if(H[j]<H[i])
if(Mi[j]>curri)
{curri=Mi[j];Mi[i]=curri+W[i];}
if(H[j]>H[i])
if(Md[j]>currd)
{currd=Md[j];Md[i]=currd+W[i];}
maxd=MAX(Md[i],maxd);
maxi=MAX(Mi[i],maxi);
}
}
if(maxi>=maxd)
printf("Case %d. Increasing (%d). Decreasing (%d).\n",k+1,maxi,maxd);
else printf("Case %d. Decreasing (%d). Increasing (%d).\n",k+1,maxd,maxi);
}
}
|
#include <cassert>
#include <cfloat>
#include <cmath>
#include <cstdbool>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <array>
#include <string>
#include <unordered_map>
#include <ap_int.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <CL/opencl.h>
using std::array;
using std::count;
using std::fill;
using std::string;
using std::unordered_map;
#include "pointwise.h"
#ifndef BURST_WIDTH
#define BURST_WIDTH 64
#endif//BURST_WIDTH
#ifndef STENCIL_DIM_0
#define STENCIL_DIM_0 1
#endif//STENCIL_DIM_0
#ifndef STENCIL_DIM_1
#define STENCIL_DIM_1 1
#endif//STENCIL_DIM_1
#ifndef STENCIL_DISTANCE
#define STENCIL_DISTANCE 0
#endif//STENCIL_DISTANCE
FILE* const* error_report = &stderr;
int64_t load_xclbin2_to_memory(const char *filename, char **kernel_binary, char** device)
{
uint64_t size = 0;
FILE *f = fopen(filename, "rb");
if(nullptr == f)
{
*kernel_binary = nullptr;
fprintf(*error_report, "ERROR: cannot open %s\n", filename);
return -1;
}
char magic[8];
unsigned char cipher[32];
unsigned char key_block[256];
uint64_t unique_id;
if (fread(magic, sizeof(magic), 1, f) != 1) {
*kernel_binary = nullptr;
fprintf(*error_report, "ERROR: %s is not a valid xclbin2 file\n", filename);
return -2;
}
if (strcmp(magic, "xclbin2") != 0) {
*kernel_binary = nullptr;
fprintf(*error_report, "ERROR: %s is not a valid xclbin2 file\n", filename);
return -2;
}
if (fread(cipher, sizeof(cipher), 1, f) != 1) {
*kernel_binary = nullptr;
fprintf(*error_report, "ERROR: %s is not a valid xclbin2 file\n", filename);
return -2;
}
if (fread(key_block, sizeof(key_block), 1, f) != 1) {
*kernel_binary = nullptr;
fprintf(*error_report, "ERROR: %s is not a valid xclbin2 file\n", filename);
return -2;
}
if (fread(&unique_id, sizeof(unique_id), 1, f) != 1) {
*kernel_binary = nullptr;
fprintf(*error_report, "ERROR: %s is not a valid xclbin2 file\n", filename);
return -2;
}
if (fread(&size, sizeof(size), 1, f) != 1) {
*kernel_binary = nullptr;
fprintf(*error_report, "ERROR: %s is not a valid xclbin2 file\n", filename);
return -2;
}
char* p = new char[size+1]();
*kernel_binary = p;
memcpy(p, magic, sizeof(magic));
p += sizeof(magic);
memcpy(p, cipher, sizeof(cipher));
p += sizeof(cipher);
memcpy(p, key_block, sizeof(key_block));
p += sizeof(key_block);
memcpy(p, &unique_id, sizeof(unique_id));
p += sizeof(unique_id);
memcpy(p, &size, sizeof(size));
p += sizeof(size);
uint64_t size_left = size - sizeof(magic) - sizeof(cipher) - sizeof(key_block) - sizeof(unique_id) - sizeof(size);
if(size_left != fread(p, sizeof(char), size_left, f))
{
delete[] p;
fprintf(*error_report, "ERROR: %s is corrupted\n", filename);
return -3;
}
*device = p + 5*8;
fclose(f);
return size;
}
static bool halide_rewrite_buffer(buffer_t *b, int32_t elem_size,
int32_t min0, int32_t extent0, int32_t stride0,
int32_t min1, int32_t extent1, int32_t stride1,
int32_t min2, int32_t extent2, int32_t stride2,
int32_t min3, int32_t extent3, int32_t stride3)
{
b->min[0] = min0;
b->min[1] = min1;
b->min[2] = min2;
b->min[3] = min3;
b->extent[0] = extent0;
b->extent[1] = extent1;
b->extent[2] = extent2;
b->extent[3] = extent3;
b->stride[0] = stride0;
b->stride[1] = stride1;
b->stride[2] = stride2;
b->stride[3] = stride3;
return true;
}
int halide_error_code_success = 0;
int halide_error_code_generic_error = -1;
int halide_error_code_explicit_bounds_too_small = -2;
int halide_error_code_bad_elem_size = -3;
int halide_error_code_access_out_of_bounds = -4;
int halide_error_code_buffer_allocation_too_large = -5;
int halide_error_code_buffer_extents_too_large = -6;
int halide_error_code_constraints_make_required_region_smaller = -7;
int halide_error_code_constraint_violated = -8;
int halide_error_code_param_too_small = -9;
int halide_error_code_param_too_large = -10;
int halide_error_code_out_of_memory = -11;
int halide_error_code_buffer_argument_is_null = -12;
int halide_error_code_debug_to_file_failed = -13;
int halide_error_code_copy_to_host_failed = -14;
int halide_error_code_copy_to_device_failed = -15;
int halide_error_code_device_malloc_failed = -16;
int halide_error_code_device_sync_failed = -17;
int halide_error_code_device_free_failed = -18;
int halide_error_code_no_device_interface = -19;
int halide_error_code_matlab_init_failed = -20;
int halide_error_code_matlab_bad_param_type = -21;
int halide_error_code_internal_error = -22;
int halide_error_code_device_run_failed = -23;
int halide_error_code_unaligned_host_ptr = -24;
int halide_error_code_bad_fold = -25;
int halide_error_code_fold_factor_too_small = -26;
int halide_error_bad_elem_size(void *user_context, const char *func_name,
const char *type_name, int elem_size_given, int correct_elem_size) {
fprintf(*error_report, "%s has type %s but elem_size of the buffer passed in is %d instead of %d",
func_name, type_name, elem_size_given, correct_elem_size);
return halide_error_code_bad_elem_size;
}
int halide_error_constraint_violated(void *user_context, const char *var, int val,
const char *constrained_var, int constrained_val) {
fprintf(*error_report, "Constraint violated: %s (%d) == %s (%d)",
var, val, constrained_var, constrained_val);
return halide_error_code_constraint_violated;
}
int halide_error_buffer_allocation_too_large(void *user_context, const char *buffer_name, uint64_t allocation_size, uint64_t max_size) {
fprintf(*error_report, "Total allocation for buffer %s is %lu, which exceeds the maximum size of %lu",
buffer_name, allocation_size, max_size);
return halide_error_code_buffer_allocation_too_large;
}
int halide_error_buffer_extents_too_large(void *user_context, const char *buffer_name, int64_t actual_size, int64_t max_size) {
fprintf(*error_report, "Product of extents for buffer %s is %ld, which exceeds the maximum size of %ld",
buffer_name, actual_size, max_size);
return halide_error_code_buffer_extents_too_large;
}
int halide_error_access_out_of_bounds(void *user_context, const char *func_name, int dimension, int min_touched, int max_touched, int min_valid, int max_valid) {
if(min_touched < min_valid) {
fprintf(*error_report, "%s is accessed at %d, which is before the min (%d) in dimension %d", func_name, min_touched, min_valid, dimension);
} else if(max_touched > max_valid) {
fprintf(*error_report, "%s is acccessed at %d, which is beyond the max (%d) in dimension %d", func_name, max_touched, max_valid, dimension);
}
return halide_error_code_access_out_of_bounds;
}
static int pointwise_wrapped(buffer_t *var_input_buffer, buffer_t *var_pointwise_buffer, const char* xclbin) HALIDE_FUNCTION_ATTRS
{
uint16_t *var_input = (uint16_t *)(var_input_buffer->host);
(void)var_input;
const bool var_input_host_and_dev_are_null = (var_input_buffer->host == nullptr) && (var_input_buffer->dev == 0);
(void)var_input_host_and_dev_are_null;
int32_t var_input_min_0 = var_input_buffer->min[0];
(void)var_input_min_0;
int32_t var_input_min_1 = var_input_buffer->min[1];
(void)var_input_min_1;
int32_t var_input_min_2 = var_input_buffer->min[2];
(void)var_input_min_2;
int32_t var_input_min_3 = var_input_buffer->min[3];
(void)var_input_min_3;
int32_t input_size_dim_0 = var_input_buffer->extent[0];
(void)input_size_dim_0;
int32_t input_size_dim_1 = var_input_buffer->extent[1];
(void)input_size_dim_1;
int32_t input_size_dim_2 = var_input_buffer->extent[2];
(void)input_size_dim_2;
int32_t input_size_dim_3 = var_input_buffer->extent[3];
(void)input_size_dim_3;
int32_t var_input_stride_0 = var_input_buffer->stride[0];
(void)var_input_stride_0;
int32_t var_input_stride_1 = var_input_buffer->stride[1];
(void)var_input_stride_1;
int32_t var_input_stride_2 = var_input_buffer->stride[2];
(void)var_input_stride_2;
int32_t var_input_stride_3 = var_input_buffer->stride[3];
(void)var_input_stride_3;
int32_t var_input_elem_size = var_input_buffer->elem_size;
(void)var_input_elem_size;
uint16_t *var_pointwise = (uint16_t *)(var_pointwise_buffer->host);
(void)var_pointwise;
const bool var_pointwise_host_and_dev_are_null = (var_pointwise_buffer->host == nullptr) && (var_pointwise_buffer->dev == 0);
(void)var_pointwise_host_and_dev_are_null;
int32_t var_pointwise_min_0 = var_pointwise_buffer->min[0];
(void)var_pointwise_min_0;
int32_t var_pointwise_min_1 = var_pointwise_buffer->min[1];
(void)var_pointwise_min_1;
int32_t var_pointwise_min_2 = var_pointwise_buffer->min[2];
(void)var_pointwise_min_2;
int32_t var_pointwise_min_3 = var_pointwise_buffer->min[3];
(void)var_pointwise_min_3;
int32_t pointwise_size_dim_0 = var_pointwise_buffer->extent[0];
(void)pointwise_size_dim_0;
int32_t pointwise_size_dim_1 = var_pointwise_buffer->extent[1];
(void)pointwise_size_dim_1;
int32_t pointwise_size_dim_2 = var_pointwise_buffer->extent[2];
(void)pointwise_size_dim_2;
int32_t pointwise_size_dim_3 = var_pointwise_buffer->extent[3];
(void)pointwise_size_dim_3;
int32_t var_pointwise_stride_0 = var_pointwise_buffer->stride[0];
(void)var_pointwise_stride_0;
int32_t var_pointwise_stride_1 = var_pointwise_buffer->stride[1];
(void)var_pointwise_stride_1;
int32_t var_pointwise_stride_2 = var_pointwise_buffer->stride[2];
(void)var_pointwise_stride_2;
int32_t var_pointwise_stride_3 = var_pointwise_buffer->stride[3];
(void)var_pointwise_stride_3;
int32_t var_pointwise_elem_size = var_pointwise_buffer->elem_size;
(void)var_pointwise_elem_size;
if(var_pointwise_host_and_dev_are_null)
{
bool assign_0 = halide_rewrite_buffer(var_pointwise_buffer, 2, var_pointwise_min_0, pointwise_size_dim_0, 1, var_pointwise_min_1, pointwise_size_dim_1, pointwise_size_dim_0, 0, 0, 0, 0, 0, 0);
(void)assign_0;
} // var_pointwise_host_and_dev_are_null
if(var_input_host_and_dev_are_null)
{
int32_t assign_1 = pointwise_size_dim_0 + 0;
int32_t assign_2 = pointwise_size_dim_1 + 0;
bool assign_3 = halide_rewrite_buffer(var_input_buffer, 2, var_pointwise_min_0, assign_1, 1, var_pointwise_min_1, assign_2, assign_1, 0, 0, 0, 0, 0, 0);
(void)assign_3;
} // var_input_host_and_dev_are_null
bool assign_4 = var_pointwise_host_and_dev_are_null || var_input_host_and_dev_are_null;
bool assign_5 = !(assign_4);
if(assign_5)
{
bool assign_6 = var_pointwise_elem_size == 2;
if(!assign_6)
{
int32_t assign_7 = halide_error_bad_elem_size(nullptr, "Buffer pointwise", "uint16", var_pointwise_elem_size, 2);
return assign_7;
}
bool assign_8 = var_input_elem_size == 2;
if(!assign_8)
{
int32_t assign_9 = halide_error_bad_elem_size(nullptr, "Buffer input", "uint16", var_input_elem_size, 2);
return assign_9;
}
// allocate buffer for tiled input/output
int32_t tile_num_dim_0 = (input_size_dim_0-STENCIL_DIM_0+1+TILE_SIZE_DIM_0-STENCIL_DIM_0)/(TILE_SIZE_DIM_0-STENCIL_DIM_0+1);
// change #bank if there is a env var defined
unordered_map<string, array<bool, 4>> use_bank;
unordered_map<string, int> num_bank;
unordered_map<string, array<int, 4>> bank_vec;
use_bank["pointwise"] = {false, true, false, false};
num_bank["pointwise"] = {1};
bank_vec["pointwise"] = {1};
use_bank["input"] = {false, true, false, false};
num_bank["input"] = {1};
bank_vec["input"] = {1};
if (const char* env_var_char = getenv("DRAM_IN")) {
const string env_var(env_var_char);
if (env_var.find(':') != string::npos) {
size_t pos = 0;
size_t next_pos;
do {
next_pos = env_var.find(',', pos);
const size_t colon_pos = env_var.find(':', pos);
const string name = env_var.substr(pos, colon_pos - pos);
pos = colon_pos + 1;
if (use_bank.count(name)) {
fill(use_bank[name].begin(), use_bank[name].end(), false);
num_bank[name] = 0;
int idx = 0;
size_t dot_pos;
do {
dot_pos = env_var.find('.', pos);
int bank = stoi(env_var.substr(pos, dot_pos - pos));
use_bank[name][bank] = true;
++num_bank[name];
bank_vec[name][idx++] = bank;
pos = dot_pos + 1;
} while (dot_pos != string::npos && dot_pos < next_pos);
} else {
fprintf(*error_report, "WARNING: unknown name %s\n", name.c_str());
}
pos = next_pos + 1;
} while (next_pos != string::npos);
} else {
for (const string name : {"input"}) {
fill(use_bank[name].begin(), use_bank[name].end(), false);
num_bank[name] = 0;
int idx = 0;
size_t pos = 0;
size_t dot_pos;
do {
dot_pos = env_var.find('.', pos);
int bank = stoi(env_var.substr(pos, dot_pos - pos));
use_bank[name][bank] = true;
++num_bank[name];
bank_vec[name][idx++] = bank;
pos = dot_pos + 1;
} while (dot_pos != string::npos);
}
}
}
if (const char* env_var_char = getenv("DRAM_OUT")) {
const string env_var(env_var_char);
if (env_var.find(':') != string::npos) {
size_t pos = 0;
size_t next_pos;
do {
next_pos = env_var.find(',', pos);
const size_t colon_pos = env_var.find(':', pos);
const string name = env_var.substr(pos, colon_pos - pos);
pos = colon_pos + 1;
if (use_bank.count(name)) {
fill(use_bank[name].begin(), use_bank[name].end(), false);
num_bank[name] = 0;
int idx = 0;
size_t dot_pos;
do {
dot_pos = env_var.find('.', pos);
int bank = stoi(env_var.substr(pos, dot_pos - pos));
use_bank[name][bank] = true;
++num_bank[name];
bank_vec[name][idx++] = bank;
pos = dot_pos + 1;
} while (dot_pos != string::npos && dot_pos < next_pos);
} else {
fprintf(*error_report, "WARNING: unknown name %s\n", name.c_str());
}
pos = next_pos + 1;
} while (next_pos != string::npos);
} else {
for (const string name : {"pointwise"}) {
fill(use_bank[name].begin(), use_bank[name].end(), false);
num_bank[name] = 0;
int idx = 0;
size_t pos = 0;
size_t dot_pos;
do {
dot_pos = env_var.find('.', pos);
int bank = stoi(env_var.substr(pos, dot_pos - pos));
use_bank[name][bank] = true;
++num_bank[name];
bank_vec[name][idx++] = bank;
pos = dot_pos + 1;
} while (dot_pos != string::npos);
}
}
}
// align each linearized tile to multiples of BURST_WIDTH
int64_t tile_pixel_num = TILE_SIZE_DIM_0*input_size_dim_1;
int64_t tile_burst_num = (tile_pixel_num-1)/(BURST_WIDTH/16*num_bank["input"])+1;
int64_t tile_size_linearized_i = tile_burst_num*(BURST_WIDTH/16*num_bank["input"]);
int64_t tile_size_linearized_o = tile_burst_num*(BURST_WIDTH/16*num_bank["pointwise"]);
// prepare for opencl
int err;
cl_platform_id platforms[16];
cl_platform_id platform_id = 0;
cl_uint platform_count;
cl_device_id device_id;
cl_context context;
cl_command_queue commands;
cl_program program;
cl_kernel kernel;
char cl_platform_vendor[1001];
cl_mem var_input_cl_bank[4] = {};
cl_mem var_pointwise_cl_bank[4] = {};
uint64_t var_input_buf_size = sizeof(uint16_t)*(tile_num_dim_0*tile_size_linearized_i/num_bank["input"]+((STENCIL_DISTANCE-1)/(BURST_WIDTH/16*num_bank["input"])+1)*(BURST_WIDTH/16));
uint64_t var_pointwise_buf_size = sizeof(uint16_t)*(tile_num_dim_0*tile_size_linearized_o/num_bank["pointwise"]+((STENCIL_DISTANCE-1)/(BURST_WIDTH/16*num_bank["pointwise"])+1)*(BURST_WIDTH/16));
unsigned char *kernel_binary;
const char *device_name;
char target_device_name[64];
fprintf(*error_report, "INFO: Loading %s\n", xclbin);
int64_t kernel_binary_size = load_xclbin2_to_memory(xclbin, (char **) &kernel_binary, (char**)&device_name);
if (strlen(device_name) == 0)
{
device_name = getenv("XDEVICE");
}
if(kernel_binary_size < 0)
{
fprintf(*error_report, "ERROR: Failed to load kernel from xclbin: %s\n", xclbin);
exit(EXIT_FAILURE);
}
for(int i = 0; i<64; ++i)
{
target_device_name[i] = (device_name[i]==':'||device_name[i]=='.') ? '_' : device_name[i];
}
err = clGetPlatformIDs(16, platforms, &platform_count);
if(err != CL_SUCCESS)
{
fprintf(*error_report, "ERROR: Failed to find an OpenCL platform\n");
exit(EXIT_FAILURE);
}
fprintf(*error_report, "INFO: Found %d platforms\n", platform_count);
int platform_found = 0;
for (unsigned iplat = 0; iplat<platform_count; iplat++)
{
err = clGetPlatformInfo(platforms[iplat], CL_PLATFORM_VENDOR, 1000, (void *)cl_platform_vendor,nullptr);
if(err != CL_SUCCESS)
{
fprintf(*error_report, "ERROR: clGetPlatformInfo(CL_PLATFORM_VENDOR) failed\n");
exit(EXIT_FAILURE);
}
if(strcmp(cl_platform_vendor, "Xilinx") == 0)
{
fprintf(*error_report, "INFO: Selected platform %d from %s\n", iplat, cl_platform_vendor);
platform_id = platforms[iplat];
platform_found = 1;
}
}
if(!platform_found)
{
fprintf(*error_report, "ERROR: Platform Xilinx not found\n");
exit(EXIT_FAILURE);
}
cl_device_id devices[16];
cl_uint device_count;
unsigned int device_found = 0;
char cl_device_name[1001];
err = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ACCELERATOR,
16, devices, &device_count);
if(err != CL_SUCCESS)
{
fprintf(*error_report, "ERROR: Failed to create a device group\n");
exit(EXIT_FAILURE);
}
for (unsigned int i=0; i<device_count; ++i)
{
err = clGetDeviceInfo(devices[i], CL_DEVICE_NAME, 1024, cl_device_name, 0);
if(err != CL_SUCCESS)
{
fprintf(*error_report, "ERROR: Failed to get device name for device %d\n", i);
exit(EXIT_FAILURE);
}
printf("INFO: Find device %s\n", cl_device_name);
if(strcmp(cl_device_name, target_device_name) == 0 || strcmp(cl_device_name, device_name) == 0)
{
device_id = devices[i];
device_found = 1;
fprintf(*error_report, "INFO: Selected %s as the target device\n", device_name);
}
}
if(!device_found)
{
fprintf(*error_report, "ERROR: Target device %s not found\n", target_device_name);
exit(EXIT_FAILURE);
}
err = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ACCELERATOR,
1, &device_id, nullptr);
if(err != CL_SUCCESS)
{
fprintf(*error_report, "ERROR: Failed to create a device group\n");
exit(EXIT_FAILURE);
}
context = clCreateContext(nullptr, 1, &device_id, nullptr, nullptr, &err);
if(!context)
{
fprintf(*error_report, "ERROR: Failed to create a compute context\n");
exit(EXIT_FAILURE);
}
commands = clCreateCommandQueue(context, device_id, 0, &err);
if(!commands)
{
fprintf(*error_report, "ERROR: Failed to create a command commands %i\n",err);
exit(EXIT_FAILURE);
}
int status;
size_t kernel_binary_sizes[1] = {static_cast<size_t>(kernel_binary_size)};
program = clCreateProgramWithBinary(context, 1, &device_id, kernel_binary_sizes,
(const unsigned char **) &kernel_binary, &status, &err);
if((!program) || (err!=CL_SUCCESS))
{
fprintf(*error_report, "ERROR: Failed to create compute program from binary %d\n", err);
exit(EXIT_FAILURE);
}
delete[] kernel_binary;
err = clBuildProgram(program, 0, nullptr, nullptr, nullptr, nullptr);
if(err != CL_SUCCESS)
{
size_t len;
char buffer[2048];
fprintf(*error_report, "ERROR: Failed to build program executable\n");
clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len);
fprintf(*error_report, "%s\n", buffer);
exit(EXIT_FAILURE);
}
kernel = clCreateKernel(program, "pointwise_kernel", &err);
if(!kernel || err != CL_SUCCESS)
{
fprintf(*error_report, "ERROR: Failed to create compute kernel %d\n", err);
exit(EXIT_FAILURE);
}
const unsigned XCL_MEM_DDR_BANK[4] = {XCL_MEM_DDR_BANK0, XCL_MEM_DDR_BANK1, XCL_MEM_DDR_BANK2, XCL_MEM_DDR_BANK3};
unordered_map<string, array<cl_mem_ext_ptr_t, 4>> mem_ext_bank;
for (const auto& use_bank_pair : use_bank) {
for (auto bank : {0, 1, 2, 3}) {
if (use_bank_pair.second[bank]) {
mem_ext_bank[use_bank_pair.first][bank].flags = XCL_MEM_DDR_BANK[bank];
}
}
}
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["input"][bank]) {
var_input_cl_bank[bank] = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_EXT_PTR_XILINX, var_input_buf_size, &mem_ext_bank["input"][bank], nullptr);
if (var_input_cl_bank[bank] == nullptr) {
fprintf(*error_report, "ERROR: Failed to allocate device memory\n");
exit(EXIT_FAILURE);
}
}
if (use_bank["pointwise"][bank]) {
var_pointwise_cl_bank[bank] = clCreateBuffer(context, CL_MEM_WRITE_ONLY|CL_MEM_EXT_PTR_XILINX, var_pointwise_buf_size, &mem_ext_bank["pointwise"][bank], nullptr);
if (var_pointwise_cl_bank[bank] == nullptr) {
fprintf(*error_report, "ERROR: Failed to allocate device memory\n");
exit(EXIT_FAILURE);
}
}
}
cl_event write_events[4];
cl_event* write_event_ptr = write_events;
uint16_t* var_input_buf_bank[4] = {};
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["input"][bank]) {
var_input_buf_bank[bank] = reinterpret_cast<uint16_t*>(clEnqueueMapBuffer(commands, var_input_cl_bank[bank], CL_FALSE, CL_MAP_WRITE, 0, var_input_buf_size, 0, nullptr, write_event_ptr++, &err));
}
}
clWaitForEvents(write_event_ptr - write_events, write_events);
// tiling
for(int32_t tile_index_dim_0 = 0; tile_index_dim_0 < tile_num_dim_0; ++tile_index_dim_0)
{
int32_t actual_tile_size_dim_0 = (tile_index_dim_0==tile_num_dim_0-1) ? input_size_dim_0-(TILE_SIZE_DIM_0-STENCIL_DIM_0+1)*tile_index_dim_0 : TILE_SIZE_DIM_0;
#pragma omp parallel for
for(int32_t j = 0; j < input_size_dim_1; ++j)
{
for(int32_t i = 0; i < actual_tile_size_dim_0; ++i)
{
// (x, y, z, w) is coordinates in tiled image
// (p, q, r, s) is coordinates in original image
// (i, j, k, l) is coordinates in a tile
int32_t burst_index = (i+j*TILE_SIZE_DIM_0) / (BURST_WIDTH / 16 * num_bank["input"]);
int32_t burst_residue = (i+j*TILE_SIZE_DIM_0) % (BURST_WIDTH / 16 * num_bank["input"]);
int32_t p = tile_index_dim_0*(TILE_SIZE_DIM_0-STENCIL_DIM_0+1)+i;
int32_t q = j;
int64_t tiled_offset = (tile_index_dim_0) * tile_size_linearized_i + burst_index * (BURST_WIDTH / 16 * num_bank["input"]) + burst_residue;
int64_t original_offset = p*var_input_stride_0+q*var_input_stride_1;
var_input_buf_bank[bank_vec["input"][tiled_offset % num_bank["input"]]][tiled_offset / num_bank["input"]] = var_input[original_offset];
}
}
}
err = 0;
write_event_ptr = write_events;
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["input"][bank]) {
err |= clEnqueueUnmapMemObject(commands, var_input_cl_bank[bank], var_input_buf_bank[bank], 0, nullptr, write_event_ptr++);
}
}
if(err != CL_SUCCESS)
{
fprintf(*error_report, "ERROR: Failed to write to input !\n");
exit(EXIT_FAILURE);
}
err = 0;
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["input"][bank]) {
fprintf(*error_report, "INFO: Using DRAM bank %d for input\n", bank);
}
}
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["pointwise"][bank]) {
fprintf(*error_report, "INFO: Using DRAM bank %d for pointwise\n", bank);
}
}
fprintf(*error_report, "INFO: tile_num_dim_0 = %d, TILE_SIZE_DIM_0 = %d\n", tile_num_dim_0, TILE_SIZE_DIM_0);
fprintf(*error_report, "INFO: input_extent_0 = %d, input_extent_1 = %d\n", input_size_dim_0, input_size_dim_1);
fprintf(*error_report, "INFO: input_min_0 = %d, input_min_1 = %d\n", var_input_min_0, var_input_min_1);
fprintf(*error_report, "INFO: pointwise_extent_0 = %d, pointwise_extent_1 = %d\n", pointwise_size_dim_0, pointwise_size_dim_1);
fprintf(*error_report, "INFO: pointwise_min_0 = %d, pointwise_min_1 = %d\n", var_pointwise_min_0, var_pointwise_min_1);
int kernel_arg = 0;
int64_t tile_data_num = ((int64_t(input_size_dim_1) * TILE_SIZE_DIM_0 - 1) / (BURST_WIDTH / 16 * num_bank["input"]) + 1) * BURST_WIDTH / 16 * num_bank["input"] / UNROLL_FACTOR;
int64_t coalesced_data_num = ((int64_t(input_size_dim_1)*TILE_SIZE_DIM_0 * tile_num_dim_0 + STENCIL_DISTANCE - 1) / (BURST_WIDTH / 16 * num_bank["input"]) + 1);
fprintf(*error_report, "INFO: tile_data_num = %ld, coalesced_data_num = %ld\n", tile_data_num, coalesced_data_num);
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["pointwise"][bank]) {
err |= clSetKernelArg(kernel, kernel_arg++, sizeof(cl_mem), &var_pointwise_cl_bank[bank]);
}
}
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["input"][bank]) {
err |= clSetKernelArg(kernel, kernel_arg++, sizeof(cl_mem), &var_input_cl_bank[bank]);
}
}
err |= clSetKernelArg(kernel, kernel_arg++, sizeof(coalesced_data_num), &coalesced_data_num);
if(err != CL_SUCCESS)
{
fprintf(*error_report, "ERROR: Failed to set kernel arguments %d\n", err);
exit(EXIT_FAILURE);
}
timespec execute_begin, execute_end;
cl_event execute_event;
err = clEnqueueTask(commands, kernel, write_event_ptr - write_events, write_events, &execute_event);
if (getenv("XCL_EMULATION_MODE") == nullptr) {
fprintf(*error_report, "INFO: FPGA warm up\n");
clWaitForEvents(1, &execute_event);
clock_gettime(CLOCK_MONOTONIC_RAW, &execute_begin);
err = clEnqueueTask(commands, kernel, 0, nullptr, &execute_event);
if (err) {
fprintf(*error_report, "ERROR: Failed to execute kernel %d\n", err);
exit(EXIT_FAILURE);
}
clWaitForEvents(1, &execute_event);
clock_gettime(CLOCK_MONOTONIC_RAW, &execute_end);
double elapsed_time = 0.;
elapsed_time = (double(execute_end.tv_sec-execute_begin.tv_sec)+(execute_end.tv_nsec-execute_begin.tv_nsec)/1e9)*1e6;
printf("Kernel execution time: %lf us\n", elapsed_time);
printf("Kernel throughput: %lf pixel/ns\n", input_size_dim_0*input_size_dim_1 / elapsed_time / 1e3);
} else {
clWaitForEvents(1, &execute_event);
fprintf(*error_report, "INFO: Emulation mode\n");
}
cl_event read_events[4];
cl_event* read_event_ptr = read_events;
uint16_t* var_pointwise_buf_bank[4] = {};
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["pointwise"][bank]) {
var_pointwise_buf_bank[bank] = reinterpret_cast<uint16_t*>(clEnqueueMapBuffer(commands, var_pointwise_cl_bank[bank], CL_FALSE, CL_MAP_READ, 0, var_pointwise_buf_size, 0, nullptr, read_event_ptr++, &err));
}
}
clWaitForEvents(read_event_ptr - read_events, read_events);
for(int32_t tile_index_dim_0 = 0; tile_index_dim_0 < tile_num_dim_0; ++tile_index_dim_0)
{
int32_t actual_tile_size_dim_0 = (tile_index_dim_0==tile_num_dim_0-1) ? input_size_dim_0-(TILE_SIZE_DIM_0-STENCIL_DIM_0+1)*tile_index_dim_0 : TILE_SIZE_DIM_0;
#pragma omp parallel for
for(int32_t j = 0; j < pointwise_size_dim_1-0; ++j)
{
for(int32_t i = 0; i < actual_tile_size_dim_0-0; ++i)
{
// (x, y, z, w) is coordinates in tiled image
// (p, q, r, s) is coordinates in original image
// (i, j, k, l) is coordinates in a tile
int32_t p = tile_index_dim_0*(TILE_SIZE_DIM_0-STENCIL_DIM_0+1)+i;
int32_t q = j;
int64_t original_offset = p*var_pointwise_stride_0+q*var_pointwise_stride_1;
int32_t burst_index_pointwise = (i+j*TILE_SIZE_DIM_0 + 0) / (BURST_WIDTH / 16 * num_bank["pointwise"]);
int32_t burst_residue_pointwise = (i+j*TILE_SIZE_DIM_0 + 0) % (BURST_WIDTH / 16 * num_bank["pointwise"]);
int64_t tiled_offset_pointwise = (tile_index_dim_0) * tile_size_linearized_o + burst_index_pointwise * (BURST_WIDTH / 16 * num_bank["pointwise"]) + burst_residue_pointwise;
var_pointwise[original_offset] = var_pointwise_buf_bank[bank_vec["pointwise"][tiled_offset_pointwise % num_bank["pointwise"]]][tiled_offset_pointwise / num_bank["pointwise"]];
}
}
}
read_event_ptr = read_events;
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["pointwise"][bank]) {
clEnqueueUnmapMemObject(commands, var_pointwise_cl_bank[bank], var_pointwise_buf_bank[bank], 0, nullptr, read_event_ptr++);
}
}
clWaitForEvents(read_event_ptr - read_events, read_events);
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["input"][bank]) {
clReleaseMemObject(var_input_cl_bank[bank]);
}
}
for (auto bank : {0, 1, 2, 3}) {
if (use_bank["pointwise"][bank]) {
clReleaseMemObject(var_pointwise_cl_bank[bank]);
}
}
clReleaseProgram(program);
clReleaseKernel(kernel);
clReleaseCommandQueue(commands);
clReleaseContext(context);
} // if(assign_5)
return 0;
}
int pointwise(buffer_t *var_input_buffer, buffer_t *var_pointwise_buffer, const char* xclbin) HALIDE_FUNCTION_ATTRS
{
uint16_t *var_input = (uint16_t *)(var_input_buffer->host);
(void)var_input;
const bool var_input_host_and_dev_are_null = (var_input_buffer->host == nullptr) && (var_input_buffer->dev == 0);
(void)var_input_host_and_dev_are_null;
int32_t var_input_min_0 = var_input_buffer->min[0];
(void)var_input_min_0;
int32_t var_input_min_1 = var_input_buffer->min[1];
(void)var_input_min_1;
int32_t var_input_min_2 = var_input_buffer->min[2];
(void)var_input_min_2;
int32_t var_input_min_3 = var_input_buffer->min[3];
(void)var_input_min_3;
int32_t input_size_dim_0 = var_input_buffer->extent[0];
(void)input_size_dim_0;
int32_t input_size_dim_1 = var_input_buffer->extent[1];
(void)input_size_dim_1;
int32_t input_size_dim_2 = var_input_buffer->extent[2];
(void)input_size_dim_2;
int32_t input_size_dim_3 = var_input_buffer->extent[3];
(void)input_size_dim_3;
int32_t var_input_stride_0 = var_input_buffer->stride[0];
(void)var_input_stride_0;
int32_t var_input_stride_1 = var_input_buffer->stride[1];
(void)var_input_stride_1;
int32_t var_input_stride_2 = var_input_buffer->stride[2];
(void)var_input_stride_2;
int32_t var_input_stride_3 = var_input_buffer->stride[3];
(void)var_input_stride_3;
int32_t var_input_elem_size = var_input_buffer->elem_size;
(void)var_input_elem_size;
uint16_t *var_pointwise = (uint16_t *)(var_pointwise_buffer->host);
(void)var_pointwise;
const bool var_pointwise_host_and_dev_are_null = (var_pointwise_buffer->host == nullptr) && (var_pointwise_buffer->dev == 0);
(void)var_pointwise_host_and_dev_are_null;
int32_t var_pointwise_min_0 = var_pointwise_buffer->min[0];
(void)var_pointwise_min_0;
int32_t var_pointwise_min_1 = var_pointwise_buffer->min[1];
(void)var_pointwise_min_1;
int32_t var_pointwise_min_2 = var_pointwise_buffer->min[2];
(void)var_pointwise_min_2;
int32_t var_pointwise_min_3 = var_pointwise_buffer->min[3];
(void)var_pointwise_min_3;
int32_t pointwise_size_dim_0 = var_pointwise_buffer->extent[0];
(void)pointwise_size_dim_0;
int32_t pointwise_size_dim_1 = var_pointwise_buffer->extent[1];
(void)pointwise_size_dim_1;
int32_t pointwise_size_dim_2 = var_pointwise_buffer->extent[2];
(void)pointwise_size_dim_2;
int32_t pointwise_size_dim_3 = var_pointwise_buffer->extent[3];
(void)pointwise_size_dim_3;
int32_t var_pointwise_stride_0 = var_pointwise_buffer->stride[0];
(void)var_pointwise_stride_0;
int32_t var_pointwise_stride_1 = var_pointwise_buffer->stride[1];
(void)var_pointwise_stride_1;
int32_t var_pointwise_stride_2 = var_pointwise_buffer->stride[2];
(void)var_pointwise_stride_2;
int32_t var_pointwise_stride_3 = var_pointwise_buffer->stride[3];
(void)var_pointwise_stride_3;
int32_t var_pointwise_elem_size = var_pointwise_buffer->elem_size;
(void)var_pointwise_elem_size;
return pointwise_wrapped(var_input_buffer, var_pointwise_buffer, xclbin);
}
int pointwise_test(const char* xclbin, const int dims[4])
{
buffer_t input;
buffer_t pointwise;
memset(&input, 0, sizeof(buffer_t));
memset(&pointwise, 0, sizeof(buffer_t));
uint16_t* input_img = new uint16_t[dims[0]*dims[1]]();
uint16_t* pointwise_img = new uint16_t[dims[0]*dims[1]]();
input.extent[0] = dims[0];
input.extent[1] = dims[1];
input.stride[0] = 1;
input.stride[1] = dims[0];
input.elem_size = sizeof(uint16_t);
input.host = (uint8_t*)input_img;
pointwise.extent[0] = dims[0];
pointwise.extent[1] = dims[1];
pointwise.stride[0] = 1;
pointwise.stride[1] = dims[0];
pointwise.elem_size = sizeof(uint16_t);
pointwise.host = (uint8_t*)pointwise_img;
// initialization can be parallelized with -fopenmp
#pragma omp parallel for
for(int32_t q = 0; q<dims[1]; ++q)
{
for(int32_t p = 0; p<dims[0]; ++p)
{
input_img[p*input.stride[0]+q*input.stride[1]] = p+q;
}
}
pointwise(&input, &pointwise, xclbin);
int error_count = 0;
// produce pointwise, can be parallelized with -fopenmp
#pragma omp parallel for
for(int32_t q = 0; q<dims[1]-0; ++q)
{
for(int32_t p = 0; p<dims[0]-0; ++p)
{
// pointwise(0, 0) = (input(0, 0) + 1)
uint16_t result_pointwise = (input_img[(p+0)*input.stride[0]+(q+0)*input.stride[1]] + 1);
uint16_t val_fpga = pointwise_img[p*pointwise.stride[0]+q*pointwise.stride[1]];
uint16_t val_cpu = result_pointwise;
if(val_fpga!=val_cpu)
{
fprintf(*error_report, "%ld != %ld @(%d, %d)\n", int64_t(val_fpga), int64_t(val_cpu), p, q);
++error_count;
}
}
}
if(error_count==0)
{
fprintf(*error_report, "INFO: PASS!\n");
}
else
{
fprintf(*error_report, "INFO: FAIL!\n");
}
delete[] input_img;
delete[] pointwise_img;
return error_count;
}
|
//Author: Angelo Gonzales & Avery Vanausdal
//Assignment Number: Lab 3
//File Name: backwardsIterative
//Course/Selection: COSC 2436 Section 003
//Due Date: 10/11/18
//Instructor: Ku, Bernard
//Description: This program takes a text file name and runs that file
// through an iterative and recursive funtion to make a
// backwards text file. Times the time it takes for the
// functions to run and then do a comparison of the results
// to display to the user.
#include <iostream>
#include <iomanip>
#include <ctime>
#include "backwardsIterative.cpp"
#include "backwardsRecursive.cpp"
using namespace std;
void speedBackwardsRecursive(int);
void speedBackwardsIterative(int);
int main ()
{
int numTrials = 0;
cout << "Enter Integer of trials for backwards file: ";
cin >> numTrials;
speedBackwardsIterative(numTrials);
speedBackwardsRecursive(numTrials);
return 0;
}
void speedBackwardsRecursive(int trials)
{
ofstream outFile("bibleTrialOutput.txt", ios::binary | ios::trunc);
int sum = 0;
cout << "\n***Recursive Time***\n";
cout << fixed << showpoint << setprecision (5);
double start = double(clock()) / CLOCKS_PER_SEC; //starts timer
cout << "Start Recursive Time = " << setw(5) << start << " seconds" << endl; //displays start time
if (trials >0)
{
for (int i=1; i<=trials; i++)
{
backwardsRecursive("bible.txt"); //calls backwards Recursive and tests number of trials
// if (i == 2500 || i == 5000 || i == 7500 || i == 10000) outFile<<"Runs: "<<i<<"\tTime: "<<(double(clock()) / CLOCKS_PER_SEC) - start<<" seconds"<<endl;
}
//cout << "Fibonacci number is: " << fibonacciRecursive(num) << endl;
}
double finish = double(clock()) / CLOCKS_PER_SEC;
cout << "Finish Recursive Time: " << setw(5) << finish << " seconds" << endl; //displays total time from beginning of program to end of recursive fibonacii
double elapsed = (finish - start); //Takes final time - beginning time, to get time to complete all iterative trials
double average = (finish - start)/trials;//finds average time to complete each trial
cout << "Time Elapsed to do Recursive: " << setw(5) << elapsed << " seconds" << endl; //displays elapsed time
cout << "Average time to do Recursive trial " << trials << " times: " << setw(5) << average << " seconds" << endl; //displays average time
outFile.close();
}
void speedBackwardsIterative(int trials)
{
//int sum = 0;
// ofstream outFile("bibleTrialOutput.txt", ios::binary | ios::trunc);
cout << "\n***Iterative Time***\n";
cout << fixed << showpoint << setprecision (5);
double start = double(clock()) / CLOCKS_PER_SEC; //starts timer
cout << "Start Iterative Time = " << setw(5) << start << " seconds" << endl; //displays start time
if (trials>0)
{
for (int i=0; i<=trials; i++)
{
backwardsIterative(); //calls backwards iterative and tests number of trials
// if (i == 2500 || i == 5000 || i == 7500 || i == 10000) outFile<<"Runs: "<<i<<"\tTime: "<<(double(clock()) / CLOCKS_PER_SEC) - start<<" seconds"<<endl;
}
//cout << "Fibonacci number is: " << backwardsIterative(name) << endl;
}
double finish = double(clock()) / CLOCKS_PER_SEC;
cout << "Finish Iterative Time = " << setw(5) << finish << " seconds" << endl; //displays total time from beginning of program to end of iterative fibonacci
double elapsed = (finish - start); //Takes final time - beginning time to get time to complete all iterative trials
double average = (finish - start)/trials;//finds average time of total trial number
cout << "Time Elapsed to do Iterative: " << setw(5) << elapsed << " seconds" << endl; //displays elapsed time
cout << "Average time to do Itertive trial " << trials << " times: " << setw(5) << average << " seconds" << endl; //displays average
// outFile.close();
}
|
//
// 14.cpp
// REVIEW BAGUS
//
// Created by Mikha Yupikha on 16/10/2016.
// Copyright © 2016 Mikha Yupikha. All rights reserved.
//
#include <iostream>
using namespace std;
int main()
{
double initialBalance, total, monthlyCharge;
int noOfChecks;
cout<<"Please input your initial balance: ";
cin>>initialBalance;
cout<<"Please input the number of checks: ";
cin>>noOfChecks;
if (noOfChecks<0)
cout<<"Invalid. Number of check cannot be negative number.";
if (initialBalance<400)
monthlyCharge = initialBalance + 10 + 15;
else
monthlyCharge = initialBalance + 10;
// counting no of checks
if (noOfChecks<20)
{
total = monthlyCharge+0.1;
cout<<"Total service fees this month is $"<<total<<endl;
}
else if (noOfChecks>=20 && noOfChecks<40)
{
total = monthlyCharge+0.8;
cout<<"Total service fees this month is $"<<total<<endl;
}
else if (noOfChecks>=40 && noOfChecks<60)
{
total = monthlyCharge+0.6;
cout<<"Total sevice fees this month is $"<<total<<endl;
}
else
{
total = monthlyCharge+ 0.4;
cout<<"The total service fees this month is $"<<total<<endl;
}
return 0;
}
|
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QTimer>
#include <QPushButton>
#include "figure.h"
#include "star.h"
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
//int typeFigure; // Текущий тип фигуры
// перечисление типов
enum FigureTypes{
triangle,
square,
circle,
trapezoid,
pentagon,
dodecagon,
star
};
private:
void buttonPosition(); // Позиция кнопки на сцене
Ui::Widget *ui;
QGraphicsScene *scene; // Объявляем графическую сцену
QTimer *timer; /* Объявляем таймер, благодаря которому
* будет производиться изменения положения объекта на сцене
* При воздействии на него клавишами клавиатуры
* */
Figure *figure; // Рисуемый объект
Star *figureStar;// Рисуем звезду
QPushButton *StarButton;// Кнопка для создания треугольника
int curButStar; // Признак нажатия кнопки
private slots:
void slotAllDel(); // Удаление всех объектов со сцены перед добавлением нового
void DrawFigure(FigureTypes typeFigure);
void on_TriangleButton_clicked(); // Создание треугольника
void on_SquareButton_clicked(); // Создание квадрата
void on_CircleButton_clicked(); // Создание круга
void on_TrapezoidButton_clicked(); // Создание трапеции
void on_PentagonButton_clicked(); // Создание пятиугольника
void on_DodecagonButton_clicked(); // Создание двенадцатиугольника
void on_StarButton_clicked(); // Создание звезды
};
#endif // WIDGET_H
|
#ifndef UTL_BIT_WINDOW_H
#define UTL_BIT_WINDOW_H
#include "utl/bit.h"
#define BIT_WINDOW_EXP true
namespace utl {
template<class T = uint32_t>
struct bit_window {
bit_window() = default;
bit_window(T seqn) : high{seqn} {}
constexpr T latest() const
{
return high;
}
#if (BIT_WINDOW_EXP)
constexpr bool check(T seqn) const
{
if (seqn > high)
return true;
if (high - seqn - 1 >= bits)
return false;
return !get_bit(mask, high - seqn - 1);
}
#else
constexpr bool check(T seqn) const
{
if (seqn > high)
return true;
if (high - seqn >= bits)
return false;
return !get_bit(mask, high - seqn);
}
#endif
#if (BIT_WINDOW_EXP)
constexpr void update(T seqn)
{
if (seqn > high)
update_latest(seqn);
else if (high - seqn - 1 < bits)
set_bit(mask, high - seqn - 1);
}
#else
constexpr void update(T seqn)
{
if (seqn > high)
update_latest(seqn);
else if (high - seqn >= bits)
return;
else
set_bit(mask, high - seqn);
}
#endif
constexpr bool check_and_update(T seqn)
{
if (seqn > high) {
update_latest(seqn);
return true;
}
auto idx = high - seqn;
if (idx >= bits)
return false;
if (get_bit(mask, idx))
return false;
set_bit(mask, idx);
return true;
}
#if (BIT_WINDOW_EXP)
public:
constexpr void update_latest(T seqn)
{
auto diff = seqn - high;
mask = diff < bits ? mask << diff : 0;
high = seqn;
}
#else
private:
constexpr void update_latest(T seqn)
{
auto diff = seqn - high;
mask = 1 | (diff < bits ? mask << diff : 0);
high = seqn;
}
#endif
#if (BIT_WINDOW_EXP)
public:
T mask = -1;
T high = 0;
#else
private:
T mask = -2;
T high = 0;
#endif
static constexpr T bits = sizeof(T) * 8;
static constexpr T edge = -bits;
};
}
#endif
|
/**
* Copyright (c) 2021, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include "base/humanize.network.hh"
#include "config.h"
#include "doctest/doctest.h"
TEST_CASE("humanize::network::path")
{
{
auto rp_opt = humanize::network::path::from_str(
string_fragment::from_const("foobar"));
CHECK(!rp_opt);
}
{
auto rp_opt = humanize::network::path::from_str(
string_fragment::from_const("dean@foobar/bar"));
CHECK(!rp_opt);
}
{
auto rp_opt = humanize::network::path::from_str(
string_fragment::from_const("dean@host1.example.com:/var/log"));
CHECK(rp_opt.has_value());
auto rp = *rp_opt;
CHECK(rp.p_locality.l_username.has_value());
CHECK(rp.p_locality.l_username.value() == "dean");
CHECK(rp.p_locality.l_hostname == "host1.example.com");
CHECK(!rp.p_locality.l_service.has_value());
CHECK(rp.p_path == "/var/log");
}
{
auto rp_opt
= humanize::network::path::from_str(string_fragment::from_const(
"dean@[fe80::184f:c67:baf1:fe02%en0]:/var/log"));
CHECK(rp_opt.has_value());
auto rp = *rp_opt;
CHECK(rp.p_locality.l_username.has_value());
CHECK(rp.p_locality.l_username.value() == "dean");
CHECK(rp.p_locality.l_hostname == "fe80::184f:c67:baf1:fe02%en0");
CHECK(!rp.p_locality.l_service.has_value());
CHECK(rp.p_path == "/var/log");
CHECK(fmt::format("{}", rp.p_locality)
== "dean@[fe80::184f:c67:baf1:fe02%en0]");
}
{
auto rp_opt
= humanize::network::path::from_str(string_fragment::from_const(
"[fe80::184f:c67:baf1:fe02%en0]:/var/log"));
CHECK(rp_opt.has_value());
auto rp = *rp_opt;
CHECK(!rp.p_locality.l_username.has_value());
CHECK(rp.p_locality.l_hostname == "fe80::184f:c67:baf1:fe02%en0");
CHECK(!rp.p_locality.l_service.has_value());
CHECK(rp.p_path == "/var/log");
CHECK(fmt::format("{}", rp.p_locality)
== "[fe80::184f:c67:baf1:fe02%en0]");
}
{
auto rp_opt = humanize::network::path::from_str(
string_fragment::from_const("host1.example.com:/var/log"));
CHECK(rp_opt.has_value());
auto rp = *rp_opt;
CHECK(!rp.p_locality.l_username.has_value());
CHECK(rp.p_locality.l_hostname == "host1.example.com");
CHECK(!rp.p_locality.l_service.has_value());
CHECK(rp.p_path == "/var/log");
}
{
auto rp_opt = humanize::network::path::from_str(
string_fragment::from_const("host1.example.com:"));
CHECK(rp_opt.has_value());
auto rp = *rp_opt;
CHECK(!rp.p_locality.l_username.has_value());
CHECK(rp.p_locality.l_hostname == "host1.example.com");
CHECK(!rp.p_locality.l_service.has_value());
CHECK(rp.p_path == ".");
}
}
|
#include <SFML/Graphics.hpp>
#include <vector>
#include "GameObject.h"
#include "Player.h"
#include "Obstacle.h"
int main()
{
sf::RenderWindow window(sf::VideoMode(640, 480), "SFML works!");
sf::Texture playerTexture;
playerTexture.loadFromFile("player.png");
sf::Texture obsTexture;
obsTexture.loadFromFile("obstacle.png");
sf::Clock deltaTime;
std::vector<GameObject*> gameObjects;
gameObjects.push_back(new Player(playerTexture));
gameObjects.push_back(new Obstacle(obsTexture));
//main game loop
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
//check if we closed the game window
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
sf::Time currentDt = deltaTime.restart();
//this will update all gameobjects in vector
for (std::vector<GameObject*>::iterator it = gameObjects.begin(); it != gameObjects.end(); it++)
{
(*it)->update(currentDt);
(*it)->draw(window);
}
window.display();
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2005-2007 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Krefting
*/
#include "core/pch.h"
#include "modules/locale/locale_module.h"
#include "modules/locale/oplanguagemanager.h"
#ifdef LANGUAGE_FILE_SUPPORT
# include "modules/locale/src/opprefsfilelanguagemanager.h"
#endif
#ifdef LOCALE_BINARY_LANGUAGE_FILE
# include "modules/locale/src/opbinaryfilelanguagemanager.h"
#endif
#ifdef USE_DUMMY_LANGUAGEMANAGER
# include "modules/locale/src/opdummylanguagemanager.h"
#endif
#if defined LANGUAGE_FILE_SUPPORT || defined LOCALE_BINARY_LANGUAGE_FILE
# include "modules/prefs/prefsmanager/collections/pc_files.h"
#endif
void LocaleModule::InitL(const OperaInitInfo &)
{
// Initialize the localization support. If the implementation we are
// using is one of our own, we do the initialization here. If not,
// we let the platform layer set things up for us manually.
#ifndef LOCALE_SELFCONTAINED
// We need to have a language manager at this point. If your platform
// is using its own implementation, you will need to call
// g_opera->locale_module.SetLanguageManager() before calling
// g_opera->InitL().
OP_ASSERT(m_language_manager);
#elif defined LANGUAGE_FILE_SUPPORT
// Create the language manager and have it load the language file.
OpStackAutoPtr<OpPrefsFileLanguageManager>
new_language_manager(OP_NEW_L(OpPrefsFileLanguageManager, ()));
new_language_manager->LoadL();
# ifdef LANGUAGEMANAGER_CAN_RELOAD
g_pcfiles->RegisterFilesListenerL(new_language_manager.get());
# endif
m_language_manager = new_language_manager.release();
#elif defined LOCALE_BINARY_LANGUAGE_FILE
// Create the language manager and have it load the language file.
OpStackAutoPtr<OpFile> language_file(OP_NEW_L(OpFile, ()));
g_pcfiles->GetFileL(PrefsCollectionFiles::LanguageFile, *language_file.get());
OpStackAutoPtr<OpBinaryFileLanguageManager>
new_language_manager(OP_NEW_L(OpBinaryFileLanguageManager, ()));
new_language_manager->LoadTranslationL(language_file.get());
m_language_manager = new_language_manager.release();
#elif defined USE_DUMMY_LANGUAGEMANAGER
// Use a dummy language manager that will just return empty strings for
// everything.
m_language_manager = OP_NEW_L(OpDummyLanguageManager, ());
#endif
}
void LocaleModule::Destroy()
{
#ifdef LANGUAGEMANAGER_CAN_RELOAD
if (g_pcfiles)
g_pcfiles->UnregisterFilesListener(static_cast<OpPrefsFileLanguageManager *>(m_language_manager));
#endif
delete m_language_manager;
m_language_manager = NULL;
}
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
* !핵심은 두 가지!
* !1부터 N까지 모든 수는 중복 없는 정수!, 따라서 오름차순으로 넣으면 1부터 N까지 삽입!
* !stack의 top이 수열의 값보다 크면, 원하는 수열을 만들 수 없으므로(여러 번 pop해야 하므로) 불가!
* series_i = answer_i = 0 인덱스를 따로 설정.
* for(N만큼 반복) {
* now(현재 데이터 값)
* now를 stack에 push
* series와 stack.top이 같을 때 동안
* sries_i 증가
* (push와 pop 동작마다 answer에 1 0으로 기록한다.)
* stack은 pop
* }
* for 이후 stack이 비어있지 않으면 불가
* 비어있다면 answer 출력
*/
int main(void)
{
ios::sync_with_stdio(false);
cout.tie(NULL); cin.tie(NULL);
int n, temp, series_i;
vector<int> stack, series, answer;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> temp;
series.push_back(temp);
}
series_i = 0;
for (int i = 1; i <= n; i++)
{
stack.push_back(i);
answer.push_back(1);
while (!stack.empty() && stack.back() == series[series_i])
{
series_i++;
stack.pop_back();
answer.push_back(0);
}
if (!stack.empty() && stack.back() > series[series_i])
break;
}
if (stack.empty())
for (int i = 0; i < answer.size(); i++)
cout << (answer[i] ? '+' : '-') << '\n';
else
cout << "NO";
return 0;
}
|
//
// GnSimpleArray.h
// Core
//
// Created by Max Yoon on 11. 6. 17..
// Copyright 2011년 __MyCompanyName__. All rights reserved.
//
#ifndef __Core__GnTSimpleArray__
#define __Core__GnTSimpleArray__
template< class TAlloc, class DataType >
class GnTSimpleArray {
protected:
DataType* mpArray;
gtuint mAllocatedSize;
public:
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.