text
stringlengths 8
6.88M
|
|---|
#pragma once
#include <fstream>
#include <iostream>
#include "figure.hpp"
class Hexagon: public Figure {
private:
std::pair<double,double> center;
double side;
public:
Hexagon() = default;
Hexagon(std::pair<double, double> ¢er, double l) : center(center), side(l) {}
double Square() override {
return 1.5*sqrt(3)*side*side ;
}
void Print() override {
std::cout << *this;
}
void Write_to_file(std::ofstream& out) override {
out << *this << std::endl;
out << "Square: " << Square() << std::endl;
out << "Center: (" << this->center.first << "; " << this->center.second << ")" << std::endl << std::endl;
}
friend std::ostream &operator<<(std::ostream &out, Hexagon &rh);
};
std::ostream &operator<<(std::ostream &out, Hexagon &six) {
std::cout << "Hexagon Coords:"<<"(" << six.center.first + six.side*sin(0) << "," << six.center.second + six.side << ");" << std::endl;
std::cout << "(" << six.center.first + six.side*sin(2*3.14*1/6) << ","<< six.center.second + six.side*cos(2*3.14*1/6) << ");" << std::endl;
std::cout << "(" << six.center.first + six.side*sin(2*3.14*2/6) << ","<< six.center.second + six.side*cos(2*3.14*2/6) << ");" << std::endl;
std::cout << "(" << six.center.first + six.side*sin(2*3.14*3/6) << ","<< six.center.second + six.side*cos(2*3.14*3/6) << ");" << std::endl;
std::cout << "(" << six.center.first + six.side*sin(2*3.14*4/6) << ","<< six.center.second + six.side*cos(2*3.14*4/6) << ");" << std::endl;
std::cout << "(" << six.center.first + six.side*sin(2*3.14*5/6) << ","<< six.center.second + six.side*cos(2*3.14*5/6) << ");" << std::endl;
}
|
class Solution {
public:
vector<vector<int>> generate(int numRows) {
int i = 0;
vector<vector<int>> ret;
while(i < numRows) {
vector<int> element;
int j = 1;
element.push_back(1);
while(j < i) {
element.push_back(ret[i - 1][j - 1] + ret[i - 1][j]);
j++;
}
if(j == i) element.push_back(1);
ret.push_back(element);
i++;
}
return ret;
}
};
|
#ifndef __QUADNODO_H__
#define __QUADNODO_H__
#include <iostream>
#include <string>
#include <list>
template< class T >
class QuadNodo {
protected:
T dato;
QuadNodo<T>* hijoIzq;
QuadNodo<T>* hijoDer;
QuadNodo<T>* hijoExtrIzq;
QuadNodo<T>* hijoExtrDer;
public:
QuadNodo();
QuadNodo(T val);
~QuadNodo();
T obtenerDato();
void fijarDato(T val);
QuadNodo<T>* obtenerHijoIzq();
QuadNodo<T>* obtenerHijoDer();
QuadNodo<T>* obtenerHijoExtIzq();
QuadNodo<T>* obtenerhijoExtrDer();
void fijarHijoIzq(QuadNodo<T>* izq);
void fijarHijoDer(QuadNodo<T>* der);
void fijarHijoExtIzq(QuadNodo<T>* extIzq);
void fijarHijoExtDer(QuadNodo<T>* extDer);
bool esHoja();
int altura();
void inOrden();
void preOrden();
void posOrden();
};
#include "quadnodo.hxx"
#endif // __QUADNODO_H__
|
#pragma once
#include<bits/stdc++.h>
#include"HEAD.h"
using namespace std;
class Hotel
{
public:
friend class Data;
friend class Room;
public:
bool insert_room(const string &s);
bool delete_room(const int & n);
Hotel(const string & s,Data * d);
~Hotel();
const int & get_num() const;
const string & get_name() const;
const string & get_city() const;
const string & get_position() const;
const map<int, ptr_room> & get_room() const;
private:
bool insert_room(const ptr_room & tmp);
public:
map <int, ptr_room> room;
Data * data;
void Warning_no_such_room(int num);
bool Warning_the_same_number(int num);
int num;
string hotel;
string city;
string position;
};
inline bool operator < (const ptr_hotel & a, const ptr_hotel & b);
|
/***********************************************************************
created: Sun Jan 11 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/OpenGL/GL.h"
#include "CEGUI/RendererModules/OpenGL/GLFBOTextureTarget.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RendererModules/OpenGL/RendererBase.h"
#include "CEGUI/RendererModules/OpenGL/Texture.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float OpenGLFBOTextureTarget::DEFAULT_SIZE = 128.0f;
//----------------------------------------------------------------------------//
OpenGLFBOTextureTarget::OpenGLFBOTextureTarget(OpenGLRendererBase& owner, bool addStencilBuffer) :
OpenGLTextureTarget(owner, addStencilBuffer)
{
if (!GLEW_EXT_framebuffer_object)
throw InvalidRequestException("Hardware does not support FBO");
// no need to initialise d_previousFrameBuffer here, it will be
// initialised in activate()
initialiseRenderTexture();
// setup area and cause the initial texture to be generated.
OpenGLFBOTextureTarget::declareRenderSize(Sizef(DEFAULT_SIZE, DEFAULT_SIZE));
}
//----------------------------------------------------------------------------//
OpenGLFBOTextureTarget::~OpenGLFBOTextureTarget()
{
glDeleteFramebuffersEXT(1, &d_frameBuffer);
}
//----------------------------------------------------------------------------//
void OpenGLFBOTextureTarget::declareRenderSize(const Sizef& sz)
{
setArea(Rectf(d_area.getPosition(), d_owner.getAdjustedTextureSize(sz)));
resizeRenderTexture();
}
//----------------------------------------------------------------------------//
void OpenGLFBOTextureTarget::activate()
{
// remember previously bound FBO to make sure we set it back
// when deactivating
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT,
reinterpret_cast<GLint*>(&d_previousFrameBuffer));
// switch to rendering to the texture
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, d_frameBuffer);
OpenGLTextureTarget::activate();
}
//----------------------------------------------------------------------------//
void OpenGLFBOTextureTarget::deactivate()
{
OpenGLTextureTarget::deactivate();
// switch back to rendering to the previously bound framebuffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, d_previousFrameBuffer);
}
//----------------------------------------------------------------------------//
void OpenGLFBOTextureTarget::clear()
{
const Sizef sz(d_area.getSize());
// Some drivers crash when clearing a 0x0 RTT. This is a workaround for
// those cases.
if (sz.d_width < 1.0f || sz.d_height < 1.0f)
return;
// save old clear colour
GLfloat old_col[4];
glGetFloatv(GL_COLOR_CLEAR_VALUE, old_col);
// remember previously bound FBO to make sure we set it back
GLuint previousFBO = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT,
reinterpret_cast<GLint*>(&previousFBO));
// switch to our FBO
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, d_frameBuffer);
// Clear it.
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT);
// switch back to rendering to the previously bound FBO
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, previousFBO);
// restore previous clear colour
glClearColor(old_col[0], old_col[1], old_col[2], old_col[3]);
}
//----------------------------------------------------------------------------//
void OpenGLFBOTextureTarget::initialiseRenderTexture()
{
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// create FBO
glGenFramebuffersEXT(1, &d_frameBuffer);
// remember previously bound FBO to make sure we set it back
GLuint previousFBO = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT,
reinterpret_cast<GLint*>(&previousFBO));
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, d_frameBuffer);
// set up the texture the FBO will draw to
glGenTextures(1, &d_texture);
glBindTexture(GL_TEXTURE_2D, d_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
static_cast<GLsizei>(DEFAULT_SIZE),
static_cast<GLsizei>(DEFAULT_SIZE),
0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
GL_TEXTURE_2D, d_texture, 0);
// TODO: Check for completeness and then maybe try some alternative stuff?
// switch from our frame buffer back to the previously bound buffer.
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, previousFBO);
// ensure the CEGUI::Texture is wrapping the gl texture and has correct size
d_CEGUITexture->setOpenGLTexture(d_texture, d_area.getSize());
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLFBOTextureTarget::resizeRenderTexture()
{
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// Some drivers (hint: Intel) segfault when glTexImage2D is called with
// any of the dimensions being 0. The downside of this workaround is very
// small. We waste a tiny bit of VRAM on cards with sane drivers and
// prevent insane drivers from crashing CEGUI.
Sizef sz(d_area.getSize());
if (sz.d_width < 1.0f || sz.d_height < 1.0f)
{
sz.d_width = 1.0f;
sz.d_height = 1.0f;
}
// set the texture to the required size
glBindTexture(GL_TEXTURE_2D, d_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
static_cast<GLsizei>(sz.d_width),
static_cast<GLsizei>(sz.d_height),
0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
clear();
// ensure the CEGUI::Texture is wrapping the gl texture and has correct size
d_CEGUITexture->setOpenGLTexture(d_texture, sz);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLFBOTextureTarget::grabTexture()
{
glDeleteFramebuffersEXT(1, &d_frameBuffer);
d_frameBuffer = 0;
OpenGLTextureTarget::grabTexture();
}
//----------------------------------------------------------------------------//
void OpenGLFBOTextureTarget::restoreTexture()
{
OpenGLTextureTarget::restoreTexture();
initialiseRenderTexture();
resizeRenderTexture();
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
|
#ifndef __SCRIPT_PRAGMAS__
#define __SCRIPT_PRAGMAS__
#include "Common.h"
#include "Entity.h"
#include "angelscript.h"
#include "preprocessor.h"
#include <set>
#include <string>
#define PRAGMA_UNKNOWN ( 0 )
#define PRAGMA_SERVER ( 1 )
#define PRAGMA_CLIENT ( 2 )
#define PRAGMA_MAPPER ( 3 )
class PropertyRegistrator;
class IgnorePragma; // just delete
class GlobalVarPragma; // just delete
class EntityPragma; // class NewEntity { [Protected] uint Field1; }
class PropertyPragma; // extend class Critter { [Protected] uint LockerId; }
class ContentPragma; // improve dynamic scan
class EnumPragma; // extend enum MyEnum { NewA, NewB }
class EventPragma; // [Event] void MyEvent(...)
class RpcPragma; // [ServerRpc] void MyRpc(...)
// add [Export] to allow access from other modules
// ???
typedef vector< Preprocessor::PragmaInstance > Pragmas;
class ScriptPragmaCallback: public Preprocessor::PragmaCallback
{
private:
int pragmaType;
Pragmas processedPragmas;
bool isError;
IgnorePragma* ignorePragma;
GlobalVarPragma* globalVarPragma;
EntityPragma* entityPragma;
PropertyPragma* propertyPragma;
ContentPragma* contentPragma;
EnumPragma* enumPragma;
EventPragma* eventPragma;
RpcPragma* rpcPragma;
public:
ScriptPragmaCallback( int pragma_type );
~ScriptPragmaCallback();
virtual void CallPragma( const Preprocessor::PragmaInstance& pragma );
const Pragmas& GetProcessedPragmas();
void Finish();
bool IsError();
PropertyRegistrator** GetPropertyRegistrators();
StrVec GetCustomEntityTypes();
#if defined ( FONLINE_SERVER ) || defined ( FONLINE_EDITOR )
bool RestoreCustomEntity( const string& class_name, uint id, const DataBase::Document& doc );
#endif
void* FindInternalEvent( const string& event_name );
bool RaiseInternalEvent( void* event_ptr, va_list args );
const IntVec& GetInternalEventArgInfos( void* event_ptr );
void RemoveEventsEntity( Entity* entity );
void HandleRpc( void* context );
};
#endif // __SCRIPT_PRAGMAS__
|
/*************************************************************
* > File Name : P1525.cpp
* > Author : Tony
* > Created Time : 2019/08/09 15:52:04
* > Algorithm : UFS
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 20010;
struct Node {
int x, y, z;
}f[100010];
int n, m, ufs[maxn], b[maxn];
bool cmp(Node a, Node b) {
return a.z > b.z;
}
int find(int x) {
if (ufs[x] == x) return x;
return ufs[x] = find(ufs[x]);
}
void unionn(int x, int y) {
x = find(ufs[x]);
y = find(ufs[y]);
ufs[x] = y;
}
bool check(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return true;
return false;
}
int main() {
n = read(); m = read();
for (int i = 1; i <= n; ++i) ufs[i] = i;
for (int i = 1; i <= m; ++i) {
f[i].x = read();
f[i].y = read();
f[i].z = read();
}
sort(f + 1, f + 1 + m, cmp);
for (int i = 1; i <= m + 1; ++i) {
if (check(f[i].x, f[i].y)) {
printf("%d\n", f[i].z);
break;
} else {
if (!b[f[i].x]) b[f[i].x] = f[i].y;
else unionn(b[f[i].x], f[i].y);
if (!b[f[i].y]) b[f[i].y] = f[i].x;
else unionn(b[f[i].y], f[i].x);
}
}
return 0;
}
|
/*
** Copyright (c) 2016, Xin YUAN, courses of Zhejiang University
** All rights reserved.
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the 2-Clause BSD License.
**
** Author contact information:
** yxxinyuan@zju.edu.cn
**
*/
/*
This file contains global variables for WLang parser component.
*/
////////////////////////////////////////////////////////////////////////////////
#include "PreComp.h"
#include "_GkcParser.h"
#include "wlang/base/WlangDef.h"
#include "wlang/action/WlangGrammarError.h"
#include "wlang/action/WlangGrammarAccepted.h"
#include "wlang/action/WlangDoNsBodyAction.h"
#include "wlang/action/WlangDoBodySemiAction.h"
#include "wlang/WlangAction.h"
#include "wlang/WlangParser.h"
////////////////////////////////////////////////////////////////////////////////
namespace GKC {
////////////////////////////////////////////////////////////////////////////////
// WlangParser
BEGIN_COM_TYPECAST(WlangParser)
COM_TYPECAST_ENTRY(_IWlangParser, _IWlangParser)
END_COM_TYPECAST()
////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////
|
#pragma once
#include "../manager/EntityManager.h"
#include "../manager/LevelManager.h"
#include "../pathfinding/pathfinder.h"
namespace Task
{
class Action
{
protected:
Entity *entity, *target;
GridBool *grid;
bool result;
public:
std::string entityName, targetName;
static EntityManager* entityManager;
static LevelManager* levelManager;
void preRun();
virtual void init() {}
virtual bool run() = 0;
bool getResult();
};
}
|
#pragma once
#include "resource.h"
#include "tpScanTable.h"
// CAppViewerDlg dialog
#include "..\include\holdem\Common\SitHoldem.h"
#include <vector>
class CAppViewerDlg : public CDialogEx
{
DECLARE_DYNAMIC(CAppViewerDlg)
public:
CAppViewerDlg(CWnd* pParent = NULL); // standard constructor
virtual ~CAppViewerDlg();
// Dialog Data
enum { IDD = IDD_APPVIEWER_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnFileLoad();
afx_msg void OnFileSave32772();
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnBnClickedButton2();
afx_msg void OnBnClickedButton4();
afx_msg void OnBnClickedButton3();
afx_msg void OnBnClickedButton5();
afx_msg void OnViewcardsPlayer0();
afx_msg void OnViewcardsPlayer1();
afx_msg void OnViewcardsPlayer2();
afx_msg void OnViewcardsPlayer3();
afx_msg void OnViewcardsPlayer4();
afx_msg void OnViewcardsPlayer5();
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedCancel();
afx_msg void OnRegimView();
afx_msg void OnRegimPlay();
afx_msg void OnBnClickedBtnFold();
afx_msg void OnBnClickedBtnCall();
afx_msg void OnBnClickedBtnAllin();
afx_msg void OnBnClickedBtnRaise();
afx_msg void OnFileLoadstrat();
afx_msg void OnBnClickedButton1();
void DrawSit(CDC *dc);
void DrawPlayer(CDC *dc, int nb);
void BuildSit();
void ViewButtonTrade();
void DisabledButtonTrade();
void EnabledButtonView(bool val);
void ExecDecide(tpDis dis);
void StartPlay();
void Clear();
void BuildAndDraw(tpScanTable table);
bool NeedToSaveSit();
int _tag, _time;
clCol _col;
clSitHoldem _sit;
clListHistory _list;
CDC *_dcMainBuffer;
CBitmap *_bmpCards[CN_CARD_COL];
CBitmap *_bmpButton, *_bmpUndefCard;
std::vector <clGameHistory> _vectH;
int _reg, _nbCurHand, _nbCurAct;
bool _viewCards[CN_PLAYER];
clDoubleCP _curRes, _allRes;
tpSeat _seat[CN_PLAYER];
virtual BOOL OnInitDialog();
};
|
#include <iostream>
#include <ctime>
#include <Windows.h>
#include <string>
using namespace std;
class Time
{
public:
Time();
Time::Time(int h, int m, int s, clock_t St,int,int);
Time::Time(int);
~Time();
void goTime(clock_t start)
{
clock_t stop;
int i = getSec();
while (true)
{
stop = clock();
if ((int)((stop - start) / CLOCKS_PER_SEC) != i )
{
i++;
setSec(i);
clearRow(y+1);
Time::Print();
}
}
}
int getSec()
{
return sec;
}
int getMin()
{
return Min;
}
int getHour()
{
return hour;
}
void setSec( int s)
{
int i = s / 60;
sec = s - i * 60;
Min = i;
if (Min == 60)
{
hour += 1;
Min = 0;
}
if (hour == 24)
{
gotoxy(x, y + 1);
cout << "started a new day)";
hour = 0;
}
}
int TimeinSec()
{
currentTimeSec = (hour * 3600 + Min * 60 + sec);
return currentTimeSec;
}
void setXY(int X, int Y)
{
x = X;
y = Y;
}
void Print()
{
gotoxy(x, y);
cout << hour << ":" << Min << ":" << sec;
}
void gotoxy(int x, int y)
{
COORD coord; // coordinates
coord.X = x; coord.Y = y; // X and Y coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); // moves to the coordinates
}
void clearRow(int row)
{
// �������� ����� ���� �������
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
// �������� ���������� ������ ��� �������
COORD coord = { 0, row - 1 };
// �������� ������ �� ������ ������ �������
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hStdOut, &csbi);
// ��������� ������ ���������
FillConsoleOutputCharacter(hStdOut, ' ', 80, coord, NULL);
// ���������� ������� �������
SetConsoleCursorPosition(hStdOut, csbi.dwCursorPosition);
}
private:
int currentTimeSec;
int sec, hour, Min, x, y;
clock_t start, stop;
};
Time::Time() : hour(0), Min(0), sec(0),x(0),y(0) ,start(clock())
{
}
Time::Time(int h, int m, int s, clock_t St,int X,int Y)
{
h<24 ? hour = h : hour = 24;
if (m<60)
Min = m;
else
{
int s = m / 60;
Min = m - s * 60;
hour += s;
}
if (s<60)
sec = s;
else
{
int i = s / 60;
sec = s - i * 60;
Min += i;
}
start = St;
x = X;
y = Y;
}
Time::Time(int s) : hour(0), Min(0), sec(s), start(0), x(0), y(0)
{
}
Time::~Time()
{
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* whatever.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: eyohn <sopka13@mail.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/02 20:03:35 by eyohn #+# #+# */
/* Updated: 2021/08/03 01:12:30 by eyohn ### ########.fr */
/* */
/* ************************************************************************** */
#pragma once
#ifndef _WHATEVER_HPP_
#define _WHATEVER_HPP_
#include <iostream>
template <typename T>
void swap(T &first, T &second)
{
T temp;
temp = first;
first = second;
second = temp;
return ;
}
template <typename T>
void swap(T *first, T *second)
{
char *temp = new char[sizeof(T)];
// temp = first;
for (unsigned long i = 0; i < sizeof(T); ++i)
*(temp + i) = *(reinterpret_cast<char*>(first + i));
// first = second;
for (unsigned long i = 0; i < sizeof(T); ++i)
*(reinterpret_cast<char*>(first + i)) = *(reinterpret_cast<char*>(second + i));
// second = reinterpret_cast<T>temp;
for (unsigned long i = 0; i < sizeof(T); ++i)
*(reinterpret_cast<char*>(second + i)) = *(temp + i);
delete[] temp;
return ;
}
template <typename T>
T min(T first, T second)
{
if (first != second)
if (first < second)
return (first);
return (second);
}
template <typename T>
T max(T first, T second)
{
if (first != second)
if (first > second)
return (first);
return (second);
}
#endif
|
// This file is subject to the terms and conditions defined in 'LICENSE' included in the source code package
#include "gui/components.h"
#include <imgui.h>
#include "core/convert.h"
#include "game/input/mouse_selection.h"
#include "game/logistic/inventory.h"
#include "gui/colors.h"
#include "gui/context.h"
#include "gui/menu_data.h"
#include "proto/sprite.h"
using namespace jactorio;
// ======================================================================
gui::GuiMenu::~GuiMenu() {
ImGui::End();
}
void gui::GuiMenu::Begin(const char* name) const {
ImGui::Begin(name, nullptr, flags_);
}
// ======================================================================
void gui::GuiItemSlots::Begin(const std::size_t slot_count, const BeginCallbackT& callback) const {
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - kInventorySlotPadding);
const auto original_cursor_x = ImGui::GetCursorPosX();
float y_offset = ImGui::GetCursorPosY();
const float x_offset = ImGui::GetCursorPosX();
std::size_t index = 0;
while (index < slot_count) {
const uint16_t x = index % slotSpan;
ImGui::SameLine(x_offset + SafeCast<float>(x * scale * (kInventorySlotWidth + kInventorySlotPadding)));
ImGui::PushID(SafeCast<int>(index)); // Uniquely identifies the button
ImGui::SetCursorPosY(y_offset);
callback(index);
ImGui::PopID();
if (x == slotSpan - 1) {
y_offset += SafeCast<float>(scale) * (kInventorySlotWidth + kInventorySlotPadding);
}
++index;
}
// If final slot is drawn without a newline, add one
if (slot_count % slotSpan != 0) {
ImGui::SetCursorPosY(y_offset);
if (endingVerticalSpace < 0)
AddVerticalSpaceAbsolute(SafeCast<float>(scale) * (kInventorySlotWidth + kInventorySlotPadding));
else
AddVerticalSpaceAbsolute(endingVerticalSpace);
}
ImGui::SetCursorPosX(original_cursor_x); // Reset to original position for next widget
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + kInventorySlotPadding); // Allows consecutive begins to line up
}
void gui::GuiItemSlots::DrawSlot(const SpriteTexCoordIndexT tex_coord_id,
const uint16_t item_count,
const DrawSlotCallbackT& callback) const {
const float original_x_offset = ImGui::GetCursorPosX();
const float original_y_offset = ImGui::GetCursorPosY();
// Backing button sticks out on all sides
ImGui::SetCursorPos({original_x_offset - SafeCast<float>(kInventorySlotPadding / 2),
original_y_offset - SafeCast<float>(kInventorySlotPadding / 2)});
DrawBackingButton();
const bool backing_button_hover = ImGui::IsItemHovered();
callback(); // Register events with backing button
// Visible button, lower width such that a border is visible between slots
// Give visible button hover style if back is hovered
ImGuard guard;
if (backing_button_hover) {
guard.PushStyleColor(ImGuiCol_Button, kGuiColButtonHover);
}
ImGui::SetCursorPos({original_x_offset, original_y_offset});
if (tex_coord_id == 0) {
// Blank button
const auto button_width = SafeCast<float>(kInventorySlotWidth * scale);
const auto padding_width = kInventorySlotPadding * (scale - 1);
const auto total_width = button_width + padding_width;
const auto frame_padding = total_width / 2;
ImGui::ImageButton(nullptr, {0, 0}, {-1, -1}, {-1, -1}, frame_padding);
}
else {
const auto button_size = scale * kInventorySlotWidth +
(scale - 1) * kInventorySlotPadding // To align with other scales, account for the padding between slots
- 2 * kInventorySlotImagePadding;
const auto& menu_data = context_->menuData;
const auto& uv = menu_data.spritePositions[tex_coord_id];
ImGui::ImageButton(reinterpret_cast<void*>(menu_data.texId),
{SafeCast<float>(button_size), SafeCast<float>(button_size)},
{uv.topLeft.x, uv.topLeft.y},
{uv.bottomRight.x, uv.bottomRight.y},
kInventorySlotImagePadding);
}
// Total items count
if (item_count != 0) {
ImGui::SetCursorPos(
{original_x_offset + kInventoryItemCountXOffset, original_y_offset + kInventoryItemCountYOffset});
ImGui::Text("%d", item_count);
}
}
void gui::GuiItemSlots::DrawSlot(const SpriteTexCoordIndexT tex_coord_id, const DrawSlotCallbackT& callback) const {
DrawSlot(tex_coord_id, 0, callback);
}
void gui::GuiItemSlots::DrawSlot(const game::ItemStack& item_stack, const DrawSlotCallbackT& callback) const {
DrawSlot(item_stack.item.Get() == nullptr ? 0 : item_stack.item->sprite->texCoordId, item_stack.count, callback);
}
void gui::GuiItemSlots::DrawBackingButton() const {
ImGuard guard;
guard.PushStyleColor(ImGuiCol_Button, kGuiColNone);
guard.PushStyleColor(ImGuiCol_ButtonHovered, kGuiColNone);
guard.PushStyleColor(ImGuiCol_ButtonActive, kGuiColNone);
// kInventorySlotWidth not multiplied by 2 so that the backing button is tile-able
const auto width = SafeCast<float>((kInventorySlotWidth + kInventorySlotPadding) * this->scale);
const auto frame_padding = width / 2;
assert(frame_padding * 2 == width); // Slots will not line up if does not halve evenly
ImGui::ImageButton(nullptr, {0, 0}, {-1, -1}, {-1, -1}, frame_padding);
}
// ======================================================================
void gui::GuiTitle::Begin(const std::string& title, const CallbackT& callback) const {
AddVerticalSpaceAbsolute(topPadding);
ImGui::Text("%s", title.c_str());
callback();
AddVerticalSpaceAbsolute(bottomPadding);
}
void gui::DrawCursorTooltip(const bool has_selected_item,
const std::string& title,
const std::string& description,
const std::function<void()>& draw_func) {
ImVec2 cursor_pos(LossyCast<float>(game::MouseSelection::GetCursor().x),
LossyCast<float>(game::MouseSelection::GetCursor().y) + 10.f);
// If an item is currently selected, move the tooltip down to not overlap
if (has_selected_item)
cursor_pos.y += kInventorySlotWidth;
ImGui::SetNextWindowPos(cursor_pos);
ImGuiWindowFlags flags = 0;
flags |= ImGuiWindowFlags_NoCollapse;
flags |= ImGuiWindowFlags_NoResize;
flags |= ImGuiWindowFlags_NoInputs;
flags |= ImGuiWindowFlags_NoScrollbar;
flags |= ImGuiWindowFlags_AlwaysAutoResize;
// Draw tooltip
ImGuard guard;
guard.PushStyleColor(ImGuiCol_TitleBgActive, kGuiColTooltipTitleBg);
guard.PushStyleColor(ImGuiCol_TitleBg, kGuiColTooltipTitleBg);
const auto min_width =
ImGui::CalcTextSize(title.c_str()).x + GetTotalWindowPaddingX(); // Minimum width to fit the title
guard.PushStyleVar(ImGuiStyleVar_WindowMinSize, {min_width, 0});
{
ImGuard title_text_guard;
title_text_guard.PushStyleColor(ImGuiCol_Text, kGuiColTooltipTitleText);
guard.Begin(title.c_str(), nullptr, flags);
}
ImGui::TextUnformatted(description.c_str());
draw_func();
// This window is always in front
ImGui::SetWindowFocus(title.c_str());
}
|
/*
* File: MarkovChain.cpp
* Author: donerkebab
*
* Created on March 12, 2014, 5:11 AM
*/
#include "MarkovChain.h"
#include <cstdio>
#include <memory>
#include <queue>
#include <string>
#include "ChainFlushError.h"
#include "Point.h"
namespace Mcmc {
MarkovChain::MarkovChain(std::shared_ptr<Mcmc::Point> point,
std::string filename,
unsigned int buffer_size)
: filename_(filename),
buffer_size_(buffer_size),
num_points_flushed_(0)
{
if ( point.get() == nullptr ) {
throw std::invalid_argument("null point used to initialize chain");
}
if ( filename == "" ) {
throw std::invalid_argument("invalid filename");
}
if ( buffer_size == 0 ) {
throw std::invalid_argument("cannot have zero buffer size");
}
// Also check to see if there are any issues opening the output file
std::FILE* output_file = std::fopen(filename_.c_str(), "a");
if ( output_file == nullptr ) {
throw Mcmc::ChainFlushError();
} else {
std::fclose(output_file);
}
buffer_.push(point);
}
MarkovChain::~MarkovChain() {
// Need to flush all of the Point objects from the chain, including the
// last one. Save on coding complexity by adding a new dummy Point to
// the buffer, and then simply calling Flush().
buffer_.push(std::shared_ptr<Mcmc::Point>(
new Mcmc::Point(gsl_vector_alloc(1), gsl_vector_alloc(1), 0.)));
Flush();
}
std::string MarkovChain::filename() const {
return filename_;
}
unsigned int MarkovChain::buffer_size() const {
return buffer_size_;
}
unsigned int MarkovChain::num_points_buffered() const {
return buffer_.size();
}
unsigned int MarkovChain::num_points_flushed() const {
return num_points_flushed_;
}
unsigned int MarkovChain::length() const {
return buffer_.size() + num_points_flushed_;
}
std::shared_ptr<Mcmc::Point> MarkovChain::last_point() const {
return buffer_.back();
}
void MarkovChain::Append(std::shared_ptr<Mcmc::Point> point) {
if ( point.get() == nullptr ) {
throw std::invalid_argument("null point appended");
}
buffer_.push(point);
if ( buffer_.size() >= buffer_size_ ) {
Flush();
}
}
void MarkovChain::Flush() {
if ( buffer_.size() == 1 ) {
return;
}
std::FILE* output_file = std::fopen(filename_.c_str(), "a");
if ( output_file == nullptr ) {
throw Mcmc::ChainFlushError();
} else {
while ( buffer_.size() > 1 ) {
std::shared_ptr<Mcmc::Point> point = buffer_.front();
gsl_vector const* parameters = point->parameters();
for ( int i = 0; i < parameters->size; ++i ) {
std::fprintf(output_file, "%- 9.8E ",
gsl_vector_get(parameters, i));
}
std::fprintf(output_file, "\n");
gsl_vector const* measurements = point->measurements();
for ( int i = 0; i < measurements->size; ++i) {
std::fprintf(output_file, "%- 9.8E ",
gsl_vector_get(measurements, i));
}
std::fprintf(output_file, "\n");
std::fprintf(output_file, "%- 9.8E\n", point->likelihood());
std::fprintf(output_file, "\n");
buffer_.pop();
++num_points_flushed_;
}
std::fclose(output_file);
}
}
}
|
#include "PhysBody3D.h"
#include "glmath.h"
#include "Bullet/include/btBulletDynamicsCommon.h"
#include "ModulePhysics3D.h"
// =================================================
PhysBody3D::PhysBody3D(btRigidBody* body) : body(body)
{
body->setUserPointer(this);
}
// ---------------------------------------------------------
PhysBody3D::~PhysBody3D()
{
delete body;
}
// ---------------------------------------------------------
void PhysBody3D::Push(float x, float y, float z)
{
body->applyCentralImpulse(btVector3(x, y, z));
}
// ---------------------------------------------------------
void PhysBody3D::GetTransform(float* matrix) const
{
if(body != NULL && matrix != NULL)
{
body->getWorldTransform().getOpenGLMatrix(matrix);
}
}
// ---------------------------------------------------------
void PhysBody3D::SetTransform(const float* matrix) const
{
if(body != NULL && matrix != NULL)
{
btTransform t;
t.setFromOpenGLMatrix(matrix);
body->setWorldTransform(t);
}
}
// ---------------------------------------------------------
void PhysBody3D::SetPos(float x, float y, float z)
{
btTransform t = body->getWorldTransform();
t.setOrigin(btVector3(x, y, z));
body->setWorldTransform(t);
}
vec3 PhysBody3D::GetPos()
{
btTransform t = body->getWorldTransform();
btVector3 pos = t.getOrigin();
return { pos.getX(), pos.getY(), pos.getZ() };
}
btQuaternion PhysBody3D::GetRotation()
{
return body->getWorldTransform().getRotation();
}
|
#ifndef FOGCASESTATEMENT_HXX
#define FOGCASESTATEMENT_HXX
class FogCaseStatement : public FogStatement
{
typedef FogStatement Super;
typedef FogCaseStatement This;
TYPEDECL_SINGLE(This, Super)
FOGTOKEN_MEMBER_DECLS
FOGTOKEN_LEAF_DECLS
private:
FogExprRef _case; // nil for default case
FogRawRef _statement;
private:
This& mutate() const { return *(This *)this; }
protected:
FogCaseStatement(const This& aStatement);
virtual ~FogCaseStatement();
public:
FogCaseStatement(FogRaw& aStatement);
FogCaseStatement(FogExpr& anExpr, FogRaw& aStatement);
virtual size_t executable_tokens() const;
virtual FogRaw *is_case(FogScopeContext& scopeContext, const FogToken& theCase);
virtual std::ostream& print_depth(std::ostream& s, int aDepth) const;
virtual std::ostream& print_members(std::ostream& s, int aDepth) const;
};
#endif
|
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package
#ifndef JACTORIO_INCLUDE_PROTO_TRANSPORT_BELT_H
#define JACTORIO_INCLUDE_PROTO_TRANSPORT_BELT_H
#pragma once
#include "proto/abstract/conveyor.h"
namespace jactorio::proto
{
class TransportBelt final : public Conveyor
{
PROTOTYPE_CATEGORY(transport_belt);
};
} // namespace jactorio::proto
#endif // JACTORIO_INCLUDE_PROTO_TRANSPORT_BELT_H
|
#ifndef SINGLY_LINKED_LIST_H
#define SINGLY_LINKED_LIST_H
#include "Container.hpp"
/**
* A minimal singly-linked list with front insertion.
*
* @tparam U is the type of element stored in the list
*/
template<class U>
class SinglyLinkedList : public Container<U> {
struct node {
U data;
node *next;
};
unsigned listSize = 0;
node *root = nullptr;
void cleanup(node *t) {
if (!t)return;
cleanup(t->next);
delete t;
}
bool contains(U x, node *t) const {
if (!t) return false;
return t->data == x || contains(x, t->next);
}
node *insert(U x, node *t) {
listSize++;
node *head = new node;
head->data = x;
head->next = t;
return head;
}
node *remove(U x, node *t) {
if (!t) return t;
else if (t->data == x) {
listSize--;
return t->next;
}
t->next = remove(x, t->next);
return t;
}
public:
explicit SinglyLinkedList() {
}
~SinglyLinkedList() {
cleanup(root);
}
bool contains(U x) const override {
return contains(x, root);
}
bool insert(U x) override {
root = insert(x, root);
return true;
}
bool remove(U x) override {
unsigned prevSize = listSize;
root = remove(x, root);
return listSize != prevSize;
}
};
#endif
|
#ifndef _shpchunk_hpp
#define _shpchunk_hpp 1
#include "chunk.hpp"
#include "chnktype.hpp"
#include "mishchnk.hpp"
// shape flags
#define SHAPE_FLAG_PALETTISED 0x0000100
#define SHAPE_FLAG_USEZSP 0x0000200
#define SHAPE_FLAG_USEAUGZS 0x0000400
#define SHAPE_FLAG_USEAUGZSL 0x0000800
#define SHAPE_FLAG_EXTERNALFILE 0x0001000
#define SHAPE_FLAG_RECENTRED 0x0002000
#define SHAPE_FLAG_UNSTABLEBOUND_ZPOS 0x00004000
#define SHAPE_FLAG_UNSTABLEBOUND_ZNEG 0x00008000
#define SHAPE_FLAG_UNSTABLEBOUND_YPOS 0x00010000
#define SHAPE_FLAG_UNSTABLEBOUND_YNEG 0x00020000
#define SHAPE_FLAG_UNSTABLEBOUND_XPOS 0x00040000
#define SHAPE_FLAG_UNSTABLEBOUND_XNEG 0x00080000
#define SHAPE_FLAG_PSX_SUBDIVIDE 0x80000000
//flags that need to be removed before being copied into the shapeheaders
#define ChunkInternalItemFlags 0x00000000
class Object_Chunk;
class Shape_Header_Chunk;
class Anim_Shape_Frame_Chunk;
class Console_Shape_Chunk;
// flags structure
struct shape_flags
{
unsigned int locked : 1;
// add more flags here as they are needed
};
enum Console_Type
{
CT_PSX=0,
CT_Saturn=1,
// IMPORTANT
// since enums are not guaranteed to assume any particular
// storage class, code compiled on different compilers or
// with different settings may result in enums to be written
// to the data block as a char and read back in as an int,
// with the three most significant bytes containing junk.
// THIS MASK MUST BE KEPT UP TO DATE AS THE ENUM IS EXTENDED;
// ALSO ENSURE THAT NEW FILES LOADED INTO OLD SOFTWARE WILL
// NOT HAVE THEIR ENUM VALUE OVER-MASKED; THE MASK IS ONLY
// HERE TO ATTEMPT TO REMOVE PROBLEMS FROM FILES MADE
// PRIOR TO ITS INTRODUCTION
CT_MASK=0xff
};
// The shape chunk contains and handles all the interface data for the
// child chunks that it recognises in ChunkShape
/*--------------------------------------------------------------------**
** N.B. all changes to shape formats should be made to the sub shapes **
**--------------------------------------------------------------------*/
class Shape_Chunk : public Lockable_Chunk_With_Children
{
public:
// constructor from buffer
Shape_Chunk (Chunk_With_Children * parent, const char *, size_t);
// constructor from data (public so that other shape tools can call)
Shape_Chunk (Chunk_With_Children * parent, ChunkShape &shp_dat);
// I want the external file load to be as transparent as possible
// i.e. we have a shape which is loaded as usaul - it should then
// load the shape which is its main copy and copy itself over !!!
// Problems will be encountered with the texturing data though -
// but this stuff should onyl be worked with with a hardware
// accelerator - so that should solve many of the problems
// destructor
virtual ~Shape_Chunk();
const ChunkShape shape_data;
Shape_Header_Chunk * get_header();
Shape_Chunk* make_copy_of_chunk();
List<Object_Chunk *> const & list_assoc_objs();
BOOL assoc_with_object(Object_Chunk *);
BOOL deassoc_with_object(Object_Chunk *);
// destroy all auxiliary chunks
// that is all except the header and the chunkshape
void destroy_auxiliary_chunks();
// functions for the locking functionality
BOOL file_equals (HANDLE &);
const char * get_head_id();
void set_lock_user(char *);
virtual void post_input_processing();
Console_Shape_Chunk* get_console_shape_data(Console_Type);
BOOL inc_v_no();
BOOL same_and_updated(Shape_Chunk &);
BOOL assoc_with_object_list(File_Chunk *);
BOOL update_my_chunkshape (ChunkShape & cshp);
// THIS IS A HACK, DO NOT USE AFTER AVP AUGUST DEMO
BOOL has_door;
private:
friend class Object_Chunk;
friend class Shape_Vertex_Chunk;
friend class Shape_Vertex_Normal_Chunk;
friend class Shape_Polygon_Normal_Chunk;
friend class Shape_Polygon_Chunk;
friend class Shape_Texture_Filenames_Chunk;
friend class Shape_UV_Coord_Chunk;
friend class Shape_Header_Chunk;
friend class Shape_External_File_Chunk;
friend class RIF_File_Chunk;
friend class File_Chunk;
friend class Shape_Centre_Chunk;
ChunkShape * shape_data_store;
static int max_id; // for id checking
};
///////////////////////////////////////////////
class Shape_Sub_Shape_Header_Chunk;
class Shape_Sub_Shape_Chunk : public Chunk_With_Children
{
public:
// constructor from buffer
Shape_Sub_Shape_Chunk (Chunk_With_Children * parent, const char *, size_t);
// constructor from data (public so that other shape tools can call)
Shape_Sub_Shape_Chunk (Chunk_With_Children * parent, ChunkShape &shp_dat);
// destructor
virtual ~Shape_Sub_Shape_Chunk();
const ChunkShape shape_data;
Shape_Sub_Shape_Header_Chunk * get_header();
Shape_Sub_Shape_Chunk* make_copy_of_chunk();
BOOL update_my_chunkshape (ChunkShape & cshp);
const char * get_shape_name();
Console_Shape_Chunk* get_console_shape_data(Console_Type);
// Number stored for list_pos when loading
int list_pos_number;
private:
friend class Shape_Vertex_Chunk;
friend class Shape_Vertex_Normal_Chunk;
friend class Shape_Polygon_Normal_Chunk;
friend class Shape_Polygon_Chunk;
friend class Shape_Texture_Filenames_Chunk;
friend class Shape_UV_Coord_Chunk;
friend class Shape_Sub_Shape_Header_Chunk;
friend class Shape_Centre_Chunk;
ChunkShape * shape_data_store;
};
///////////////////////////////////////////////
class Shape_Sub_Shape_Header_Chunk : public Chunk
{
public:
// constructor from buffer
Shape_Sub_Shape_Header_Chunk (Shape_Sub_Shape_Chunk * parent, const char * pdata, size_t psize);
~Shape_Sub_Shape_Header_Chunk();
virtual size_t size_chunk ();
virtual void fill_data_block (char * data_start);
const ChunkShape * const shape_data;
int file_id_num;
int flags;
private:
friend class Shape_Sub_Shape_Chunk;
friend class Shape_Morphing_Frame_Data_Chunk;
// constructor from data
Shape_Sub_Shape_Header_Chunk (Shape_Sub_Shape_Chunk * parent)
: Chunk (parent, "SUBSHPHD"),
shape_data (parent->shape_data_store),
flags (0), file_id_num (-1)
{}
};
///////////////////////////////////////////////
#define AnimCentreFlag_CentreSetByUser 0x00000001 //centre should not be recalculated from the extents of the sequences
class Anim_Shape_Centre_Chunk : public Chunk
{
public:
Anim_Shape_Centre_Chunk(Chunk_With_Children* const parent,const char*,size_t const);
Anim_Shape_Centre_Chunk(Chunk_With_Children* const parent);
ChunkVectorInt Centre;
int flags;
int pad2;
virtual void fill_data_block(char* data_start);
virtual size_t size_chunk();
};
///////////////////////////////////////////////
class Anim_Shape_Sequence_Chunk :public Chunk_With_Children
{
public:
//if the first constructor is used then the vertex normals and extents won't be calculated
//unless the post_input_processing function is called
Anim_Shape_Sequence_Chunk(Chunk_With_Children* const parent,const char*,size_t const);
Anim_Shape_Sequence_Chunk(Chunk_With_Children* const parent,int sequencenum,const char* name);
Anim_Shape_Sequence_Chunk(Chunk_With_Children* const parent,ChunkAnimSequence const* cas);
virtual void post_input_processing();
const ChunkAnimSequence sequence_data;
void update_my_sequencedata (ChunkAnimSequence &);
void set_sequence_flags(int flags);
void set_frame_flags(int frameno,int flags);
void GenerateInterpolatedFrames();
private :
ChunkAnimSequence *sequence_data_store;
int ConstructSequenceDataFromChildren();//copies everyting into the sequence_data
void RegenerateChildChunks();
};
///////////////////////////////////////////////
class Anim_Shape_Sequence_Data_Chunk:public Chunk
{
public:
Anim_Shape_Sequence_Data_Chunk(Anim_Shape_Sequence_Chunk* const parent,const char*,size_t const);
Anim_Shape_Sequence_Data_Chunk(Anim_Shape_Sequence_Chunk* const parent,ChunkAnimSequence* cas);
private:
friend class Anim_Shape_Sequence_Chunk;
int SequenceNum;
int flags,pad2,pad3,pad4;
char* name;
virtual size_t size_chunk();
virtual void fill_data_block(char* data_start);
};
///////////////////////////////////////////////
class Anim_Shape_Frame_Chunk : public Chunk_With_Children
{
public:
Anim_Shape_Frame_Chunk(Anim_Shape_Sequence_Chunk* const parent,const char*,size_t const);
Anim_Shape_Frame_Chunk(Anim_Shape_Sequence_Chunk * const parent,ChunkAnimFrame* caf,int frameno);
};
///////////////////////////////////////////////
class Anim_Shape_Frame_Data_Chunk : public Chunk
{
public:
Anim_Shape_Frame_Data_Chunk(Anim_Shape_Frame_Chunk* const parent,const char*,size_t const);
Anim_Shape_Frame_Data_Chunk(Anim_Shape_Frame_Chunk* const parent,ChunkAnimFrame* caf,int frameno);
private:
friend class Anim_Shape_Frame_Chunk;
friend class Anim_Shape_Sequence_Chunk;
int FrameNum;
int flags,num_interp_frames,pad3,pad4;
char* name;//name of asc file for frame
virtual size_t size_chunk();
virtual void fill_data_block(char* data_start);
};
///////////////////////////////////////////////
class Anim_Shape_Alternate_Texturing_Chunk : public Chunk_With_Children
{
public :
Anim_Shape_Alternate_Texturing_Chunk(Chunk_With_Children* const parent,const char*,size_t const);
Anim_Shape_Alternate_Texturing_Chunk(Chunk_With_Children* const parent)
:Chunk_With_Children(parent,"ASALTTEX")
{}
Shape_Sub_Shape_Chunk* CreateNewSubShape(const char* name);
};
///////////////////////////////////////////////
class Poly_Not_In_Bounding_Box_Chunk : public Chunk
{
public :
Poly_Not_In_Bounding_Box_Chunk(Chunk_With_Children* const parent,const char*,size_t const);
Poly_Not_In_Bounding_Box_Chunk(Chunk_With_Children* const parent);
virtual size_t size_chunk();
virtual void fill_data_block(char* data_start);
List<int> poly_no;
int pad1,pad2;
};
///////////////////////////////////////////////
class Console_Type_Chunk: public Chunk
{
public :
Console_Type_Chunk(Chunk_With_Children* const parent,const char* data,size_t)
:Chunk(parent,"CONSTYPE"),console((Console_Type)(*(int*)data & CT_MASK))
{}
Console_Type_Chunk(Chunk_With_Children* const parent,Console_Type ct)
:Chunk(parent,"CONSTYPE"),console(ct)
{}
Console_Type console;
virtual size_t size_chunk()
{return chunk_size=16;}
virtual void fill_data_block(char * data_start);
};
///////////////////////////////////////////////
class Console_Shape_Chunk : public Chunk_With_Children
{
public :
Console_Shape_Chunk(Chunk_With_Children* const parent,const char*,size_t);
Console_Shape_Chunk(Chunk_With_Children* const parent,Console_Type ct);
const ChunkShape shape_data;
void generate_console_chunkshape();//needs parent's chunkshape to be set up first
void update_my_chunkshape(ChunkShape&);
private:
friend class Shape_Polygon_Chunk;
friend class Shape_UV_Coord_Chunk;
ChunkShape * shape_data_store;
};
///////////////////////////////////////////////
class Shape_Vertex_Chunk : public Chunk
{
public:
virtual size_t size_chunk ()
{
return (chunk_size = (12 + (num_verts*sizeof(ChunkVectorInt))));
}
virtual BOOL output_chunk (HANDLE &);
virtual void fill_data_block (char * data_start);
const ChunkVectorInt * const vert_data;
const int num_verts;
// constructor from buffer
Shape_Vertex_Chunk (Shape_Sub_Shape_Chunk * parent, const char * vtdata, size_t vtsize);
Shape_Vertex_Chunk (Shape_Chunk * parent, const char * vtdata, size_t vtsize);
Shape_Vertex_Chunk (Anim_Shape_Frame_Chunk * parent, const char * vtdata, size_t vtsize);
private:
friend class Shape_Chunk;
friend class Shape_Sub_Shape_Chunk;
friend class Anim_Shape_Frame_Chunk;
// constructor from data
Shape_Vertex_Chunk (Shape_Sub_Shape_Chunk * parent, int n_verts)
: Chunk (parent, "SHPRAWVT"),
vert_data (parent->shape_data_store->v_list), num_verts (n_verts)
{}
Shape_Vertex_Chunk (Shape_Chunk * parent, int n_verts)
: Chunk (parent, "SHPRAWVT"),
vert_data (parent->shape_data_store->v_list), num_verts (n_verts)
{}
Shape_Vertex_Chunk (Anim_Shape_Frame_Chunk * parent,ChunkVectorInt* v_list ,int n_verts)
: Chunk (parent, "SHPRAWVT"),
vert_data (v_list), num_verts (n_verts)
{}
};
///////////////////////////////////////////////
class Shape_Vertex_Normal_Chunk: public Chunk
{
public:
// constructor from buffer
Shape_Vertex_Normal_Chunk (Shape_Sub_Shape_Chunk * parent, const char * vtdata, size_t vtsize);
Shape_Vertex_Normal_Chunk (Shape_Chunk * parent, const char * vtdata, size_t vtsize);
virtual size_t size_chunk ()
{
return (chunk_size = (12 + (num_verts*sizeof(ChunkVectorFloat))));
}
virtual BOOL output_chunk (HANDLE &);
virtual void fill_data_block (char * data_start);
const ChunkVectorFloat * const vert_norm_data;
const int num_verts;
private:
friend class Shape_Chunk;
friend class Shape_Sub_Shape_Chunk;
// constructor from data
Shape_Vertex_Normal_Chunk (Shape_Sub_Shape_Chunk * parent, int n_verts)
: Chunk (parent, "SHPVNORM"),
vert_norm_data (parent->shape_data_store->v_normal_list), num_verts (n_verts)
{}
Shape_Vertex_Normal_Chunk (Shape_Chunk * parent, int n_verts)
: Chunk (parent, "SHPVNORM"),
vert_norm_data (parent->shape_data_store->v_normal_list), num_verts (n_verts)
{}
};
///////////////////////////////////////////////
class Shape_Polygon_Normal_Chunk: public Chunk
{
public:
// constructor from buffer
Shape_Polygon_Normal_Chunk (Shape_Sub_Shape_Chunk * parent, const char * pndata, size_t pnsize);
Shape_Polygon_Normal_Chunk (Shape_Chunk * parent, const char * pndata, size_t pnsize);
Shape_Polygon_Normal_Chunk (Anim_Shape_Frame_Chunk * parent, const char * pndata, size_t pnsize);
virtual size_t size_chunk ()
{
return (chunk_size = (12 + (num_polys*sizeof(ChunkVectorFloat))));
}
virtual BOOL output_chunk (HANDLE &);
virtual void fill_data_block (char * data_start);
const ChunkVectorFloat * const poly_norm_data;
const int num_polys;
private:
friend class Shape_Chunk;
friend class Shape_Sub_Shape_Chunk;
friend class Anim_Shape_Frame_Chunk;
// constructor from data
Shape_Polygon_Normal_Chunk (Shape_Sub_Shape_Chunk * parent, int n_polys)
: Chunk (parent, "SHPPNORM"),
poly_norm_data (parent->shape_data_store->p_normal_list), num_polys (n_polys)
{}
Shape_Polygon_Normal_Chunk (Shape_Chunk * parent, int n_polys)
: Chunk (parent, "SHPPNORM"),
poly_norm_data (parent->shape_data_store->p_normal_list), num_polys (n_polys)
{}
Shape_Polygon_Normal_Chunk (Anim_Shape_Frame_Chunk * parent,ChunkVectorFloat* p_normal_list ,int n_polys)
: Chunk (parent, "SHPPNORM"),
poly_norm_data (p_normal_list), num_polys (n_polys)
{}
};
///////////////////////////////////////////////
class Shape_Polygon_Chunk : public Chunk
{
public:
// constructor from buffer
Shape_Polygon_Chunk (Shape_Sub_Shape_Chunk * parent, const char * pdata, size_t psize);
Shape_Polygon_Chunk (Shape_Chunk * parent, const char * pdata, size_t psize);
Shape_Polygon_Chunk (Console_Shape_Chunk * parent, const char * pdata, size_t psize);
virtual size_t size_chunk ()
{
return (chunk_size = (12 + (num_polys*36)));// 36 bytes per vertex
}
virtual BOOL output_chunk (HANDLE &);
virtual void fill_data_block (char * data_start);
const ChunkPoly * const poly_data;
const int num_polys;
private:
friend class Shape_Chunk;
friend class Shape_Sub_Shape_Chunk;
friend class Console_Shape_Chunk;
// constructor from data
Shape_Polygon_Chunk (Shape_Sub_Shape_Chunk * parent, int n_polys)
: Chunk (parent, "SHPPOLYS"),
poly_data (parent->shape_data_store->poly_list), num_polys (n_polys)
{}
Shape_Polygon_Chunk (Shape_Chunk * parent, int n_polys)
: Chunk (parent, "SHPPOLYS"),
poly_data (parent->shape_data_store->poly_list), num_polys (n_polys)
{}
Shape_Polygon_Chunk (Console_Shape_Chunk * parent, int n_polys)
: Chunk (parent, "SHPPOLYS"),
poly_data (parent->shape_data_store->poly_list), num_polys (n_polys)
{}
};
///////////////////////////////////////////////
class Shape_Header_Chunk : public Chunk
{
public:
// constructor from buffer
Shape_Header_Chunk (Shape_Chunk * parent, const char * pdata, size_t psize);
~Shape_Header_Chunk();
virtual size_t size_chunk ();
virtual BOOL output_chunk (HANDLE &);
virtual void fill_data_block (char * data_start);
const ChunkShape * const shape_data;
virtual void prepare_for_output();
char lock_user[17];
List<char *> object_names_store;
int flags;
private:
friend class Shape_Chunk;
friend class Object_Chunk;
friend class RIF_File_Chunk;
friend class File_Chunk;
friend class Environment;
friend class Shape_Morphing_Frame_Data_Chunk;
friend class Shape_External_File_Chunk;
int version_no;
int file_id_num;
List<Object_Chunk *> associated_objects_store;
// constructor from data
Shape_Header_Chunk (Shape_Chunk * parent)
: Chunk (parent, "SHPHEAD1"),
shape_data (parent->shape_data_store),
flags (0), file_id_num (-1), version_no (0)
{}
};
///////////////////////////////////////////////
class Shape_Centre_Chunk : public Chunk
{
public :
// constructor from buffer
Shape_Centre_Chunk (Chunk_With_Children * parent, const char * data, size_t datasize);
virtual size_t size_chunk ()
{return chunk_size=4*4+12;}
virtual void fill_data_block (char * data_start);
private:
friend class Shape_Chunk;
friend class Shape_Sub_Shape_Chunk;
// constructor from data
Shape_Centre_Chunk (Chunk_With_Children * parent)
: Chunk (parent, "SHPCENTR")
{}
//the data for this chunk is stored in its parent's ChunkShape
};
///////////////////////////////////////////////
class Shape_UV_Coord_Chunk : public Chunk
{
public:
// constructor from buffer
Shape_UV_Coord_Chunk (Shape_Sub_Shape_Chunk * parent, const char * uvdata, size_t uvsize);
Shape_UV_Coord_Chunk (Shape_Chunk * parent, const char * uvdata, size_t uvsize);
Shape_UV_Coord_Chunk (Console_Shape_Chunk * parent, const char * uvdata, size_t uvsize);
virtual size_t size_chunk ();
virtual BOOL output_chunk (HANDLE &);
virtual void fill_data_block (char * data_start);
const ChunkUV_List * const uv_data;
const int num_uvs;
private:
friend class Shape_Chunk;
friend class Shape_Sub_Shape_Chunk;
friend class Console_Shape_Chunk;
// constructor from data
Shape_UV_Coord_Chunk (Shape_Sub_Shape_Chunk * parent, int n_uvs)
: Chunk (parent, "SHPUVCRD"),
uv_data (parent->shape_data_store->uv_list), num_uvs (n_uvs)
{}
Shape_UV_Coord_Chunk (Shape_Chunk * parent, int n_uvs)
: Chunk (parent, "SHPUVCRD"),
uv_data (parent->shape_data_store->uv_list), num_uvs (n_uvs)
{}
Shape_UV_Coord_Chunk (Console_Shape_Chunk * parent, int n_uvs)
: Chunk (parent, "SHPUVCRD"),
uv_data (parent->shape_data_store->uv_list), num_uvs (n_uvs)
{}
};
///////////////////////////////////////////////
class Shape_Texture_Filenames_Chunk : public Chunk
{
public:
// constructor from buffer
Shape_Texture_Filenames_Chunk (Shape_Sub_Shape_Chunk * parent, const char * tfndata, size_t tfnsize);
Shape_Texture_Filenames_Chunk (Shape_Chunk * parent, const char * tfndata, size_t tfnsize);
virtual size_t size_chunk ();
virtual BOOL output_chunk (HANDLE &);
virtual void fill_data_block (char * data_start);
char ** tex_fns;
const int num_tex_fns;
private:
friend class Shape_Chunk;
friend class Shape_Sub_Shape_Chunk;
// constructor from data
Shape_Texture_Filenames_Chunk (Shape_Sub_Shape_Chunk * parent, int n_tfns)
: Chunk (parent, "SHPTEXFN"),
tex_fns (parent->shape_data_store->texture_fns), num_tex_fns (n_tfns)
{}
Shape_Texture_Filenames_Chunk (Shape_Chunk * parent, int n_tfns)
: Chunk (parent, "SHPTEXFN"),
tex_fns (parent->shape_data_store->texture_fns), num_tex_fns (n_tfns)
{}
};
///////////////////////////////////////////////
class Shape_Merge_Data_Chunk : public Chunk
{
public:
Shape_Merge_Data_Chunk (Shape_Sub_Shape_Chunk * parent, int *, int);
Shape_Merge_Data_Chunk (Shape_Chunk * parent, int *, int);
~Shape_Merge_Data_Chunk ();
int * merge_data;
int num_polys;
size_t size_chunk()
{
return chunk_size = 12 + num_polys*4;
}
void fill_data_block (char *);
Shape_Merge_Data_Chunk (Shape_Sub_Shape_Chunk * parent, const char *, size_t);
Shape_Merge_Data_Chunk (Shape_Chunk * parent, const char *, size_t);
};
///////////////////////////////////////////////
class Shape_External_File_Chunk : public Chunk_With_Children
{
public:
Shape_External_File_Chunk (Chunk_With_Children * parent, const char * fname);
Shape_External_File_Chunk (Chunk_With_Children * const parent, const char *, size_t const);
void post_input_processing();
#if cencon || InterfaceEngine
void update_from_external_rif(BOOL force_scale_update);
#endif
//gets name from shape_external_object_name_chunk if it has one
//otherwise takes name from rif_name_chunk
const char * get_shape_name();
private:
friend class Shape_Chunk;
friend class Shape_Sub_Shape_Chunk;
//Used to avoid updating external shapes in files that have been loaded
//by Shape_External_File_Chunk::post_input_processing
static BOOL UpdatingExternalShape;
};
///////////////////////////////////////////////
class Shape_External_Filename_Chunk : public Chunk
{
public:
Shape_External_Filename_Chunk (Chunk_With_Children * parent, const char * fname);
Shape_External_Filename_Chunk (Chunk_With_Children * parent, const char *, size_t);
~Shape_External_Filename_Chunk ();
// Here is stored the shape name, rescale value and version number.
char * file_name;
double rescale;
int version_no;
size_t size_chunk()
{
return chunk_size = 12 + 8 + 4 + strlen(file_name) + (4-strlen(file_name)%4);
}
void fill_data_block (char *);
private:
friend class Shape_External_File_Chunk;
friend class Sprite_Header_Chunk;
};
///////////////////////////////////////////////
//This is needed if more than one shape is being imported from a rif file
class Shape_External_Object_Name_Chunk : public Chunk
{
public :
Shape_External_Object_Name_Chunk(Chunk_With_Children * parent, const char * fname);
Shape_External_Object_Name_Chunk (Chunk_With_Children * parent, const char *, size_t);
~Shape_External_Object_Name_Chunk();
int pad;
char* object_name;
char* shape_name; //a combination of object and file name
size_t size_chunk()
{
return chunk_size = 12 +4+ strlen(object_name) + (4-strlen(object_name)%4);
}
void post_input_processing();
void fill_data_block (char *);
private:
friend class Shape_External_File_Chunk;
};
///////////////////////////////////////////////
class Shape_Morphing_Data_Chunk : public Chunk_With_Children
{
public:
Shape_Morphing_Data_Chunk (Shape_Chunk * parent)
: Chunk_With_Children (parent, "SHPMORPH"), parent_shape (parent) {}
Shape_Chunk * parent_shape;
Shape_Sub_Shape_Chunk * parent_sub_shape;
virtual void prepare_for_output();
Shape_Morphing_Data_Chunk (Shape_Chunk * parent, const char *, size_t);
Shape_Morphing_Data_Chunk (Shape_Sub_Shape_Chunk * parent, const char *, size_t);
};
///////////////////////////////////////////////
class Shape_Morphing_Frame_Data_Chunk : public Chunk
{
public:
// constructor from wherever
Shape_Morphing_Frame_Data_Chunk (Shape_Morphing_Data_Chunk * parent)
: Chunk (parent, "FRMMORPH"), frame_store (0), num_frames(0)
{}
// constructor from buffer
Shape_Morphing_Frame_Data_Chunk (Shape_Morphing_Data_Chunk * parent,const char *, size_t);
~Shape_Morphing_Frame_Data_Chunk();
int a_flags;
int a_speed;
List<a_frame *> anim_frames;
virtual void fill_data_block (char *);
virtual size_t size_chunk ()
{
return (chunk_size = 12 + 12 + num_frames * 12);
}
virtual void prepare_for_output();
virtual void post_input_processing();
private:
int num_frames;
int * frame_store;
friend class Shape_Morphing_Data_Chunk;
};
///////////////////////////////////////////////
class Shape_Poly_Change_Info_Chunk : public Chunk
{
public:
Shape_Poly_Change_Info_Chunk (Shape_Chunk * parent, List<poly_change_info> & pci, int orig_num_v)
: Chunk (parent, "SHPPCINF"), change_list (pci), original_num_verts (orig_num_v)
{}
int original_num_verts;
List<poly_change_info> change_list;
virtual void fill_data_block (char *);
virtual size_t size_chunk ()
{
return (chunk_size = 12 + 4 + 4 + change_list.size() * 12);
}
Shape_Poly_Change_Info_Chunk (Chunk_With_Children * parent,const char *, size_t);
};
///////////////////////////////////////////////
class Shape_Name_Chunk : public Chunk
{
public:
Shape_Name_Chunk (Chunk_With_Children * parent, const char * rname);
// constructor from buffer
Shape_Name_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize);
~Shape_Name_Chunk();
char * shape_name;
virtual size_t size_chunk ()
{
return (chunk_size = 12 + strlen (shape_name) + 4 - strlen (shape_name)%4);
}
virtual void fill_data_block (char * data_start);
private:
friend class Shape_Sub_Shape_Chunk;
};
///////////////////////////////////////////////
class Shape_Fragments_Chunk : public Chunk_With_Children
{
public:
Shape_Fragments_Chunk (Chunk_With_Children * parent)
: Chunk_With_Children (parent, "SHPFRAGS")
{}
Shape_Fragments_Chunk (Chunk_With_Children * const parent, char const *, const size_t);
};
///////////////////////////////////////////////
class Shape_Fragment_Type_Chunk : public Chunk
{
public :
Shape_Fragment_Type_Chunk(Chunk_With_Children* parent,const char* name);
Shape_Fragment_Type_Chunk (Chunk_With_Children * const parent,const char *, size_t const);
~Shape_Fragment_Type_Chunk();
size_t size_chunk ();
void fill_data_block (char * data_start);
char* frag_type_name;
int pad1,pad2;
};
///////////////////////////////////////////////
class Shape_Fragments_Data_Chunk : public Chunk
{
public:
Shape_Fragments_Data_Chunk (Chunk_With_Children * parent, int num_frags)
: Chunk (parent, "FRAGDATA"), num_fragments (num_frags),
pad1(0), pad2(0), pad3(0)
{}
Shape_Fragments_Data_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize);
int num_fragments;
int pad1, pad2, pad3;
virtual size_t size_chunk ()
{
return (chunk_size = 12 + 16);
}
virtual void fill_data_block (char *);
private:
friend class Shape_Sub_Shape_Chunk;
};
///////////////////////////////////////////////
class Shape_Fragment_Location_Chunk : public Chunk
{
public:
Shape_Fragment_Location_Chunk (Chunk_With_Children * parent, ChunkVectorInt & location)
: Chunk (parent, "FRAGLOCN"), frag_loc (location),
pad1(0), pad2(0), pad3(0), pad4(0)
{}
Shape_Fragment_Location_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize);
ChunkVectorInt frag_loc;
int pad1, pad2, pad3, pad4;
virtual size_t size_chunk ()
{
return (chunk_size = 12 + 28);
}
virtual void fill_data_block (char *);
private:
friend class Shape_Sub_Shape_Chunk;
};
///////////////////////////////////////////////
class Shape_Preprocessed_Data_Chunk : public Chunk
{
public:
Shape_Preprocessed_Data_Chunk (Chunk_With_Children * parent,int _blocksize,int _first_pointer,unsigned int* _memory_block);
Shape_Preprocessed_Data_Chunk (Chunk_With_Children * parent, const char * data, size_t ssize);
~Shape_Preprocessed_Data_Chunk ()
{
if(extra_data) delete extra_data;
if(memory_block) delete memory_block;
}
virtual size_t size_chunk ()
{
return (chunk_size = 12 + 12+block_size*4+num_extra_data*4);
}
virtual void fill_data_block (char *);
int num_extra_data;
int* extra_data;
void* GetMemoryBlock();
private:
int block_size;
int first_pointer;
unsigned int* memory_block;
friend class Shape_Chunk;
friend class Shape_Sub_Shape_Chunk;
};
#endif
|
//
// Created by vybirto1 on 16.3.18.
//
#include "CException.h"
|
#include "genetics.h"
const double Neuron::ACTIVATION_RESPONSE = 1.0;
|
// Copyright (c) 2014-2019 winking324
//
#include "view/video_widget.h"
namespace avc {
VideoWidget::VideoWidget(QWidget *parent)
: QWidget(parent) {
}
int VideoWidget::SetViewProperties(int zOrder, float left, float top, float right, float bottom)
{
}
int VideoWidget::DeliverFrame(const agora::media::IVideoFrame &videoFrame, int rotation, bool mirrored)
{
}
void VideoWidget::OnRenderFrame()
{
}
void VideoWidget::OnCleanup()
{
}
void VideoWidget::paintEvent(QPaintEvent *event)
{
}
} // namespace avc
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tmatis <tmatis@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/21 15:25:50 by tmatis #+# #+# */
/* Updated: 2021/08/21 17:47:13 by tmatis ### ########.fr */
/* */
/* ************************************************************************** */
#include "PresidentialPardonForm.hpp"
#include "RobotomyRequestForm.hpp"
#include "ShrubberyCreationForm.hpp"
#include "Intern.hpp"
#include <stdlib.h>
int main(void)
{
Intern intern;
Form *form;
Bureaucrat bob("Bob", 1);
form = intern.makeForm("robotomy request", "Bender");
bob.signForm(*form);
bob.executeForm(*form);
delete form;
form = intern.makeForm("presidential pardon", "Benala");
bob.signForm(*form);
bob.executeForm(*form);
delete form;
form = intern.makeForm("shrubbery creation", "House");
bob.signForm(*form);
bob.executeForm(*form);
delete form;
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _STEADYSTATERUNNER_HPP_
#define _STEADYSTATERUNNER_HPP_
#ifdef CHASTE_CVODE
#include "AbstractSteadyStateRunner.hpp"
#include "VectorHelperFunctions.hpp"
/**
* This class is to get a cell model to (approximately) steady state.
*
* It does it by simply pacing and looking for a small change in the norm of the
* state variables between subsequent paces.
*
* Note - because it looks for a small change in state variables between solves
* this method requires quite an accurate CVODE solution to do this efficiently
* (otherwise you just have to wait to get lucky on subsequent solves).
*
* So although running with stricter tolerances takes longer per pace
* it can mean you detect a steady state in up to 3x fewer paces, so it is
* recommended to use a model with SetTolerances(1e-6, 1e-8); or stricter.
*/
class SteadyStateRunner: public AbstractSteadyStateRunner
{
private:
/** whether we should do two paces at once (should detect steady alternans as well as single paces) */
bool mTwoPaceScan;
protected:
/**
* Run the cell model to steady state
*
* Here we don't do anything clever - we just gradually drift to the steady state,
* defined by < 1e-6 change in the norm of state variables between 1 (or 2 - see #mTwoPaceScan) beats.
*/
virtual void RunToSteadyStateImplementation();
public:
/**
* Constructor of a helper class for getting action potential models to steady state
*
* @param pModel The cell model to run to steady state.
* @param twoPaces Whether to run two paces at once, for detection of steady state alternans.
*/
SteadyStateRunner(boost::shared_ptr<AbstractCvodeCell> pModel, bool twoPaces=false)
: AbstractSteadyStateRunner(pModel),
mTwoPaceScan(twoPaces)
{};
};
#endif // CHASTE_CVODE
#endif // _STEADYSTATERUNNER_HPP_
|
#ifndef WIZAPI_H
#define WIZAPI_H
#include "wizdef.h"
#include "wizXmlRpcServer.h"
#include "wizobject.h"
#include "wizDatabase.h"
#define WIZ_API_VERSION "3"
#define WIZ_API_URL "http://service.wiz.cn/wizkm/xmlrpc"
#define WIZAPI_TRUNK_SIZE 512*1024
#define WIZAPI_PAGE_MAX 80
#define WIZAPI_RETURN_SUCCESS "200"
const char* const SyncMethod_CreateAccount = "accounts.createAccount";
const char* const SyncMethod_ClientLogin = "accounts.clientLogin";
const char* const SyncMethod_ClientKeepAlive = "accounts.keepAlive";
const char* const SyncMethod_ClientLogout = "accounts.clientLogout";
const char* const SyncMethod_GetUserInfo = "wiz.getInfo";
const char* const SyncMethod_GetUserCert = "accounts.getCert";
const char* const SyncMethod_GetGroupList = "accounts.getGroupKbList";
const char* const SyncMethod_GetDeletedList = "deleted.getList";
const char* const SyncMethod_PostDeletedList = "deleted.postList";
const char* const SyncMethod_GetTagList = "tag.getList";
const char* const SyncMethod_PostTagList = "tag.postList";
const char* const SyncMethod_GetStyleList = "style.getList";
const char* const SyncMethod_PostStyleList = "style.postList";
// document
// get a list of WIZDOCUMENTDATABASE object of specified sync version
// return: data_md5, document_category, document_guid, document_title
// dt_data_modified, dt_info_modified, dt_param_modified, info_md5, param_md5
// version
const char* const SyncMethod_GetDocumentList = "document.getList";
// get document full info WIZDOCUMENTDATAEX object of specified document
// return: data_md5, document_attachment_count, document_author, document_category,
// document_data, document_filename, document_filetype, document_guid,
// document_iconindex, document_info, document_keywords, document_owner,
// document_param, document_params, document_protected, document_seo, document_share,
// document_styleguid, document_tags, document_title, document_type, document_url,
// dt_accessed, dt_created, dt_data_modified, dt_info_modified, dt_modified,
// dt_param_modified, dt_shared, info_md5, param_md5, public_tags, version
const char* const SyncMethod_GetDocumentFullInfo = "document.getData";
// get a list of WIZDOCUMENTDATABASE object of specified document guid
const char* const SyncMethod_GetDocumentsInfo = "document.downloadList";
// attachment
const char* const SyncMethod_GetAttachmentList = "attachment.getList";
const char* const SyncMethod_GetAttachmentsInfo = "attachment.downloadList";
const char* const SyncMethod_DownloadObjectPart = "data.download";
const char* const SyncMethod_PostDocumentData = "document.postData";
const char* const SyncMethod_PostAttachmentData = "attachment.postData";
const char* const SyncMethod_UploadObjectPart = "data.upload";
// messages
// args: token, biz_guid, kb_guid, document_guid, sender_guid, sender_id,
// message_type, read_status, page(default: 1), page_size(default: 100)
// version, count
// status: 301 token invalid, 322 args error, 500 server error, 200 ok
// return: message object, count, result?
const char* const SyncMethod_GetMessages = "accounts.getMessages";
// args: token, ids(id list, seperate by comma), status(0 unread, 1 read)
// return: success_ids
const char* const SyncMethod_SetMessageStatus = "accounts.setReadStatus";
// key-value api
// This api is multi-usage api, set key-value for user private or group scope.
// used for syncing folder list, biz users and also user settings.
// This key is used for syncing biz users list, %s is biz_guid
#define WIZAPI_KV_KEY_USER_ALIAS "biz_users/%1"
#define WIZAPI_KV_KEY_FOLDERS "folders"
enum WizApiKVType {
KVTypeUserAlias,
KVTypeFolders
};
// args: token, kb_guid(only used for kb.getValue), key
// status: 200 ok, 404 not exist
// return: value_of_key, version
const char* const SyncMethod_GetValue = "accounts.getValue";
const char* const SyncMethod_KbGetValue = "kb.getValue";
// args: totken, kb_guid(only used for kb.getValue), key
// status: 200 ok, 404 not exist
// return: version
const char* const SyncMethod_GetValueVersion = "accounts.getValueVersion";
const char* const SyncMethod_KbGetValueVersion = "kb.getValueVersion";
// args: token, kb_guid(only used for kb.getValue), key, value_of_key
// return: version
const char* const SyncMethod_SetValue = "accounts.setValue";
const char* const SyncMethod_KbSetValue = "kb.setValue";
/*
CWizApiBase is an abstract class, which do nothing useful but just construct
invoke flow of xmlprc not related to database(eg: login, create account, logout).
subclass of CWizApiBase should reimplement "onXXX" like callback functions to
do some useful things.
*/
class CWizApiBase : public QObject
{
Q_OBJECT
public:
CWizApiBase(const QString& strKbUrl = WIZ_API_URL, QObject* parent = 0);
// CWizXmlRpcServer passthrough method
void resetProxy();
virtual void abort() { m_server->abort(); }
// kb url, used for sync document data.
void setKbUrl(const QString& strKbUrl) { m_server->setKbUrl(strKbUrl); }
QString kbGUID() const { return m_strKbGUID; }
void setKbGUID(const QString& strKbGUID) { m_strKbGUID = strKbGUID; }
virtual bool callXmlRpc(CWizXmlRpcValue* pVal, const QString& strMethodName,
const QString& arg1 = "", const QString& arg2 = "");
public:
virtual bool callClientLogin(const QString& strUserId, const QString& strPassword);
virtual bool callGetUserInfo();
virtual bool callGetUserCert(const QString& strUserId, const QString& strPassword);
virtual bool callGetGroupList();
virtual bool callCreateAccount(const CString& strUserId, const CString& strPassword);
virtual bool callGetBizUsers(const QString& bizGUID);
virtual bool callGetMessages(qint64 nVersion);
virtual bool callSetMessageStatus(const QList<qint64>& ids, bool bRead);
// use key-value api to sync user folders
virtual bool callFolderGetList();
virtual bool callFolderGetVersion();
virtual bool callFolderPostList(const CWizStdStringArray& arrayFolder);
virtual bool callDeletedGetList(qint64 nVersion);
virtual bool callDeletedPostList(const std::deque<WIZDELETEDGUIDDATA>& arrayData);
virtual bool callTagGetList(qint64 nVersion);
virtual bool callTagPostList(const std::deque<WIZTAGDATA>& arrayData);
virtual bool callStyleGetList(qint64 nVersion);
virtual bool callStylePostList(const std::deque<WIZSTYLEDATA>& arrayData);
virtual bool callDocumentGetList(qint64 nVersion);
virtual bool callDocumentGetInfo(const QString& documentGUID);
virtual bool callDocumentsGetInfo(const CWizStdStringArray& arrayDocumentGUID);
virtual bool callDocumentGetData(const QString& documentGUID);
virtual bool callDocumentGetData(const WIZDOCUMENTDATABASE& data);
virtual bool callDocumentPostData(const WIZDOCUMENTDATAEX& data);
virtual bool callAttachmentGetList(qint64 nVersion);
virtual bool callAttachmentGetInfo(const QString& attachmentGUID);
virtual bool callAttachmentsGetInfo(const CWizStdStringArray& arrayAttachmentGUID);
virtual bool callAttachmentPostData(const WIZDOCUMENTATTACHMENTDATAEX& data);
virtual bool downloadObjectData(const WIZOBJECTDATA& data);
virtual bool uploadObjectData(const WIZOBJECTDATA& data);
protected:
virtual void onXmlRpcReturn(CWizXmlRpcValue& ret, const QString& strMethodName,
const QString& arg1, const QString& arg2);
virtual void onXmlRpcError(const QString& strMethodName, WizXmlRpcError err, int errorCode, const QString& errorMessage);
virtual void onClientLogin(const WIZUSERINFO& userInfo) { Q_UNUSED(userInfo); }
virtual void onGetUserInfo(CWizXmlRpcValue& ret) { Q_UNUSED(ret); }
virtual void onGetUserCert(const WIZUSERCERT& data) { Q_UNUSED(data); }
virtual void onGetGroupList(const CWizGroupDataArray& arrayGroup) { Q_UNUSED(arrayGroup); }
virtual void onCreateAccount() {}
virtual void onGetMessages(const CWizMessageDataArray& messages) { Q_UNUSED(messages); }
virtual void onSetMessageStatus() {}
virtual void onGetBizUsers(const QString& strJsonUsers) { Q_UNUSED(strJsonUsers); }
virtual void onGetFolders(const QString& strFolders) { Q_UNUSED(strFolders); }
virtual void onDeletedGetList(const std::deque<WIZDELETEDGUIDDATA>& arrayRet) { Q_UNUSED(arrayRet); }
virtual void onDeletedPostList(const std::deque<WIZDELETEDGUIDDATA>& arrayData) { Q_UNUSED(arrayData); }
virtual void onTagGetList(const std::deque<WIZTAGDATA>& arrayRet) { Q_UNUSED(arrayRet); }
virtual void onTagPostList(const std::deque<WIZTAGDATA>& arrayData) { Q_UNUSED(arrayData); }
virtual void onStyleGetList(const std::deque<WIZSTYLEDATA>& arrayRet) { Q_UNUSED(arrayRet); }
virtual void onStylePostList(const std::deque<WIZSTYLEDATA>& arrayData) { Q_UNUSED(arrayData); }
virtual void onDocumentGetList(const std::deque<WIZDOCUMENTDATABASE>& arrayRet) { Q_UNUSED(arrayRet); }
virtual void onDocumentGetData(const WIZDOCUMENTDATAEX& data) { Q_UNUSED(data); }
virtual void onDocumentsGetInfo(const std::deque<WIZDOCUMENTDATABASE>& arrayRet) { Q_UNUSED(arrayRet); }
virtual void onDocumentPostData(const WIZDOCUMENTDATAEX& data) { Q_UNUSED(data); }
virtual void onAttachmentGetList(const std::deque<WIZDOCUMENTATTACHMENTDATAEX>& arrayRet) { Q_UNUSED(arrayRet); }
virtual void onAttachmentsGetInfo(const std::deque<WIZDOCUMENTATTACHMENTDATAEX>& arrayRet) { Q_UNUSED(arrayRet); }
virtual void onAttachmentPostData(const WIZDOCUMENTATTACHMENTDATAEX& data) { Q_UNUSED(data); }
// download trunk data
virtual bool callDownloadDataPart(const CString& strObjectGUID,
const CString& strObjectType,
int pos);
virtual bool downloadNextPartData();
virtual void onDownloadDataPart(const WIZOBJECTPARTDATA& data);
virtual void onDownloadObjectDataCompleted(const WIZOBJECTDATA& data) { Q_UNUSED(data); }
// upload trunk data
virtual bool callUploadDataPart(const CString& strObjectGUID, \
const CString& strObjectType, \
const CString& strObjectMD5, \
int allSize, int partCount, \
int partIndex, int partSize, \
const QByteArray& arrayData);
virtual bool uploadNextPartData();
virtual void onUploadDataPart();
virtual void onUploadObjectDataCompleted(const WIZOBJECTDATA& data) { Q_UNUSED(data); }
bool callGetList(const QString& strMethodName, qint64 nVersion);
template <class TData> bool callPostList(const QString& strMethodName,
const CString& strArrayName,
const std::deque<TData>& arrayData);
private:
CWizXmlRpcServer* m_server;
QString m_strKbGUID;
QString m_strUserId;
QString m_strPasswd;
CWizDeletedGUIDDataArray m_arrayCurrentPostDeletedGUID;
CWizTagDataArray m_arrayCurrentPostTag;
CWizStyleDataArray m_arrayCurrentPostStyle;
WIZDOCUMENTDATAEX m_currentDocument;
WIZDOCUMENTATTACHMENTDATAEX m_currentAttachment;
WIZOBJECTPARTDATA m_currentObjectPartData;
WIZOBJECTDATA m_currentObjectData;
int m_nCurrentObjectAllSize;
CString m_strCurrentObjectMD5;
bool m_bDownloadingObject;
CString MakeXmlRpcUserId(const CString& strUserId);
CString MakeXmlRpcPassword(const CString& strPassword);
void _onXmlRpcError(const QString& strMethodName, WizXmlRpcError err, int errorCode, const QString& errorMessage);
// not have to invoke outside
virtual bool callClientKeepAlive();
virtual bool callClientLogout();
virtual void onClientLogout();
Q_SIGNALS:
void progressChanged(int pos);
void processLog(const QString& str);
void processDebugLog(const QString& str);
void processErrorLog(const QString& str);
void clientLoginDone();
void clientLogoutDone();
void getGroupListDone(const CWizGroupDataArray& arrayGroup);
void createAccountDone();
void getUserInfoDone();
void getUserCertDone(const WIZUSERCERT& data);
// folders
void folderGetVersionDone(qint64 nVersion);
void folderGetListDone(const QStringList& listFolder, qint64 nVersion);
void folderPostListDone(qint64 nVersion);
public Q_SLOTS:
void xmlRpcReturn(CWizXmlRpcValue& ret, const QString& strMethodName,
const QString& arg1, const QString& arg2);
void xmlRpcError(const QString& strMethodName, WizXmlRpcError err, \
int errorCode, const QString& errorMessage);
void on_acquireApiEntry_finished(const QString& strReply);
};
/*
This class is used to do some default operations on database, subclass of
CWizApi(eg: CWizKbSync, CWizDownloadObjectData) should not operate database
directly, instead call CWizApi base implementations
*/
class CWizApi : public CWizApiBase
{
Q_OBJECT
public:
CWizApi(CWizDatabase& db, const CString& strKbUrl = WIZ_API_URL);
CWizDatabase* database() { return m_db; }
void setDatabase(CWizDatabase& db) { m_db = &db; }
protected:
CWizDatabase* m_db;
WIZDOCUMENTDATAEX m_currentDocument;
WIZDOCUMENTATTACHMENTDATAEX m_currentAttachment;
protected:
virtual void onClientLogin(const WIZUSERINFO& userInfo);
virtual void onGetGroupList(const CWizGroupDataArray& arrayGroup);
virtual void onDeletedGetList(const std::deque<WIZDELETEDGUIDDATA>& arrayRet);
virtual void onDeletedPostList(const std::deque<WIZDELETEDGUIDDATA>& arrayData);
virtual void onTagGetList(const std::deque<WIZTAGDATA>& arrayRet);
virtual void onTagPostList(const std::deque<WIZTAGDATA>& arrayData);
virtual void onStyleGetList(const std::deque<WIZSTYLEDATA>& arrayRet);
virtual void onStylePostList(const std::deque<WIZSTYLEDATA>& arrayData);
virtual void onDocumentGetData(const WIZDOCUMENTDATAEX& data);
virtual void onAttachmentGetList(const std::deque<WIZDOCUMENTATTACHMENTDATAEX>& arrayRet);
virtual void onDownloadObjectDataCompleted(const WIZOBJECTDATA& data);
virtual void onUploadObjectDataCompleted(const WIZOBJECTDATA& data);
// upload both document info (callDocumentPostData) and document data (callUploadDataPart)
virtual bool uploadDocument(const WIZDOCUMENTDATAEX& data);
virtual void onDocumentPostData(const WIZDOCUMENTDATAEX& data);
virtual void onUploadDocument(const WIZDOCUMENTDATAEX& data) { Q_UNUSED(data); }
// upload both attachment info (callAttachmentPostData) and document data (callUploadDataPart)
virtual bool uploadAttachment(const WIZDOCUMENTATTACHMENTDATAEX& data);
virtual void onAttachmentPostData(const WIZDOCUMENTATTACHMENTDATAEX& data);
virtual void onUploadAttachment(const WIZDOCUMENTATTACHMENTDATAEX& data) { Q_UNUSED(data); }
};
class CWizApiParamBase : public CWizXmlRpcStructValue
{
public:
CWizApiParamBase();
};
class CWizApiTokenParam : public CWizApiParamBase
{
public:
CWizApiTokenParam(CWizApiBase& api);
};
#endif //WIZAPI_H
|
/*
Copyright (c) 2017, Matthew Toews
All rights reserved.
By downloading, copying, installing or using the software you agree to this license.
If you do not agree to this license, do not download, install, copy or use the software.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
#include "neldermead.h"
//#include "nlopt.h"
#define PARAMETER_DIM_ROT 3
#define PARAMETER_DIM_RIG 7
void
vec3D_cross_3d(
float *pv1,
float *pv2,
float *pvCross
)
{
pvCross[0] = pv1[1]*pv2[2] - pv1[2]*pv2[1];
pvCross[1] = -pv1[0]*pv2[2] + pv1[2]*pv2[0];
pvCross[2] = pv1[0]*pv2[1] - pv1[1]*pv2[0];
}
void
vec3D_diff_3d(
float *pv1,
float *pv2,
float *pv12
)
{
pv12[0] = pv2[0]-pv1[0];
pv12[1] = pv2[1]-pv1[1];
pv12[2] = pv2[2]-pv1[2];
}
float
vec3D_dot_3d(
float *pv1,
float *pv2
)
{
return pv2[0]*pv1[0] + pv2[1]*pv1[1] + pv2[2]*pv1[2];
}
float
vec3D_dist_3d(
float *pv1,
float *pv2
)
{
float dx = pv2[0]-pv1[0];
float dy = pv2[1]-pv1[1];
float dz = pv2[2]-pv1[2];
return sqrt( dx*dx+dy*dy+dz*dz );
}
float
vec3D_distsqr_3d(
float *pv1,
float *pv2
)
{
float dx = pv2[0]-pv1[0];
float dy = pv2[1]-pv1[1];
float dz = pv2[2]-pv1[2];
return dx*dx+dy*dy+dz*dz;
}
void
vec3D_mult_scalar(
float *pf1,
float mult
)
{
pf1[0] *= mult;
pf1[1] *= mult;
pf1[2] *= mult;
}
void
vec3D_norm_3d(
float *pf1
)
{
float fSumSqr = pf1[0]*pf1[0] + pf1[1]*pf1[1] + pf1[2]*pf1[2];
if( fSumSqr > 0 )
{
float fDiv = 1.0/sqrt( fSumSqr );
pf1[0] *= fDiv;
pf1[1] *= fDiv;
pf1[2] *= fDiv;
}
else
{
pf1[0] = 1;
pf1[1] = 0;
pf1[2] = 0;
}
}
float
vec3D_mag(
float *pf1
)
{
float fSumSqr = pf1[0]*pf1[0] + pf1[1]*pf1[1] + pf1[2]*pf1[2];
if( fSumSqr > 0 )
{
return sqrt( fSumSqr );
}
else
{
return 0;
}
}
void
mult_3x3_matrix(
float *mat1,
float *mat2,
float *mat_out
)
{
for( int i = 0; i < 3; i++ )
{
for( int j = 0; j < 3; j++ )
{
mat_out[i*3+j]=0;
for( int ii = 0; ii < 3; ii++ )
{
mat_out[i*3+j] += mat1[i*3+ii]*mat2[ii*3+j];
}
}
}
}
void
mult_3x3_scalar(
float *mat1,
float multiple,
float *mat_out
)
{
for( int i = 0; i < 3; i++ )
{
for( int j = 0; j < 3; j++ )
{
mat_out[i*3+j] = mat1[i*3+j]*multiple;
}
}
}
void
mult_1x3_scalar(
float *vec,
float multiple,
float *vec_out
)
{
for( int i = 0; i < 3; i++ )
{
vec_out[i] = vec[i]*multiple;
}
}
void
sum_3x3_matrix(
float *mat1,
float *mat2,
float *mat_out
)
{
for( int i = 0; i < 3; i++ )
{
for( int j = 0; j < 3; j++ )
{
mat_out[i*3+j] = mat1[i*3+j] + mat2[i*3+j];
}
}
}
void
mult_3x3_vector(
float *mat,
float *vec_in,
float *vec_out
)
{
for( int i = 0; i < 3; i++ )
{
vec_out[i] = 0;
for( int j = 0; j < 3; j++ )
{
vec_out[i] += mat[i*3+j]*vec_in[j];
}
}
}
void
mult_4x4_matrix(
float *mat1,
float *mat2,
float *mat_out
)
{
for( int i = 0; i < 4; i++ )
{
for( int j = 0; j < 4; j++ )
{
mat_out[i*4+j]=0;
for( int ii = 0; ii < 4; ii++ )
{
mat_out[i*4+j] += mat1[i*4+ii]*mat2[ii*4+j];
}
}
}
}
void
mult_4x4_vector(
float *mat,
float *vec_in,
float *vec_out
)
{
for( int i = 0; i < 4; i++ )
{
vec_out[i] = 0;
for( int j = 0; j < 4; j++ )
{
vec_out[i] += mat[i*4+j]*vec_in[j];
}
}
}
//
// Assume last row of mat is [0,0,0,1] and that
// vec_in[3] = 1
// vec_out[3] = 1
//
// Here, mat is a 4x4 matrix, vec_in is 1x3, vec_out is 1x3
//
void
mult_4x4_vector_homogenous(
float *mat,
float *vec_in,
float *vec_out
)
{
for( int i = 0; i < 3; i++ )
{
vec_out[i] = 0;
for( int j = 0; j < 3; j++ )
{
vec_out[i] += mat[i*4+j]*vec_in[j];
}
vec_out[i] += mat[i*4+3];
}
//vec_out[3] = 1;
}
void
mult_4x4_scalar(
float *mat1,
float multiple,
float *mat_out
)
{
for( int i = 0; i < 4; i++ )
{
for( int j = 0; j < 4; j++ )
{
mat_out[i*4+j] = mat1[i*4+j]*multiple;
}
}
}
int
invert_4x4(
float *m,
float *invOut
)
{
float inv[16], det;
int i;
inv[0] = m[5] * m[10] * m[15] -
m[5] * m[11] * m[14] -
m[9] * m[6] * m[15] +
m[9] * m[7] * m[14] +
m[13] * m[6] * m[11] -
m[13] * m[7] * m[10];
inv[4] = -m[4] * m[10] * m[15] +
m[4] * m[11] * m[14] +
m[8] * m[6] * m[15] -
m[8] * m[7] * m[14] -
m[12] * m[6] * m[11] +
m[12] * m[7] * m[10];
inv[8] = m[4] * m[9] * m[15] -
m[4] * m[11] * m[13] -
m[8] * m[5] * m[15] +
m[8] * m[7] * m[13] +
m[12] * m[5] * m[11] -
m[12] * m[7] * m[9];
inv[12] = -m[4] * m[9] * m[14] +
m[4] * m[10] * m[13] +
m[8] * m[5] * m[14] -
m[8] * m[6] * m[13] -
m[12] * m[5] * m[10] +
m[12] * m[6] * m[9];
inv[1] = -m[1] * m[10] * m[15] +
m[1] * m[11] * m[14] +
m[9] * m[2] * m[15] -
m[9] * m[3] * m[14] -
m[13] * m[2] * m[11] +
m[13] * m[3] * m[10];
inv[5] = m[0] * m[10] * m[15] -
m[0] * m[11] * m[14] -
m[8] * m[2] * m[15] +
m[8] * m[3] * m[14] +
m[12] * m[2] * m[11] -
m[12] * m[3] * m[10];
inv[9] = -m[0] * m[9] * m[15] +
m[0] * m[11] * m[13] +
m[8] * m[1] * m[15] -
m[8] * m[3] * m[13] -
m[12] * m[1] * m[11] +
m[12] * m[3] * m[9];
inv[13] = m[0] * m[9] * m[14] -
m[0] * m[10] * m[13] -
m[8] * m[1] * m[14] +
m[8] * m[2] * m[13] +
m[12] * m[1] * m[10] -
m[12] * m[2] * m[9];
inv[2] = m[1] * m[6] * m[15] -
m[1] * m[7] * m[14] -
m[5] * m[2] * m[15] +
m[5] * m[3] * m[14] +
m[13] * m[2] * m[7] -
m[13] * m[3] * m[6];
inv[6] = -m[0] * m[6] * m[15] +
m[0] * m[7] * m[14] +
m[4] * m[2] * m[15] -
m[4] * m[3] * m[14] -
m[12] * m[2] * m[7] +
m[12] * m[3] * m[6];
inv[10] = m[0] * m[5] * m[15] -
m[0] * m[7] * m[13] -
m[4] * m[1] * m[15] +
m[4] * m[3] * m[13] +
m[12] * m[1] * m[7] -
m[12] * m[3] * m[5];
inv[14] = -m[0] * m[5] * m[14] +
m[0] * m[6] * m[13] +
m[4] * m[1] * m[14] -
m[4] * m[2] * m[13] -
m[12] * m[1] * m[6] +
m[12] * m[2] * m[5];
inv[3] = -m[1] * m[6] * m[11] +
m[1] * m[7] * m[10] +
m[5] * m[2] * m[11] -
m[5] * m[3] * m[10] -
m[9] * m[2] * m[7] +
m[9] * m[3] * m[6];
inv[7] = m[0] * m[6] * m[11] -
m[0] * m[7] * m[10] -
m[4] * m[2] * m[11] +
m[4] * m[3] * m[10] +
m[8] * m[2] * m[7] -
m[8] * m[3] * m[6];
inv[11] = -m[0] * m[5] * m[11] +
m[0] * m[7] * m[9] +
m[4] * m[1] * m[11] -
m[4] * m[3] * m[9] -
m[8] * m[1] * m[7] +
m[8] * m[3] * m[5];
inv[15] = m[0] * m[5] * m[10] -
m[0] * m[6] * m[9] -
m[4] * m[1] * m[10] +
m[4] * m[2] * m[9] +
m[8] * m[1] * m[6] -
m[8] * m[2] * m[5];
det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
if (det == 0)
return false;
det = 1.0 / det;
for (i = 0; i < 16; i++)
invOut[i] = inv[i] * det;
return true;
}
nlopt_result
nldrmd_minimize(
int n,
nlopt_func f,
void *f_data,
const double *lb,
const double *ub, /* bounds */
double *x, /* in: initial guess, out: minimizer */
double *minf,
const double *xstep, /* initial step sizes */
nlopt_stopping *stop
);
//
// Declare constraint data
//
typedef struct _my_constraint_data
{
int iPoints;
float *pfPoints1;
float *pfPoints2;
float fPercentToKeep; // usuall 0.75 of lowest error points, for robustness
int iErrorCalib; // Boolean, if true, algorithm evaluates error of pfPoints1/2 using ground truth calib
float pfCalib[PARAMETER_DIM_RIG]; // Ground truth calibration matrix: 16 floats
int bPerformAlign; // If true, generate and apply the alignment matrix
float pfAlign[PARAMETER_DIM_RIG]; // Alignment matrix: 16 floats
// *** 2014 3D reconstruction
// Keep track of frame indices
int *piFrames1;
int *piFrames2;
} my_constraint_data;
int
convert_vector_to_rotation_matrix(
float *vec,
float *mat
)
{
float pfOmega[3];
memcpy( pfOmega, vec, sizeof(pfOmega) );
float fTheta = vec3D_mag( pfOmega );
vec3D_norm_3d( pfOmega );
float fThetaSin = sin( fTheta );
float fThetaCos = cos( fTheta );
float fThetaCosInv = 1.0f-fThetaCos;
float pfOmegaHat[9];
memset( pfOmegaHat, 0, sizeof(pfOmegaHat) );
pfOmegaHat[1] = -pfOmega[2];
pfOmegaHat[2] = pfOmega[1];
pfOmegaHat[3] = pfOmega[2];
pfOmegaHat[5] = -pfOmega[0];
pfOmegaHat[6] = -pfOmega[1];
pfOmegaHat[7] = pfOmega[0];
float pfOmegaHatSqr[9];
mult_3x3_matrix( pfOmegaHat, pfOmegaHat, pfOmegaHatSqr );
memset( mat, 0, sizeof(float)*9 );
mat[0]=1;
mat[4]=1;
mat[8]=1;
mult_3x3_scalar( pfOmegaHat, fThetaSin, pfOmegaHat );
mult_3x3_scalar( pfOmegaHatSqr, fThetaCosInv, pfOmegaHatSqr );
sum_3x3_matrix( mat, pfOmegaHat, mat );
sum_3x3_matrix( mat, pfOmegaHatSqr, mat );
return 1;
}
int
convert_rotation_matrix_to_vector(
float *vec,
float *mat
)
{
float fTrace = mat[0] + mat[4] + mat[8];
float fTheta = acos( (fTrace - 1.0) / 2.0 );
vec[0] = mat[7]-mat[5];
vec[1] = mat[2]-mat[6];
vec[2] = mat[3]-mat[1];
vec3D_norm_3d( vec );
vec[0] *= fTheta;
vec[1] *= fTheta;
vec[2] *= fTheta;
return 1;
}
int
set_vector_to_identity(
float *vec
)
{
for( int m = 0; m < 7; m++ )
{
// zero rotation,
vec[m] = 0;
}
return 1;
}
int
set_vector_to_identity(
double *vec
)
{
for( int m = 0; m < 7; m++ )
{
// zero rotation,
vec[m] = 0;
}
return 1;
}
int
convert_vector_to_matrix4x4(
float *vec,
float *mat44 // length 16 vector
)
{
convert_vector_to_rotation_matrix( vec, mat44 );
//mult_3x3_scalar( mat44, exp(vec[6]), mat44 );
mat44[10] = mat44[8];
mat44[9] = mat44[7];
mat44[8] = mat44[6];
mat44[6] = mat44[5];
mat44[5] = mat44[4];
mat44[4] = mat44[3];
mat44[3] = vec[3];
mat44[7] = vec[4];
mat44[11] = vec[5];
mat44[12] = 0;
mat44[13] = 0;
mat44[14] = 0;
mat44[15] = 1;
return 1;
}
//
// This code has been verified.
// The plane parameters (a,b,c) are normalized to a unit vector.
//
int
determine_plane_3point(
float *pfP01, float *pfP02, float *pfP03, // points in image 1 (3d)
float *pfPlane // ax + by + cz + d = 0;
)
{
float pfV0_12[3];
float pfV0_13[3];
float pfV0_nm[3];
// Subtract point 1 to convert to vectors
vec3D_diff_3d( pfP01, pfP02, pfV0_12 );
vec3D_diff_3d( pfP01, pfP03, pfV0_13 );
// Normalize vectors
//vec3D_norm_3d( pfV0_12 );
//vec3D_norm_3d( pfV0_13 );
// Cross product between 2 vectors to get normal
vec3D_cross_3d( pfV0_12, pfV0_13, pfV0_nm );
vec3D_norm_3d( pfV0_nm );
pfPlane[0] = pfV0_nm[0]; // a
pfPlane[1] = pfV0_nm[1]; // b
pfPlane[2] = pfV0_nm[2]; // c
pfPlane[3] = -(pfV0_nm[0]*pfP01[0] + pfV0_nm[1]*pfP01[1] + pfV0_nm[2]*pfP01[2]); // d
pfPlane[3] = -(pfV0_nm[0]*pfP02[0] + pfV0_nm[1]*pfP02[1] + pfV0_nm[2]*pfP02[2]); // d
pfPlane[3] = -(pfV0_nm[0]*pfP03[0] + pfV0_nm[1]*pfP03[1] + pfV0_nm[2]*pfP03[2]); // d
return 1;
}
//
// ransac_plane_estimation()
//
// Determine robust plane estimate from 3 or more points.
//
int
ransac_plane_estimation(
int iPoints,
float *pts,
int iIterations,
float fDistThreshold,
float *pfPlane // 4 parameters: a b c d, abc is normalized
)
{
if( iPoints < 3 )
{
// 3 unique points are required
return -1;
}
if( iPoints == 3 )
{
// Determine exact plane
determine_plane_3point( pts + 3*0, pts + 3*1, pts + 3*2, pfPlane );
return 3;
}
int iMaxInliers = 0;
for( int i = 0; i < iIterations; i++ )
{
// Find a set of unique points
int i1 = (rand()*iPoints)/(RAND_MAX+1.0f);
int i2 = (rand()*iPoints)/(RAND_MAX+1.0f);
int i3 = (rand()*iPoints)/(RAND_MAX+1.0f);
while( i1 == i2 || i1 == i3 || i2 == i3 )
{
i1 = (rand()*iPoints)/(RAND_MAX+1.0f);
i2 = (rand()*iPoints)/(RAND_MAX+1.0f);
i3 = (rand()*iPoints)/(RAND_MAX+1.0f);
}
float *pfP01 = pts + 3*i1;
float *pfP02 = pts + 3*i2;
float *pfP03 = pts + 3*i3;
float pfPTest[4];
determine_plane_3point( pfP01, pfP02, pfP03, pfPTest );
if( pfPTest[0]*pfPTest[1]*pfPTest[2]*pfPTest[3] == 0 )
{
// Error - probably duplicate points
continue;
}
int iInliers = 0;
for( int j = 0; j < iPoints; j++ )
{
// Compute distance from each point to plane
float *pfPt = pts + 3*j;
float fDist = pfPTest[0]*pfPt[0] + pfPTest[1]*pfPt[1] + pfPTest[2]*pfPt[2] + pfPTest[3];
if( fDist < 0 )
{
fDist = -fDist;
}
if( fDist < fDistThreshold )
{
iInliers++;
}
}
if( iInliers > iMaxInliers )
{
iMaxInliers = iInliers;
for( int j = 0; j < 4; j++ )
{
pfPlane[j] = pfPTest[j];
}
// Go through and compute error again
for( int j = 0; j < iPoints; j++ )
{
// Compute distance from each point to plane
float *pfPt = pts + 3*j;
float fDist = pfPTest[0]*pfPt[0] + pfPTest[1]*pfPt[1] + pfPTest[2]*pfPt[2] + pfPTest[3];
if( fDist < 0 )
{
fDist = -fDist;
}
if( fDist < fDistThreshold )
{
iInliers++;
}
}
}
}
return iMaxInliers;
}
int
convert_vector_to_rotation_matrix_4X4(
float *vec,
float *mat
)
{
convert_vector_to_rotation_matrix( vec, mat );
mat[10] = mat[8];
mat[9] = mat[7];
mat[8] = mat[6];
mat[6] = mat[5];
mat[5] = mat[4];
mat[4] = mat[3];
mat[3] = 0;
mat[7] = 0;
mat[11] = 0;
mat[12] = mat[13] = mat[14] = 0;
mat[15] = 1;
return 1;
}
int
generate_random_rigid_transformation_matrix_4x4(
float *mat
)
{
float vec[3];
vec[0] = rand()/(RAND_MAX+1.0f) - 0.5;
vec[1] = rand()/(RAND_MAX+1.0f) - 0.5;
vec[2] = rand()/(RAND_MAX+1.0f) - 0.5;
convert_vector_to_rotation_matrix_4X4( vec, mat );
// Put in translation
mat[3] = 100*(rand()/(RAND_MAX+1.0f) - 0.5);
mat[7] = 100*(rand()/(RAND_MAX+1.0f) - 0.5);
mat[11] = 100*(rand()/(RAND_MAX+1.0f) - 0.5);
return 1;
}
int
test_convert_vector_to_rotation_matrix(
)
{
//float vec[3] = {-0.406417548, -0.247176698, -0.334497981 };
//float vec[3] = {-2.19563893, -1.335352724, -1.80709911};
float vec[3] = {-6.586916789, -4.006058171, -5.421297331};
float vec2[3];
float mat[9];
convert_vector_to_rotation_matrix( vec, mat );
float vec_out[3];
mult_3x3_vector( mat, vec, vec_out );
mult_1x3_scalar( vec, 102, vec2 );
convert_vector_to_rotation_matrix( vec2, mat );
mult_3x3_vector( mat, vec, vec_out );
return 1;
}
//
// select_half_data()
//
// Select a random subset of half the data.
//
int
select_half_data(
my_constraint_data &dat,
int iSubset
)
{
int iNewPoints = dat.iPoints / 2;
if( iSubset > 0 )
{
dat.pfPoints1 += 15*iNewPoints;
dat.pfPoints2 += 15*iNewPoints;
}
dat.iPoints = iNewPoints;
return 1;
}
int
select_half_data_interleaved(
my_constraint_data &dat,
int iSubset
)
{
int iBit = iSubset != 0 ? 1 : 0;
int iNewPoints = dat.iPoints / 2;
for( int i = 0; i < iNewPoints; i++ )
{
memcpy( dat.pfPoints1 + 15*i, dat.pfPoints1 + 15*(2*i+iBit), 15*sizeof(float) );
memcpy( dat.pfPoints2 + 15*i, dat.pfPoints2 + 15*(2*i+iBit), 15*sizeof(float) );
}
dat.iPoints = iNewPoints;
return 1;
}
int
generate_minimization_test_data(
my_constraint_data &dat,
int iPoints
)
{
dat.iPoints = iPoints;
dat.pfPoints1 = new float[3*iPoints];
dat.pfPoints2 = new float[3*iPoints];
float vec_original[3] = {-6.586916789, -4.006058171, -5.421297331};
for( int i = 0; i < iPoints; i++ )
{
// Create random vector & rotation matrix
float vec2[3];
memcpy( vec2, vec_original, sizeof(vec2) );
vec2[0] += rand()/(RAND_MAX+1.0) - 0.5f;
vec2[1] += rand()/(RAND_MAX+1.0) - 0.5f;
vec2[2] += rand()/(RAND_MAX+1.0) - 0.5f;
float mat[9];
convert_vector_to_rotation_matrix( vec2, mat );
float *point_in = dat.pfPoints1 + 3*i;
float *point_out = dat.pfPoints2 + 3*i;
// Create random input point (-10 to 10)
point_in[0] = (rand()/(RAND_MAX+1.0) - 0.5f)*10;
point_in[1] = (rand()/(RAND_MAX+1.0) - 0.5f)*10;
point_in[2] = (rand()/(RAND_MAX+1.0) - 0.5f)*10;
// Create random output point: multiply input point by random rotation matrix
mult_3x3_vector( mat, point_in, point_out );
}
return 1;
}
//
// Format: | rot-vec 3 | trs-vec 3 | log scale 1 |
//
int
generate_minimization_test_data_rigid(
my_constraint_data &dat,
int iPoints
)
{
dat.iPoints = iPoints;
dat.pfPoints1 = new float[3*iPoints];
dat.pfPoints2 = new float[3*iPoints];
//srand(50);
#define LN_2 0.69314718
float vec_original[PARAMETER_DIM_RIG] = {-6.586916789, -4.006058171, -5.421297331, 30, -25, -5, LN_2 };
for( int i = 0; i < iPoints; i++ )
{
// Create random vector
float vec2[PARAMETER_DIM_RIG];
memcpy( vec2, vec_original, sizeof(vec2) );
// Theta +- 0.5
vec2[0] += rand()/(RAND_MAX+1.0) - 0.5f;
vec2[1] += rand()/(RAND_MAX+1.0) - 0.5f;
vec2[2] += rand()/(RAND_MAX+1.0) - 0.5f;
// Trans +- 10
vec2[3] += (rand()/(RAND_MAX+1.0) - 0.5f)*10;
vec2[4] += (rand()/(RAND_MAX+1.0) - 0.5f)*10;
vec2[5] += (rand()/(RAND_MAX+1.0) - 0.5f)*10;
// Scale +- 0.25
vec2[6] += (rand()/(RAND_MAX+1.0) - 0.5f)*.5;
float mat[9];
// Create rotation matrix
convert_vector_to_rotation_matrix( vec2, mat );
// Multiply scale
mult_3x3_scalar( mat, exp(vec2[6]), mat );
float *point_in = dat.pfPoints1 + 3*i;
float *point_out = dat.pfPoints2 + 3*i;
// Create random input point (-50 to 50)
point_in[0] = (rand()/(RAND_MAX+1.0) - 0.5f)*100;
point_in[1] = (rand()/(RAND_MAX+1.0) - 0.5f)*100;
point_in[2] = (rand()/(RAND_MAX+1.0) - 0.5f)*100;
// Create random output point: multiply input point by random rotation matrix
mult_3x3_vector( mat, point_in, point_out );
// Add translation and we're done
point_out[0] += vec2[3];
point_out[1] += vec2[4];
point_out[2] += vec2[5];
}
return 1;
}
//
// Format: | rot-vec 3 | trs-vec 3 | log scale 1 |
//
int
generate_minimization_test_data_rigid_US(
my_constraint_data &dat,
int iPoints
)
{
dat.iPoints = iPoints;
dat.pfPoints1 = new float[15*iPoints];
dat.pfPoints2 = new float[15*iPoints];
#define LN_2 0.69314718
float vec_original[PARAMETER_DIM_RIG] = {0.0001, 0.0001, 0.0001, 30, -25, -5, LN_2 };
// Create rotation matrix from current vector (length 7)
// Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
float vec2[PARAMETER_DIM_RIG];
float mat[9];
// Create rotation matrix
convert_vector_to_rotation_matrix( vec_original, mat );
// Multiply scale
mult_3x3_scalar( mat, exp(vec_original[6]), mat );
// Copy scaled rotation matrix to 4x4 homogenous matrix
float mat44[16];
memset( &mat44[0], 0, sizeof(mat44) );
memcpy( &mat44[0], &mat[0], 3*sizeof(float) );
memcpy( &mat44[4], &mat[3], 3*sizeof(float) );
memcpy( &mat44[8], &mat[6], 3*sizeof(float) );
// Copy translations to 4x4 homegenous matrix
mat44[3] = vec_original[3];
mat44[7] = vec_original[4];
mat44[11] = vec_original[5];
mat44[15] = 1;
// Two US tracker transform matrices
float mat44_1[16];
float mat44_2[16];
// Set last row to: [0,0,0,1]
memset( &mat44_1[0], 0, sizeof(mat44_1) );
memset( &mat44_2[0], 0, sizeof(mat44_2) );
mat44_1[15] = 1;
mat44_2[15] = 1;
// Two product transform matrices
float mat44_1_p[16];
float mat44_2_p[16];
for( int i = 0; i < iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
float *p_in = point_in+12;
float *p_out = point_out+12;
// Generate left hand side
p_in[0] = (rand()*100)/(RAND_MAX+1.0);
p_in[1] = (rand()*100)/(RAND_MAX+1.0);
p_in[2] = 0;
generate_random_rigid_transformation_matrix_4x4( mat44_1 );
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
float point_test_in[3];
mult_4x4_vector_homogenous( mat44_1_p,p_in, point_test_in );
// Generate right hand side
p_out[0] = (rand()*100)/(RAND_MAX+1.0);
p_out[1] = (rand()*100)/(RAND_MAX+1.0);
p_out[2] = 0;
float point_test_out[3];
mult_4x4_vector_homogenous( mat44,p_out, point_test_out );
mat44_2[0] = mat44_2[5] = mat44_2[10] = 1; mat44_2[15] = 1;
// Add Translation
mat44_2[ 3] = point_test_in[0] - point_test_out[0];
mat44_2[ 7] = point_test_in[1] - point_test_out[1];
mat44_2[11] = point_test_in[2] - point_test_out[2];
// Save matrices (points already saved)
memcpy( point_in, &mat44_1[0], sizeof(float)*12 );
memcpy( point_out, &mat44_2[0], sizeof(float)*12 );
// Now perform self test
//
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Multiply current calibration matrix
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
// Generate output 3D test points
mult_4x4_vector_homogenous( mat44_1_p, point_in+12, point_test_in );
mult_4x4_vector_homogenous( mat44_2_p, point_out+12, point_test_out );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( point_test_in, point_test_out );
assert( fErrorSqr*fErrorSqr < 0.1*0.1 );
}
return 1;
}
int
allocateArray(
float ***pppdX,
int iCols,
int iRows
)
{
float *pdDataX = new float[iRows*iCols];
if( !pdDataX )
{
return -1;
}
float **pdX = new float*[iRows];
for( int i = 0; i < iRows; i++ )
{
pdX[i] = &pdDataX[i*iCols];
}
*pppdX = pdX;
return 1;
}
int
deallocateArray(
float ***pppdX
)
{
float **pdX = *pppdX;
delete [] pdX[0];
delete *pppdX;
return 1;
}
int
readArray(
char *pcFileNameBase,
float ***pppdX,
int &iCols,
int &iRows,
char *pcFormat
)
{
FILE *infile;
char pcFileName[300];
int iReturn;
*pppdX = 0;
// Open header
sprintf( pcFileName, "%s.txt", pcFileNameBase );
infile = fopen( pcFileName, "rt" );
if( !infile )
{
return -1;
}
iReturn = fscanf( infile, "cols:\t%d\n", &iCols );
iReturn = fscanf( infile, "rows:\t%d\n", &iRows );
iReturn = fscanf( infile, "format:\t%s\n", pcFormat );
fclose( infile );
// Open data
sprintf( pcFileName, "%s.bin", pcFileNameBase );
infile = fopen( pcFileName, "rb" );
if( !infile )
{
return -1;
}
float *pdDataX = new float[iRows*iCols];
if( !pdDataX )
{
fclose( infile );
return -1;
}
if( pcFormat[0] == 'i' )
{
for( int i = 0; i < iRows*iCols; i++ )
{
int iData;
fread( &iData, sizeof(int), 1, infile );
pdDataX[i] = (float)iData;
}
}
else if( pcFormat[0] == 'f' )
{
for( int i = 0; i < iRows*iCols; i++ )
{
double dData;
fread( &dData, sizeof(double), 1, infile );
pdDataX[i] = (float)dData;
}
}
fclose( infile );
float **pdX = new float*[iRows];
for( int i = 0; i < iRows; i++ )
{
pdX[i] = &pdDataX[i*iCols];
}
*pppdX = pdX;
return 0;
}
//
// readArrayNoAllocation()
//
// Read the array from file, allocation of pdX has taken place elsewhere
//
int
readArrayNoAllocation(
char *pcFileNameBase,
float *pdX,
int &iCols,
int &iRows,
char *pcFormat
)
{
FILE *infile;
char pcFileName[300];
int iReturn;
// Open header
sprintf( pcFileName, "%s.txt", pcFileNameBase );
infile = fopen( pcFileName, "rt" );
if( !infile )
{
return -1;
}
iReturn = fscanf( infile, "cols:\t%d\n", &iCols );
iReturn = fscanf( infile, "rows:\t%d\n", &iRows );
iReturn = fscanf( infile, "format:\t%s\n", pcFormat );
fclose( infile );
// Open data
sprintf( pcFileName, "%s.bin", pcFileNameBase );
infile = fopen( pcFileName, "rb" );
if( !infile )
{
return -1;
}
if( pcFormat[0] == 'i' )
{
for( int i = 0; i < iRows*iCols; i++ )
{
int iData;
fread( &iData, sizeof(int), 1, infile );
pdX[i] = (float)iData;
}
}
else if( pcFormat[0] == 'f' )
{
for( int i = 0; i < iRows*iCols; i++ )
{
double dData;
fread( &dData, sizeof(double), 1, infile );
pdX[i] = (float)dData;
}
}
fclose( infile );
return 0;
}
//
// readArraySize()
//
// Just to size up the arrays.
//
int
readArraySize(
char *pcFileNameBase,
int &iCols,
int &iRows,
char *pcFormat
)
{
FILE *infile;
char pcFileName[300];
int iReturn;
// Open header
sprintf( pcFileName, "%s.txt", pcFileNameBase );
infile = fopen( pcFileName, "rt" );
if( !infile )
{
return -1;
}
iReturn = fscanf( infile, "cols:\t%d\n", &iCols );
iReturn = fscanf( infile, "rows:\t%d\n", &iRows );
iReturn = fscanf( infile, "format:\t%s\n", pcFormat );
fclose( infile );
return 0;
}
int
read_point_data_US_multiple(
int argc,
char **argv,
my_constraint_data &dat
)
{
char pcFileName[400];
int iCols;
int iRows;
int iDataCount = 0;
char pcFormat[10];
// Pass1: figure out how much space is necessary
dat.iPoints = 0;
for( int i = 0; i < argc; i++ )
{
sprintf( pcFileName, "%s.non-linear.matches.X", argv[i] );
if( readArraySize( pcFileName, iCols, iRows, pcFormat ) < 0 )
{
return -1;
}
dat.iPoints += iRows;
iDataCount += iCols*iRows;
}
// Allocate arrays
dat.pfPoints1 = new float[iDataCount];
dat.pfPoints2 = new float[iDataCount];
if( !dat.pfPoints1 || !dat.pfPoints2 )
{
return -1;
}
// Pass2: read in
int iCurrCount = 0;
for( int i = 0; i < argc; i++ )
{
sprintf( pcFileName, "%s.non-linear.matches.X", argv[i] );
readArrayNoAllocation( pcFileName, dat.pfPoints1+iCurrCount, iCols, iRows, pcFormat );
sprintf( pcFileName, "%s.non-linear.matches.Y", argv[i] );
readArrayNoAllocation( pcFileName, dat.pfPoints2+iCurrCount, iCols, iRows, pcFormat );
iCurrCount += iCols*iRows;
}
//sprintf( pcFileName, "%s.non-linear.matches.X", pcFNameBase );readArray( pcFileName, &p1, iCols, iRows, pf1 );
//sprintf( pcFileName, "%s.non-linear.matches.Y", pcFNameBase );readArray( pcFileName, &p2, iCols, iRows, pf2 );
return 1;
}
// Experimental - add offset to points in the image plane to
// change center of rotation / reduce optimizer bias?
// It seems the optimizer is choosing a translation vs a rotation.
int
add_point_offset(
my_constraint_data &dat,
int iColOffset=315, // Center of ultrasound fan in MNI data
int iRowOffset=315
)
{
for( int i = 0; i < dat.iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
float *p_in = point_in+12;
float *p_out = point_out+12;
// Center around
p_in[0] -= iColOffset;
p_in[1] -= iRowOffset;
p_out[0] -= iColOffset;
p_out[1] -= iRowOffset;
}
return 1;
}
int
read_point_data_US(
char *pcFNameBase,
my_constraint_data &dat
)
{
// Read data from files
int iRows, iCols;
float ** p1, ** p2;
char pf1[2], pf2[2];
char pcFileName[400];
sprintf( pcFileName, "%s.non-linear.matches.X", pcFNameBase );readArray( pcFileName, &p1, iCols, iRows, pf1 );
sprintf( pcFileName, "%s.non-linear.matches.Y", pcFNameBase );readArray( pcFileName, &p2, iCols, iRows, pf2 );
//readArray( "C:\\writting\\cvs_stuff\\papers\\miccai-2013\\pics\\reconstruction\\non-linear.matches.X", &p1, iCols, iRows, pf1 );
//readArray( "C:\\writting\\cvs_stuff\\papers\\miccai-2013\\pics\\reconstruction\\non-linear.matches.Y", &p2, iCols, iRows, pf2 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\non-linear.matches.X", &p1, iCols, iRows, pf1 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\non-linear.matches.Y", &p2, iCols, iRows, pf2 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\mr-non-linear.matches.X", &p1, iCols, iRows, pf1 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\mr-non-linear.matches.Y", &p2, iCols, iRows, pf2 );
dat.iPoints = iRows;
dat.pfPoints1 = p1[0];
dat.pfPoints2 = p2[0];
return 1;
}
//
// read_point_data_US_frame_indices()
//
// *** 2014 3D reconstruction
//
int
read_point_data_US_frame_indices(
char *pcFNameBase,
my_constraint_data &dat
)
{
// Read data from files
int iRows, iCols;
float ** p1, ** p2;
char pf1[2], pf2[2];
char pcFileName[400];
sprintf( pcFileName, "%s.non-linear.matches.X", pcFNameBase );readArray( pcFileName, &p1, iCols, iRows, pf1 );
sprintf( pcFileName, "%s.non-linear.matches.Y", pcFNameBase );readArray( pcFileName, &p2, iCols, iRows, pf2 );
//readArray( "C:\\writting\\cvs_stuff\\papers\\miccai-2013\\pics\\reconstruction\\non-linear.matches.X", &p1, iCols, iRows, pf1 );
//readArray( "C:\\writting\\cvs_stuff\\papers\\miccai-2013\\pics\\reconstruction\\non-linear.matches.Y", &p2, iCols, iRows, pf2 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\non-linear.matches.X", &p1, iCols, iRows, pf1 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\non-linear.matches.Y", &p2, iCols, iRows, pf2 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\mr-non-linear.matches.X", &p1, iCols, iRows, pf1 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\mr-non-linear.matches.Y", &p2, iCols, iRows, pf2 );
dat.iPoints = iRows;
dat.pfPoints1 = p1[0];
dat.pfPoints2 = p2[0];
return 1;
}
int
read_point_data_US(
char *pcFNameBase1,
char *pcFNameBase2,
my_constraint_data &dat
)
{
my_constraint_data dat1;
my_constraint_data dat2;
read_point_data_US( pcFNameBase1, dat1 );
read_point_data_US( pcFNameBase2, dat2 );
dat.iPoints = dat1.iPoints + dat2.iPoints;
dat.pfPoints1 = new float[15*dat.iPoints];
dat.pfPoints2 = new float[15*dat.iPoints];
for( int i = 0; i < dat1.iPoints*15; i++ )
{
dat.pfPoints1[i] = dat1.pfPoints1[i];
dat.pfPoints2[i] = dat1.pfPoints2[i];
}
for( int i = 0; i < dat2.iPoints*15; i++ )
{
dat.pfPoints1[dat1.iPoints*15+i] = dat2.pfPoints1[i];
dat.pfPoints2[dat1.iPoints*15+i] = dat2.pfPoints2[i];
}
delete [] dat1.pfPoints1;
delete [] dat1.pfPoints2;
delete [] dat2.pfPoints1;
delete [] dat2.pfPoints2;
return 1;
}
int
read_point_data_US_intersection(
char *pcFNameBase1,
char *pcFNameBase2,
my_constraint_data &dat
)
{
read_point_data_US( pcFNameBase1, dat );
my_constraint_data dat2;
read_point_data_US( pcFNameBase2, dat2 );
// Hash everything into a code to identify duplicates to be kept
// The idea is to keep the intersection of points in dat & dat2, which
// should be the most reliable correspondences (bipartitle nearest neighbors)
map<float,int> mapMatchDuplicateFinder;
for( int i = 0; i < dat2.iPoints; i++ )
{
float *points21 = dat2.pfPoints1 + 15*i;
float *points22 = dat2.pfPoints2 + 15*i;
float fKey = 1;
for( int j = 0; j < 15; j++ )
{
float fNum = points21[j]*points22[j]+1;
if( fNum != 0 )
{
fKey *= fNum;
}
}
mapMatchDuplicateFinder.insert( pair<float,int>(fKey,i) );
}
int iSavePoint = 0;
for( int i = 0; i < dat.iPoints; i++ )
{
float *points21 = dat.pfPoints1 + 15*i;
float *points22 = dat.pfPoints2 + 15*i;
float fKey = 1;
for( int j = 0; j < 15; j++ )
{
float fNum = points21[j]*points22[j]+1;
if( fNum != 0 )
{
fKey *= fNum;
}
}
// Test this hash code - to avoid multiple matches between precisely the same locations
map<float,int>::iterator itAmazingDupeFinder = mapMatchDuplicateFinder.find(fKey);
if( itAmazingDupeFinder != mapMatchDuplicateFinder.end() )
{
// Save
for( int j = 0; j < 15; j++ )
{
dat.pfPoints1[15*iSavePoint+j] = dat.pfPoints1[15*i+j];
dat.pfPoints2[15*iSavePoint+j] = dat.pfPoints2[15*i+j];
}
iSavePoint++;
}
}
dat.iPoints = iSavePoint;
// Delete secondary array
delete [] dat2.pfPoints1;
delete [] dat2.pfPoints2;
return 1;
}
//
// Fitness function for rotation data
//
double
nlopt_func_Fitness(
unsigned n,
const double *x,
double *gradient, /* NULL if not needed */
void *func_data
)
{
double dSumSqrError = 0;
my_constraint_data &dat = *(my_constraint_data *) func_data;
// Create rotation matrix from current vector
float vec2[3];
vec2[0] = x[0];
vec2[1] = x[1];
vec2[2] = x[2];
float mat[9];
convert_vector_to_rotation_matrix( vec2, mat );
for( int i = 0; i < dat.iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 3*i;
float *point_out = dat.pfPoints2 + 3*i;
float point_out_test[3];
// Multiply input point by current rotation matrix
mult_3x3_vector( mat, point_in, point_out_test );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( point_out, point_out_test );
// Sum up
dSumSqrError += fErrorSqr;
}
return dSumSqrError;
}
//
// Fitness function for scaled rigid transform
//
//double
//nlopt_func_Fitness_rigid(
// unsigned n,
// const double *x,
// double *gradient, /* NULL if not needed */
// void *func_data
// )
//{
// double dSumSqrError = 0;
//
// my_constraint_data &dat = *(my_constraint_data *) func_data;
//
// // Create rotation matrix from current vector
// float vec2[PARAMETER_DIM_RIG];
// float mat[9];
//
// for( int i = 0; i < 7; i++ )
// vec2[i] = x[i];
//
// // Create rotation matrix
// convert_vector_to_rotation_matrix( vec2, mat );
// // Multiply scale
// mult_3x3_scalar( mat, exp(vec2[6]), mat );
//
// for( int i = 0; i < dat.iPoints; i++ )
// {
// float *point_in = dat.pfPoints1 + 3*i;
// float *point_out = dat.pfPoints2 + 3*i;
//
// float point_out_test[3];
//
// // Multiply input point by current rotation matrix
// mult_3x3_vector( mat, point_in, point_out_test );
//
// // Add translation
// point_out_test[0] += vec2[3];
// point_out_test[1] += vec2[4];
// point_out_test[2] += vec2[5];
//
// // Compute squared error
// float fErrorSqr = vec3D_distsqr_3d( point_out, point_out_test );
//
// // Sum up
// dSumSqrError += fErrorSqr;
// }
//
// return dSumSqrError;
//}
int
_compareFloat(const void *v1, const void *v2)
{
float *pf1 = (float*)v1;
float *pf2 = (float*)v2;
if( *pf1 < *pf2 )
{
return -1;
}
else
{
return *pf1 > *pf2;
}
}
//
// Fitness function for scaled rigid transform of ultrasound data
//
// Here, points in my_constraint_data are 15 dimensional vectors.
// storing the first 3 rows of a 3D transform matrix (12), then input point (3)
//
//double
//nlopt_func_Fitness_rigid_US(
// unsigned n,
// const double *x,
// double *gradient, /* NULL if not needed */
// void *func_data
// )
//{
// double dSumSqrError = 0;
//
// my_constraint_data &dat = *(my_constraint_data *) func_data;
//
// // Create rotation matrix from current vector (length 7)
// // Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
// float vec2[PARAMETER_DIM_RIG];
// float mat[9];
//
// for( int i = 0; i < 7; i++ )
// vec2[i] = x[i];
//
// // Create rotation matrix
// convert_vector_to_rotation_matrix( vec2, mat );
// // Multiply scale
// //mult_3x3_scalar( mat, exp(vec2[6]), mat );
//
// // Copy scaled rotation matrix to 4x4 homogenous matrix
// float mat44[16];
// memset( &mat44[0], 0, sizeof(mat44) );
// memcpy( &mat44[0], &mat[0], 3*sizeof(float) );
// memcpy( &mat44[4], &mat[3], 3*sizeof(float) );
// memcpy( &mat44[8], &mat[6], 3*sizeof(float) );
//
// // Copy translations to 4x4 homegenous matrix
// mat44[3] = vec2[3];
// mat44[7] = vec2[4];
// mat44[11] = vec2[5];
// mat44[15] = 1;
//
// // Two US tracker transform matrices
// float mat44_1[16];
// float mat44_2[16];
// // Set last row to: [0,0,0,1]
// memset( &mat44_1[0], 0, sizeof(mat44_1) );
// memset( &mat44_2[0], 0, sizeof(mat44_2) );
// mat44_1[15] = 1;
// mat44_2[15] = 1;
//
// // Two product transform matrices
// float mat44_1_p[16];
// float mat44_2_p[16];
//
// float *pfDistSqr = new float[dat.iPoints];
//
// for( int i = 0; i < dat.iPoints; i++ )
// {
// float *point_in = dat.pfPoints1 + 15*i;
// float *point_out = dat.pfPoints2 + 15*i;
//
// // Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
// memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
// memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
//
// // Multiply current calibration matrix
// mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
// mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
//
// // Generate output 3D test points
// float point_test_in[3];
// float point_test_out[3];
// mult_4x4_vector_homogenous( mat44_1_p, point_in+12, point_test_in );
// mult_4x4_vector_homogenous( mat44_2_p, point_out+12, point_test_out );
//
// // Compute squared error
// float fErrorSqr = vec3D_distsqr_3d( point_test_in, point_test_out );
//
// // Sum up
// dSumSqrError += fErrorSqr;
// pfDistSqr[i] = fErrorSqr;
// }
//
// // Robust: keep top half of distance
// qsort( pfDistSqr, dat.iPoints, sizeof(float), _compareFloat );
// dSumSqrError = 0;
// float fPercentToKeep = 3.0/4.0;
// for( int i = 0; i < fPercentToKeep*dat.iPoints; i++ )
// {
// dSumSqrError += pfDistSqr[i];
// }
//
// delete [] pfDistSqr;
//
// return dSumSqrError;
//}
//
// nlopt_func_Fitness_rigid_US_scaled()
//
// Original US autocalibration function (e.g. MICCAI 2013)
//
double
nlopt_func_Fitness_rigid_US_scaled(
unsigned n,
const double *x,
double *gradient, /* NULL if not needed */
void *func_data
)
{
double dSumSqrError = 0;
my_constraint_data &dat = *(my_constraint_data *) func_data;
// Create rotation matrix from current vector (length 7)
// Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
float vec2[PARAMETER_DIM_RIG];
float mat[9];
for( int i = 0; i < 7; i++ )
vec2[i] = x[i];
float fScale = 1;
if( n == 7 )
{
fScale = exp(vec2[6]);
}
// Copy scaled rotation matrix to 4x4 homogenous matrix
float mat44[16];
convert_vector_to_matrix4x4( vec2, mat44 );
// Two US tracker transform matrices
float mat44_1[16];
float mat44_2[16];
// Set last row to: [0,0,0,1]
memset( &mat44_1[0], 0, sizeof(mat44_1) );
memset( &mat44_2[0], 0, sizeof(mat44_2) );
mat44_1[15] = 1;
mat44_2[15] = 1;
// Two product transform matrices
float mat44_1_p[16];
float mat44_2_p[16];
float *pfDistSqr = new float[dat.iPoints];
double pdAbsErrorXYZ[3];
pdAbsErrorXYZ[0] = pdAbsErrorXYZ[1] = pdAbsErrorXYZ[2] = 0;
for( int i = 0; i < dat.iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
// Copy in scaled points
float p_in[3];
float p_out[3];
for( int j = 0; j < 3; j++ )
{
p_in[j] = fScale*point_in[12+j];
p_out[j] = fScale*point_out[12+j];
if( j < 2 )
{
// Add 10 to each coordinate to see the effect
//p_in[j] += 50;
//p_out[j] += 50;
}
}
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Point 1: multiply current calibration matrix
float point_test_in[3];
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_vector_homogenous( mat44_1_p, p_in, point_test_in );
// Point 2: multiply current calibration matrix
float point_test_out[3];
if( dat.iErrorCalib )
{
printf( "Error: this code has been changed & untested\n" );
//// Pass Point 1 through ground truth calibration, for evaluating calibratin error
//mult_4x4_matrix( mat44_1, &dat.pfCalib[0], mat44_2_p );
//mult_4x4_vector_homogenous( mat44_2_p, p_in, point_test_out );
//// Alternative 1 - pass point 2 though ground truth calibration
//mult_4x4_matrix( mat44_2, &dat.pfCalib[0], mat44_2_p );
//mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
//// Alternative 2 - for shifted image points, reverse shift,
//// pass through ground truth.
//float point_out_shifted[3];
//point_out_shifted[0] = p_in[0] + 315;
//point_out_shifted[1] = p_in[1] + 315;
//point_out_shifted[2] = p_in[2];
//mult_4x4_matrix( mat44_1, &dat.pfCalib[0], mat44_2_p );
//mult_4x4_vector_homogenous( mat44_2_p, point_out_shifted, point_test_out );
}
else
{
// Pass Point 2 through current calibration matrix, for autocalibration optimization
mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
}
// Rescale to pixel units??
//vec3D_mult_scalar( point_test_in, 1.0f/fScale );
//vec3D_mult_scalar( point_test_out, 1.0f/fScale );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( point_test_in, point_test_out );
for( int k = 0; k < 3; k++ )
pdAbsErrorXYZ[k] = fabs(point_test_in[k] - point_test_out[k]);
// Sum up
dSumSqrError += fErrorSqr;
pfDistSqr[i] = fErrorSqr;
}
// Robust: keep top half of distance
qsort( pfDistSqr, dat.iPoints, sizeof(float), _compareFloat );
dSumSqrError = 0;
//float fPercentToKeep = 3.0/4.0;
float fPercentToKeep = dat.fPercentToKeep;
for( int i = 0; i < fPercentToKeep*dat.iPoints; i++ )
{
dSumSqrError += sqrt(pfDistSqr[i]);
}
// Original return value
float fReturnValueMM = dSumSqrError / (fPercentToKeep*dat.iPoints);
return fReturnValueMM;
// This here is all experimental stuff
// didn't really pan out ... yet
dSumSqrError = 1;
for( int i = 0; i < dat.iPoints; i++ )
{
float fDist = sqrt(pfDistSqr[i]);
if( fDist < 4.0f )
{
dSumSqrError += (4.0f-fDist);
}
else
{
dSumSqrError += 10;
}
}
delete [] pfDistSqr;
float fReturnValueRANSAC = dSumSqrError;//1.0f / dSumSqrError;
return fReturnValueRANSAC;
}
//
// nlopt_func_Fitness_rigid_US_scaled_test_alignment()
//
// Modified nlopt_func_Fitness_rigid_US_scaled_test() to
// include case where data are misaligned.
//
double
nlopt_func_Fitness_rigid_US_scaled_test_alignment(
unsigned n,
const double *x,
double *gradient, /* NULL if not needed */
void *func_data
)
{
double dSumSqrError = 0;
my_constraint_data &dat = *(my_constraint_data *) func_data;
// Create rotation matrix from current vector (length 7)
// Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
float vec2[PARAMETER_DIM_RIG];
float mat[9];
for( int i = 0; i < 7; i++ )
vec2[i] = x[i];
float fScale = 1;
if( n == 7 )
{
fScale = exp(vec2[6]);
}
//vec2[0] = 0; vec2[1] = 0; vec2[2] = 0;
// Copy scaled rotation matrix to 4x4 homogenous matrix
float mat44[16];
float mat44_align[16];
convert_vector_to_matrix4x4( dat.pfCalib, mat44 );
convert_vector_to_matrix4x4( dat.pfAlign, mat44_align );
// Initialze
if( dat.bPerformAlign )
{
convert_vector_to_matrix4x4( vec2, mat44_align );
}
else
{
convert_vector_to_matrix4x4( vec2, mat44 );
}
// Two US tracker transform matrices
float mat44_1[16];
float mat44_2[16];
// Set last row to: [0,0,0,1]
memset( &mat44_1[0], 0, sizeof(mat44_1) );
memset( &mat44_2[0], 0, sizeof(mat44_2) );
mat44_1[15] = 1;
mat44_2[15] = 1;
// Two product transform matrices
float mat44_1_p[16];
float mat44_2_p[16];
float mat44_2_p_align[16];
float *pfDistSqr = new float[dat.iPoints];
double pdAbsErrorXYZ[3];
pdAbsErrorXYZ[0] = pdAbsErrorXYZ[1] = pdAbsErrorXYZ[2] = 0;
for( int i = 0; i < dat.iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
// Copy in scaled points
float p_in[3];
float p_out[3];
for( int j = 0; j < 3; j++ )
{
p_in[j] = fScale*point_in[12+j];
p_out[j] = fScale*point_out[12+j];
if( j < 2 )
{
// Add 10 to each coordinate to see the effect
//p_in[j] += 50;
//p_out[j] += 50;
}
}
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Point 1: multiply current calibration matrix
float point_test_in[3];
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_vector_homogenous( mat44_1_p, p_in, point_test_in );
// Point 2: multiply current calibration matrix, left multiply 3D alignment matrix.
float point_test_out[3];
mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
mult_4x4_matrix( mat44_align, mat44_2_p, mat44_2_p_align );
mult_4x4_vector_homogenous( mat44_2_p_align, p_out, point_test_out );
//mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
//mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( point_test_in, point_test_out );
for( int k = 0; k < 3; k++ )
pdAbsErrorXYZ[k] = fabs(point_test_in[k] - point_test_out[k]);
// Sum up
dSumSqrError += fErrorSqr;
pfDistSqr[i] = fErrorSqr;
}
// Robust: keep top half of distance
qsort( pfDistSqr, dat.iPoints, sizeof(float), _compareFloat );
dSumSqrError = 0;
//float fPercentToKeep = 3.0/4.0;
float fPercentToKeep = dat.fPercentToKeep;
for( int i = 0; i < fPercentToKeep*dat.iPoints; i++ )
{
dSumSqrError += sqrt(pfDistSqr[i]);
}
// Original return value
float fReturnValueMM = dSumSqrError / (fPercentToKeep*dat.iPoints);
return fReturnValueMM;
}
//
// nlopt_func_Fitness_rigid_US_scaled_centered()
//
// This function was derived from nlopt_func_Fitness_rigid_US_scaled(), the goal
// is to compute
//
double
nlopt_func_Fitness_rigid_US_scaled_centered(
unsigned n,
const double *x,
double *gradient, /* NULL if not needed */
void *func_data
)
{
double dSumSqrError = 0;
my_constraint_data &dat = *(my_constraint_data *) func_data;
// Create rotation matrix from current vector (length 7)
// Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
float vec2[PARAMETER_DIM_RIG];
float mat[9];
for( int i = 0; i < 7; i++ )
vec2[i] = x[i];
float fScale = 1;
if( n == 7 )
{
fScale = exp(vec2[6]);
}
// Copy scaled rotation matrix to 4x4 homogenous matrix
float mat44[16];
convert_vector_to_matrix4x4( vec2, mat44 );
// Two US tracker transform matrices
float mat44_1[16];
float mat44_2[16];
// Set last row to: [0,0,0,1]
memset( &mat44_1[0], 0, sizeof(mat44_1) );
memset( &mat44_2[0], 0, sizeof(mat44_2) );
mat44_1[15] = 1;
mat44_2[15] = 1;
// Two product transform matrices
float mat44_1_p[16];
float mat44_2_p[16];
float *pfDistSqr = new float[dat.iPoints];
double pdAbsErrorXYZ[3];
pdAbsErrorXYZ[0] = pdAbsErrorXYZ[1] = pdAbsErrorXYZ[2] = 0;
for( int i = 0; i < dat.iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
// Copy in scaled points
float p_in[3];
float p_out[3];
for( int j = 0; j < 3; j++ )
{
p_in[j] = fScale*point_in[12+j];
p_out[j] = fScale*point_out[12+j];
if( j < 2 )
{
// Add 10 to each coordinate to see the effect
//p_in[j] += 50;
//p_out[j] += 50;
}
}
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Point 1: multiply current calibration matrix
float point_test_in[3];
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_vector_homogenous( mat44_1_p, p_in, point_test_in );
// Point 2: multiply current calibration matrix
float point_test_out[3];
if( dat.iErrorCalib )
{
// Pass Point 1 through ground truth calibration, for evaluating calibratin error
mult_4x4_matrix( mat44_1, &dat.pfCalib[0], mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_in, point_test_out );
// Alternative 1 - pass point 2 though ground truth calibration
mult_4x4_matrix( mat44_2, &dat.pfCalib[0], mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
// Alternative 2 - for shifted image points, reverse shift,
// pass through ground truth.
float point_out_shifted[3];
point_out_shifted[0] = p_in[0] + 315;
point_out_shifted[1] = p_in[1] + 315;
point_out_shifted[2] = p_in[2];
mult_4x4_matrix( mat44_1, &dat.pfCalib[0], mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, point_out_shifted, point_test_out );
}
else
{
// Pass Point 2 through current calibration matrix, for autocalibration optimization
mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
}
// Rescale to pixel units??
//vec3D_mult_scalar( point_test_in, 1.0f/fScale );
//vec3D_mult_scalar( point_test_out, 1.0f/fScale );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( point_test_in, point_test_out );
for( int k = 0; k < 3; k++ )
pdAbsErrorXYZ[k] = fabs(point_test_in[k] - point_test_out[k]);
// Sum up
dSumSqrError += fErrorSqr;
pfDistSqr[i] = fErrorSqr;
}
// Robust: keep top half of distance
qsort( pfDistSqr, dat.iPoints, sizeof(float), _compareFloat );
dSumSqrError = 0;
//float fPercentToKeep = 3.0/4.0;
float fPercentToKeep = dat.fPercentToKeep;
for( int i = 0; i < fPercentToKeep*dat.iPoints; i++ )
{
dSumSqrError += sqrt(pfDistSqr[i]);
}
delete [] pfDistSqr;
return dSumSqrError / (fPercentToKeep*dat.iPoints);
}
//
// nlopt_func_Fitness_rigid_US_scaled_compute_transformed_point_distances()
//
// This is Sandy's idea, to test inter-point distances in 3D.
// Goal: see if distances between points remain constant, to see if transform is rigid.
//
double
nlopt_func_Fitness_rigid_US_scaled_compute_transformed_point_distances(
unsigned n,
const double *x,
double *gradient, /* NULL if not needed */
void *func_data
)
{
double dSumSqrError = 0;
my_constraint_data &dat = *(my_constraint_data *) func_data;
// Create rotation matrix from current vector (length 7)
// Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
float vec2[PARAMETER_DIM_RIG];
float mat[9];
for( int i = 0; i < 7; i++ )
vec2[i] = x[i];
float fScale = 1;
if( n == 7 )
{
fScale = exp(vec2[6]);
}
// Copy scaled rotation matrix to 4x4 homogenous matrix
float mat44[16];
convert_vector_to_matrix4x4( vec2, mat44 );
// Two US tracker transform matrices
float mat44_1[16];
float mat44_2[16];
// Set last row to: [0,0,0,1]
memset( &mat44_1[0], 0, sizeof(mat44_1) );
memset( &mat44_2[0], 0, sizeof(mat44_2) );
mat44_1[15] = 1;
mat44_2[15] = 1;
// Two product transform matrices
float mat44_1_p[16];
float mat44_2_p[16];
float *pfDistSqr = new float[dat.iPoints];
double pdAbsErrorXYZ[3];
pdAbsErrorXYZ[0] = pdAbsErrorXYZ[1] = pdAbsErrorXYZ[2] = 0;
float *pfPoints3D = new float[3*dat.iPoints];
for( int i = 0; i < dat.iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
// Copy in scaled points
float p_in[3];
float p_out[3];
for( int j = 0; j < 3; j++ )
{
p_in[j] = fScale*point_in[12+j];
p_out[j] = fScale*point_out[12+j];
if( j < 2 )
{
// Add 10 to each coordinate to see the effect
//p_in[j] += 50;
//p_out[j] += 50;
}
}
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Point 1: multiply current calibration matrix
float point_test_in[3];
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_vector_homogenous( mat44_1_p, p_in, point_test_in );
mult_4x4_vector_homogenous( mat44_1_p, p_in, pfPoints3D+3*i );
}
// Now compute inter-point distances for a random subset of (20 points)
FILE *outfile = fopen( "interpoint_distance.txt", "wt" );
for( int i = 0; i < dat.iPoints; i += dat.iPoints/20 )
{
for( int j = i; j < dat.iPoints; j += dat.iPoints/20 )
{
float fErrorSqr = vec3D_distsqr_3d( pfPoints3D+3*i, pfPoints3D+3*j );
fprintf( outfile, "%f\t", fErrorSqr );
}
fprintf( outfile, "\n" );
}
fclose( outfile );
return 1.0;
}
//
// nlopt_func_Fitness_rigid_US_scaled_compute_transformed_point_distances_to_ground_truth()
//
// Here try to figure out what precisely is the error compared to ground truth (identity) calibration matrix.
//
double
nlopt_func_Fitness_rigid_US_scaled_compute_transformed_point_distances_to_ground_truth(
unsigned n,
const double *x,
double *gradient, /* NULL if not needed */
void *func_data,
char *pcOutFile
)
{
double dSumSqrError = 0;
my_constraint_data &dat = *(my_constraint_data *) func_data;
// Create rotation matrix from current vector (length 7)
// Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
float vec2[PARAMETER_DIM_RIG];
float mat[9];
for( int i = 0; i < 7; i++ )
vec2[i] = x[i];
float fScale = 1;
if( n == 7 )
{
fScale = exp(vec2[6]);
}
// Copy scaled rotation matrix to 4x4 homogenous matrix
float mat44[16];
convert_vector_to_matrix4x4( vec2, mat44 );
// Two US tracker transform matrices
float mat44_1[16];
float mat44_2[16];
// Set last row to: [0,0,0,1]
memset( &mat44_1[0], 0, sizeof(mat44_1) );
memset( &mat44_2[0], 0, sizeof(mat44_2) );
mat44_1[15] = 1;
mat44_2[15] = 1;
// Two product transform matrices
float mat44_1_p[16];
float mat44_2_p[16];
float *pfDistSqr = new float[dat.iPoints];
double pdAbsErrorXYZ[3];
pdAbsErrorXYZ[0] = pdAbsErrorXYZ[1] = pdAbsErrorXYZ[2] = 0;
float *pfPoints3D1 = new float[3*dat.iPoints];
float *pfPoints3D2 = new float[3*dat.iPoints];
FILE *outfile = fopen( pcOutFile, "a+" );
for( int i = 0; i < 16; i++ )
{
if( i % 4 == 0 )
{
fprintf( outfile, "\n" );
}
fprintf( outfile, "%f\t", mat44[i] );
}
fprintf( outfile, " ------ \n" );
for( int i = 0; i < dat.iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
// Copy in scaled points
float p_in[3];
float p_out[3];
for( int j = 0; j < 3; j++ )
{
p_in[j] = fScale*point_in[12+j];
p_out[j] = fScale*point_out[12+j];
if( j < 2 )
{
// Add 10 to each coordinate to see the effect
//p_in[j] += 50;
//p_out[j] += 50;
}
}
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Point 1: multiply current calibration matrix
float point_test_in[3];
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_vector_homogenous( mat44_1_p, p_in, point_test_in );
// Point 2: multiply current calibration matrix
float point_test_out[3];
// Pass Point 2 through current calibration matrix, for autocalibration optimization
mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
fprintf( outfile, "%f\t%f\t%f\n%f\t%f\t%f\n",
point_test_in[0], point_test_in[1], point_test_in[2],
point_test_out[0], point_test_out[1], point_test_out[2]
);
}
fclose( outfile );
return 1.0;
}
//
// nlopt_func_Fitness_rigid_US_scaled_plane()
//
// This function was develop to determine the scaled rigid transform
// from 2D points in an ultrasound plane to 3D points in the world.
// June 10 2013.
// Here, argument *x is the transformation matrix for a particular
// ultrasound plane. In func_data (my_constraint_data), the
//
double
nlopt_func_Fitness_rigid_US_scaled_plane(
unsigned n,
const double *x,
double *gradient, /* NULL if not needed */
void *func_data
)
{
double dSumSqrError = 0;
my_constraint_data &dat = *(my_constraint_data *) func_data;
// Create rotation matrix from current vector (length 7)
// Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
float vec2[PARAMETER_DIM_RIG];
float mat[9];
for( int i = 0; i < 7; i++ )
vec2[i] = x[i];
// Create rotation matrix
convert_vector_to_rotation_matrix( vec2, mat );
// Multiply scale - pretend it doesn't change
//mult_3x3_scalar( mat, exp(vec2[6]), mat );
float fScale = 1;//exp(vec2[6]);
// Copy scaled rotation matrix to 4x4 homogenous matrix
float mat44[16];
memset( &mat44[0], 0, sizeof(mat44) );
memcpy( &mat44[0], &mat[0], 3*sizeof(float) );
memcpy( &mat44[4], &mat[3], 3*sizeof(float) );
memcpy( &mat44[8], &mat[6], 3*sizeof(float) );
// Copy translations to 4x4 homegenous matrix
mat44[3] = vec2[3];
mat44[7] = vec2[4];
mat44[11] = vec2[5];
mat44[15] = 1;
// Two US tracker transform matrices
float mat44_1[16];
float mat44_2[16];
// Set last row to: [0,0,0,1]
memset( &mat44_1[0], 0, sizeof(mat44_1) );
memset( &mat44_2[0], 0, sizeof(mat44_2) );
mat44_1[15] = 1;
mat44_2[15] = 1;
// Two product transform matrices
float mat44_1_p[16];
float mat44_2_p[16];
float *pfDistSqr = new float[dat.iPoints];
for( int i = 0; i < dat.iPoints; i++ )
{
// Note: each data record is 15 elements long (4x3=12 for transformation matrix, 3 for an xyz point).
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
// Copy in scaled points
float p_in[3];
float p_out[3];
for( int j = 0; j < 3; j++ )
{
// Determine scaled 3D point
p_in[j] = fScale*point_in[12+j];
p_out[j] = fScale*point_out[12+j];
if( j < 2 )
{
// Add 10 to each coordinate to see the effect
//p_in[j] += 50;
//p_out[j] += 50;
}
}
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 ); // ***
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Copy in current estimated transformation matrix - should hopefully converge
// to something like what is currently there ...
// This is actually redundant from the step above *** ...
memcpy( &mat44_1[0], mat44, sizeof(float)*16 );
// Multiply current calibration matrix - embedded in data
mult_4x4_matrix( mat44_1, dat.pfCalib, mat44_1_p );
mult_4x4_matrix( mat44_2, dat.pfCalib, mat44_2_p );
// Generate output 3D test points
float point_test_in[3];
float point_test_out[3];
mult_4x4_vector_homogenous( mat44_1_p, p_in, point_test_in );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( point_test_in, point_test_out );
// Sum up
dSumSqrError += fErrorSqr;
pfDistSqr[i] = fErrorSqr;
}
// Robust: keep top half of distance
qsort( pfDistSqr, dat.iPoints, sizeof(float), _compareFloat );
dSumSqrError = 0;
//float fPercentToKeep = 3.0/4.0;
float fPercentToKeep =0.75;
for( int i = 0; i < fPercentToKeep*dat.iPoints; i++ )
{
dSumSqrError += sqrt(pfDistSqr[i]);
}
delete [] pfDistSqr;
if( fPercentToKeep*dat.iPoints > 0 )
{
dSumSqrError /= fPercentToKeep*dat.iPoints;
}
return dSumSqrError;
}
int
main_test_rotation_minimization(
)
{
nlopt_stopping nlStopCond;
double xtolabs[PARAMETER_DIM_ROT] = {0,0,0};
memset( &nlStopCond, 0, sizeof(nlStopCond) );
nlStopCond.xtol_abs = &xtolabs[0];
nlStopCond.xtol_rel = -1;
nlStopCond.ftol_abs = -1;
nlStopCond.ftol_rel = -1;
nlStopCond.maxeval = 300; // Go 300 iterations
nlStopCond.n = PARAMETER_DIM_ROT;
my_constraint_data dat;
generate_minimization_test_data( dat, 1000 );
int n = PARAMETER_DIM_ROT;
double x_params[PARAMETER_DIM_ROT] = {1,1,1};
double x_lb[PARAMETER_DIM_ROT] = {-10,-10,-10};
double x_ub[PARAMETER_DIM_ROT] = {10,10,10};
double x_step[PARAMETER_DIM_ROT] = {5,5,5};
double minf;
nldrmd_minimize(
n, nlopt_func_Fitness, &dat,
&x_lb[0],
&x_ub[0],
&x_params[0],
&minf,
&x_step[0], //const double *xstep, /* initial step sizes */
&nlStopCond
);
return 1;
}
//
// premultiply_data()
//
// Multiply data by a test matrix.
//
//
//
int
random_multiply_data(
my_constraint_data &dat,
int iParamCount,
int bPostMultiply = 1, // 0 for pre-multiply (alignment), 1 for post-multiply (calibration)
int iSide = 0 // If 1, then only premultiple pfPoints1, if 2 then only pfPoints2, if 0 (default) then both
)
{
float x_params[PARAMETER_DIM_RIG] = {1,2,3,0,0,0,2};
float fNum;
//x_params[0] = 30*(0.5f-(rand()/((float)RAND_MAX)));
//x_params[1] = 30*(0.5f-(rand()/((float)RAND_MAX)));
//x_params[2] = 30*(0.5f-(rand()/((float)RAND_MAX)));
x_params[3] = 200*2*(0.5f-(rand()/((float)RAND_MAX)));
x_params[4] = 200*2*(0.5f-(rand()/((float)RAND_MAX)));
x_params[5] = 200*2*(0.5f-(rand()/((float)RAND_MAX)));
x_params[0] = 10*(0.5f-rand()/((float)RAND_MAX));
x_params[1] = 10*(0.5f-rand()/((float)RAND_MAX));
x_params[2] = 10*(0.5f-rand()/((float)RAND_MAX));
if( iParamCount > 6 )
{
//x_params[6] = 2*(0.5f-rand()/((float)RAND_MAX));
//x_params[6] = 2.3*2.0*(0.5f-rand()/((float)RAND_MAX));
x_params[6] = 2.3*2.0*(0.5f-rand()/((float)RAND_MAX));
}
else
{
x_params[6] = 0;
}
printf( "Random pre-multiply: one-side %d:\n%f %f %f %f %f %f %f\n",
iSide,
x_params[0],
x_params[1],
x_params[2],
x_params[3],
x_params[4],
x_params[5],
x_params[6]
);
// Create rotation matrix from current vector (length 7)
// Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
float mat[9];
// Create scaled rotation matrix
convert_vector_to_rotation_matrix( x_params, mat );
float fScale = exp(x_params[6]);
mult_3x3_scalar( mat, fScale, mat );
// Copy scaled rotation matrix to 4x4 homogenous matrix
float mat44[16];
memset( &mat44[0], 0, sizeof(mat44) );
memcpy( &mat44[0], &mat[0], 3*sizeof(float) );
memcpy( &mat44[4], &mat[3], 3*sizeof(float) );
memcpy( &mat44[8], &mat[6], 3*sizeof(float) );
// Copy translations to 4x4 homegenous matrix
mat44[3] = x_params[3];
mat44[7] = x_params[4];
mat44[11] = x_params[5];
mat44[15] = 1;
// Two US tracker transform matrices - initialize constant entries
float mat44_1[16];
float mat44_2[16];
// Set last row to: [0,0,0,1]
memset( &mat44_1[0], 0, sizeof(mat44_1) );
memset( &mat44_2[0], 0, sizeof(mat44_2) );
mat44_1[15] = 1;
mat44_2[15] = 1;
// Two product transform matrices
float mat44_1_p[16];
float mat44_2_p[16];
float *pfDistSqr = new float[dat.iPoints];
for( int i = 0; i < dat.iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
if( bPostMultiply ) // Post-multiply, random calibration maxtrix, typically applied to both sides to test calibration
{
// Multiply current calibration matrix
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
}
else // Pre-multiply, random alignment matrix, typically applied to one side to test alignment
{
// Multiply current calibration matrix
mult_4x4_matrix( mat44, mat44_1, mat44_1_p );
mult_4x4_matrix( mat44, mat44_2, mat44_2_p );
}
// Write out transformed 3 rows (length 3x4 = 12) of US tracker transform matrices
if( iSide == 0 || iSide == 1 )
memcpy( point_in, &mat44_1_p[0], sizeof(float)*12 );
if( iSide == 0 || iSide == 2 )
memcpy( point_out, &mat44_2_p[0], sizeof(float)*12 );
}
return 1;
}
int
main_test_rigid_US_minimization(
my_constraint_data &dat,
float &fResultError,
int bRandomStartPoint = 0 // For a random starting point
)
{
nlopt_stopping nlStopCond;
double xtolabs[PARAMETER_DIM_RIG] = {0,0,0,0,0,0,0};
memset( &nlStopCond, 0, sizeof(nlStopCond) );
nlStopCond.xtol_abs = &xtolabs[0]; // tolerances for individual parameters, for assessing convergence
nlStopCond.xtol_rel = -1; // tolerance
nlStopCond.ftol_abs = -1;
nlStopCond.ftol_rel = -1;
nlStopCond.maxeval = 10000; // Go 300 iterations
nlStopCond.n = PARAMETER_DIM_RIG;
// Calibration matrix for one good AMIGO calibration
float pfCalib[] = {0.104828101, 0.000981117, 0.004546451, -36.313503, 0.004569771, -0.002627669, -0.104798743, -1.8013641, -0.000866027, 0.104893735, -0.002667809, -1.0628991, 0, 0, 0, 1 };
// Calibration matrix: identity
float pfCalibIdenity[] =
{1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };
// Set input data fields for optimization
dat.fPercentToKeep = 0.2;//3.0/4.0;
dat.iErrorCalib = 0;
dat.bPerformAlign = 0;
// Set to
memset( dat.pfAlign, 0, sizeof(dat.pfAlign) );
memset( dat.pfCalib, 0, sizeof(dat.pfCalib) );
//float vec[3] = {-.3,-.2,.1};
//float mat[3*3] = {1,0,0,0,1,0,0,0,1};
//convert_vector_to_rotation_matrix( vec, mat );
//convert_rotation_matrix_to_vector( vec, mat );
int n = PARAMETER_DIM_RIG;
//
// *** Note: we need to specify proper/effective bounds
//
//
//double x_params[PARAMETER_DIM_RIG] = {1,-4,3,0,0,0,1};
double x_params[PARAMETER_DIM_RIG] = {0,0.0,0.0,0,0,0,0};
//double x_lb[PARAMETER_DIM_RIG] = {-10,-10,-10,-500,-500,-500,-5};
//double x_ub[PARAMETER_DIM_RIG] = { 10, 10, 10, 500, 500, 500, 5};
double x_lb[PARAMETER_DIM_RIG] = {-10,-10,-10,-200,-200,-200,-5};
double x_ub[PARAMETER_DIM_RIG] = { 10, 10, 10, 200, 200, 200, 5};
double x_step[PARAMETER_DIM_RIG] = {2,2,2,100,100,100,1};
//double x_params[PARAMETER_DIM_RIG] = {0.01,0.01,0.01,0,0,0,0};
//double x_lb[PARAMETER_DIM_RIG] = {-7,-7,-7,-20000,-20000,-2000,-3};
//double x_ub[PARAMETER_DIM_RIG] = { 7, 7, 7, 20000, 20000, 2000, 3};
//double x_step[PARAMETER_DIM_RIG] = {1,1,1,1000,1000,1000,1};
// Control wether last scale parameter is considered
//n = 7;
n = 6;
// **********************************************
// This is for testing random calibration matrices
// Comment this out when testing ground truth error
//
// random_multiply_data( dat, n, 1 ); // For testing calibration
//
// random_multiply_data( dat, n, 0, 1 ); // For testing alignment
dat.bPerformAlign = 1;
float fError;
fError = nlopt_func_Fitness_rigid_US_scaled( n, &x_params[0],0,&dat);
fError = nlopt_func_Fitness_rigid_US_scaled_test_alignment( n, &x_params[0],0,&dat);
//x_params[4] = 20000;
//fError = nlopt_func_Fitness_rigid_US_scaled( n, &x_params[0],0,&dat);
if( bRandomStartPoint )
{
// Initialize algorithm starting point to somewhere within search range
for( int i = 0; i < PARAMETER_DIM_RIG; i++ )
{
float fRange = x_ub[i]-x_lb[i];
float fRand = rand()/(RAND_MAX+1.0f);
x_params[i] = x_lb[i]+fRand*fRange;
}
}
double minf;
nlopt_result res;
for( int i = 0; i < 100; i++ )
{
// 1) Perform alignment - should be independent of calibration
dat.bPerformAlign = 0;
dat.fPercentToKeep = 0.7;
//n = 6;
nlStopCond.nevals = 0;
res =
nldrmd_minimize(
//sbplx_minimize(
n,
nlopt_func_Fitness_rigid_US_scaled_test_alignment,
//nlopt_func_Fitness_rigid_US_scaled, // ** US paper results
//nlopt_func_Fitness_rigid_US,
&dat,
&x_lb[0],
&x_ub[0],
&x_params[0],
&minf,
&x_step[0], //const double *xstep, /* initial step sizes */
&nlStopCond
);
// See how it works ...
fError = nlopt_func_Fitness_rigid_US_scaled( n, &x_params[0],0,&dat);
fError = nlopt_func_Fitness_rigid_US_scaled_test_alignment( n, &x_params[0],0,&dat);
fResultError = fError;
// save alignment matrix, perform calibration
if( dat.bPerformAlign )
{
for( int j = 0; j < PARAMETER_DIM_RIG; j++ ) dat.pfAlign[j] = x_params[j];
}
else
{
for( int j = 0; j < PARAMETER_DIM_RIG; j++ ) dat.pfCalib[j] = x_params[j];
}
// 2) Perform calibration - should be independent of alignment, if alignment is correct...
dat.bPerformAlign = 0;
dat.fPercentToKeep = 0.2;
res =
nldrmd_minimize(
//sbplx_minimize(
n,
nlopt_func_Fitness_rigid_US_scaled_test_alignment,
//nlopt_func_Fitness_rigid_US_scaled, // ** US paper results
//nlopt_func_Fitness_rigid_US,
&dat,
&x_lb[0],
&x_ub[0],
&x_params[0],
&minf,
&x_step[0], //const double *xstep, /* initial step sizes */
&nlStopCond
);
// save calibration matrix for alignment
// save alignment matrix, perform calibration
if( dat.bPerformAlign )
{
for( int j = 0; j < PARAMETER_DIM_RIG; j++ ) dat.pfAlign[j] = x_params[j];
}
else
{
for( int j = 0; j < PARAMETER_DIM_RIG; j++ ) dat.pfCalib[j] = x_params[j];
}
// See how it works ...
fError = nlopt_func_Fitness_rigid_US_scaled( n, &x_params[0],0,&dat);
fError = nlopt_func_Fitness_rigid_US_scaled_test_alignment( n, &x_params[0],0,&dat);
printf( "Iteration: %d\tError: %f\n", i, fError );
printf( "Calib:\n%f %f %f %f %f %f %f\n",
dat.pfCalib[0],
dat.pfCalib[1],
dat.pfCalib[2],
dat.pfCalib[3],
dat.pfCalib[4],
dat.pfCalib[5],
dat.pfCalib[6]
);
printf( "Align:\n%f %f %f %f %f %f %f\n",
dat.pfAlign[0],
dat.pfAlign[1],
dat.pfAlign[2],
dat.pfAlign[3],
dat.pfAlign[4],
dat.pfAlign[5],
dat.pfAlign[6]
);
fResultError = fError;
}
// Test distances between transformed points - sanity check
// nlopt_func_Fitness_rigid_US_scaled_compute_transformed_point_distances( n, &x_params[0],0,&dat);
// Output points according to identified transform
nlopt_func_Fitness_rigid_US_scaled_compute_transformed_point_distances_to_ground_truth( n, &x_params[0],0,&dat, "transformed_points_calibration.txt" );
// **********************************************
// Test ground truth calibration
//
// Works when random_postmultiply_data( dat, n ) above is disabled/commented out
// This should be commented out when running randomized calibration,
// because the ground truth transform is no longer identity.
//
set_vector_to_identity( &x_params[0] );
fError = nlopt_func_Fitness_rigid_US_scaled( n, &x_params[0],0,&dat);
//x_params[3] = 315;x_params[4] = 315;
// Test distances between transformed points - sanity check
// nlopt_func_Fitness_rigid_US_scaled_compute_transformed_point_distances( n, &x_params[0],0,&dat);
// Output points according to identity transform
nlopt_func_Fitness_rigid_US_scaled_compute_transformed_point_distances_to_ground_truth( n, &x_params[0],0,&dat, "transformed_points_identity.txt" );
float fScale = exp( x_params[6] );
return 1;
}
//
// main_test_plane_fitting()
//
// The idea here is to test fitting of individual ultrasound planes.
// June, 2013.
//
int
main_test_plane_fitting(
)
{
nlopt_stopping nlStopCond;
double xtolabs[PARAMETER_DIM_RIG] = {0,0,0,0,0,0,0};
memset( &nlStopCond, 0, sizeof(nlStopCond) );
nlStopCond.xtol_abs = &xtolabs[0]; // tolerances for individual parameters, for assessing convergence
nlStopCond.xtol_rel = -1; // tolerance
nlStopCond.ftol_abs = -1;
nlStopCond.ftol_rel = -1;
nlStopCond.maxeval = 10000; // Go 300 iterations
nlStopCond.n = PARAMETER_DIM_RIG;
my_constraint_data dat;
// Calibration matrix for one good AMIGO calibration
float pfCalib[] = {0.104828101, 0.000981117, 0.004546451, -36.313503, 0.004569771, -0.002627669, -0.104798743, -1.8013641, -0.000866027, 0.104893735, -0.002667809, -1.0628991, 0, 0, 0, 1 };
//dat.pfCalib = pfCalib;
memset( dat.pfCalib, 0, sizeof(dat.pfCalib) );
if( 1 )
{
// Read data from files
int iRows, iCols;
float ** p1, ** p2;
char pf1[2], pf2[2];
readArray( "C:\\writting\\cvs_stuff\\papers\\miccai-2013\\pics\\reconstruction\\non-linear.matches.X", &p1, iCols, iRows, pf1 );
readArray( "C:\\writting\\cvs_stuff\\papers\\miccai-2013\\pics\\reconstruction\\non-linear.matches.Y", &p2, iCols, iRows, pf2 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\non-linear.matches.X", &p1, iCols, iRows, pf1 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\non-linear.matches.Y", &p2, iCols, iRows, pf2 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\mr-non-linear.matches.X", &p1, iCols, iRows, pf1 );
//readArray( "C:\\Visual Studio Projects\\libs\\OpenCV2.2\\windows\\samples\\cpp\\mr-non-linear.matches.Y", &p2, iCols, iRows, pf2 );
dat.iPoints = iRows;
dat.pfPoints1 = p1[0];
dat.pfPoints2 = p2[0];
}
else
{
generate_minimization_test_data_rigid_US( dat, 200 );
}
int n = PARAMETER_DIM_RIG;
double x_params[PARAMETER_DIM_RIG] = {0.01,0.01,0.01,0,0,0,0};
double x_lb[PARAMETER_DIM_RIG] = {-10,-10,-10,-200,-200,-200,-5};
double x_ub[PARAMETER_DIM_RIG] = { 10, 10, 10, 200, 200, 200, 5};
double x_step[PARAMETER_DIM_RIG] = {1,1,1,5,5,5,1};
FILE *outfile = fopen( "correspondences-error.txt", "wt" );
int iFrame = 0;
for( int iIndex = 0; iIndex < dat.iPoints; iIndex++ )
{
// Start of current testing point
int iStartIndex = iIndex;
// Collect all correspondences with similar transform matrices
while( iIndex < dat.iPoints
&& memcmp( dat.pfPoints1+iStartIndex*15, dat.pfPoints1+iIndex*15, sizeof(float)*12 ) == 0
)
{
iIndex++;
}
// Init optimization parameters close to pre-existing transform
my_constraint_data dat_one_slice;
dat_one_slice.iPoints = iIndex-iStartIndex;
dat_one_slice.pfPoints1 = dat.pfPoints1 + 15*iStartIndex;
dat_one_slice.pfPoints2 = dat.pfPoints2 + 15*iStartIndex;
memcpy( dat_one_slice.pfCalib, dat.pfCalib, sizeof(dat.pfCalib) );
// Determine plane
n = 6; // Forget scale parameter for now
double minf;
nlopt_result res =
nldrmd_minimize(
n,
nlopt_func_Fitness_rigid_US_scaled_plane,
&dat_one_slice,
&x_lb[0],
&x_ub[0],
&x_params[0],
&minf,
&x_step[0], //const double *xstep, /* initial step sizes */
&nlStopCond
);
float pfPointIn[3] = {320,240,0};
float pfPointOut1[3];
float pfPointOut2[3];
float vec[3];
float mat44[16];
vec[0] = x_params[0];
vec[1] = x_params[1];
vec[2] = x_params[2];
convert_vector_to_rotation_matrix_4X4( vec, mat44 );
mat44[3] = x_params[3];
mat44[7] = x_params[4];
mat44[11] = x_params[5];
// Generate test point from estimated matrix
mult_4x4_vector_homogenous( mat44, pfPointIn, pfPointOut1 );
// Generate test point from ground truth matrix
// Copy in ground truth
memcpy( mat44, dat.pfPoints1+iStartIndex*15, sizeof(float)*12 );
mult_4x4_vector_homogenous( mat44, pfPointIn, pfPointOut2 );
float fErrorPlane = vec3D_dist_3d( pfPointOut1, pfPointOut2 );
// Test error
float fRobustError = nlopt_func_Fitness_rigid_US_scaled_plane( n, &x_params[0],0,&dat_one_slice);
fprintf( outfile, "%d\t%d\t%f\t%f\n", iFrame, iIndex-iStartIndex, fRobustError, fErrorPlane );
iFrame++;
}
fclose( outfile );
return 1;
}
typedef struct _KEYPOINT
{
float x;
float y;
float size;
float angle;
float response;
int octave;
int id;
} KEYPOINT;
typedef float DESCRIPTOR[64];
//
// read_in_features()
//
// Description:
// Reads in arrays from two binary files:
// 1) *.surf.key : keypoints
// 2) *.surf.dsc : descriptors
//
// Input:
// Text file name for ultrasound sequence/directory, e.g. "_02\pre\sweep_2a\2d\2a.txt"
//
// Outputs:
// None for the moment, only internal data structures are filed up:
// int iImages; // Number of images
// int * piKeysPerImage; // Array of keypoint counts for each image
// KEYPOINT ** ppkKeypoints; // Array of keypoints for each image
// float ** ppfDescriptors; // Array of descriptors for each image
//
int
read_in_features(
char *pcInputFile // "_02\\pre\\sweep_2a\\2d\\2a.txt"
)
{
// Data structures to read in
int iImages; // Number of images
int * piKeysPerImage; // Array of keypoint counts for each image
KEYPOINT ** ppkKeypoints; // Array of keypoints for each image
float ** ppfDescriptors; // Array of descriptors for each image
FILE *infile;
int iReturn;
int iKeypoints;
char pcFileName[400];
// Identify extension
//pcInputFile = "C:\\downloads\\data\\MNI\\bite-us\\group1\\_02\\pre\\sweep_2a\\2d\\2a.txt";
sprintf( pcFileName, pcInputFile );
char *pch = strstr( pcFileName, ".txt" );
// Open keypoints file
sprintf( pch, "%s", ".surf.key" );
infile = fopen( pcFileName, "rb" );
if( !infile )
{
printf( "Error: no key file found\n" );
return -1;
}
fread( &iImages, sizeof(iImages), 1, infile ); // number of images
ppkKeypoints = new KEYPOINT*[iImages];
piKeysPerImage = new int[iImages];
for( int i = 0; i < iImages; i++ )
{
fread( &iKeypoints, sizeof(iKeypoints), 1, infile ); // number of keypoints perimage
ppkKeypoints[i] = new KEYPOINT[iKeypoints];
piKeysPerImage[i] = iKeypoints;
for( int j = 0; j < iKeypoints; j++ )
{
fread( &(ppkKeypoints[i][j]), sizeof(KEYPOINT), 1, infile );
}
}
fclose( infile );
// Open descriptor file
sprintf( pch, "%s", ".surf.dsc" );
infile = fopen( pcFileName, "rb" );
fread( &iImages, sizeof(iImages), 1, infile ); // number of images, should be the same as previous
ppfDescriptors = new float*[iImages];
for( int i = 0; i < iImages; i++ )
{
int iRows;
int iCols;
int iType;
fread( &iRows, sizeof(iRows), 1, infile ); // number of keypoints perimage
fread( &iCols, sizeof(iCols), 1, infile ); // Should always be 64
fread( &iType, sizeof(iType), 1, infile ); // Should always be 5
if( iRows > 0 && iCols > 0 )
{
ppfDescriptors[i] = new float[iRows*iCols];
iReturn = fread( ppfDescriptors[i], sizeof(float), iRows*iCols, infile );
if( iReturn != iRows*iCols )
{
printf( "Something went wrong.\n" );
}
}
else
{
printf( "Zero feature image: %d\n", i );
}
}
fclose( infile );
return 0;
}
template <class T, class DIV>
void
mult_3x3_matrix_template(
T mat1[3][3],
T mat2[3][3],
T mat_out[3][3]
)
{
for( int i = 0; i < 3; i++ )
{
for( int j = 0; j < 3; j++ )
{
mat_out[i][j]=0;
for( int ii = 0; ii < 3; ii++ )
{
mat_out[i][j] += mat1[i][ii]*mat2[ii][j];
}
}
}
}
template <class T, class DIV>
void
mult_3x3_template(
T mat[3][3],
T vec_in[3],
T vec_out[3]
)
{
for( int i = 0; i < 3; i++ )
{
vec_out[i] = 0;
for( int j = 0; j < 3; j++ )
{
vec_out[i] += mat[i][j]*vec_in[j];
}
}
}
template <class T, class DIV>
void
transpose_3x3(
T mat_in[3][3],
T mat_trans[3][3]
)
{
for( int i = 0; i < 3; i++ )
{
for( int j = 0; j < 3; j++ )
{
mat_trans[i][j] = mat_in[j][i];
}
}
}
//
// determine_rotation_3point()
//
// Determines a 3D rotation matrix from 3 points to the cartesian frame.
// The first point pfP01 is at the origin (0,0,0)=(x,y,z)
// Vector pfP01->pfP02 defines the x-axis (1,0,0)=(x,y,z)
// The cross product of vectors pfP01->pfP02 and pfP01->pfP03 (pfV0_nm) defines the z-axis (0,0,1)=(x,y,z)
// The cross product of vectors pfP01->pfP02 and pfV0_nm definex the y-axis (0,1,0)=(x,y,z)
//
int
determine_rotation_3point(
float *pfP01, float *pfP02, float *pfP03, // points in image 1 (3d)
float *rot // rotation matrix (3x3)
)
{
float pfV0_12[3];
float pfV0_13[3];
float pfV0_nm[3];
// Subtract point 1 to convert to vectors
vec3D_diff_3d( pfP01, pfP02, pfV0_12 );
vec3D_diff_3d( pfP01, pfP03, pfV0_13 );
// Normalize vectors
vec3D_norm_3d( pfV0_12 );
vec3D_norm_3d( pfV0_13 );
// Cross product between 2 vectors to get normal
vec3D_cross_3d( pfV0_12, pfV0_13, pfV0_nm );
vec3D_norm_3d( pfV0_nm );
// Cross product between 1st vectors and normal to get orthogonal 3rd vector
vec3D_cross_3d( pfV0_nm, pfV0_12, pfV0_13 );
vec3D_norm_3d( pfV0_13 );
rot[0]=pfV0_12[0];
rot[1]=pfV0_12[1];
rot[2]=pfV0_12[2];
rot[3]=pfV0_13[0];
rot[4]=pfV0_13[1];
rot[5]=pfV0_13[2];
rot[6]=pfV0_nm[0];
rot[7]=pfV0_nm[1];
rot[8]=pfV0_nm[2];
return 1;
}
//
// determine_similarity_transform_3point()
//
// Determines a 3 point similarity transform in 3D.
//
// Inputs:
// Corresponding points
// float *pfP01, float *pfP02, float *pfP03,
// float *pfP11, float *pfP12, float *pfP13,
//
// Outputs
// rot0: rotation matrix, about the first pair of corresponding points pfP01<->pfP11.
// fScaleDiff: scale change.
// (rot1: used internally)
//
int
determine_similarity_transform_3point(
float *pfP01, float *pfP02, float *pfP03,
float *pfP11, float *pfP12, float *pfP13,
// Output
// Rotation about point pfP01/pfP11
float *rot0,
float *rot1,
// Scale change (magnification) from image 1 to image 2
float &fScaleDiff
)
{
// Points cannot be equal or colinear
float fDist012 = vec3D_dist_3d( pfP01, pfP02 );
float fDist013 = vec3D_dist_3d( pfP01, pfP03 );
float fDist023 = vec3D_dist_3d( pfP02, pfP03 );
float fDist112 = vec3D_dist_3d( pfP11, pfP12 );
float fDist113 = vec3D_dist_3d( pfP11, pfP13 );
float fDist123 = vec3D_dist_3d( pfP12, pfP13 );
if(
fDist012 == 0 ||
fDist013 == 0 ||
fDist023 == 0 ||
fDist112 == 0 ||
fDist113 == 0 ||
fDist123 == 0 )
{
// Points have to be distinct
return -1;
}
fScaleDiff = (fDist112+fDist113+fDist123)/(fDist012+fDist013+fDist023);
// Determine rotation about point pfP01/pfP11
int iReturn;
iReturn = determine_rotation_3point( pfP01, pfP02, pfP03, rot0 );
iReturn = determine_rotation_3point( pfP11, pfP12, pfP13, rot1 );
// Create
float ori0[3][3];
memcpy( &(ori0[0][0]), rot0, sizeof(float)*3*3 );
float ori1[3][3];
memcpy( &(ori1[0][0]), rot1, sizeof(float)*3*3 );
float ori1trans[3][3];
transpose_3x3<float,float>( ori1, ori1trans );
float rot_one[3][3];
mult_3x3_matrix_template<float,float>( ori1trans, ori0, rot_one );
memcpy( rot0, &(rot_one[0][0]), sizeof(float)*3*3 );
return iReturn;
}
//
// angular_difference()
//
// Measure angular difference.
//
float
consistency_angle(
float *pfP01, float *pfP02, float *pfP03,
float *pfP11, float *pfP12, float *pfP13
)
{
float fDist012 = vec3D_dist_3d( pfP01, pfP02 );
float fDist013 = vec3D_dist_3d( pfP01, pfP03 );
float fDist023 = vec3D_dist_3d( pfP02, pfP03 );
float fDist112 = vec3D_dist_3d( pfP11, pfP12 );
float fDist113 = vec3D_dist_3d( pfP11, pfP13 );
float fDist123 = vec3D_dist_3d( pfP12, pfP13 );
if(
fDist012 == 0 ||
fDist013 == 0 ||
fDist023 == 0 ||
fDist112 == 0 ||
fDist113 == 0 ||
fDist123 == 0 )
{
// Points have to be distinct
return -1;
}
float pfV012[3];
float pfV013[3];
vec3D_diff_3d( pfP01, pfP02, pfV012 );
vec3D_diff_3d( pfP01, pfP03, pfV013 );
vec3D_norm_3d(pfV012);
vec3D_norm_3d(pfV013);
float pfV112[3];
float pfV113[3];
vec3D_diff_3d( pfP11, pfP12, pfV112 );
vec3D_diff_3d( pfP11, pfP13, pfV113 );
vec3D_norm_3d(pfV112);
vec3D_norm_3d(pfV113);
}
//
// consistency_side_scale_difference()
//
// Perfect consistency is 0, side legth ratios are exact.
// Imperfect consistency higher or lower than 0.
//
float
consistency_side_scale_difference(
float *pfP01, float *pfP02, float *pfP03,
float *pfP11, float *pfP12, float *pfP13
)
{
// Points cannot be equal or colinear
float fDist012 = vec3D_dist_3d( pfP01, pfP02 );
float fDist013 = vec3D_dist_3d( pfP01, pfP03 );
float fDist023 = vec3D_dist_3d( pfP02, pfP03 );
float fDist112 = vec3D_dist_3d( pfP11, pfP12 );
float fDist113 = vec3D_dist_3d( pfP11, pfP13 );
float fDist123 = vec3D_dist_3d( pfP12, pfP13 );
if(
fDist012 == 0 ||
fDist013 == 0 ||
fDist023 == 0 ||
fDist112 == 0 ||
fDist113 == 0 ||
fDist123 == 0 )
{
// Points have to be distinct
return -10000;
}
float fR0 = fDist012/fDist013;
float fR1 = fDist112/fDist113;
return log(fR1/fR0);
}
void
vec3D_summ_3d(
float *pv1,
float *pv2,
float *pv12
)
{
pv12[0] = pv2[0]+pv1[0];
pv12[1] = pv2[1]+pv1[1];
pv12[2] = pv2[2]+pv1[2];
}
int
similarity_transform_3point(
float *pfP0,
float *pfP1,
float *pfCenter0,
float *pfCenter1,
float *rot01,
float fScaleDiff
)
{
// Subtract origin from point
float pfP0Diff[3];
vec3D_diff_3d( pfCenter0, pfP0, pfP0Diff );
// Rotate from image 0 to image 1
float rot_one[3][3];
memcpy( &(rot_one[0][0]), rot01, sizeof(float)*3*3 );
mult_3x3_template<float,float>( rot_one, pfP0Diff, pfP1 );
// Scale
pfP1[0] *= fScaleDiff;
pfP1[1] *= fScaleDiff;
pfP1[2] *= fScaleDiff;
// Add to origin
vec3D_summ_3d( pfP1, pfCenter1, pfP1 );
return 0;
}
int
determine_similarity_transform_ransac(
float *pf0, // Points in image 1
float *pf1, // Points in image 2
float *pfs0, // Scale for points in image 1
float *pfs1, // Scale for points in image 2
int iPoints, // number of points
int iIterations,
float fDistThreshold,
int *piInlierFlags
// ,
//float fScaleDiffThreshold,
//float fShiftThreshold,
//float fCosineAngleThreshold
)
{
if( iPoints < 4 )
{
return 0;
}
int iMaxInliers = 0;
float fMinErrorSum = 1000000;
for( int i = 0; i < iIterations; i++ )
{
// Find a set of unique points
int i1 = iPoints*(rand()/(RAND_MAX+1.0f));
int i2 = iPoints*(rand()/(RAND_MAX+1.0f));
int i3 = iPoints*(rand()/(RAND_MAX+1.0f));
while( i1 == i2 || i1 == i3 || i2 == i3 )
{
i1 = iPoints*(rand()/(RAND_MAX+1.0f));
i2 = iPoints*(rand()/(RAND_MAX+1.0f));
i3 = iPoints*(rand()/(RAND_MAX+1.0f));
}
// Calculate transform
float rot_here0[3][3];
float rot_here1[3][3];
float fScaleDiffHere;
float fConsistencyScale = consistency_side_scale_difference(
pf0+i1*3, pf0+i2*3, pf0+i3*3,
pf1+i1*3, pf1+i2*3, pf1+i3*3
);
//float fConsistencyAngle = consistency_side_scale_difference(
// pf0+i1*3, pf0+i2*3, pf0+i3*3,
// pf1+i1*3, pf1+i2*3, pf1+i3*3
// );
int iResult = determine_similarity_transform_3point(
pf0+i1*3, pf0+i2*3, pf0+i3*3,
pf1+i1*3, pf1+i2*3, pf1+i3*3,
(float*)(&(rot_here0[0][0])),
(float*)(&(rot_here1[0][0])),
fScaleDiffHere
);
if( iResult < 0 )
{
// Didn't work
continue;
}
float fErrorSum = 0;
// Count the number of inliers
int iInliers = 0;
int iInputInliers = 0;
float pfTest[3];
for( int j = 0; j < iPoints; j++ )
{
similarity_transform_3point(
pf0+j*3, pfTest,
pf0+i1*3, pf1+i1*3,
(float*)(&(rot_here0[0][0])), fScaleDiffHere );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( pf1, pfTest );
float fDist = sqrt( fErrorSqr );
if( fDist < fDistThreshold )
{
fErrorSum += fDist;
iInliers++;
if( j == i1 || j == i2 || j == i3 )
{
// Count indices of input features
// - are the features used to generate the transform part of the solution?
// Not necessarily in noisy error cases. The computed similarity transform
// does not necessarily operate well in noise conditions, but it should in valid conditions.
iInputInliers++;
}
}
}
if( iInputInliers != 3 )
{
// Didn't work - similarity transform must
// correctly map inliers used to compute it
continue;
}
if( iMaxInliers < iInliers )
{
iMaxInliers = iInliers;
fMinErrorSum = fErrorSum;
// Set flags
float pfTest[3];
for( int j = 0; j < iPoints; j++ )
{
similarity_transform_3point(
pf0+j*3, pfTest,
pf0+i1*3, pf1+i1*3,
(float*)(&(rot_here0[0][0])), fScaleDiffHere );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( pf1, pfTest );
float fDist = sqrt( fErrorSqr );
if( fDist < fDistThreshold )
{
piInlierFlags[j]=1;
}
else
{
piInlierFlags[j] = 0;
}
}
assert( piInlierFlags[i1]==1);
assert( piInlierFlags[i2]==1);
assert( piInlierFlags[i3]==1);
piInlierFlags[i1]=2;
piInlierFlags[i2]=3;
piInlierFlags[i3]=4;
}
else if( iMaxInliers == iInliers && fErrorSum < fMinErrorSum && iInliers >= 3 )
{
iMaxInliers = iInliers;
fMinErrorSum = fErrorSum;
// Set flags
float pfTest[3];
for( int j = 0; j < iPoints; j++ )
{
similarity_transform_3point(
pf0+j*3, pfTest,
pf0+i1*3, pf1+i1*3,
(float*)(&(rot_here0[0][0])), fScaleDiffHere );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( pf1, pfTest );
float fDist = sqrt( fErrorSqr );
if( fDist < fDistThreshold )
{
piInlierFlags[j]=1;
}
else
{
piInlierFlags[j] = 0;
}
}
assert( piInlierFlags[i1]==1);
assert( piInlierFlags[i2]==1);
assert( piInlierFlags[i3]==1);
piInlierFlags[i1]=2;
piInlierFlags[i2]=3;
piInlierFlags[i3]=4;
}
}
return iMaxInliers;
}
//
// test_navigation_error()
//
// Testing navigation error for MICCAI 2014
//
double
test_navigation_error(
char *pcFileName,
my_constraint_data &dat
)
{
double dSumSqrError = 0;
dat.iErrorCalib = 0;
dat.fPercentToKeep = 1;
// Create rotation matrix from current vector (length 7)
// Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
float vec2[PARAMETER_DIM_RIG] = {0,0,0,0,0,0,0};
float mat[9];
float fScale = 1;
// Copy scaled rotation matrix to 4x4 homogenous matrix
float mat44[16];
convert_vector_to_matrix4x4( vec2, mat44 );
// Two US tracker transform matrices
float mat44_1[16];
float mat44_2[16];
// Set last row to: [0,0,0,1]
memset( &mat44_1[0], 0, sizeof(mat44_1) );
memset( &mat44_2[0], 0, sizeof(mat44_2) );
mat44_1[15] = 1;
mat44_2[15] = 1;
// Two product transform matrices
float mat44_1_p[16];
float mat44_2_p[16];
float *pfDistSqr = new float[dat.iPoints];
double pdAbsErrorXYZ[3];
pdAbsErrorXYZ[0] = pdAbsErrorXYZ[1] = pdAbsErrorXYZ[2] = 0;
vector<int> vecFrameIndices;
//
// Here we gather statistics about correspondences in data
//
// Identify correspondences part of the same solution
int iStartCountIndex = 0;
vecFrameIndices.push_back(iStartCountIndex);
int *piInlierCountPerFeature = new int[dat.iPoints];
int *piInlierFrequency = new int[dat.iPoints];
float *pfDotProductZ = new float[dat.iPoints];
memset( piInlierCountPerFeature, 0, sizeof(int)*dat.iPoints );
memset( piInlierFrequency, 0, sizeof(int)*dat.iPoints );
float fVecMag1 = dat.pfPoints1[ 2]*dat.pfPoints1[ 2] + dat.pfPoints1[ 6]*dat.pfPoints1[ 6] + dat.pfPoints1[10]*dat.pfPoints1[10];
float fVecMag2 = dat.pfPoints2[ 2]*dat.pfPoints2[ 2] + dat.pfPoints2[ 6]*dat.pfPoints2[ 6] + dat.pfPoints2[10]*dat.pfPoints2[10];
float fVecNorm = sqrt( fVecMag1*fVecMag2 );
for( int i = 0; i < dat.iPoints; i++ )
{
// Compute dot product with z-vectors
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
float fDot =
point_in[ 2]*point_out[ 2] +
point_in[ 6]*point_out[ 6] +
point_in[10]*point_out[10];
pfDotProductZ[i] = fDot/fVecNorm;
if( dat.pfPoints1[15*i] != dat.pfPoints1[15*iStartCountIndex] )
{
int iInlierCount = i-iStartCountIndex;
piInlierFrequency[iInlierCount]++;
for( int j = iStartCountIndex; j < i; j++ )
{
piInlierCountPerFeature[j] = iInlierCount;
}
iStartCountIndex = i;
vecFrameIndices.push_back(iStartCountIndex);
}
}
// Finish up
int iInlierCount = dat.iPoints-iStartCountIndex;
piInlierFrequency[dat.iPoints-iStartCountIndex]++;
for( int j = iStartCountIndex; j < dat.iPoints; j++ )
{
piInlierCountPerFeature[j] = dat.iPoints-iStartCountIndex;
}
FILE *outXFormFit = fopen( "_transform_fit.txt", "a+" );
//
// Here we create vectors of points in 3D in the pre-operative model.
//
//
vector< float > vecPoints3DImage1;
vector< float > vecDotProduct;
vector< float > vecPoints3DImage2;
vector< float > vecPoints3DError;
// Keep cooridinate errors
vector< float > vecErrorX;
vector< float > vecErrorY;
vector< float > vecErrorZ;
for( int i = 0; i < dat.iPoints; i++ )
{
if( piInlierCountPerFeature[i] <= 3 )
{
continue;
}
vecPoints3DImage1.clear();
vecPoints3DImage2.clear();
vecPoints3DError.clear();
vecDotProduct.clear();
vecErrorX.clear();
vecErrorY.clear();
vecErrorZ.clear();
// Valid plane here, check error
int iStartPointIndex = vecPoints3DImage2.size();
int iInlierCount = piInlierCountPerFeature[i];
for( int ik = i; ik < i + iInlierCount; ik++ )
{
float *point_in = dat.pfPoints1 + 15*ik;
float *point_out = dat.pfPoints2 + 15*ik;
// Copy in scaled points
float p_in[3];
float p_out[3];
for( int j = 0; j < 3; j++ )
{
p_in[j] = fScale*point_in[12+j];
p_out[j] = fScale*point_out[12+j];
}
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Point 1: multiply current calibration matrix
float point_test_in[3];
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_vector_homogenous( mat44_1_p, p_in, point_test_in );
// Pass Point 2 through current calibration matrix
float point_test_out[3];
mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
// Compute error: for debugging
float fErrorSqr = sqrt( vec3D_distsqr_3d( point_test_in, point_test_out ) );
vecErrorX.push_back( point_test_out[0]-point_test_in[0] );
vecErrorY.push_back( point_test_out[1]-point_test_in[1] );
vecErrorZ.push_back( point_test_out[2]-point_test_in[2] );
vecDotProduct.push_back( pfDotProductZ[ik] );
vecPoints3DError.push_back( fErrorSqr );
for( int j = 0; j < 3; j++ )
{
vecPoints3DImage1.push_back( p_in[j] ); // In-plane pixel coordinates
vecPoints3DImage2.push_back( point_test_out[j] ); // 3D coordinates
}
}
int piInlierFlags[200];
memset( piInlierFlags, 0, sizeof(piInlierFlags) );
float pfPlane[4];
// Estimate plane & error
int iInliers;
//iInliers =
//ransac_plane_estimation(
// iInlierCount,
// &vecPoints3DImage2[iStartPointIndex],
// 100,
// 1.5f,
// pfPlane );
iInliers =
determine_similarity_transform_ransac(
&vecPoints3DImage1[iStartPointIndex],
&vecPoints3DImage2[iStartPointIndex],
0, 0, iInlierCount, 100, 3.0f, piInlierFlags );
if( iInliers >= 3 )
{
static int iFrameCount = 0;
for( int j = 0; j < iInlierCount; j++ )
{
if( piInlierFlags[j] )
{
fprintf( outXFormFit, "%s\t%d\t%f\t%f\n", strrchr( pcFileName, '\\')+1, iFrameCount, vecPoints3DError[j], vecDotProduct[j] );
}
}
iInliers =
determine_similarity_transform_ransac(
&vecPoints3DImage1[iStartPointIndex],
&vecPoints3DImage2[iStartPointIndex],
0, 0, iInlierCount, 100, 3.0f, piInlierFlags );
iFrameCount++;
}
// Skip past current inliers
i += iInlierCount-1;
}
fclose( outXFormFit );
return 1;
// Now loop through all frames and compute planes
for( int i = 0; i < vecFrameIndices.size(); i++ )
{
float pfPlane[4];
int iFrameStartIndex = vecFrameIndices[i];
ransac_plane_estimation(
piInlierCountPerFeature[iFrameStartIndex],
&vecPoints3DImage2[3*iFrameStartIndex],
100,
1.5f,
pfPlane );
}
for( int i = 0; i < dat.iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
// Copy in scaled points
float p_in[3];
float p_out[3];
for( int j = 0; j < 3; j++ )
{
p_in[j] = fScale*point_in[12+j];
p_out[j] = fScale*point_out[12+j];
if( j < 2 )
{
// Add 10 to each coordinate to see the effect
//p_in[j] += 50;
//p_out[j] += 50;
}
}
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Point 1: multiply current calibration matrix
float point_test_in[3];
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_vector_homogenous( mat44_1_p, p_in, point_test_in );
// Point 2: multiply current calibration matrix
float point_test_out[3];
if( dat.iErrorCalib )
{
// Pass Point 1 through ground truth calibration, for evaluating calibratin error
mult_4x4_matrix( mat44_1, &dat.pfCalib[0], mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_in, point_test_out );
// Alternative 1 - pass point 2 though ground truth calibration
mult_4x4_matrix( mat44_2, &dat.pfCalib[0], mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
// Alternative 2 - for shifted image points, reverse shift,
// pass through ground truth.
float point_out_shifted[3];
point_out_shifted[0] = p_in[0] + 315;
point_out_shifted[1] = p_in[1] + 315;
point_out_shifted[2] = p_in[2];
mult_4x4_matrix( mat44_1, &dat.pfCalib[0], mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, point_out_shifted, point_test_out );
}
else
{
// Pass Point 2 through current calibration matrix, for autocalibration optimization
mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
}
// Rescale to pixel units??
//vec3D_mult_scalar( point_test_in, 1.0f/fScale );
//vec3D_mult_scalar( point_test_out, 1.0f/fScale );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( point_test_in, point_test_out );
for( int k = 0; k < 3; k++ )
pdAbsErrorXYZ[k] = fabs(point_test_in[k] - point_test_out[k]);
// Sum up
dSumSqrError += fErrorSqr;
pfDistSqr[i] = fErrorSqr;
}
FILE *outf = fopen( "inliers.txt", "a+" );
//fprintf( outf, "InlierCountInImage\tErrorThisFeature\tDotProductZ\tInlierFrequency (not related to individual features)\n" );
for( int i = 0; i < dat.iPoints; i++ )
{
if( piInlierCountPerFeature[i] > 3 )
{
fprintf( outf, "%s\t%d\t%f\t%f\t%d\n", strrchr( pcFileName, '\\'), piInlierCountPerFeature[i], sqrt(pfDistSqr[i]), pfDotProductZ[i], piInlierFrequency[i] );
}
}
fclose( outf );
delete [] pfDotProductZ;
delete [] piInlierCountPerFeature;
delete [] piInlierFrequency;
// Robust: keep top half of distance
qsort( pfDistSqr, dat.iPoints, sizeof(float), _compareFloat );
dSumSqrError = 0;
//float fPercentToKeep = 3.0/4.0;
float fPercentToKeep = dat.fPercentToKeep;
for( int i = 0; i < fPercentToKeep*dat.iPoints; i++ )
{
dSumSqrError += sqrt(pfDistSqr[i]);
}
delete [] pfDistSqr;
return dSumSqrError / (fPercentToKeep*dat.iPoints);
}
//
// test_trackerless_reconstruction()
//
// This function was scavanged from test_navigation_error()
//
// test_trackerless_reconstruction
//
double
test_trackerless_reconstruction(
char *pcFileName,
my_constraint_data &dat
)
{
double dSumSqrError = 0;
dat.iErrorCalib = 0;
dat.fPercentToKeep = 1;
// Create rotation matrix from current vector (length 7)
// Parameters: rotation vector (3), translation vector (3), isotropic scale (1)
float vec2[PARAMETER_DIM_RIG] = {0,0,0,0,0,0,0};
float mat[9];
float fScale = 1;
// Copy scaled rotation matrix to 4x4 homogenous matrix
float mat44[16];
convert_vector_to_matrix4x4( vec2, mat44 );
// Two US tracker transform matrices
float mat44_1[16];
float mat44_2[16];
// Set last row to: [0,0,0,1]
memset( &mat44_1[0], 0, sizeof(mat44_1) );
memset( &mat44_2[0], 0, sizeof(mat44_2) );
mat44_1[15] = 1;
mat44_2[15] = 1;
// Two product transform matrices
float mat44_1_p[16];
float mat44_2_p[16];
float *pfDistSqr = new float[dat.iPoints];
double pdAbsErrorXYZ[3];
pdAbsErrorXYZ[0] = pdAbsErrorXYZ[1] = pdAbsErrorXYZ[2] = 0;
vector<int> vecFrameIndices;
//
// Here we gather statistics about correspondences in data
//
// Identify correspondences part of the same solution
int iStartCountIndex = 0;
vecFrameIndices.push_back(iStartCountIndex);
int *piInlierCountPerFeature = new int[dat.iPoints];
int *piInlierFrequency = new int[dat.iPoints];
float *pfDotProductZ = new float[dat.iPoints];
memset( piInlierCountPerFeature, 0, sizeof(int)*dat.iPoints );
memset( piInlierFrequency, 0, sizeof(int)*dat.iPoints );
float fVecMag1 = dat.pfPoints1[ 2]*dat.pfPoints1[ 2] + dat.pfPoints1[ 6]*dat.pfPoints1[ 6] + dat.pfPoints1[10]*dat.pfPoints1[10];
float fVecMag2 = dat.pfPoints2[ 2]*dat.pfPoints2[ 2] + dat.pfPoints2[ 6]*dat.pfPoints2[ 6] + dat.pfPoints2[10]*dat.pfPoints2[10];
float fVecNorm = sqrt( fVecMag1*fVecMag2 );
for( int i = 0; i < dat.iPoints; i++ )
{
// Compute dot product with z-vectors
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
float fDot =
point_in[ 2]*point_out[ 2] +
point_in[ 6]*point_out[ 6] +
point_in[10]*point_out[10];
pfDotProductZ[i] = fDot/fVecNorm;
if( dat.pfPoints1[15*i] != dat.pfPoints1[15*iStartCountIndex] )
{
int iInlierCount = i-iStartCountIndex;
piInlierFrequency[iInlierCount]++;
for( int j = iStartCountIndex; j < i; j++ )
{
piInlierCountPerFeature[j] = iInlierCount;
}
iStartCountIndex = i;
vecFrameIndices.push_back(iStartCountIndex);
}
}
// Finish up
int iInlierCount = dat.iPoints-iStartCountIndex;
piInlierFrequency[dat.iPoints-iStartCountIndex]++;
for( int j = iStartCountIndex; j < dat.iPoints; j++ )
{
piInlierCountPerFeature[j] = dat.iPoints-iStartCountIndex;
}
FILE *outXFormFit = fopen( "_transform_fit.txt", "a+" );
//
// Here we create vectors of points in 3D in the pre-operative model.
//
//
vector< float > vecPoints3DImage1;
vector< float > vecDotProduct;
vector< float > vecPoints3DImage2;
vector< float > vecPoints3DError;
// Keep cooridinate errors
vector< float > vecErrorX;
vector< float > vecErrorY;
vector< float > vecErrorZ;
for( int i = 0; i < dat.iPoints; i++ )
{
if( piInlierCountPerFeature[i] <= 3 )
{
continue;
}
vecPoints3DImage1.clear();
vecPoints3DImage2.clear();
vecPoints3DError.clear();
vecDotProduct.clear();
vecErrorX.clear();
vecErrorY.clear();
vecErrorZ.clear();
// Valid plane here, check error
int iStartPointIndex = vecPoints3DImage2.size();
int iInlierCount = piInlierCountPerFeature[i];
for( int ik = i; ik < i + iInlierCount; ik++ )
{
float *point_in = dat.pfPoints1 + 15*ik;
float *point_out = dat.pfPoints2 + 15*ik;
// Copy in scaled points
float p_in[3];
float p_out[3];
for( int j = 0; j < 3; j++ )
{
p_in[j] = fScale*point_in[12+j];
p_out[j] = fScale*point_out[12+j];
}
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Point 1: multiply current calibration matrix
float point_test_in[3];
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_vector_homogenous( mat44_1_p, p_in, point_test_in );
// Pass Point 2 through current calibration matrix
float point_test_out[3];
mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
// Compute error: for debugging
float fErrorSqr = sqrt( vec3D_distsqr_3d( point_test_in, point_test_out ) );
vecErrorX.push_back( point_test_out[0]-point_test_in[0] );
vecErrorY.push_back( point_test_out[1]-point_test_in[1] );
vecErrorZ.push_back( point_test_out[2]-point_test_in[2] );
vecDotProduct.push_back( pfDotProductZ[ik] );
vecPoints3DError.push_back( fErrorSqr );
for( int j = 0; j < 3; j++ )
{
vecPoints3DImage1.push_back( p_in[j] ); // In-plane pixel coordinates
vecPoints3DImage2.push_back( point_test_out[j] ); // 3D coordinates
}
}
int piInlierFlags[200];
memset( piInlierFlags, 0, sizeof(piInlierFlags) );
float pfPlane[4];
// Estimate plane & error
int iInliers;
//iInliers =
//ransac_plane_estimation(
// iInlierCount,
// &vecPoints3DImage2[iStartPointIndex],
// 100,
// 1.5f,
// pfPlane );
iInliers =
determine_similarity_transform_ransac(
&vecPoints3DImage1[iStartPointIndex],
&vecPoints3DImage2[iStartPointIndex],
0, 0, iInlierCount, 100, 3.0f, piInlierFlags );
if( iInliers >= 3 )
{
static int iFrameCount = 0;
for( int j = 0; j < iInlierCount; j++ )
{
if( piInlierFlags[j] )
{
fprintf( outXFormFit, "%s\t%d\t%f\t%f\n", strrchr( pcFileName, '\\')+1, iFrameCount, vecPoints3DError[j], vecDotProduct[j] );
}
}
iInliers =
determine_similarity_transform_ransac(
&vecPoints3DImage1[iStartPointIndex],
&vecPoints3DImage2[iStartPointIndex],
0, 0, iInlierCount, 100, 3.0f, piInlierFlags );
iFrameCount++;
}
// Skip past current inliers
i += iInlierCount-1;
}
fclose( outXFormFit );
return 1;
// Now loop through all frames and compute planes
for( int i = 0; i < vecFrameIndices.size(); i++ )
{
float pfPlane[4];
int iFrameStartIndex = vecFrameIndices[i];
ransac_plane_estimation(
piInlierCountPerFeature[iFrameStartIndex],
&vecPoints3DImage2[3*iFrameStartIndex],
100,
1.5f,
pfPlane );
}
for( int i = 0; i < dat.iPoints; i++ )
{
float *point_in = dat.pfPoints1 + 15*i;
float *point_out = dat.pfPoints2 + 15*i;
// Copy in scaled points
float p_in[3];
float p_out[3];
for( int j = 0; j < 3; j++ )
{
p_in[j] = fScale*point_in[12+j];
p_out[j] = fScale*point_out[12+j];
if( j < 2 )
{
// Add 10 to each coordinate to see the effect
//p_in[j] += 50;
//p_out[j] += 50;
}
}
// Copy in first 3 rows (length 3x4 = 12) of US tracker transform matrices
memcpy( &mat44_1[0], point_in, sizeof(float)*12 );
memcpy( &mat44_2[0], point_out, sizeof(float)*12 );
// Point 1: multiply current calibration matrix
float point_test_in[3];
mult_4x4_matrix( mat44_1, mat44, mat44_1_p );
mult_4x4_vector_homogenous( mat44_1_p, p_in, point_test_in );
// Point 2: multiply current calibration matrix
float point_test_out[3];
if( dat.iErrorCalib )
{
// Pass Point 1 through ground truth calibration, for evaluating calibratin error
mult_4x4_matrix( mat44_1, &dat.pfCalib[0], mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_in, point_test_out );
// Alternative 1 - pass point 2 though ground truth calibration
mult_4x4_matrix( mat44_2, &dat.pfCalib[0], mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
// Alternative 2 - for shifted image points, reverse shift,
// pass through ground truth.
float point_out_shifted[3];
point_out_shifted[0] = p_in[0] + 315;
point_out_shifted[1] = p_in[1] + 315;
point_out_shifted[2] = p_in[2];
mult_4x4_matrix( mat44_1, &dat.pfCalib[0], mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, point_out_shifted, point_test_out );
}
else
{
// Pass Point 2 through current calibration matrix, for autocalibration optimization
mult_4x4_matrix( mat44_2, mat44, mat44_2_p );
mult_4x4_vector_homogenous( mat44_2_p, p_out, point_test_out );
}
// Rescale to pixel units??
//vec3D_mult_scalar( point_test_in, 1.0f/fScale );
//vec3D_mult_scalar( point_test_out, 1.0f/fScale );
// Compute squared error
float fErrorSqr = vec3D_distsqr_3d( point_test_in, point_test_out );
for( int k = 0; k < 3; k++ )
pdAbsErrorXYZ[k] = fabs(point_test_in[k] - point_test_out[k]);
// Sum up
dSumSqrError += fErrorSqr;
pfDistSqr[i] = fErrorSqr;
}
FILE *outf = fopen( "inliers.txt", "a+" );
//fprintf( outf, "InlierCountInImage\tErrorThisFeature\tDotProductZ\tInlierFrequency (not related to individual features)\n" );
for( int i = 0; i < dat.iPoints; i++ )
{
if( piInlierCountPerFeature[i] > 3 )
{
fprintf( outf, "%s\t%d\t%f\t%f\t%d\n", strrchr( pcFileName, '\\'), piInlierCountPerFeature[i], sqrt(pfDistSqr[i]), pfDotProductZ[i], piInlierFrequency[i] );
}
}
fclose( outf );
delete [] pfDotProductZ;
delete [] piInlierCountPerFeature;
delete [] piInlierFrequency;
// Robust: keep top half of distance
qsort( pfDistSqr, dat.iPoints, sizeof(float), _compareFloat );
dSumSqrError = 0;
//float fPercentToKeep = 3.0/4.0;
float fPercentToKeep = dat.fPercentToKeep;
for( int i = 0; i < fPercentToKeep*dat.iPoints; i++ )
{
dSumSqrError += sqrt(pfDistSqr[i]);
}
delete [] pfDistSqr;
return dSumSqrError / (fPercentToKeep*dat.iPoints);
}
//
// main()
//
// Main function for Autocalibration, TMI 2017
//
int
main(
int argc,
char **argv
)
{
// Testing calibration
// Test on rigid US minimization with simulated data
my_constraint_data dat;
if( read_point_data_US_multiple( argc-1, argv+1, dat ) < 0 )
{
printf( "Could not read data\n" );
return -1;
}
float fError;
FILE *outfile = fopen( "result.txt", "a+" );
fprintf( outfile, "\n%s\t", argv[1] );
for( int i = 0; i < 10/*10*/; i++ )
{
main_test_rigid_US_minimization( dat, fError, 1 );
fprintf( outfile, "%f\t", fError );
}
fclose( outfile );
return 1;
}
|
// MFCSingleScrollDoc.cpp : implementation of the CMFCSingleScrollDoc class
//
#include "stdafx.h"
// SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail
// and search filter handlers and allows sharing of document code with that project.
#ifndef SHARED_HANDLERS
#include "MFCSingleScroll.h"
#endif
#include "MFCSingleScrollDoc.h"
#include "MFCSingleScrollView.h"
#include <propkey.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMFCSingleScrollDoc
IMPLEMENT_DYNCREATE(CMFCSingleScrollDoc, CDocument)
BEGIN_MESSAGE_MAP(CMFCSingleScrollDoc, CDocument)
END_MESSAGE_MAP()
// CMFCSingleScrollDoc construction/destruction
CMFCSingleScrollDoc::CMFCSingleScrollDoc()
{
// TODO: add one-time construction code here
}
CMFCSingleScrollDoc::~CMFCSingleScrollDoc()
{
}
BOOL CMFCSingleScrollDoc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
// TODO: add reinitialization code here
// (SDI documents will reuse this document)
//----我的代码
//在程序启动时调用
//SetTitle(L"我的文档ABC");//可以修改文档的标题,
//也可在Resource View中的String Table有一个IDR_MAINFRAME,以\n分隔,第二个是空可以修改它,优先级低
//也可以修改String Table 中的IDR_MAINFRAME的值
return TRUE;
}
// CMFCSingleScrollDoc serialization
void CMFCSingleScrollDoc::Serialize(CArchive& ar)
{
//----------------我的代码 ,文件->打开 或者 保存 调用这里
/*
if (ar.IsStoring())
{
int id=2008;
CString name=L"李";
ar<<id<<name;
}
else
{
//如果已经保存,再打开同一个文件就不会调用Serialize函数,因已经在内存中
int id;
CString name;
ar>>id>>name;
CString result;
result.Format(L"id=%d,name=%s",id,name);
AfxMessageBox(result);
}*/
//Doc中得到View
POSITION pos=GetFirstViewPosition();
CMFCSingleScrollView * view=(CMFCSingleScrollView*)GetNextView(pos);
/*
if (ar.IsStoring())//---图形类
{
int len=view->m_allLine.GetSize();
ar<<len;//自定的,先写记录数
int i;
for (i=0;i<len;i++)
{
MyShape* shape=(MyShape*)view->m_allLine.GetAt(i);
ar<<shape;//对象指针,CObject*
}
}else
{
int len;
ar>>len;;//先读记录数
int i;
MyShape* shape;
for (i=0;i<len;i++)
{
ar>>shape;
view->m_allLine.Add(shape);
}
}
*/
//也可以把集合入在Doc类中,View类有GetDocment();
m_allObj.Serialize(ar);//集合类,CPtrArray不行的,要使用使用 CObArray
}
#ifdef SHARED_HANDLERS
// Support for thumbnails
void CMFCSingleScrollDoc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds)
{
// Modify this code to draw the document's data
dc.FillSolidRect(lprcBounds, RGB(255, 255, 255));
CString strText = _T("TODO: implement thumbnail drawing here");
LOGFONT lf;
CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT));
pDefaultGUIFont->GetLogFont(&lf);
lf.lfHeight = 36;
CFont fontDraw;
fontDraw.CreateFontIndirect(&lf);
CFont* pOldFont = dc.SelectObject(&fontDraw);
dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK);
dc.SelectObject(pOldFont);
}
// Support for Search Handlers
void CMFCSingleScrollDoc::InitializeSearchContent()
{
CString strSearchContent;
// Set search contents from document's data.
// The content parts should be separated by ";"
// For example: strSearchContent = _T("point;rectangle;circle;ole object;");
SetSearchContent(strSearchContent);
}
void CMFCSingleScrollDoc::SetSearchContent(const CString& value)
{
if (value.IsEmpty())
{
RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid);
}
else
{
CMFCFilterChunkValueImpl *pChunk = NULL;
ATLTRY(pChunk = new CMFCFilterChunkValueImpl);
if (pChunk != NULL)
{
pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT);
SetChunkValue(pChunk);
}
}
}
#endif // SHARED_HANDLERS
// CMFCSingleScrollDoc diagnostics
#ifdef _DEBUG
void CMFCSingleScrollDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CMFCSingleScrollDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
// CMFCSingleScrollDoc commands
//----自己的代码,用于清资源,会在打开或者新建文档时调用
void CMFCSingleScrollDoc::DeleteContents()
{
// TODO: Add your specialized code here and/or call the base class
//------View中的 集合
/*
//Doc中得到View
POSITION pos=GetFirstViewPosition();
CMFCSingleScrollView * view=(CMFCSingleScrollView*)GetNextView(pos);
int len=view->m_allLine.GetSize();
int i;
for(i=0;i<len;i++)
{
delete view->m_allLine.GetAt(i);
}
view->m_allLine.RemoveAll();
*/
//------Doc中的 集合
//int len=m_allObj.GetSize();
int i;
for(i=0;i<m_allObj.GetSize();)
{
delete m_allObj.GetAt(i);//会改变 Size 大小,for中要使用i<m_allObj.GetSize(),去i++
m_allObj.RemoveAt(i);
}
//m_allObj.RemoveAll();
CDocument::DeleteContents();
}
|
#include "Number.h"
Number::Number(std::string input) {
this->number = input;
}
std::string Number::calculate() {
return this->number;
}
|
#ifndef _GLSLSHADER_H
#define _GLSLSHADER_H
//#include <windows.h>
#include <gl/glew.h>
#include <string>
#include <iostream>
using namespace std;
/*
定义一些全局函数,用来测试显卡对GL扩展的支持
*/
static bool g_bUseGLSL = false;
static bool g_bInitGLExtension = false;
bool CheckGLSL(void);
bool CheckGL2(void);
//初始化glew
bool InitGLExtensions(void);
class GLSLShader
{
public:
GLSLShader(void);
~GLSLShader(void);
/*初始化shader
strVertexShader 顶点shader文件名
strFragment 片断shader文件名
*/
void InitShaders(const string strVertexShader, const string strFragmentShader);
void ReloadShaders(const string strVertexShader, const string strFragmentShader);
//释放已经存在的shader程序
void Release(void);
//开始和停止使用shader
void Begin(void);
void End(void);
GLint GetUniformLoc(const char* varname);
// 设置 Uniform 变量
bool SetUniform1f(const char* varname, GLfloat v0);
bool SetUniform2f(const char* varname, GLfloat v0, GLfloat v1);
bool SetUniform3f(const char* varname, GLfloat v0, GLfloat v1, GLfloat v2);
bool SetUniform4f(const char* varname, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
bool SetUniform1i(const char* varname, GLint v0);
bool SetUniform2i(const char* varname, GLint v0, GLint v1);
bool SetUniform3i(const char* varname, GLint v0, GLint v1, GLint v2);
bool SetUniform4i(const char* varname, GLint v0, GLint v1, GLint v2, GLint v3);
bool SetUniform1fv(const char* varname, GLsizei count, const GLfloat *value);
bool SetUniform2fv(const char* varname, GLsizei count, const GLfloat *value);
bool SetUniform3fv(const char* varname, GLsizei count, const GLfloat *value);
bool SetUniform4fv(const char* varname, GLsizei count, const GLfloat *value);
bool SetUniform1iv(const char* varname, GLsizei count, const GLint *value);
bool SetUniform2iv(const char* varname, GLsizei count, const GLint *value);
bool SetUniform3iv(const char* varname, GLsizei count, const GLint *value);
bool SetUniform4iv(const char* varname, GLsizei count, const GLint *value);
bool SetUniformMatrix2fv(const char* varname, GLsizei count, GLboolean transpose, const GLfloat *value);
bool SetUniformMatrix3fv(const char* varname, GLsizei count, GLboolean transpose, const GLfloat *value);
bool SetUniformMatrix4fv(const char* varname, GLsizei count, GLboolean transpose, const GLfloat *value);
// 返回uniform变量
bool GetUniformfv(const char* varname, GLfloat* values);
bool GetUniformiv(const char* varname, GLint* values);
// 顶点 Attribute 变量
bool SetVertexAttrib1f(GLuint index, GLfloat v0);
bool SetVertexAttrib2f(GLuint index, GLfloat v0, GLfloat v1);
bool SetVertexAttrib3f(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2);
bool SetVertexAttrib4f(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
protected:
private:
//解析文件,并返回一个字符串
string LoadShaderFile(string strFileName);
GLhandleARB m_hGLSLProgramObject;
GLhandleARB m_hGLSLVertexShader;
GLhandleARB m_hGLSLFragmentShader;
};
#endif
|
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "Borland International", *str2 = "national !";
char *result;
result = strstr(str1, str2);
if (result)
printf("The substring is: %s\n", result);
else
printf("Not found the substring");
return 0;
}
|
#include "EchoServer.h"
#include "TcpConnection.h"
#include "../../include/WebPageQuery.h"
#include "../../include/configuration.h"
#include "../../include/loadFile.h"
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
void onConnection(const TcpConnectionPtr & conn)
{
cout<<">>"<<conn->toString()<<" has connected!"<<endl;
/* conn->send("Welcome to Server!"); */
}
void onMessage(const TcpConnectionPtr &conn, Threadpool* threadpool, Configuration & conf,loadFile *lf)
{
string msg=conn->receive();
cout<<">>> receive:"<<msg<<endl;
//交给处理任务线程
WebPageQuery mytask(msg,conn,conf,lf);
threadpool->addTask(std::bind(&WebPageQuery::doQuery,mytask));
}
void onClose(const TcpConnectionPtr &conn)
{
cout<<">>"<<conn->toString()<<" has closed!"<<endl;
}
int main(int argc,char *argv[])
{
EchoServer server(4,10,"192.168.75.128",2000);
Configuration conf("../conf/path.conf");
loadFile *lf=loadFile::getInstance();//获取到单例类对象
lf->loadPageLib(conf.getConfigMap()["repage_path"],conf.getConfigMap()["reoffset_path"],conf);
lf->loadInvertIndexTable(conf.getConfigMap()["invertIndex_path"]);
server.setConnectionCallBack(onConnection);
server.setMessageCallBack(std::bind(onMessage,std::placeholders::_1,server.getThreadpool(),conf,lf));
server.setCloseCallBack(onClose);
server.start();
return 0;
}
|
// forword linklist
#include<iostream>
using namespace std;
struct link{
int data;
link* next;
};
class linklist{
private:
link* first,*ptr;
public:
//link* ptr;
linklist(){
first = NULL;
//ptr = NULL;
link* test = new link;
cout<< " enter first data"<< endl;
cin>> test -> data;
first = test;
ptr = first;
}
void addition(){
link* newlink = new link;
cout<< "enter data"<< endl;
cin>> newlink -> data;
ptr -> next = newlink;
ptr = ptr->next;
ptr -> next = NULL;
}
void display();
};
void linklist:: display(){
link* current = first;
while( current !=NULL){
cout << current->data << endl;
current = current -> next;
}
}
int main(){
linklist li;
char ch;
cout<< "enter choice <y/n> to add more data or exit>"<<endl;
cin>> ch;
cout<< endl;
do{
li.addition();
cout<< "enter choice <y/n> to add more data or exit"<<endl;
cin>> ch;
cout<< endl;
}while(ch=='y');
li.display();
return 0;
}
|
/**
* Copyright 2017
*
* This file is part of On-line POMDP Planning Toolkit (OPPT).
* OPPT is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License published by the Free Software Foundation,
* either version 2 of the License, or (at your option) any later version.
*
* OPPT 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 OPPT.
* If not, see http://www.gnu.org/licenses/.
*/
#ifndef _ROCKSAMPLE_INITIAL_STATE_SAMPLER_PLUGIN_HPP_
#define _ROCKSAMPLE_INITIAL_STATE_SAMPLER_PLUGIN_HPP_
#include "oppt/plugin/Plugin.hpp"
#include "RocksampleInitialBeliefOptions.hpp"
#include "oppt/gazeboInterface/GazeboInterface.hpp"
namespace oppt
{
class RocksampleInitialBeliefPlugin: public InitialBeliefPlugin
{
public:
RocksampleInitialBeliefPlugin():
InitialBeliefPlugin() {
}
virtual ~RocksampleInitialBeliefPlugin() = default;
virtual bool load(const std::string& optionsFile) override {
parseOptions_<RocksampleInitialBeliefOptions>(optionsFile);
return true;
}
virtual RobotStateSharedPtr sampleAnInitState() override {
auto options = static_cast<RocksampleInitialBeliefOptions*>(options_.get());
VectorFloat initStateVec = options->initialStateVec;
if (initStateVec.size() != robotEnvironment_->getRobot()->getStateSpace()->getNumDimensions())
ERROR("Init state size doesnt fit");
unsigned int stateDimension = robotEnvironment_->getRobot()->getStateSpace()->getNumDimensions();
std::uniform_int_distribution<unsigned int> d(0, 1);
auto randomGenerator = robotEnvironment_->getRobot()->getRandomEngine();
// Rock are good/bad with equal probability
for (size_t i = 2; i != stateDimension; ++i) {
initStateVec[i] = (FloatType)d(*(randomGenerator.get()));
}
RobotStateSharedPtr initState(new VectorState(initStateVec));
return initState;
}
};
OPPT_REGISTER_INITIAL_BELIEF_PLUGIN(RocksampleInitialBeliefPlugin)
}
#endif
|
// Led5kSDKDemo.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "Led5kSDKDemo.h"
#include "Led5kSDKDemoDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CLed5kSDKDemoApp
BEGIN_MESSAGE_MAP(CLed5kSDKDemoApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CLed5kSDKDemoApp 构造
CLed5kSDKDemoApp::CLed5kSDKDemoApp()
{
// 支持重新启动管理器
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CLed5kSDKDemoApp 对象
CLed5kSDKDemoApp theApp;
// CLed5kSDKDemoApp 初始化
BOOL CLed5kSDKDemoApp::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// 创建 shell 管理器,以防对话框包含
// 任何 shell 树视图控件或 shell 列表视图控件。
CShellManager *pShellManager = new CShellManager;
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
CLed5kSDKDemoDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 在此放置处理何时用
// “确定”来关闭对话框的代码
}
else if (nResponse == IDCANCEL)
{
// TODO: 在此放置处理何时用
// “取消”来关闭对话框的代码
}
// 删除上面创建的 shell 管理器。
if (pShellManager != NULL)
{
delete pShellManager;
}
// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
// 而不是启动应用程序的消息泵。
return FALSE;
}
void CString2Char(CString str, char ch[])
{
#ifdef _UNICODE
int i;
char *tmpch;
int wLen = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);//得到Char的长度
tmpch = new char[wLen + 1]; //分配变量的地址大小
WideCharToMultiByte(CP_ACP, 0, str, -1, tmpch, wLen, NULL, NULL); //将CString转换成char*
for(i = 0; tmpch[i] != '\0'; i++) ch[i] = tmpch[i];
ch[i] = '\0';
delete tmpch;
#else
strcpy(ch,str.GetBuffer());
#endif
}
/*/////
pwstr 输入缓冲
len 输入缓冲长度
*/////
void Char2TCHAR(TCHAR *pwstr,size_t len,const char *str)
{
#ifdef _UNICODE
if(str)
{
size_t nu = strlen(str);
size_t n =(size_t)MultiByteToWideChar(CP_ACP,0,(const char *)str,(int)nu,NULL,0);
if(n>=len)
n=len-1;
memset(pwstr,0,len);
MultiByteToWideChar(CP_ACP,0,(const char *)str,(int)nu,pwstr,(int)n);
}
#else
strcpy(pwstr,str);
#endif
}
BYTE byte2bcd(BYTE num)
{
return num/10*16+num%10;
}
BYTE bcd2byte(BYTE num)
{
return num/16*10+num%16;
}
USHORT short2bcd(USHORT num)
{
BYTE high=num/100;
BYTE low=num%100;
return byte2bcd(high)*256+byte2bcd(low);
}
|
#include "BranchAndBoundQueue.h"
#include <iostream>
#include <sstream>
using namespace std;
BranchAndBoundQueue::BranchAndBoundQueue()
{
length = 0;
first = NULL;
}
BranchAndBoundQueue::~BranchAndBoundQueue()
{
BBElemQueue * pointer;
pointer = first;
while (first)
{
pointer = first->next;
delete[] first->items;
delete first;
first = pointer;
}
first = NULL;
}
void BranchAndBoundQueue::Add(int treeLevel, float upperBound, int value, int weight, bool* items, int itemsCount)
{
BBElemQueue *temp = new BBElemQueue();
temp->treeLevel = treeLevel;
temp->upperBound = upperBound;
temp->value = value;
temp->weight = weight;
temp->items = new bool[itemsCount];
for (int i = 0; i < itemsCount; i++)
temp->items[i] = items[i];
temp->next = NULL;
BBElemQueue * pointer, *pointerPrev;
pointerPrev = first;
pointer = first;
// no elements
if (pointer == NULL)
{
first = temp;
length++;
return;
}
// 1 element
if (pointer->next == NULL)
{
if (pointer->upperBound < temp->upperBound)
{
first = temp;
temp->next = pointer;
length++;
return;
}
else
{
pointer->next = temp;
length++;
return;
}
}
if (first->next != NULL && first->upperBound < temp->upperBound)
{
pointer = first;
first = temp;
temp->next = pointer;
length++;
return;
}
// 2 or more elements
while (pointer != NULL)
{
if (pointer->upperBound < temp->upperBound)
{
pointerPrev->next = temp;
temp->next = pointer;
length++;
return;
}
pointerPrev = pointer;
pointer = pointer->next;
}
pointerPrev->next = temp;
length++;
}
void BranchAndBoundQueue::Remove()
{
BBElemQueue * pointer;
if (first != NULL)
{
pointer = first->next;
delete[] first->items;
delete first;
first = pointer;
length--;
}
if (length == 0)
first = NULL;
}
BBElemQueue *BranchAndBoundQueue::GetFirst()
{
return first;
}
string BranchAndBoundQueue::Display()
{
BBElemQueue *pointer;
string res = "";
stringstream ss;
pointer = first;
while (pointer != NULL)
{
ss << pointer->treeLevel << " ";
pointer = pointer->next;
}
res = ss.str();
ss.str(string());
ss.clear();
return res;
}
|
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 1010;
const int MAXT = 2010;
const int INF = 0x3fffffff;
struct node
{
int v;
int weight;
};
int N, T;
vector<node> graph[MAXT];
int d[MAXT];
bool inq[MAXT];
void spfa()
{
fill(d, d + MAXT, INF);
fill(inq, inq + MAXT, false);
queue<int> q;
q.push(1);
d[1] = 0;
inq[1] = true;
while (!q.empty())
{
int u = q.front();
q.pop();
inq[u] = false;
for (int i = 0; i < graph[u].size(); i++)
{
int v = graph[u][i].v;
int weight = graph[u][i].weight;
if (d[u] + weight < d[v])
{
d[v] = d[u] + weight;
if (!inq[v])
{
q.push(v);
inq[v] = true;
}
}
}
}
}
// 有bug,但查很久愣是没发现,时间不多,先不管
int main()
{
scanf("%d%d", &N, &T);
int u, v, w;
for (int i = 0; i < T; i++)
{
scanf("%d%d%d", &u, &v, &w);
// 有重边,但邻接表有重边没影响吧?
graph[u].push_back({v, w});
// 要注意是不是无向图
graph[v].push_back({u, w});
}
spfa();
printf("%d\n", d[N]);
}
|
#ifndef __WHISKEY_Core_Verbose_HPP
#define __WHISKEY_Core_Verbose_HPP
#include <ostream>
#define W_VERBOSE_PATH_MAXLEN 256
#ifdef W_ENABLE_VERBOSE
#define W_VERBOSE(desc) { \
if (::whiskey::verbose) { \
::whiskey::printVerbosePrefix(__FILE__, __LINE__, __FUNCTION__); \
::whiskey::getVerboseOStream() << desc; \
::whiskey::printVerboseSuffix(); \
} \
}
#else
#define W_VERBOSE(desc)
#endif
namespace whiskey {
extern bool verbose;
std::ostream &getVerboseOStream();
void setVerboseOStream(std::ostream &os);
void printVerbosePrefix(const char *file, int line, const char *func);
void printVerboseSuffix();
}
#endif
|
/* Idesk -- Action.h
*
* Copyright (c) 2002, Chris (nikon) (nikon@sc.rr.com)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the <ORGANIZATION> nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* (See the included file COPYING / BSD )
*/
#ifndef ACTION_CLASS
#define ACTION_CLASS
#include <iostream>
using namespace std;
enum Click { none, singleClk, doubleClk, tripleClk, hold };
class Action
{
protected:
//keyboard modifiers
bool shift, control, alt;
//mouse modifiers
Click left, middle, right;
//other modifiers - Implemented later
//int clickDelay;
public:
Action();
Action(bool s, bool c, bool a, Click l, Click m, Click r);
virtual ~Action() {}
virtual void clear();
virtual void print();
virtual bool isOccuring(Action current);
virtual void setShift(bool s) { shift = s; }
virtual void setControl(bool c) { control = c; }
virtual void setAlt(bool a) { alt = a; }
virtual void setLeft(Click l) { left = l; }
virtual void setMiddle(Click m) { middle = m; }
virtual void setRight(Click r) { right = r; }
virtual void setButton(int button, Click c);
virtual Click getButton(int button);
virtual bool getShift() { return shift; }
virtual bool getControl() { return control; }
virtual bool getAlt() { return alt; }
virtual Click getLeft() { return left; }
virtual Click getMiddle() { return middle; }
virtual Click getRight() { return right; }
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
//The above problem can be easily solved if O(n) extra space is allowed. It becomes interesting due to the limitations that O(1) extra space and order of appearances.
//The idea is to process array from left to right. While processing, find the first out of place element in the remaining unprocessed array. An element is out of place if it is negative and at odd index, or it is positive and at even index. Once we find an out of place element, we find the first element after it with opposite sign. We right rotate the subarray between these two elements (including these two).
// always cur we will greater than out_of_place
void right_rotate(int* arr,int out_of_place,int cur)
{
int temp = arr[cur];
for(int i= cur;i>out_of_place;i--)
{
arr[i]=arr[i-1];
}
arr[out_of_place]=temp;
return ;
}
// time-complexity o(n) and extra space is o(1)
// negative element should be in even index
// positive element should be in odd index
int main()
{
int n;
cin >> n;
int* arr = new int[n];
for(int i=0;i<n;i++)
{
cin >> arr[i];
}
int out_of_place = -1;
// negative at even index
// positive at odd index
for(int i=0;i<n;i++)
{
// we will find the opposite sign element for out_of_place
if(out_of_place >=0)
{
if((arr[out_of_place] < 0 && arr[i] >=0) || (arr[out_of_place] >=0 && arr[i] < 0))
{
right_rotate(arr,out_of_place,i);
// now new out_of_place will be 2 steps ahead
if((i - out_of_place) >=2)
{
out_of_place = out_of_place + 2;
}
else
{
out_of_place = -1;
}
}
}
if(out_of_place == -1)
{
if( (arr[i]>=0 && (i%2)==0) || (arr[i]<0 && (i%2)!=0))
{
out_of_place = i;
}
}
}
for(int i=0;i<n;i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
// o(n) time and o(n) space
// int main()
// {
// int n;
// cin >> n;
// int* arr = new int[n];
// vector<int> positive;
// vector<int> negative;
// for(int i=0;i<n;i++)
// {
// cin >> arr[i];
// if(arr[i] >= 0)
// {
// positive.push_back(arr[i]);
// }
// else
// {
// negative.push_back(arr[i]);
// }
// }
// int i= 0;
// int j = 0;
// int k = 0;
// while(i < negative.size() && j<positive.size())
// {
// arr[k++] = negative[i];
// i++;
// arr[k++]=positive[j];
// j++;
// }
// while(i < negative.size())
// {
// arr[k++]=negative[i];
// i++;
// }
// while(j < positive.size())
// {
// arr[k++]=positive[j];
// j++;
// }
// for(int i=0;i<n;i++)
// {
// cout << arr[i] << " ";
// }
// cout <<endl;
// return 0;
// }
|
#ifndef STORERFORELLIPSE_H_
#define STORERFORELLIPSE_H_
#include "Storer.h"
class StorerForEllipse : public Storer {
public:
void save(Graph* g, ofstream& f);
Graph* load(int id, ifstream& f);
};
#endif // !StorerFORCIRCLE_H_
#pragma once
|
/*
* @lc app=leetcode.cn id=224 lang=cpp
*
* [224] 基本计算器
*
* https://leetcode-cn.com/problems/basic-calculator/description/
*
* algorithms
* Hard (36.88%)
* Likes: 158
* Dislikes: 0
* Total Accepted: 11.2K
* Total Submissions: 30.3K
* Testcase Example: '"1 + 1"'
*
* 实现一个基本的计算器来计算一个简单的字符串表达式的值。
*
* 字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。
*
* 示例 1:
*
* 输入: "1 + 1"
* 输出: 2
*
*
* 示例 2:
*
* 输入: " 2-1 + 2 "
* 输出: 3
*
* 示例 3:
*
* 输入: "(1+(4+5+2)-3)+(6+8)"
* 输出: 23
*
* 说明:
*
*
* 你可以假设所给定的表达式都是有效的。
* 请不要使用内置的库函数 eval。
*
*
*/
// @lc code=start
class Solution {
public:
static const int N_OPTR = 7;
// [栈顶][当前]
// ’>'表示栈顶优先级更高代表可以出栈计算;
// '<'表示栈顶优先级更低轮空什么都不做继续读入;
// '='表示匹配,不入队同时弹出;
// '-'表示不可能出现的情况
// 栈顶跟当前左括号/右括号的优先级比较,用最简单的情况作为例子来判断即可
// 这表其实不太容易填,也要理解得比较清楚,而且栈顶/当前到底是哪个比哪个也很容易混
char pri[N_OPTR][N_OPTR] = {'>', '>', '<', '<', '<', '>', '>',
'>', '>', '<', '<', '<', '>', '>',
'>', '>', '>', '>', '<', '>', '>',
'>', '>', '>', '>', '<', '>', '>',
'<', '<', '<', '<', '<', '=', '-',
'-', '-', '-', '-', '-', '-', '-',
'<', '<', '<', '<', '<', '<', '='};
map<char, int> c2i = {{'+', 0}, {'-', 1}, {'*', 2}, {'/', 3}, {'(', 4}, {')', 5}, {'!', 6}};
int calculate(string s)
{
s = s + '!';
// 取出空格的简单写法
s.erase(remove(s.begin(), s.end(), ' '), s.end());
stack<long long> opndStack;
stack<char> optrStack;
// 这种分情况的问题,i++一般也是分情况来写
int i = 0;
// 有!就可以避免对i到边界的判断,具体如果没有的话还会不会有其他bug记不太清,反正按照这个范式去处理就没错
optrStack.push('!');
while (!optrStack.empty())
{
if (isdigit(s[i]))
{
opndStack.push(readNum(s, i));
}
else
{
switch (pri[c2i[optrStack.top()]][c2i[s[i]]])
{
case '>':
{
char optr = optrStack.top();
optrStack.pop();
long long opnd2 = opndStack.top();
opndStack.pop();
long long opnd1 = opndStack.top();
opndStack.pop();
opndStack.push(cal(opnd1, optr, opnd2));
break;
}
case '<':
{
optrStack.push(s[i]);
i++;
break;
}
case '=':
{
optrStack.pop();
i++;
break;
}
default:
exit(-1);
}
}
}
return opndStack.top();
}
// 比起用sscanf和sstream,还是这种人工编码的方式要快很多,而且莫名其妙不容易控制的bug反而少
long long readNum(string& s, int& i)
{
long long num = 0;
while (isdigit(s[i]))
num = num * 10 + s[i++] - '0';
return num;
}
long long cal(long long opnd1, char optr, long long opnd2)
{
switch (optr)
{
case '+':
return opnd1 + opnd2;
case '-':
return opnd1 - opnd2;
case '*':
return opnd1 * opnd2;
case '/':
return opnd1 / opnd2;
default:
exit(-1);
}
}
};
// @lc code=end
|
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int new_k = k % int(nums.size());
if(new_k == 0) return;
reverse(nums.begin(), nums.end());
// second parameter should be the begin() + length of the target array
reverse(nums.begin(), nums.begin() + new_k);
reverse(nums.begin() + new_k, nums.end());
}
};
|
//===--- MandatoryOptUtils.cpp --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-mandatory-utils"
#include "MandatoryOptUtils.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Expr.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/CFG.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
STATISTIC(NumAssignRewritten, "Number of assigns rewritten");
using namespace swift;
/// Emit the sequence that an assign instruction lowers to once we know
/// if it is an initialization or an assignment. If it is an assignment,
/// a live-in value can be provided to optimize out the reload.
void swift::lowerAssignInstruction(SILBuilderWithScope &B, AssignInst *Inst,
PartialInitializationKind isInitialization) {
LLVM_DEBUG(llvm::dbgs() << " *** Lowering [isInit="
<< unsigned(isInitialization)
<< "]: " << *Inst << "\n");
++NumAssignRewritten;
SILValue Src = Inst->getSrc();
SILLocation Loc = Inst->getLoc();
if (isInitialization == PartialInitializationKind::IsInitialization ||
Inst->getDest()->getType().isTrivial(Inst->getModule())) {
// If this is an initialization, or the storage type is trivial, we
// can just replace the assignment with a store.
assert(isInitialization != PartialInitializationKind::IsReinitialization);
B.createTrivialStoreOr(Loc, Src, Inst->getDest(),
StoreOwnershipQualifier::Init);
Inst->eraseFromParent();
return;
}
if (isInitialization == PartialInitializationKind::IsReinitialization) {
// We have a case where a convenience initializer on a class
// delegates to a factory initializer from a protocol extension.
// Factory initializers give us a whole new instance, so the existing
// instance, which has not been initialized and never will be, must be
// freed using dealloc_partial_ref.
SILValue Pointer =
B.createLoad(Loc, Inst->getDest(), LoadOwnershipQualifier::Take);
B.createStore(Loc, Src, Inst->getDest(), StoreOwnershipQualifier::Init);
auto MetatypeTy = CanMetatypeType::get(
Inst->getDest()->getType().getASTType(), MetatypeRepresentation::Thick);
auto SILMetatypeTy = SILType::getPrimitiveObjectType(MetatypeTy);
SILValue Metatype = B.createValueMetatype(Loc, SILMetatypeTy, Pointer);
B.createDeallocPartialRef(Loc, Pointer, Metatype);
Inst->eraseFromParent();
return;
}
assert(isInitialization == PartialInitializationKind::IsNotInitialization);
// Otherwise, we need to replace the assignment with the full
// load/store/release dance. Note that the new value is already
// considered to be retained (by the semantics of the storage type),
// and we're transferring that ownership count into the destination.
// This is basically TypeLowering::emitStoreOfCopy, except that if we have
// a known incoming value, we can avoid the load.
SILValue IncomingVal =
B.createLoad(Loc, Inst->getDest(), LoadOwnershipQualifier::Take);
B.createStore(Inst->getLoc(), Src, Inst->getDest(),
StoreOwnershipQualifier::Init);
B.emitDestroyValueOperation(Loc, IncomingVal);
Inst->eraseFromParent();
}
|
// This file has been generated by Py++.
#ifndef OpenGLTextureTarget_hpp__pyplusplus_wrapper
#define OpenGLTextureTarget_hpp__pyplusplus_wrapper
void register_OpenGLTextureTarget_class();
#endif//OpenGLTextureTarget_hpp__pyplusplus_wrapper
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
double meal;
cin >> meal;
int tip;
cin >> tip;
int tax;
cin >> tax;
cout << round(meal * (1 + (tip + tax) * 0.01)) << endl;
return 0;
}
|
/*NodeStoreAsyncTest.cpp
NodeStoreAsync
copyright Vixac Ltd. All Rights Reserved
*/
#include "NodeStoreAsync.h"
#include "Node.h"
#include "NodeGenAsync.h"
#include "LocalNodeStore.h"
#include <gtest/gtest.h>
#include <functional>
namespace VI = vixac;
namespace IA = VI::ina;
namespace IN = vixac::inout;
namespace
{
class Foo
{
public:
Foo(int base):base_(base){}
int dub(int x){return x*2 + base_;}
int base_;
};
class Bar
{
public:
int redub(std::function<int(int)> f)
{
int v = f(20);
return v +=1;
}
};
class SimpleAsyncStore : public vixac::ina::NodeStoreAsync
{
public:
int doNothing_;
std::map<vixac::inout::NodeId, std::set<IA::NodeAsyncObserver *> >* observers(){
return &observers_;
}
};
class SimpleNodeObserver : public vixac::ina::NodeAsyncObserver
{
public:
SimpleNodeObserver():tg(0),sc(0),trem(0),trec(0),ic(0),nc(0){}
void tieGained(IA::TieChange t)
{
tg++;
ltg = t;
}
void stringChanged(IA::StringChange t)
{
sc++;
lsc=t;
}
void tieRemoved(IA::TieChange t)
{
trem++;
ltrem = t;
}
void tieRecieved(IA::TieChange t)
{
trec++;
ltrec = t;
}
void intChanged(IA::IntChange t)
{
ic++;
lic = t;
}
void nodeIDChanged(IA::NodeIdChange t)
{
nc++;
lnc =t;
}
~SimpleNodeObserver() {
}
int tg;
int sc;
int trem;
int trec;
int ic;
int nc;
IA::TieChange ltg;
IA::StringChange lsc;
IA::TieChange ltrem;
IA::TieChange ltrec;
IA::IntChange lic;
IA::NodeIdChange lnc;
};
}
TEST(NodeStoreAsync, observers)
{
::SimpleAsyncStore store;
::SimpleNodeObserver oneObs;
::SimpleNodeObserver twoObs;
::SimpleNodeObserver threeObs;
::SimpleNodeObserver oneAndTwoObs;
IN::NodeId NODE_ONE(1);
IN::NodeId NODE_TWO(2);
IN::NodeId NODE_THREE(3);
store.subscribeToNode(NODE_ONE, &oneObs);
store.subscribeToNode(NODE_TWO, &twoObs);
store.subscribeToNode(NODE_THREE, &threeObs);
store.subscribeToNode(NODE_ONE, &oneAndTwoObs);
store.subscribeToNode(NODE_TWO, &oneAndTwoObs);
store.tieGained(IA::TieChange(NODE_ONE,IN::Tie(IN::TieType("friend"), NODE_TWO)));
{
EXPECT_EQ(oneObs.tg, NODE_ONE);
EXPECT_EQ (oneObs.ltg.tie.target(), NODE_TWO);
EXPECT_EQ(oneObs.ltg.tie.type().type, "friend");
}
{
EXPECT_EQ(twoObs.trec, 1);
}
{
store.stringChanged(IA::StringChange(NODE_ONE, "name", "alice"));
EXPECT_EQ(oneObs.sc, 1);
EXPECT_EQ(oneObs.lsc.key, "name");
EXPECT_EQ(oneObs.lsc.value, "alice");
}
}
//proof that i can gtest C++11 calls and bind member functions
TEST(cpp11test, aTest)
{
::Foo fooTen(10);
std::function<int(int)> func = std::bind(& ::Foo::dub, &fooTen, std::placeholders::_1);
int v = func(3);//3 *2 +10 = 16;
EXPECT_EQ(v, 16);
::Bar bar;
EXPECT_EQ(bar.redub(func), 51);
}
TEST(NodeStoreAsync, observersLifetimes)
{
::SimpleAsyncStore store;
std::map<vixac::inout::NodeId, std::set<IA::NodeAsyncObserver *> >* observers =store.observers();
SimpleNodeObserver oneAndTwoObs;
IN::NodeId NODE_ONE(1);
{
::SimpleNodeObserver oneObs;
EXPECT_EQ(observers->size(),0);
store.subscribeToNode(NODE_ONE, &oneObs);
ASSERT_TRUE(observers->find(NODE_ONE)!= observers->end());;
EXPECT_EQ(observers->find(NODE_ONE)->second.size(),1);
}
EXPECT_EQ(observers->find(NODE_ONE)->second.size(),0);
}
|
#include "Model.h"
Model::Model(std::vector<Mesh> meshes) {
this->meshes = meshes;
}
|
#include <iostream>
using namespace std;
struct Item
{
char fullname[35];
double payment;
};
class Stack
{
private:
enum {MAX = 10}; // constant specific to class
Item items[MAX]; // holds stack items
int top; // index for top stack item
public:
Stack();
bool isempty() const;
bool isfull() const;
// push() returns false if stack already is full, true otherwise
bool push(const Item & item); // add item to stack
// pop() returns false if stack already is empty, true otherwise
bool pop(Item & item); // pop top into item
};
Stack::Stack() // create an empty stack
{
top = 0;
}
bool Stack::isempty() const
{
return top == 0;
}
bool Stack::isfull() const
{
return top == MAX;
}
bool Stack::push(const Item & item)
{
if (top < MAX)
{
items[top++] = item;
return true;
}
else
return false;
}
bool Stack::pop(Item & item)
{
if (top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
using namespace std;
int main()
{
/* Write a program that adds and removes customer structures from a stack, represented by
a Stack class declaration. Each time a customer is removed, his or her payment should
be added to a running total, and the running total should be reported */
Stack tastic;
double total = 0;
Item ilist[12] = {{"Magic Sum", 5.3},
{"Salty Drum", 4.3},
{"Cruel Plum", 3},
{"Angry Crumb", 2.8},
{"Paltry Bum", 90.5},
{"Sitting Numb", 12.23},
{"Saber Gum", 34.43},
{"Candied Hum", 1.001},
{"Angled Mum", 10},
{"Power Rum", 45.3},
{"Bacon Yum", 2.02},
{"Kalan Xum", 0.001}};
if(tastic.isempty())
{
cout << "Stack Tastic is empty!\n";
}
int i = 0;
while(tastic.push(ilist[i]))
{
cout << "Adding " << ilist[i].fullname << " to Stack Tastic.\n";
i++;
}
if(tastic.isfull())
{
cout << "Stack Tastic is full!\n";
}
i--;
while(tastic.pop(ilist[i]))
{
cout << "Paying a price of " << ilist[i].payment << " for " << ilist[i].fullname << endl;;
total += ilist[i].payment;
i--;
}
if(tastic.isempty())
{
cout << "Stack Tastic is empty!\n";
}
cout << "\n\nHere's the new ilist:\n";
for(i = 0; i < 12; i++)
{
cout << ilist[i].fullname << " " << ilist[i].payment << endl;
}
cout << "Here's the total: " << total;
return 0;
}
|
#ifndef _HO_EFFECT_
#define _HO_EFFECT_
//Effect Object들의 기본 클래스..
#define CLASS_NONE 10000
#define CLASS_PRIMITIVE_BILLBOARD 20000
#define CLASS_PAT 30000
#define CLASS_ID_PARTICLE_DEST 40000
class HoEffectObject
{
protected:
float WorldX, WorldY, WorldZ;
float LocalX, LocalY, LocalZ;
int StartFlag;
int ClassID; //생성된 클래스의 종류..(BillBoard, Pat)
int SkillCode;
HoEffectObject *Parent;
public:
HoEffectObject();
virtual ~HoEffectObject();
virtual int Main();
virtual int Draw(int x, int y, int z, int ax, int ay, int az);
void SetParentObject(HoEffectObject *parent) { Parent = parent; }
BOOL GetState() { return StartFlag; }
virtual void SetState(BOOL startFlag) { StartFlag = startFlag; }
void SetClassID( int classID) { ClassID = classID; }
int GetClassID() { return ClassID; }
//오브젝트를 월드 좌표에서 이동을 한다..
virtual void TranslateWorld(int x, int y, int z) { WorldX = (float)x, WorldY = (float)y, WorldZ = (float)z;}
virtual hoPOINT3D GetWorld()
{
hoPOINT3D temp;
temp.x = WorldX;
temp.y = WorldY;
temp.z = WorldZ;
return temp;
}
//오브젝트를 로칼 좌표에서 이동을 한다..
virtual void TranslateLocal(int x, int y, int z) { LocalX = (float)x, LocalY = (float)y, LocalZ = (float)z;}
virtual void SetEffectEnd()
{
StartFlag = FALSE;
}
virtual POINT3D GetPos()
{
POINT3D pos;
pos.x = int(WorldX+LocalX);
pos.y = int(WorldY+LocalY);
pos.z = int(WorldZ+LocalZ);
return pos;
}
virtual int GetSkillCode()
{
return SkillCode;
}
virtual void SetSkillCode(int skillCode)
{
SkillCode = skillCode;
}
};
#define MAX_VERTEX 100
#define MAX_FACE 40
#define MAX_TEXLINK 80
//Render Type
#define RENDER_NONE 0
#define RENDER_BILLBOARD 1 //BillBoard일 경우... (카메라의 어느 방향에서나 같이 보인다.)
#define RENDER_BILLBOARD_PATH 2 //BillBoard를 경로에 따라 찍을 경우...
//Wolrd에서 위로 볼경우...
#define RENDER_FACE 4
#define RENDER_FACEPATH 5 //페이스가 움직이는 방향으로 페이스를 재 계산...
#define ANI_NONE 0
#define ANI_ONE 100
#define ANI_LOOP 300
//가장 기본적인 폴리곤.. (삼각형, 사각형, 삼각형 두장 크로스, 사각형 두장 크로스)
class HoPrimitivePolygon : public HoEffectObject
{
public:
HoPrimitivePolygon();
~HoPrimitivePolygon();
protected:
int TimeCount; //시간 카운트
int CurrentFrame; //현재 텍스쳐 프레임..
int SumCount; //텍스쳐용...
int AniDataIndex; //AnimationDataIndex번호..
int AniType; //ANI_NONE, ANI_ONE, ANI_LOOP
float CurrentBlendValue; //현재 블렌딩 값..
float BlendStep; //블렌딩 값 변화 스텝...
float SizeX; //가로 크기
float SizeY; //세로 크기..
smSTAGE_VERTEX Vertex[MAX_VERTEX];
int VertexCount;
smSTAGE_FACE Face[MAX_FACE];
int FaceCount;
smTEXLINK TexLink[MAX_TEXLINK];
int TexLinkCount;
HoPhysicsObject *Physics;
virtual void Init();
virtual int Main();
virtual int Draw(int x, int y, int z, int ax, int ay, int az);
public:
virtual int StartPathTri(POINT3D ¤tPos, POINT3D &destPos, char *iniName);
virtual int StartParticleTri(POINT3D ¤tPos, POINT3D &velocity, char *intName);
int CreatePathFace();
};
//AnimFrame Data Flag
#define PRIMITIVE_DEFAULT_RECT 0x00000001 //기본 모양(BILLBOARD 기본 모양)
#define PRIMITIVE_DEFAULT_RECT_STRETCH 0x00000008 //기본 모양에서 늘어나는 모양.(중심점에서 늘어남)
#define PRIMITIVE_PATH_RECT 0x00000002 //패스를 따라가는 모양
#define PRIMITIVE_PATH_RECT_STRETCH 0x00000004 //첨위치에서 늘어나는 모양.
#define PRIMITIVE_PATH_OBJECT (PRIMITIVE_PATH_RECT | PRIMITIVE_PATH_RECT_STRETCH) //모양이 경로를 따라 가는 경우..
#define MOVE_LINE 0x00000010 //직선 이동
#define MOVE_PARTICLE 0x00000020 //파티클 이동.
#define MOVE_ANGLE 0X00000040 //회전을 함.
#define MOVE_OBJECT (MOVE_LINE | MOVE_PARTICLE | MOVE_ANGLE) //이동하는 경우.
#define PRIMITIVE_DEFAULT_RECT_PARTICLE (PRIMITIVE_DEFAULT_RECT | MOVE_PARTICLE)
#define PRIMITIVE_DEFAULT_RECT_LINE (PRIMITIVE_DEFAULT_RECT | MOVE_LINE)
#define PRIMITIVE_PATH_RECT_PARTICLE (PRIMITIVE_PATH_RECT | MOVE_PARTICLE) //이동경로에 따라 모양이 따라가며 파티클 이동.
#define PRIMITIVE_PATH_RECT_LINE (PRIMITIVE_PATH_RECT | MOVE_LINE)
#define PRIMITIVE_PATH_RECT_STRETCH_LINE (PRIMITIVE_PATH_RECT_STRETCH | MOVE_LINE) //이동경로에 따라 모양이 따라가면 직선 이동.
//빌보드 관련 클래스..
class HoPrimitiveBillboard : public HoEffectObject
{
protected:
int TimeCount; //시간 카운트
int CurrentFrame; //현재 텍스쳐 프레임..
int AniDataIndex; //AnimationDataIndex번호..
int AniType; //ANI_NONE, ANI_ONE, ANI_LOOP
float CurrentBlendValue; //현재 블렌딩 값..
float BlendStep; //블렌딩 값 변화 스텝...
float SizeWidth; //가로 크기
float SizeHeight; //세로 크기..
float PutAngle; //찍을 앵글...
float SizeStep;
float AngleStep; //Angle 스텝..
smFACE2D Face2d;
//이동에 관한 변수들..
HoPhysicsObject *Physics;
POINT3D DirectionVelocity; //이동 속도..
POINT3D DirectionAngle; //이동 각도..
POINT3D DirectionAngleStep;
int WorkState; //작업 상태.
hoPOINT3D LocalStartPos; //로칼 좌표의 처음 시작 위치..
protected:
BOOL AddFace2D(smFACE2D *face);
public:
void SetAniState(int aniType) { AniType = aniType; }
HoPrimitiveBillboard();
virtual ~HoPrimitiveBillboard();
//void Move(int x, int y, int z);
int MoveTo(int x, int y, int z);
void SetDirectionVelocity(POINT3D velocity)
{
DirectionVelocity = velocity;
}
void SetWorkState(int workState) { WorkState = workState;}
virtual void Init();
virtual int Main();
virtual int Draw(int x, int y, int z, int ax, int ay, int az);
//중심점과 가로, 세로 크기만 있으면 되는 폴리곤..(BILLBOARD)
int StartBillRect(int x, int y, int z, char *iniName, int aniType, int workState = PRIMITIVE_DEFAULT_RECT);
int StartBillRect(int x, int y, int z, int sizeX, int sizeY, char *iniName, int aniType);
//파티클 경로를 따라가며 파티클 모양도 경로를 따라 가는 파티클..
int StartParticlePath(POINT3D currentPos, POINT3D velocity, POINT size, char *iniName, int aniType, int workState = PRIMITIVE_PATH_RECT_PARTICLE);
//직선 경로를 따라가는 파티클..
int StartDestPath(POINT3D worldPos, POINT3D localPos, POINT3D destPos, POINT size, char *iniName, int speed, int workState = PRIMITIVE_PATH_RECT_STRETCH_LINE);
//폴리곤 한장 에니..
int StartPath(POINT3D currentPos, char *iniName, int aniType);
//이동 정보와 primitive 정보를 넣는다.
void SetPhysics(HoPhysicsObject *object, int primitiveInfo)
{
if(object == NULL)
return;
Physics = object;
if(Physics->GetWorkId() == MOVE_PARTICLE) //파티클 이동..
{
WorkState = MOVE_PARTICLE;
WorkState |= primitiveInfo;
}
else if(Physics->GetWorkId() == MOVE_LINE) //라인 이동..
{
WorkState = MOVE_LINE;
WorkState |= primitiveInfo;
}
}
//시작 크기..
void SetSize(POINT size)
{
SizeWidth = (float)size.x;
SizeHeight = (float)size.y;
Face2d.width = (int)SizeWidth<<FLOATNS;
Face2d.height = (int)SizeHeight<<FLOATNS;
}
};
//일정 패턴으로 움직이는 이미지(반딧불.)
class HoEffectCircleLine : public HoPrimitiveBillboard
{
public:
HoEffectCircleLine();
~HoEffectCircleLine();
float DxVelocity; //x방향 속도.
float DyVelocity; //y방향 속도..
float Step;
int Start(int x, int y, int z, int sizeX, int sizeY, char *iniName, int aniType);
int Main();
int CircleTimeCount;
};
//일정 좌표를 쫒아 가는거..(x, z 좌표에서만 테스트)
class HoEffectTracker : public HoEffectObject
{
public:
HoEffectTracker();
~HoEffectTracker();
//ktj : 삽입함.
int liveCount ;//= 0;
BOOL liveFlag ;//= FALSE;
int sparkCount ;//= 0;
int IMP_SHOT2_liveCount ;//= 0;
int IMP_SHOT3_liveCount ;//= 0;
POINT3D DestPos; //날아갈 목적지...
float Vx; //속도 벡터..
float Vy;
float Vz;
//int Start(POINT3D currentPos, POINT3D destPos, POINT3D startVelocity, HoEffectObject *effectObj = NULL);
int Start(POINT3D currentPos, POINT3D destPos, int skillCode, HoEffectObject *effectObj = NULL, int level = 1);
int Main();
int Level;
HoEffectObject *EffectObj;
};
#define MAX_2DVERTEX 40
#define STATE_NONE 0
#define STATE_UP 1
#define STATE_DOWN 2
class HoEtc2dPrimitive : public HoEffectObject
{
protected:
int TimeCount; //시간 카운트
int CurrentFrame; //현재 텍스쳐 프레임...
int SumCount; //텍스쳐 프레임...
int AniDataIndex;
int CurrentBlendValue;
int BlendStep;
D3DTLVERTEX TLVertex[MAX_2DVERTEX];
int VertexCount;
HoAnimDataMgr AnimationData;
int WorkState;
int Velocity;
public:
HoEtc2dPrimitive();
~HoEtc2dPrimitive();
int Load();
int StartUp(int x, int y);
int StartDown();
virtual int Init();
virtual int Main();
virtual int Draw();
};
class HoEtcPrimitiveBillboardMove : public HoPrimitiveBillboard
{
public:
HoEtcPrimitiveBillboardMove();
~HoEtcPrimitiveBillboardMove();
private:
smRENDFACE *AddRendFace; //렌더링에 올라간 Face들...
float Step;
public:
int MoveState; //1: left 2:top 3:right 4:bottom
float TranslateMoveX;
float TranslateMoveY;
int PrimitiveMoveCount;
int PrimitiveStopCount;
public:
int Draw(int x, int y, int z, int ax, int ay, int az);
int Start(int x, int y, int z, int sizeX, int sizeY, char *iniName, int aniType);
int Main();
};
class HoEffectPat : public HoEffectObject
{
protected:
smPAT3D *PatObj;
int CurrentFrame;
int FrameStep;
int BlendStep;
POINT3D Angle;
int AniType;
public:
int AnimationEnd;
HoEffectPat();
~HoEffectPat();
protected:
void Init();
public:
int StartAni(int x, int y, int z, int angleX, int angleY, int angleZ, smPAT3D *pat, int aniType = ANI_ONE);
int Main();
int Draw(int x, int y, int z, int ax, int ay, int az);
void SetBlendStep(int blendStep) { BlendStep = blendStep; }
};
class HoEffectPatGetPos : public HoEffectObject
{
protected:
smPAT3D *PatObj;
int CurrentFrame;
int FrameStep;
int BlendStep;
POINT3D Angle;
smOBJ3D *ObjBip;
public:
int AnimationEnd;
HoEffectPatGetPos();
~HoEffectPatGetPos();
void Init();
int StartAni(int x, int y, int z, int angleX, int angleY, int angleZ, smPAT3D *pat, char *searchObjName = NULL);
int Main();
int Draw(int x, int y, int z, int ax, int ay, int az);
};
//매를 날리기 위한.. 클래스...(Scout Hawk 전용)
class HoEffectPatHawk : public HoEffectPat
{
public:
HoEffectPatHawk();
~HoEffectPatHawk();
int Loop;
smOBJ3D *ObjBip;
int AngleY;
POINT3D HawkPos;
//int SkillEndAniFlag;
smCHAR *Character;
public:
void SetEffectEnd()
{
Loop = 1;
};
int Draw(int x, int y, int z, int ax, int ay, int az);
int Main();
int StartAni(int x, int y, int z, int angleX, int angleY, int angleZ, smPAT3D *patBone, smPAT3D *pat, smCHAR *character, int loop=0);
};
//ktj : FALCON : 아처가 데리고 다니는 새이름임)
enum {FALCON_GATE_START, FALCON_START, FALCON_KEEP_ON, FALCON_ATTACK, FALCON_TURN_START, FALCON_TURN_PROCESS, FALCON_TURN_END};
class HoEffectPatFalcon : public HoEffectPat
{
public:
HoEffectPatFalcon();
~HoEffectPatFalcon();
smOBJ3D *ObjBip;
smCHAR *Character;
int WorkState;
POINT3D AttackAngle;
POINT3D AttackDest;
int pDelay;
int pCounter;
int pEndCounter;
short pAttackDamage[2];
D3DVECTOR ParticleGlowPos;
int ParticleGlowID;
int ParticleStarID;
public:
int Draw(int x, int y, int z, int ax, int ay, int az);
int Main();
int StartAni(int x, int y, int z, int angleX, int angleY, int angleZ, smPAT3D *patBone, smPAT3D *patAni, smCHAR *character , int SkillPoint );
int StartGoldenFalconAni(int x, int y, int z, int angleX, int angleY, int angleZ, smPAT3D *patBone, smPAT3D *patAni, smCHAR *character, int liveCount);
};
/*
//Particle 한개를 관리하는 클래스...
//속도와 중력, 바람의 영향에 스스로 날아가는 입자...
class HoEffectParticle : public HoPrimitiveBillboard
{
public:
HoEffectParticle();
virtual ~HoEffectParticle();
protected:
float Xv, Yv, Zv; //Velocity of Particle(Vector)
float Gravity; //중력...
float Wind; //바람...
int Live;
protected:
//int CreatePathFace();
public:
void SetSize(int sizeX, int sizeY) { SizeWidth = (float)sizeX, SizeHeight = (float)sizeY; }
void SetGravity(int gravity) { Gravity = (float)gravity; }
void SetLive(int live) { Live = live; }
virtual int Main();
virtual void Init();
virtual int Draw(int x, int y, int z, int ax, int ay, int az);
int StartBillBoard(int x, int y, int z, float xv, float yv, float zv,char *iniName, int aniType = ANI_ONE);
int StartWorldTri(int x, int y, int z, int xv, int yv, int zv, char *iniName, int aniType = ANI_ONE);
};
*/
#define MAX_EFFECTOBJECT_BUFFER 500
#define MAX_TIMEOBJECT_BUFFER 100
#define MAX_MATERIAL_NUM 100
#define MAX_OBJECT_NUM 100
#define EFFECT_NORMAL_HIT1 100
#define EFFECT_NORMAL_HIT2 150
#define EFFECT_CRITICAL_HIT1 200
#define EFFECT_CRITICAL_HIT2 210
#define EFFECT_LEVELUP1 300
#define EFFECT_ROUND_IMPACT 400
#define EFFECT_GAME_START1 500
#define EFFECT_POTION1 600
#define EFFECT_POTION2 700
#define EFFECT_POTION3 800
#define EFFECT_BROKEN1 850
#define EFFECT_DAMAGE1 900
#define EFFECT_GAS1 1000
#define EFFECT_DUST1 1100
#define EFFECT_LIGHT1 1200
#define EFFECT_BANDI1 1300
#define EFFECT_GATE1 1350
#define EFFECT_TEST1 1400
#define EFFECT_TEST2 2000
#define EFFECT_PARTICLE_BOW1 1500
#define EFFECT_PARTICLE_BOW2 2520
#define EFFECT_FIRE_HIT1 3000
#define EFFECT_FIRE_HIT2 3200
#define EFFECT_RETURN1 3500
#define EFFECT_MECHANICBOMB_DUST1 4000
#define EFFECT_SHIELD1_PARTICLE 5000
#define EFFECT_AGING 5001
#define SKILL_NONE 500
#define SKILL_HOMING 5500
#define SKILL_METEO 6000
#define SKILL_UP1 6500
//ktj : 임시로 새로 넣은것임. (SKILL_TORNADO1의 색깔을 붉은색으로)=====================
#define SKILL_TORNADO2 6800
#define SKILL_GREAT_SMASH2 6810
//=====================================================================================
//ktj : 임시로 새로 넣은것임. 번개치기=================================================
#define SKILL_TORNADO3 6801
#define SKILL_GREAT_SMASH3 6811
//=====================================================================================
#define EFFECT_PHYSICAL_ABSORB_DAMAGE 7000
#define SKILL_SHIELD1 20000 //Physical Absorb 방어막..
#define SKILL_SHIELD2 20001 //automation 방어막...
#define EFFECT_SHIELD2_PARTICLE 20002
//ktj : 보류
//#define SKILL_SHIELD1_WHITE 20003 //SKILL_SHIELD1을 흰색으로바꾼것.
//#define EFFECT_POWER1 21000
#define EFFECT_SPARK1 24000
#define EFFECT_SPARK2 24001
#define MONSTER_PIGON_POWER1 29000
#define MONSTER_PIGON_PARTICLE1 29001
#define MONSTER_PIGON_SHOT1 29002
//ktj : 임시로 새로 넣은것임. =========================================================
#define MONSTER_PIGON_POWER2 29003
#define MONSTER_PIGON_PARTICLE2 29004
#define MONSTER_PIGON_PARTICLE1_BLH 29005
//=====================================================================================
#define MONSTER_WEB_SHOT1 35000
#define MONSTER_WEB_HIT1 30000
#define MONSTER_IMP_SHOT1 35100
#define MONSTER_IMP_HIT1 35200
//ktj : 임시로 새로 넣은것임. =========================================================
#define MONSTER_IMP_SHOT2 35101 //1보다좀더크다
#define MONSTER_IMP_HIT2 35201
#define MONSTER_IMP_SHOT3 35102 //블랙홀을 표현한것임
#define MONSTER_IMP_HIT3 35102 //블랙홀용애니
//=====================================================================================
#define MONSTER_MEPHIT_SHOT1 35300
#define MONSTER_MEPHIT_HIT1 35400
#define MONSTER_HEADER_CUTTER_HIT1 35411
#define MONSTER_HULK_HIT1 35422
#define MONSTER_FURY_MAGIC1 35623
#define MONSTER_OMICRON_HIT1 35626
#define MONSTER_DMACHINE_PARTICLE1 35628
#define MONSTER_DMACHINE_MISSILE1 35630
#define MONSTER_DMACHINE_MISSILE2 35631
#define MONSTER_STYGIANLORD_SHOT1 35633
#define MONSTER_STYGIANLORD_PARTICLE1 35634
#define MONSTER_STYGIANLORD_MAGIC1 35635
#define MONSTER_SERQBUS_SHOT1 70000
#define MONSTER_SERQBUS_SHOT2 70001
#define MONSTER_SERQBUS_SHOT3 70002
#define MONSTER_SERQBUS_MAGIC1 70003
#define MONSTER_SERQBUS_MAGIC2 70004
#define MONSTER_SERQBUS_MAGIC3 70005
#define MONSTER_SERQBUS_MAGIC_ATTACK1 70006
#define MONSTER_SERQBUS_MAGIC_ATTACK2 70007
#define MONSTER_SERQBUS_MAGIC_ATTACK3 70008
#define MONSTER_SERQBUS_STATE1 70009
#define MONSTER_SERQBUS_STATE2 70010
#define MONSTER_SERQBUS_STATE3 70011
#define MONSTER_SHADOW_SHOT1 35639
//ktj : 임시로 새로 넣은것임. =========================================================
#define MONSTER_MEPHIT_SHOT2 35301 //1하고 색깔다름
#define MONSTER_MEPHIT_HIT2 35401
//=====================================================================================
//박철호 : 프로즌미스트 (아이스 볼트/ 아이스볼). ======================================
#define MONSTER_FORZENMIST_SHOT1 60601 //1하고 색깔다름
#define MONSTER_FORZENMIST_HIT1 60611
#define MONSTER_FORZENMIST_SHOT2 60602 //1하고 색깔다름
#define MONSTER_FORZENMIST_HIT2 60612
#define EFFECT_ICE_HIT1 60650
#define EFFECT_ICE_HIT2 60651
#define MONSTER_COLDEYE_SKILL 60680
#define MONSTER_VALENTO_HIT1 60690
#define MONSTER_VALENTO_HIT2 60691
#define MONSTER_POSION_STATE1 60700 // 독효과
#define MONSTER_MUMMY_SHOT 60710 // 머미로드
#define MONSTER_TURTLECANON_SHOT 60720 // 터틀캐논 일반공격
#define EFFECT_FIRE_CRACKER 60730 // 폭죽 이펙트
#define EFFECT_FIRE_CRACKER_HIT 60731 // 폭죽 이펙트 터질때
#define EFFECT_CHIMERA_SKILL 60740 // 키메라 스킬쓸때 헤딩
#define EFFECT_BLOODKNIGHT_SKILL 60741 // Blood Knight 스킬 (로어)
//=====================================================================================
#define ARROW_OF_RAGE_POWER1 35401
#define SKILL_ARROW_OF_RAGE_END 40000 //화살이 떨어지는 단계..
#define SKILL_RAGE_OF_ZECRAM_POWER1 44000
#define SKILL_RAGE_OF_ZECRAM_HIT1 44001
#define SKILL_RAGE_OF_ZECRAM_HIT2 44002
#define SKILL_AVALANCHE_PARTICLE 50001
#define EFFECT_ARROW_OF_RAGE_HIT1 53000
#define EFFECT_GROUND_PIKE_PARTICLE 54000
#define EFFECT_STUN1 55000
#define EFFECT_FALCON_GATE1 56000
#define EFFECT_TERRAIN_WAVE 60000
#define SKILL_METALARMOR 61000
//#define SKILL_DIASTROPHISM 63000
class HoEffectLight : public HoEffectObject
{
public:
HoEffectLight();
~HoEffectLight();
int Start(int x, int y, int z, int r, int g, int b, int a, int power, int decPower, int endPowerUp = 0);
private:
int R;
int G;
int B;
int A;
int Power;
int DecPower;
int EndPowerUp;
public:
int Init();
int Main();
};
//이펙트가 여러게 겹치는 경우의 이펙트처리..
class HoEffectTime
{
public:
HoEffectTime();
~HoEffectTime();
void Init();
void Main();
void Draw(int x, int y, int z, int ax, int ay, int az);
void Start();
bool AddObject(HoEffectObject *object, int startTime);
BOOL GetState() { return StartFlag; }
private:
HoEffectObject *TimeObjectBuffer[MAX_TIMEOBJECT_BUFFER];
int StartTime[MAX_TIMEOBJECT_BUFFER];
int DelayTimeCount;
BOOL StartFlag;
};
struct hoChrInfoObject
{
HoEffectObject *object;
smCHAR *character;
};
class HoEffectMgr
{
public:
HoEffectMgr();
~HoEffectMgr();
private:
//임시 이펙트 한번만 나오고 마는 이펙트들....
HoEffectObject *EffectZSortBuffer[MAX_EFFECTOBJECT_BUFFER]; //Z축 소트를 해야하는 이펙트(bmp)
HoEffectObject *EffectObjectBuffer[MAX_EFFECTOBJECT_BUFFER]; //Z축 소트를 하지 않아도 되는 이펙트..(tga)
//이펙트가 여러개 나오는 이펙트들.. 시간에 따라서...
HoEffectTime EffectTimeObjectBuffer[MAX_EFFECTOBJECT_BUFFER];
int MaterialNum[MAX_MATERIAL_NUM];
smPAT3D *PatObj[MAX_OBJECT_NUM];
int PatAnimationEnd[MAX_OBJECT_NUM];
smPAT3D *PatMissile;
int EmptyObjectBufferIndex();
int EmptyZSortBufferIndex();
int EmptyTimeObjectBufferIndex();
int StartBillRectPrimitive(int x, int y, int z, int sizeX, int sizeY, char *iniName);
public:
public:
int StartBillRectPrimitive(int x, int y, int z, char *iniName);
//int StartFaceUpCylinder(int x, int y, int z, int width, int termFrame, char *iniName);
public:
void Init();
int Main();
int Draw(int x, int y, int z, int ax, int ay, int az);
int Start(int x, int y, int z, int effectType, int level = 1);
int Start(int x, int y, int z, int sizeX, int sizeY, int effectType);
int Start(int x, int y, int z, int r, int g, int b, int a, int effectType);
int Start(int x, int y, int z, int effectType, smCHAR *character);
int Start(int x, int y, int z, int effectType, HoEffectObject *parent);
int StartSkillDest(int x, int y, int z, int destX, int destY, int destZ, int skillType = SKILL_NONE, int level=0);
int StartSkill(int x, int y, int z, int angleX, int angleY, int angleZ, int skillType = SKILL_NONE, int level=0);
int StartSkill(int x, int y, int z, int angleX, int angleY, int angleZ, smCHAR *character, int skillType = SKILL_NONE, int level=0);
int StartMonsterDest(POINT3D current, POINT3D dest, int effectType); //몬스터가 쓰는 날라가는 이펙트..
int StartMonsterDest(POINT3D current, POINT3D dest, POINT3D angle, int effectType);
int StartMonster(POINT3D current, int effecctType);
int StartMonster(POINT3D pos, POINT3D angle, int effectType);
//int StartMonster(POINT3D current, int effectType, int liveCount);
int StartChrState(smCHAR *chr, int effectType, int liveCount);
};
//캐릭터를 따라가는 이펙트들....
class HoNewEffectChrMove : public HoEffectObject
{
public:
HoNewEffectChrMove();
~HoNewEffectChrMove();
smCHAR *Character; //이펙트가 따라 다닐 Character
int PartEmitterID;
int LiveCount; //살아 있는 시간 카운트
int TimeCount;
BOOL MyCharacterFlag;
BOOL FlagShow;
int Main();
int Start(smCHAR *chr, int skillCode, int liveCount);
int StopEffect();
};
//움직이는 이펙트들...
class HoNewEffectMove : public HoEffectObject
{
public:
HoNewEffectMove();
~HoNewEffectMove();
private:
smPAT3D *PatObj;
int CurrentFrame;
POINT3D DestPos; //목적 위치..
POINT3D Angle;
int PartEmitterID;
int PartEmitterIDExt;
D3DVECTOR Velocity;
bool ParticleStartFlag;
smOBJ3D *ObjBip;
float Length;
POINT3D OldPos;
BOOL BlendFlag;
int BlendStep;
int BlendCount;
int TimeCount;
public:
int Start(POINT3D curPos, POINT3D destPos, smPAT3D *pat, int skillCode);
int Start(POINT3D curPos, POINT3D destPos, int skillCode);
int Start(POINT3D curPos, POINT3D destPos, POINT3D angle, smPAT3D *pat, int skillCode);
int Main();
int Draw(int x, int y, int z, int ax, int ay, int az);
};
extern int InitEffect();
extern int StartTerrainEffect(int x, int y, int z, int effectType);
extern int StartEffect(int x, int y, int z, int sizeX, int sizeY, int effectType);
extern int StartEffect(int x, int y, int z, int effecType, int level = 1);
extern int StartEffect(int x, int y, int z, char *iniName);
extern int StartEffect(int x, int y, int z, int effectType, smCHAR *character);
extern int StartChildEffect(int x, int y, int z, int effectType, HoEffectObject *parent = NULL);
extern int StartEffect(int x, int y, int z, int r, int g, int b, int a, int type);
extern int StartSkillDest(int x, int y, int z, int destX, int destY, int destZ, int skillType, int level=0);
extern int StartSkill(int x, int y, int z, int angleX, int angleY, int angleZ, int skillType, int level=0);
extern int StartSkill(int x, int y, int z, int angleX, int angleY, int angleZ, smCHAR *character, int skillType, int level);
extern int StartTracker(POINT3D currentPos, POINT3D destPos);
extern int StartEffectMonsterDest(int x, int y, int z, int destX, int destY, int destZ, int effectType);
extern int StartEffectMonsterDest(int x, int y, int z, int destX, int destY, int destZ, int angleX, int angleY, int angleZ, int effectType);
extern int StartEffectMonster(int x, int y, int z, int effectType);
extern int StartEffectMonster(int x, int y, int z, int angleX, int angleY, int angleZ, int effectType);
extern int StartEffectMonster(int x, int y, int z, int effectType, int liveCount);
extern int StartEffectChrState(smCHAR *chr, int effectType, int liveCount);
extern int MainEffect();
extern int DrawEffect(int x, int y, int z, int ax, int ay, int az);
extern int DrawMenuFlame();
extern int StartMenuFlame(int x, int y);
extern HoAnimDataMgr AnimDataMgr;
extern HoPhysicsMgr PhysicsMgr;
extern HoEffectMgr EffectMgr;
#define CHR_IN_EFFECT_OBJECT_MAX 100
extern hoChrInfoObject ChrInEffectObject[CHR_IN_EFFECT_OBJECT_MAX];
#endif
|
#include <iostream>
#include "SavingsManager.h"
using namespace std;
int main() {
char choice;
SavingsManager savingsManager("users.xml", "incomes.xml", "expenses.xml");
while (true) {
if (!savingsManager.checkIfUserIsLoggedIn()) {
choice = savingsManager.choseOptionFromMainMenu();
switch (choice) {
case '1':
savingsManager.registerUser();
break;
case '2':
savingsManager.signInUser();
break;
case '9':
exit(0);
break;
default:
cout << endl << "Nie ma takiej opcji w menu." << endl << endl;
cout << "Nacisnij dowolny przycisk, aby kontynuowac." << endl;
getch();
break;
}
} else {
choice = savingsManager.choseOptionFromUserMenu();
switch (choice) {
case '1':
savingsManager.addIncome();
break;
case '2':
savingsManager.addExpense();
break;
case '3':
savingsManager.showCurrentMonthBalance();
break;
case '4':
savingsManager.showLastMonthBalance();
break;
case '5':
savingsManager.showChosenPeriodBalance();
break;
case '6':
savingsManager.changeLoggedInUserPassword();
break;
case '7':
savingsManager.signOutUser();
break;
}
}
}
}
|
//
// ShadowAssault.h
// Boids
//
// Created by chenyanjie on 7/14/15.
//
//
#ifndef __Boids__ShadowAssault__
#define __Boids__ShadowAssault__
#include "SkillNode.h"
class ShadowAssault : public SkillNode {
private:
float _damage;
public:
ShadowAssault();
virtual ~ShadowAssault();
static ShadowAssault* create( UnitNode* owner, const cocos2d::ValueMap& data, const cocos2d::ValueMap& params );
virtual bool init( UnitNode* owner, const cocos2d::ValueMap& data, const cocos2d::ValueMap& params );
virtual void updateFrame( float delta );
virtual void begin();
virtual void end();
};
#endif /* defined(__Boids__ShadowAssault__) */
|
#ifndef SARIBBONPANNELOPTIONBUTTON_H
#define SARIBBONPANNELOPTIONBUTTON_H
#include <QToolButton>
#include "SARibbonGlobal.h"
class QAction;
/**
* @brief Pannel右下角的操作按钮
*
* 此按钮和一个action关联,使用@ref SARibbonPannel::addOptionAction 函数用于生成此按钮,正常来说
* 用户并不需要直接操作此类,仅仅用于样式设计
* 如果一定要重载此按钮,可以通过重载@ref SARibbonElementCreateDelegate
* 的 @ref SARibbonElementCreateDelegate::createRibbonPannelOptionButton来实现新的OptionButton
*
*/
class SA_RIBBON_EXPORT SARibbonPannelOptionButton : public QToolButton
{
Q_OBJECT
public:
SARibbonPannelOptionButton(QWidget *parent = Q_NULLPTR);
//有别于setDefaultAction 此函数只关联action的响应,而不设置text,icon等
void connectAction(QAction* action);
};
#endif // SAROBBONPANNELOPTIONBUTTON_H
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "../base.h"
#include "Windows.Devices.SerialCommunication.0.h"
#include "Windows.Foundation.0.h"
#include "Windows.Storage.Streams.0.h"
#include "Windows.Foundation.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Devices::SerialCommunication {
struct __declspec(uuid("fcc6bf59-1283-4d8a-bfdf-566b33ddb28f")) __declspec(novtable) IErrorReceivedEventArgs : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Error(winrt::Windows::Devices::SerialCommunication::SerialError * value) = 0;
};
struct __declspec(uuid("a2bf1db0-fc9c-4607-93d0-fa5e8343ee22")) __declspec(novtable) IPinChangedEventArgs : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_PinChange(winrt::Windows::Devices::SerialCommunication::SerialPinChange * value) = 0;
};
struct __declspec(uuid("e187ccc6-2210-414f-b65a-f5553a03372a")) __declspec(novtable) ISerialDevice : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_BaudRate(uint32_t * value) = 0;
virtual HRESULT __stdcall put_BaudRate(uint32_t value) = 0;
virtual HRESULT __stdcall get_BreakSignalState(bool * value) = 0;
virtual HRESULT __stdcall put_BreakSignalState(bool value) = 0;
virtual HRESULT __stdcall get_BytesReceived(uint32_t * value) = 0;
virtual HRESULT __stdcall get_CarrierDetectState(bool * value) = 0;
virtual HRESULT __stdcall get_ClearToSendState(bool * value) = 0;
virtual HRESULT __stdcall get_DataBits(uint16_t * value) = 0;
virtual HRESULT __stdcall put_DataBits(uint16_t value) = 0;
virtual HRESULT __stdcall get_DataSetReadyState(bool * value) = 0;
virtual HRESULT __stdcall get_Handshake(winrt::Windows::Devices::SerialCommunication::SerialHandshake * value) = 0;
virtual HRESULT __stdcall put_Handshake(winrt::Windows::Devices::SerialCommunication::SerialHandshake value) = 0;
virtual HRESULT __stdcall get_IsDataTerminalReadyEnabled(bool * value) = 0;
virtual HRESULT __stdcall put_IsDataTerminalReadyEnabled(bool value) = 0;
virtual HRESULT __stdcall get_IsRequestToSendEnabled(bool * value) = 0;
virtual HRESULT __stdcall put_IsRequestToSendEnabled(bool value) = 0;
virtual HRESULT __stdcall get_Parity(winrt::Windows::Devices::SerialCommunication::SerialParity * value) = 0;
virtual HRESULT __stdcall put_Parity(winrt::Windows::Devices::SerialCommunication::SerialParity value) = 0;
virtual HRESULT __stdcall get_PortName(hstring * value) = 0;
virtual HRESULT __stdcall get_ReadTimeout(Windows::Foundation::TimeSpan * value) = 0;
virtual HRESULT __stdcall put_ReadTimeout(Windows::Foundation::TimeSpan value) = 0;
virtual HRESULT __stdcall get_StopBits(winrt::Windows::Devices::SerialCommunication::SerialStopBitCount * value) = 0;
virtual HRESULT __stdcall put_StopBits(winrt::Windows::Devices::SerialCommunication::SerialStopBitCount value) = 0;
virtual HRESULT __stdcall get_UsbVendorId(uint16_t * value) = 0;
virtual HRESULT __stdcall get_UsbProductId(uint16_t * value) = 0;
virtual HRESULT __stdcall get_WriteTimeout(Windows::Foundation::TimeSpan * value) = 0;
virtual HRESULT __stdcall put_WriteTimeout(Windows::Foundation::TimeSpan value) = 0;
virtual HRESULT __stdcall get_InputStream(Windows::Storage::Streams::IInputStream ** value) = 0;
virtual HRESULT __stdcall get_OutputStream(Windows::Storage::Streams::IOutputStream ** value) = 0;
virtual HRESULT __stdcall add_ErrorReceived(Windows::Foundation::TypedEventHandler<Windows::Devices::SerialCommunication::SerialDevice, Windows::Devices::SerialCommunication::ErrorReceivedEventArgs> * reportHandler, event_token * token) = 0;
virtual HRESULT __stdcall remove_ErrorReceived(event_token token) = 0;
virtual HRESULT __stdcall add_PinChanged(Windows::Foundation::TypedEventHandler<Windows::Devices::SerialCommunication::SerialDevice, Windows::Devices::SerialCommunication::PinChangedEventArgs> * reportHandler, event_token * token) = 0;
virtual HRESULT __stdcall remove_PinChanged(event_token token) = 0;
};
struct __declspec(uuid("058c4a70-0836-4993-ae1a-b61ae3be056b")) __declspec(novtable) ISerialDeviceStatics : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_GetDeviceSelector(hstring * value) = 0;
virtual HRESULT __stdcall abi_GetDeviceSelectorFromPortName(hstring portName, hstring * result) = 0;
virtual HRESULT __stdcall abi_GetDeviceSelectorFromUsbVidPid(uint16_t vendorId, uint16_t productId, hstring * result) = 0;
virtual HRESULT __stdcall abi_FromIdAsync(hstring deviceId, Windows::Foundation::IAsyncOperation<Windows::Devices::SerialCommunication::SerialDevice> ** result) = 0;
};
}
namespace ABI {
template <> struct traits<Windows::Devices::SerialCommunication::ErrorReceivedEventArgs> { using default_interface = Windows::Devices::SerialCommunication::IErrorReceivedEventArgs; };
template <> struct traits<Windows::Devices::SerialCommunication::PinChangedEventArgs> { using default_interface = Windows::Devices::SerialCommunication::IPinChangedEventArgs; };
template <> struct traits<Windows::Devices::SerialCommunication::SerialDevice> { using default_interface = Windows::Devices::SerialCommunication::ISerialDevice; };
}
namespace Windows::Devices::SerialCommunication {
template <typename D>
struct WINRT_EBO impl_IErrorReceivedEventArgs
{
Windows::Devices::SerialCommunication::SerialError Error() const;
};
template <typename D>
struct WINRT_EBO impl_IPinChangedEventArgs
{
Windows::Devices::SerialCommunication::SerialPinChange PinChange() const;
};
template <typename D>
struct WINRT_EBO impl_ISerialDevice
{
uint32_t BaudRate() const;
void BaudRate(uint32_t value) const;
bool BreakSignalState() const;
void BreakSignalState(bool value) const;
uint32_t BytesReceived() const;
bool CarrierDetectState() const;
bool ClearToSendState() const;
uint16_t DataBits() const;
void DataBits(uint16_t value) const;
bool DataSetReadyState() const;
Windows::Devices::SerialCommunication::SerialHandshake Handshake() const;
void Handshake(Windows::Devices::SerialCommunication::SerialHandshake value) const;
bool IsDataTerminalReadyEnabled() const;
void IsDataTerminalReadyEnabled(bool value) const;
bool IsRequestToSendEnabled() const;
void IsRequestToSendEnabled(bool value) const;
Windows::Devices::SerialCommunication::SerialParity Parity() const;
void Parity(Windows::Devices::SerialCommunication::SerialParity value) const;
hstring PortName() const;
Windows::Foundation::TimeSpan ReadTimeout() const;
void ReadTimeout(const Windows::Foundation::TimeSpan & value) const;
Windows::Devices::SerialCommunication::SerialStopBitCount StopBits() const;
void StopBits(Windows::Devices::SerialCommunication::SerialStopBitCount value) const;
uint16_t UsbVendorId() const;
uint16_t UsbProductId() const;
Windows::Foundation::TimeSpan WriteTimeout() const;
void WriteTimeout(const Windows::Foundation::TimeSpan & value) const;
Windows::Storage::Streams::IInputStream InputStream() const;
Windows::Storage::Streams::IOutputStream OutputStream() const;
event_token ErrorReceived(const Windows::Foundation::TypedEventHandler<Windows::Devices::SerialCommunication::SerialDevice, Windows::Devices::SerialCommunication::ErrorReceivedEventArgs> & reportHandler) const;
using ErrorReceived_revoker = event_revoker<ISerialDevice>;
ErrorReceived_revoker ErrorReceived(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::SerialCommunication::SerialDevice, Windows::Devices::SerialCommunication::ErrorReceivedEventArgs> & reportHandler) const;
void ErrorReceived(event_token token) const;
event_token PinChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::SerialCommunication::SerialDevice, Windows::Devices::SerialCommunication::PinChangedEventArgs> & reportHandler) const;
using PinChanged_revoker = event_revoker<ISerialDevice>;
PinChanged_revoker PinChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::SerialCommunication::SerialDevice, Windows::Devices::SerialCommunication::PinChangedEventArgs> & reportHandler) const;
void PinChanged(event_token token) const;
};
template <typename D>
struct WINRT_EBO impl_ISerialDeviceStatics
{
hstring GetDeviceSelector() const;
hstring GetDeviceSelector(hstring_view portName) const;
hstring GetDeviceSelectorFromUsbVidPid(uint16_t vendorId, uint16_t productId) const;
Windows::Foundation::IAsyncOperation<Windows::Devices::SerialCommunication::SerialDevice> FromIdAsync(hstring_view deviceId) const;
};
}
namespace impl {
template <> struct traits<Windows::Devices::SerialCommunication::IErrorReceivedEventArgs>
{
using abi = ABI::Windows::Devices::SerialCommunication::IErrorReceivedEventArgs;
template <typename D> using consume = Windows::Devices::SerialCommunication::impl_IErrorReceivedEventArgs<D>;
};
template <> struct traits<Windows::Devices::SerialCommunication::IPinChangedEventArgs>
{
using abi = ABI::Windows::Devices::SerialCommunication::IPinChangedEventArgs;
template <typename D> using consume = Windows::Devices::SerialCommunication::impl_IPinChangedEventArgs<D>;
};
template <> struct traits<Windows::Devices::SerialCommunication::ISerialDevice>
{
using abi = ABI::Windows::Devices::SerialCommunication::ISerialDevice;
template <typename D> using consume = Windows::Devices::SerialCommunication::impl_ISerialDevice<D>;
};
template <> struct traits<Windows::Devices::SerialCommunication::ISerialDeviceStatics>
{
using abi = ABI::Windows::Devices::SerialCommunication::ISerialDeviceStatics;
template <typename D> using consume = Windows::Devices::SerialCommunication::impl_ISerialDeviceStatics<D>;
};
template <> struct traits<Windows::Devices::SerialCommunication::ErrorReceivedEventArgs>
{
using abi = ABI::Windows::Devices::SerialCommunication::ErrorReceivedEventArgs;
static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.SerialCommunication.ErrorReceivedEventArgs"; }
};
template <> struct traits<Windows::Devices::SerialCommunication::PinChangedEventArgs>
{
using abi = ABI::Windows::Devices::SerialCommunication::PinChangedEventArgs;
static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.SerialCommunication.PinChangedEventArgs"; }
};
template <> struct traits<Windows::Devices::SerialCommunication::SerialDevice>
{
using abi = ABI::Windows::Devices::SerialCommunication::SerialDevice;
static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.SerialCommunication.SerialDevice"; }
};
}
}
|
#include <iostream>
#include <math.h>
#include <fstream>
using namespace std;
// function to perform one step of the explicit method
double* explstep(double xn[2], double dt, double zw){
zw = xn[0];
xn[0] += dt*xn[1];
xn[1] -= dt*zw;
return xn;
}
// function to perform one step in the implicit method
double* implstep(double xn[2], double dt, double zw){
zw = xn[0];
xn[0] = (xn[0]-dt*xn[1])/(1+dt*dt);
xn[1] = (xn[1]+dt*zw)/(1+dt*dt);
return xn;
}
int main(){
double dt = M_PI/100;
double x[2];
x[0] = 1;
x[1] = 0;
double zw;
double* xn = x; // pointer to x
ofstream explout("explicit.txt");
explout << 0 << "\t" << xn[0] << endl;
// generating output file for explicit method
for(int i = 1; i*dt <= 20*M_PI; i++){
xn = explstep(xn,dt,zw);
explout << i*dt << "\t" << xn[0] << endl;
}
explout.close();
// generating output file for implicit method
x[0] = 1;
x[1] = 0;
ofstream implout("implicit.txt");
implout << 0 << "\t" << xn[0] << endl;
for(int i = 1; i*dt <= 20*M_PI; i++){
xn = implstep(xn,dt,zw);
implout << i*dt << "\t" << xn[0] << endl;
}
implout.close();
}
|
//
// sceneManager.hpp
// led_matrix
//
// Created by Alex on 17.11.15.
//
//
#ifndef sceneManager_h
#define sceneManager_h
#include "scenes.h"
class sceneManager : public ofBaseApp{
public:
vector < scene * > scenes;
sceneIntro intro;
sceneMirror mirror;
ofColor pixelMatrixBlended[10][10];
int currentScene;
int sceneChange;
void setup();
void update();
void getSceneBlend(float crossfade, ofColor A[][10], ofColor B[][10]);
// hacks
bool alwaysOn;
int globalBrightness;
};
#endif /* sceneManager_h */
|
#include <cassert>
#include <iomanip>
#include <iostream>
#include "json.hpp"
#include "CCloudGCP.hpp"
#include "CLinkSelector.hpp"
#include "SFile.hpp"
namespace gcp
{
CBucket::CBucket(std::string&& name, CRegion* region)
: CStorageElement(std::move(name), region),
mRegion(region)
{}
void CBucket::OnIncreaseReplica(std::uint64_t amount, TickType now)
{
if (now > mTimeLastCostUpdate)
{
mCosts += BYTES_TO_GiB(mUsedStorage) * mRegion->GetStoragePrice() * SECONDS_TO_MONTHS((now - mTimeLastCostUpdate));
mTimeLastCostUpdate = now;
}
CStorageElement::OnIncreaseReplica(amount, now);
}
void CBucket::OnRemoveReplica(const SReplica* replica, TickType now)
{
std::unique_lock<std::mutex> lock(mReplicaRemoveMutex);
if (now > mTimeLastCostUpdate)
{
mCosts += BYTES_TO_GiB(mUsedStorage) * mRegion->GetStoragePrice() * SECONDS_TO_MONTHS((now - mTimeLastCostUpdate));
mTimeLastCostUpdate = now;
}
CStorageElement::OnRemoveReplica(replica, now, false);
}
double CBucket::CalculateStorageCosts(TickType now)
{
if (now > mTimeLastCostUpdate)
{
mCosts += BYTES_TO_GiB(mUsedStorage) * mRegion->GetStoragePrice() * SECONDS_TO_MONTHS((now - mTimeLastCostUpdate));
mTimeLastCostUpdate = now;
}
double costs = mCosts;
mCosts = 0;
return costs;
}
static double CalculateNetworkCostsRecursive(std::uint64_t traffic, CLinkSelector::PriceInfoType::const_iterator curLevelIt, const CLinkSelector::PriceInfoType::const_iterator &endIt, std::uint64_t prevThreshold = 0)
{
assert(curLevelIt->first >= prevThreshold);
const std::uint64_t threshold = curLevelIt->first - prevThreshold;
CLinkSelector::PriceInfoType::const_iterator nextLevelIt = curLevelIt + 1;
if (traffic <= threshold || nextLevelIt == endIt)
return BYTES_TO_GiB(traffic) * curLevelIt->second;
const double lowerLevelCosts = CalculateNetworkCostsRecursive(traffic - threshold, nextLevelIt, endIt, curLevelIt->first);
return (BYTES_TO_GiB(threshold) * curLevelIt->second) + lowerLevelCosts;
}
CRegion::CRegion(const std::uint32_t multiLocationIdx, std::string&& name, std::string&& locationName, const std::uint32_t numJobSlots, const double storagePrice, std::string&& skuId)
: ISite(multiLocationIdx, std::move(name), std::move(locationName)),
mSKUId(std::move(skuId)),
mStoragePrice(storagePrice),
mNumJobSlots(numJobSlots)
{}
auto CRegion::CreateStorageElement(std::string&& name) -> CBucket*
{
CBucket* newBucket = new CBucket(std::move(name), this);
mStorageElements.emplace_back(newBucket);
return newBucket;
}
double CRegion::CalculateStorageCosts(TickType now)
{
double regionStorageCosts = 0;
for (const std::unique_ptr<CBucket>& bucket : mStorageElements)
regionStorageCosts += bucket->CalculateStorageCosts(now);
return regionStorageCosts;
}
double CRegion::CalculateNetworkCosts(double& sumUsedTraffic, std::uint64_t& sumDoneTransfers)
{
double regionNetworkCosts = 0;
for (const std::unique_ptr<CLinkSelector>& linkSelector : mLinkSelectors)
{
double costs = CalculateNetworkCostsRecursive(linkSelector->mUsedTraffic, linkSelector->mNetworkPrice.cbegin(), linkSelector->mNetworkPrice.cend());
regionNetworkCosts += costs;
sumUsedTraffic += BYTES_TO_GiB(linkSelector->mUsedTraffic);
sumDoneTransfers += linkSelector->mDoneTransfers;
linkSelector->mUsedTraffic = 0;
linkSelector->mDoneTransfers = 0;
linkSelector->mFailedTransfers = 0;
}
return regionNetworkCosts;
}
auto CCloud::CreateRegion(const std::uint32_t multiLocationIdx,
std::string&& name,
std::string&& locationName,
const std::uint32_t numJobSlots,
const double storagePrice,
std::string&& skuId) -> CRegion*
{
CRegion* newRegion = new CRegion(multiLocationIdx, std::move(name), std::move(locationName), numJobSlots, storagePrice, std::move(skuId));
mRegions.emplace_back(newRegion);
return newRegion;
}
auto CCloud::ProcessBilling(TickType now) -> std::pair<double, std::pair<double, double>>
{
double totalStorageCosts = 0;
double totalNetworkCosts = 0;
double sumUsedTraffic = 0;
std::uint64_t sumDoneTransfer = 0;
for (const std::unique_ptr<ISite>& site : mRegions)
{
auto region = dynamic_cast<CRegion*>(site.get());
assert(region != nullptr);
const double regionStorageCosts = region->CalculateStorageCosts(now);
const double regionNetworkCosts = region->CalculateNetworkCosts(sumUsedTraffic, sumDoneTransfer);
totalStorageCosts += regionStorageCosts;
totalNetworkCosts += regionNetworkCosts;
}
return { totalStorageCosts, {totalNetworkCosts, sumUsedTraffic } };
}
void CCloud::SetupDefaultCloud()
{
//CreateRegion("us", "northamerica-northeast1", "Montreal", 0.02275045, "E466-8D73-08F4");
//CreateRegion("northamerica-northeast1', 'northamerica-northeast1', 'Montreal', 0.02275045, "E466-8D73-08F4")
/*
eu - apac EF0A-B3BA-32CA 0.1121580 0.1121580 0.1028115 0.0747720
na - apac 6B37-399C-BF69 0.0000000 0.1121580 0.1028115 0.0747720
na - eu C7FF-4F9E-C0DB 0.0000000 0.1121580 0.1028115 0.0747720
au - apac CDD1-6B91-FDF8 0.1775835 0.1775835 0.1682370 0.1401975
au - eu 1E7D-CBB0-AF0C 0.1775835 0.1775835 0.1682370 0.1401975
au - na 27F0-D54C-619A 0.1775835 0.1775835 0.1682370 0.1401975
au - sa 7F66-C883-4D7D 0.1121580 0.1121580 0.1028115 0.0747720
apac - sa 1F9A-A9AC-FFC3 0.1121580 0.1121580 0.1028115 0.0747720
eu - sa 96EB-C6ED-FBDE 0.1121580 0.1121580 0.1028115 0.0747720
na - sa BB86-91E8-5450 0.1121580 0.1121580 0.1028115 0.0747720
*/
//download apac 1F8B-71B0-3D1B 0.0000000 0.1121580 0.1028115 0.0747720
//download australia 9B2D-2B7D-FA5C 0.1775835 0.1775835 0.1682370 0.1401975
//download china 4980-950B-BDA6 0.2149695 0.2149695 0.2056230 0.1869300
//download us emea 22EB-AAE8-FBCD 0.0000000 0.1121580 0.1028115 0.0747720
const CLinkSelector::PriceInfoType priceSameRegion = { {0,0} };
const CLinkSelector::PriceInfoType priceSameMulti = { {1,0.0093465} };
typedef std::unordered_map<std::uint32_t, CLinkSelector::PriceInfoType> InnerMapType;
typedef std::unordered_map<std::uint32_t, InnerMapType> OuterMapType;
const OuterMapType priceWW
{
{ 0, { { 0, priceSameMulti },
{ 1,{ { 1024, 0.1775835 }, { 10240, 0.1682370 }, { 10240, 0.1401975 } } },
{ 2,{ { 1024, 0.1121580 },{ 10240, 0.1028115 },{ 10240, 0.0747720 } } },
{ 3,{ { 1024, 0.1121580 },{ 10240, 0.1028115 },{ 10240, 0.0747720 } } },
{ 4,{ {1, 0.0}, { 1024, 0.1121580 },{ 10240, 0.1028115 },{ 10240, 0.0747720 } } }
}
},
{ 1, { { 1, priceSameMulti },
{ 2,{ { 1024, 0.1775835 },{ 10240, 0.1682370 },{ 10240, 0.1401975 } } },
{ 3,{ { 1024, 0.1121580 },{ 10240, 0.1028115 },{ 10240, 0.0747720 } } },
{ 4,{ { 1024, 0.1775835 },{ 10240, 0.1682370 },{ 10240, 0.1401975 } } }
}
},
{ 2, { { 2, priceSameMulti },
{ 3,{ { 1024, 0.1121580 },{ 10240, 0.1028115 },{ 10240, 0.0747720 } } },
{ 4,{ { 1, 0.0 },{ 1024, 0.1121580 },{ 10240, 0.1028115 },{ 10240, 0.0747720 } } }
}
},
{ 3, { { 3, priceSameMulti },
{ 4,{ { 1024, 0.1121580 },{ 10240, 0.1028115 },{ 10240, 0.0747720 } } }
}
},
{ 4, { { 4, priceSameMulti } } }
};
for (const std::unique_ptr<ISite>& srcSite : mRegions)
{
auto srcRegion = dynamic_cast<CRegion*>(srcSite.get());
assert(srcRegion != nullptr);
const std::uint32_t srcRegionMultiLocationIdx = srcRegion->GetMultiLocationIdx();
//first set prices for existing links (outgoing links)
for(std::unique_ptr<CLinkSelector> &linkSelector : srcRegion->mLinkSelectors)
{
OuterMapType::const_iterator outerIt = priceWW.find(srcRegionMultiLocationIdx);
InnerMapType::const_iterator innerIt;
if(outerIt != priceWW.cend())
{
//found the srcRegion idx in the outer map
//lets see if we find the dstRegion idx in the inner map
innerIt = outerIt->second.find(linkSelector->GetDstSite()->GetMultiLocationIdx());
if(innerIt == outerIt->second.cend())
outerIt = priceWW.cend(); //Nope. Reset outerIt and try with swapped order
}
if(outerIt == priceWW.cend())
{
outerIt = priceWW.find(linkSelector->GetDstSite()->GetMultiLocationIdx());
assert(outerIt != priceWW.cend());
innerIt = outerIt->second.find(srcRegionMultiLocationIdx);
}
assert(innerIt != outerIt->second.cend());
linkSelector->mNetworkPrice = innerIt->second;
}
for (const std::unique_ptr<ISite>& dstSite : mRegions)
{
auto dstRegion = dynamic_cast<CRegion*>(dstSite.get());
assert(dstRegion != nullptr);
const std::uint32_t dstRegionMultiLocationIdx = dstRegion->GetMultiLocationIdx();
const bool isSameLocation = (*srcRegion) == (*dstRegion);
if (!isSameLocation && (srcRegionMultiLocationIdx != dstRegionMultiLocationIdx))
{
OuterMapType::const_iterator outerIt = priceWW.find(srcRegionMultiLocationIdx);
InnerMapType::const_iterator innerIt;
if(outerIt != priceWW.cend())
{
//found the srcRegion idx in the outer map
//lets see if we find the dstRegion idx in the inner map
innerIt = outerIt->second.find(dstRegionMultiLocationIdx);
if(innerIt == outerIt->second.cend())
outerIt = priceWW.cend(); //Nope. Reset outerIt and try with swapped order
}
if(outerIt == priceWW.cend())
{
outerIt = priceWW.find(dstRegionMultiLocationIdx);
assert(outerIt != priceWW.cend());
innerIt = outerIt->second.find(srcRegionMultiLocationIdx);
}
assert(innerIt != outerIt->second.cend());
CLinkSelector* linkSelector = srcRegion->CreateLinkSelector(dstRegion, ONE_GiB/64);
linkSelector->mNetworkPrice = innerIt->second;
}
else if (isSameLocation)
{
// 2. case: r1 and r2 are the same region
//linkselector.network_price_chf = priceSameRegion
CLinkSelector* linkSelector = srcRegion->CreateLinkSelector(dstRegion, ONE_GiB/8);
linkSelector->mNetworkPrice = priceSameRegion;
}
else
{
// 3. case: region r1 is inside the multi region r2
//linkselector.network_price_chf = priceSameMulti
CLinkSelector* linkSelector = srcRegion->CreateLinkSelector(dstRegion, ONE_GiB/32);
linkSelector->mNetworkPrice = priceSameMulti;
}
}
}
}
bool CCloud::TryConsumeConfig(const nlohmann::json& json)
{
nlohmann::json::const_iterator rootIt = json.find("gcp");
if(rootIt == json.cend())
return false;
for( const auto& [key, value] : rootIt.value().items() )
{
if( key == "regions" )
{
for(const auto& regionJson : value)
{
std::unique_ptr<std::uint32_t> multiLocationIdx;
std::string regionName, regionLocation, skuId;
double price = 0;
std::uint32_t numJobSlots = 0;
nlohmann::json bucketsJson;
for(const auto& [regionJsonKey, regionJsonValue] : regionJson.items())
{
if(regionJsonKey == "multiLocationIdx")
multiLocationIdx = std::make_unique<std::uint32_t>(regionJsonValue.get<std::uint32_t>());
else if(regionJsonKey == "name")
regionName = regionJsonValue.get<std::string>();
else if(regionJsonKey == "location")
regionLocation = regionJsonValue.get<std::string>();
else if (regionJsonKey == "numJobSlots")
numJobSlots = regionJsonValue.get<std::uint32_t>();
else if(regionJsonKey == "buckets")
bucketsJson = regionJsonValue;
else if(regionJsonKey == "price")
price = regionJsonValue.get<double>();
else if(regionJsonKey == "skuId")
skuId = regionJsonValue.get<std::string>();
else
std::cout << "Ignoring unknown attribute while loading regions: " << regionJsonKey << std::endl;
}
if(multiLocationIdx == nullptr)
{
std::cout << "Couldn't find multiLocationIdx attribute of region" << std::endl;
continue;
}
if (regionName.empty())
{
std::cout << "Couldn't find name attribute of region" << std::endl;
continue;
}
if (regionLocation.empty())
{
std::cout << "Couldn't find location attribute of region: " << regionName << std::endl;
continue;
}
std::cout << "Adding region " << regionName << " in " << regionLocation << std::endl;
CRegion *region = CreateRegion(*multiLocationIdx, std::move(regionName), std::move(regionLocation), numJobSlots, price, std::move(skuId));
if (bucketsJson.empty())
{
std::cout << "No buckets to create for this region" << std::endl;
continue;
}
for(const auto& bucketJson : bucketsJson)
{
std::string bucketName;
for(const auto& [bucketJsonKey, bucketJsonValue] : bucketJson.items())
{
if(bucketJsonKey == "name")
bucketName = bucketJsonValue.get<std::string>();
else
std::cout << "Ignoring unknown attribute while loading bucket: " << bucketJsonKey << std::endl;
}
if (bucketName.empty())
{
std::cout << "Couldn't find name attribute of bucket" << std::endl;
continue;
}
std::cout << "Adding bucket " << bucketName << std::endl;
region->CreateStorageElement(std::move(bucketName));
}
}
}
}
return true;
}
}
|
#include "studentsummation.h"
//Tevékenység: Meghatározza az adott neptunkódhoz tartozó átlagot.
//Bemenet:Student
//Kimenet:Student
void StudentSummation::Add(const Student &x)
{
result->neptun = student.neptun;
result->summark += x.summark; //jegyek summázása
result->pcs += 1; //azonos neptun kód hányszor szerepel
result->average = (double)result->summark/result->pcs; // (double) ?
}
|
/* Copyright 2017-2018 All Rights Reserved.
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* [Contact]
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* Licensed under the Apache License, Version 2.0(the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "../inc/WfdDevice.h"
#include "../inc/CommandIwpriv.h"
#include "../../common/inc/ChildProcess.h"
#include "../../common/inc/Counter.h"
#include "../../configs/WfdConfig.h"
#include <mutex>
#include <thread>
#include <stdio.h>
using namespace sc;
bool WfdDevice::turn_on_impl(void) {
// this->ifup();
// this->ifconfig_up();
#if CONFIG_REALTEK_MODE == 1
// RTL81xx series require iwpriv setting for Wi-fi P2P.
CommandIwpriv::p2p_set_enable(DEFAULT_WFD_INTERFACE_NAME,
IwprivP2PRole::kP2PGroupOwner);
#endif
return true;
}
bool WfdDevice::turn_off_impl(void) {
// this->ifconfig_down();
// this->ifdown();
return true;
}
bool WfdDevice::ifup() {
char const *const params[] = {"ifup", DEFAULT_WFD_INTERFACE_NAME, NULL};
sleep(1);
return ChildProcess::run(IFUP_PATH, params, true);
}
bool WfdDevice::ifdown() {
char const *const params[] = {"ifdown", DEFAULT_WFD_INTERFACE_NAME, NULL};
return ChildProcess::run(IFDOWN_PATH, params, true);
}
bool WfdDevice::ifconfig_up() {
char const *const params[] = {"ifconfig", DEFAULT_WFD_INTERFACE_NAME, "up",
NULL};
sleep(1);
return ChildProcess::run(IFCONFIG_PATH, params, true);
}
bool WfdDevice::ifconfig_down() {
char const *const params[] = {"ifconfig", DEFAULT_WFD_INTERFACE_NAME, "down",
NULL};
return ChildProcess::run(IFCONFIG_PATH, params, true);
}
|
/*
* Copyright (c) 2006-2016 RDA Microelectronics, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
/////////////////////////////////////////////////////////////////////////////
// CKeypad wrapper class
class CKeypad : public COleDispatchDriver
{
public:
CKeypad() {} // Calls COleDispatchDriver default constructor
CKeypad(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
CKeypad(const CKeypad& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// Attributes
public:
// Operations
public:
long GetKeySize();
long AddItem(LPCTSTR lpszName, long nKeyCode, long nLeft, long nTop, long nWidth, long nHeight, LPCTSTR lpszImageUp, LPCTSTR lpszImageDown);
void RemoveAll();
};
|
#ifndef KDTREE_H
#define KDTREE_H
#include "kdtree_c.h"
namespace location
{
struct xyz_coords
{
double x, y, z;
double distance(xyz_coords const& r)
{
return sqrt(pow(x-r.x,2)
+ pow(y-r.y,2)
+ pow(z-r.z,2));
}
};
class KDTree
{
kdtree* self_;
// запретить копирование
KDTree(KDTree const&);
void operator=(KDTree const&);
public:
KDTree()
{
self_ = kd_create(3);
}
~KDTree()
{
kd_free(self_);
}
void clear()
{
kd_clear(self_);
}
void add(xyz_coords const& p, int id)
{
kd_insert3(self_, p.x, p.y, p.z, (void*)id);
}
int getclosest_ids(xyz_coords const& p, int *ids, int count, double range)
{
kdres *res = kd_nearest_range3(self_, p.x, p.y, p.z, range);
if (!res) return 0;
std::vector<std::pair<double, int> > vec;
for(unsigned index=0;; ++index)
{
if (kd_res_end(res))
{
kd_res_free(res);
break;
}
// получаем данные точки
double pos[3];
int id = (int)kd_res_item(res, pos);
kd_res_next(res);
xyz_coords q = {pos[0], pos[1], pos[2]};
vec.push_back( std::make_pair(q.distance(p), id));
}
std::sort(vec.begin(), vec.end());
count = std::min<unsigned>(count, vec.size());
for(unsigned index=0; index < count; ++index)
{
ids[index] = vec[index].second;
}
return count;
}
int getclosest_id(xyz_coords const& p)
{
kdres *res = kd_nearest3(self_, p.x, p.y, p.z);
if (!res) return -1;
if (!kd_res_end(res))
{
return (int)kd_res_item(res, 0);
}
kd_res_free(res);
return -1;
}
};
}
#endif // KDTREE_H
|
#ifndef _SAGEFUNCTORS_H
#define _SAGEFUNCTORS_H
/// \file sageFunctors.h
/// This file implements utility functors for using sage containers
/// with STL functions:
/// - ScopeSetter, VarRefBuilder, InitNameCloner, and SageInserter
/// (a generic inserter for sage containers).
/// \email peter.pirkelbauer@llnl.gov
#include "sageInterface.h"
#include "sageBuilder.h"
namespace sg
{
/// \brief returns a deep copy of a sage node
/// \details allows NULL input nodes (in contrast to SageInterface::deepCopy)
template <class SageNode>
static inline
SageNode* cloneNode(const SageNode* n)
{
if (!n) return 0;
return SageInterface::deepCopy(n);
}
/// \brief unified interface for storing an element in a sage container
/// \note internal use
static inline
void _append(SgExprListExp& container, SgExpression* elem)
{
SageInterface::appendExpression(&container, elem);
}
/// \overload
static inline
void _append(SgFunctionParameterList& container, SgInitializedName* elem)
{
SageInterface::appendArg(&container, elem);
}
/// \brief Functor setting the scope of a sage node to a specified (at Functor construction time) scope
struct ScopeSetter
{
explicit
ScopeSetter(SgScopeStatement& the_scope)
: scope(the_scope)
{}
template <class ScopedSageNode>
void handle(ScopedSageNode* scopeElem) const
{
ROSE_ASSERT(scopeElem);
scopeElem->set_scope(&scope);
}
void operator()(SgStatement* scopeElem) const { handle(scopeElem); }
void operator()(SgInitializedName* scopeElem) const { handle(scopeElem); }
private:
SgScopeStatement& scope;
};
/// \brief Functor building a variable reference from an initialized name
struct VarRefBuilder
{
explicit
VarRefBuilder(SgScopeStatement& the_scope)
: scope(the_scope)
{}
SgVarRefExp* operator()(SgInitializedName* initName) const
{
return SageBuilder::buildVarRefExp(initName, &scope);
}
private:
SgScopeStatement& scope;
};
/// \brief Functor copying an initialized name into a different scope
struct InitNameCloner
{
InitNameCloner(SgDeclarationStatement& declaration, SgScopeStatement* enclosing_scope = 0)
: decl(declaration), scope(enclosing_scope)
{}
SgInitializedName* operator()(const SgInitializedName* orig) const
{
SgInitializer* copy_init = cloneNode(orig->get_initializer());
SgInitializedName* res = SageBuilder::buildInitializedName(orig->get_name(), orig->get_type(), copy_init);
res->set_scope(scope);
return res;
}
private:
SgDeclarationStatement& decl;
SgScopeStatement* scope;
};
/// \brief Generic inserter for sage containers
/// \tparam SageSequenceContainer, a sage container that supports appending an element
/// \details forwards actual insert to function family _append
template <class SageSequenceContainer>
struct SageInserter : std::iterator<std::output_iterator_tag, void, void, void, void>
{
typedef SageSequenceContainer Container;
Container& container;
explicit
SageInserter(Container& cont)
: container(cont)
{}
// \todo SageElem should be derived form the container type
template <class SageElem>
SageInserter& operator=(SageElem* elem)
{
_append(container, elem);
return *this;
}
SageInserter& operator*() { return *this; }
SageInserter& operator++() { return *this; }
SageInserter& operator++(int) { return *this; }
};
/// \brief generates a SageInserter, adding elements at the end of a sequence
/// \tparam SageSequenceContainer, a sage container that supports appending an element
template <class SageSequenceContainer>
SageInserter<SageSequenceContainer>
sage_inserter(SageSequenceContainer& cont)
{
return SageInserter<SageSequenceContainer>(cont);
}
}
#endif /* _SAGEFUNCTORS_H */
|
/**
* **** Code generated by the RIDL Compiler ****
* RIDL has been developed by:
* Remedy IT
* Westervoort, GLD
* The Netherlands
* http://www.remedy.nl
*/
#ifndef __RIDL_TESTC_H_HHACBDCA_INCLUDED__
#define __RIDL_TESTC_H_HHACBDCA_INCLUDED__
#pragma once
#include /**/ "ace/pre.h"
#include "tao/x11/stddef.h"
#include "tao/x11/basic_traits.h"
#include "tao/x11/corba.h"
#include "tao/x11/system_exception.h"
#include "tao/x11/orb.h"
#include "tao/x11/bounded_string_t.h"
#include "tao/x11/bounded_type_traits_t.h"
#include "tao/x11/fixed_t.h"
#include "tao/x11/object.h"
#include "tao/x11/corba_ostream.h"
#include /**/ "tao/x11/versionx11.h"
#if TAOX11_MAJOR_VERSION != 1 || TAOX11_MINOR_VERSION != 7 || TAOX11_MICRO_VERSION != 1
#error This file was generated with another RIDL C++11 backend version (1.7.1). Please re-generate.
#endif
using namespace TAOX11_NAMESPACE;
// generated from StubHeaderWriter#enter_module
/// @copydoc test.idl::Test
namespace Test
{
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::ch_val
constexpr char ch_val {'a'};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::wch_val
constexpr wchar_t wch_val {L'X'};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::oct_val
constexpr uint8_t oct_val {123};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::sh_val
constexpr int16_t sh_val {-1023};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::ush_val
constexpr uint16_t ush_val {1023U};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::l_val
constexpr int32_t l_val {-81234};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::ul_val
constexpr uint32_t ul_val {81234UL};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::ll_val
constexpr int64_t ll_val {-12345678LL};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::ull_val
constexpr uint64_t ull_val {12345678ULL};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::f_val
constexpr float f_val {1.23F};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::d_val
constexpr double d_val {454.23};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::ld_val
constexpr long double ld_val {678.91L};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::b_val
constexpr bool b_val {true};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::s_val
const std::string s_val {"text"};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::ws_val
const std::wstring ws_val {L"widestring\n \xbf \xfe0e"};
// generated from c++11/templates/cli/hdr/typedef.erb
/// @copydoc test.idl::Test::TCounter
typedef int32_t TCounter;
// generated from c++11/templates/cli/hdr/typedef.erb
/// @copydoc test.idl::Test::TName
typedef TAOX11_IDL::bounded_basic_string<char, 30> TName;
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::count
constexpr TCounter count {99};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::name
const TName name {"wilco"};
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::double_count
constexpr TCounter double_count = (::Test::count * 2);
// generated from c++11/templates/cli/hdr/typedef.erb
/// @copydoc test.idl::Test::fixed_type
typedef TAOX11_NAMESPACE::IDL::Fixed <10, 3> fixed_type;
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::Test::pi2
const fixed_type pi2;
} // namespace Test
// generated from StubHeaderWriter#enter_interface
// generated from c++11/templates/cli/hdr/interface_fwd.erb
#if !defined (_INTF_A_FWD_)
#define _INTF_A_FWD_
class A;
class A_proxy;
typedef A_proxy* A_proxy_ptr;
#endif // !_INTF_A_FWD_
// generated from c++11/templates/cli/hdr/interface_object_traits.erb
#if !defined (_INTF_A_TRAITS_DECL_)
#define _INTF_A_TRAITS_DECL_
namespace TAOX11_NAMESPACE
{
namespace CORBA
{
template<>
object_traits< ::A>::shared_ptr_type
object_traits< ::A>::lock_shared (
::A* p);
template<>
object_traits< ::A>::ref_type
object_traits< ::A>::narrow (
object_traits<TAOX11_NAMESPACE::CORBA::Object>::ref_type);
} // namespace CORBA
namespace IDL
{
template<>
struct traits < ::A> :
public IDL::common_byval_traits <CORBA::object_reference < ::A>>,
public CORBA::object_traits < ::A>
{
/// std::false_type or std::true_type type indicating whether
/// this interface is declared as local
typedef std::false_type is_local;
/// std::false_type or std::true_type type indicating whether
/// this interface is declared as abstract
typedef std::false_type is_abstract;
template <typename OStrm_, typename Formatter = formatter< ::A, OStrm_>>
static inline OStrm_& write_on(
OStrm_& os_, in_type val_,
Formatter fmt_ = Formatter ())
{
return fmt_ (os_, val_);
}
template <typename Formatter = std::false_type>
static inline __Writer<Formatter> write (in_type val) { return {val}; }
};
} // namespace IDL
} // namespace TAOX11_NAMESPACE
#endif // !_INTF_A_TRAITS_DECL_
// generated from c++11/templates/cli/hdr/interface_pre.erb
/// @copydoc test.idl::A
class A
: public virtual TAOX11_NAMESPACE::CORBA::Object
{
public:
template <typename T> friend struct TAOX11_CORBA::object_traits;
/// @name Member types
//@{
typedef TAOX11_IDL::traits< A> _traits_type;
/// Strong reference type
typedef TAOX11_IDL::traits< A>::ref_type _ref_type;
//@}
// generated from StubHeaderWriter#visit_const
/// @copydoc test.idl::A::pi
static constexpr float pi {3.14159F};
// generated from c++11/templates/cli/hdr/interface_post.erb
protected:
typedef std::shared_ptr<A> _shared_ptr_type;
template <typename _Tp1, typename, typename ...Args>
friend TAOX11_CORBA::object_reference<_Tp1> TAOX11_CORBA::make_reference(Args&& ...args);
explicit A (A_proxy_ptr p, bool inherited = false);
/// Default constructor
A () = default;
/// Destructor
~A () = default;
private:
/** @name Illegal to be called. Deleted explicitly to let the compiler detect any violation */
//@{
A(const A&) = delete;
A(A&&) = delete;
A& operator=(const A&) = delete;
A& operator=(A&&) = delete;
//@}
A_proxy_ptr a_proxy_ {};
}; // class A
// generated from StubHeaderIDLTraitsWriter#pre_visit
namespace TAOX11_NAMESPACE
{
namespace IDL
{
// generated from c++11/templates/cli/hdr/string_idl_traits.erb
// Unaliased type : TAOX11_IDL::bounded_basic_string<char, 30>
// MD5 : 4FC4252C9D149C59A6F97B9D11EF60DC
#if !defined(_ALIAS_4FC4252C9D149C59A6F97B9D11EF60DC_TRAITS_DECL_)
#define _ALIAS_4FC4252C9D149C59A6F97B9D11EF60DC_TRAITS_DECL_
template<>
struct traits < TAOX11_IDL::bounded_basic_string<char, 30>>
: IDL::common_traits< TAOX11_IDL::bounded_basic_string<char, 30>>
, IDL::bounded_traits< TAOX11_IDL::bounded_basic_string<char, 30>>
{
/// std::false_type or std::true_type type indicating whether
/// this string is declared as bounded
typedef std::true_type is_bounded;
/// IDL::traits<> for the element of the string
typedef IDL::traits<char> element_traits;
template <typename OStrm_, typename Formatter = formatter<value_type, OStrm_>>
static inline OStrm_& write_on(
OStrm_& os_, in_type val_,
Formatter fmt_ = Formatter ())
{
return fmt_ (os_, val_);
}
template <typename Formatter = std::false_type>
static inline __Writer<Formatter> write (in_type val) { return {val}; }
};
template <typename OStrm_, typename Fmt>
inline OStrm_& operator <<(
OStrm_& os,
IDL::traits< TAOX11_IDL::bounded_basic_string<char, 30>>::__Writer<Fmt> w)
{
typedef IDL::traits< TAOX11_IDL::bounded_basic_string<char, 30>>::__Writer<Fmt> writer_t;
typedef typename std::conditional<
std::is_same<
typename writer_t::formatter_t,
std::false_type>::value,
formatter< TAOX11_IDL::bounded_basic_string<char, 30>, OStrm_>,
typename writer_t::formatter_t>::type formatter_t;
return IDL::traits< TAOX11_IDL::bounded_basic_string<char, 30>>::write_on (
os, w.val_,
formatter_t ());
}
#endif
// generated from c++11/templates/cli/hdr/fixed_idl_traits.erb
// Unaliased type : TAOX11_NAMESPACE::IDL::Fixed <10, 3>
// MD5 : 26C447B68D082EEA72A00BE046CE87A7
#if !defined(_ALIAS_26C447B68D082EEA72A00BE046CE87A7_TRAITS_DECL_)
#define _ALIAS_26C447B68D082EEA72A00BE046CE87A7_TRAITS_DECL_
template<>
struct traits < TAOX11_NAMESPACE::IDL::Fixed <10, 3>>
: IDL::common_traits< TAOX11_NAMESPACE::IDL::Fixed <10, 3>>
{
typedef std::integral_constant< uint16_t, 10> digits;
typedef std::integral_constant< uint16_t, 3> scale;
template <typename OStrm_, typename Formatter = formatter<value_type, OStrm_>>
static inline OStrm_& write_on(
OStrm_& os_, in_type val_,
Formatter fmt_ = Formatter ())
{
return fmt_ (os_, val_);
}
template <typename Formatter = std::false_type>
static inline __Writer<Formatter> write (in_type val) { return {val}; }
};
template <typename OStrm_>
struct formatter< TAOX11_NAMESPACE::IDL::Fixed <10, 3>, OStrm_>
{
inline OStrm_& operator ()(
OStrm_& os_,
const TAOX11_NAMESPACE::IDL::Fixed <10, 3>& val_)
{
os_ << "IDL::Fixed <10, 3> "
<< val_.to_string ();
return os_;
}
};
template <typename OStrm_, typename Fmt>
inline OStrm_& operator <<(
OStrm_& os,
IDL::traits< TAOX11_NAMESPACE::IDL::Fixed <10, 3>>::__Writer<Fmt> w)
{
typedef IDL::traits< TAOX11_NAMESPACE::IDL::Fixed <10, 3>>::__Writer<Fmt> writer_t;
typedef typename std::conditional<
std::is_same<
typename writer_t::formatter_t,
std::false_type>::value,
formatter< TAOX11_NAMESPACE::IDL::Fixed <10, 3>, OStrm_>,
typename writer_t::formatter_t>::type formatter_t;
return IDL::traits< TAOX11_NAMESPACE::IDL::Fixed <10, 3>>::write_on (
os, w.val_,
formatter_t ());
}
#endif
// generated from c++11/templates/cli/hdr/interface_idl_traits.erb
#if !defined (_INTF_FMT_A_TRAITS_DECL_)
#define _INTF_FMT_A_TRAITS_DECL_
template <typename OStrm_>
struct formatter< ::A, OStrm_>
{
OStrm_& operator ()(
OStrm_& ,
IDL::traits< ::A>::ref_type);
};
template <typename OStrm_, typename Fmt>
OStrm_& operator <<(
OStrm_&,
IDL::traits< ::A>::__Writer<Fmt>);
#endif // !_INTF_FMT_A_TRAITS_DECL_
} // namespace IDL
} // namespace TAOX11_NAMESPACE
// generated from StubHeaderIDLTraitsDefWriter#pre_visit
namespace TAOX11_NAMESPACE
{
namespace IDL
{
// generated from c++11/templates/cli/hdr/interface_idl_traits_def.erb
template <typename OStrm_>
inline OStrm_&
formatter< ::A, OStrm_>::operator ()(
OStrm_& os_,
IDL::traits< ::A>::ref_type val_)
{
os_ << IDL::traits<TAOX11_CORBA::Object>::_dump (
std::move (val_),
"A");
return os_;
}
template <typename OStrm_, typename Fmt>
inline OStrm_& operator <<(
OStrm_& os,
IDL::traits< ::A>::__Writer<Fmt> w)
{
typedef IDL::traits< ::A>::__Writer<Fmt> writer_t;
typedef typename std::conditional<
std::is_same<
typename writer_t::formatter_t,
std::false_type>::value,
formatter< ::A, OStrm_>,
typename writer_t::formatter_t>::type formatter_t;
return IDL::traits< ::A>::write_on (
os, w.val_,
formatter_t ());
}
} // namespace IDL
} // namespace TAOX11_NAMESPACE
// generated from c++11/templates/cli/hdr/fixed_os.erb
// Unaliased type : TAOX11_NAMESPACE::IDL::Fixed <10, 3>
// MD5 : 26C447B68D082EEA72A00BE046CE87A7
#if !defined (_ALIAS_OSTREAM_26C447B68D082EEA72A00BE046CE87A7_DECL_)
#define _ALIAS_OSTREAM_26C447B68D082EEA72A00BE046CE87A7_DECL_
inline std::ostream& operator<< (
std::ostream& strm,
const TAOX11_NAMESPACE::IDL::Fixed <10, 3>& _v)
{
return IDL::traits< TAOX11_NAMESPACE::IDL::Fixed <10, 3>>::write_on (strm, _v);
}
#endif // _ALIAS_OSTREAM_26C447B68D082EEA72A00BE046CE87A7_DECL_
// generated from c++11/templates/cli/hdr/interface_os.erb
inline std::ostream& operator<< (
std::ostream& strm,
IDL::traits< ::A>::ref_type _v)
{
return IDL::traits< ::A>::write_on (strm, std::move(_v));
}
// generated from c++11/templates/cli/hdr/post.erb
#if defined (__TAOX11_INCLUDE_STUB_PROXY__)
#include "testCP.h"
#endif
#include /**/ "ace/post.h"
#endif /* __RIDL_TESTC_H_HHACBDCA_INCLUDED__ */
// -*- END -*-
|
#include <vector>
#include <string>
#include "Player.h"
class Card { // abstract class
string name;
int cost;
string description;
Player *Owner;
public:
virtual ~Card();
enum cardType {Minion = 0, Spell, Enchantment, Ritual}
virtual cardType getType()=0;
};
std::ostream &operator<<(std::ostream &out, const Card &c);
|
#include <iostream>
#include "abstractfactory.hpp"
using std::cout;
using std::endl;
FigureFactory::FigureFactory() {
}
FigureFactory::~FigureFactory() {
}
RoundFactory::RoundFactory() {
cout<<"Init RoundFactory"<<endl;
}
RoundFactory::~RoundFactory() {
}
MaskARound* RoundFactory::CreateFigureA() {
return new MaskARound();
}
MaskBRound* RoundFactory::CreateFigureB() {
return new MaskBRound();
}
RecFactory::RecFactory() {
cout<<"Init RecFactory"<<endl;
}
RecFactory::~RecFactory() {
}
MaskARec* RecFactory::CreateFigureA() {
return new MaskARec();
}
MaskBRec* RecFactory::CreateFigureB() {
return new MaskBRec();
}
TriFactory::TriFactory() {
cout<<"Init TriFactory"<<endl;
}
TriFactory::~TriFactory() {
}
MaskATri* TriFactory::CreateFigureA() {
return new MaskATri();
}
MaskBTri* TriFactory::CreateFigureB() {
return new MaskBTri();
}
|
#ifndef MAINWINDOWPAINTER_H
#define MAINWINDOWPAINTER_H
#include <QMainWindow>
#include <QtGui/QPainter>
#include <stdio.h>
namespace Ui {
class MainWindowPainter;
}
class MainWindowPainter : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindowPainter(QWidget *parent = 0);
~MainWindowPainter();
private:
Ui::MainWindowPainter *ui;
QPainter *painter;
void paintEvent(QPaintEvent *e);
};
#endif // MAINWINDOWPAINTER_H
|
//
/// \file
/// \brief ublas storage array compatible with numpy
/// \ingroup python
//
#ifndef __NUMPY_ARRAY_UBLAS_HPP__
#define __NUMPY_ARRAY_UBLAS_HPP__
#include <cstdlib>
#include <numeric>
#include <complex>
#include <jflib/python/helpers.hpp>
#include <boost/assert.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/storage.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/type_traits/is_signed.hpp>
#include <boost/foreach.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/range.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_class.hpp>
#include <numpy/arrayobject.h>
namespace jflib { namespace python {
static struct _pyublas_array_importer {
_pyublas_array_importer() {
import_array();
}
} _array_importer;
}}
namespace jflib { namespace python { namespace numpy {
inline NPY_TYPES get_typenum(bool) { return NPY_BOOL; }
inline NPY_TYPES get_typenum(npy_bool) { return NPY_BOOL; }
inline NPY_TYPES get_typenum(npy_byte) { return NPY_BYTE; }
inline NPY_TYPES get_typenum(npy_short) { return NPY_SHORT; }
inline NPY_TYPES get_typenum(npy_ushort) { return NPY_USHORT; }
inline NPY_TYPES get_typenum(npy_int) { return NPY_INT; }
inline NPY_TYPES get_typenum(npy_uint) { return NPY_UINT; }
inline NPY_TYPES get_typenum(npy_long) { return NPY_LONG; }
inline NPY_TYPES get_typenum(npy_ulong) { return NPY_ULONG; }
//inline NPY_TYPES get_typenum(npy_longlong) { return NPY_LONGLONG; }
inline NPY_TYPES get_typenum(npy_ulonglong) { return NPY_ULONGLONG; }
inline NPY_TYPES get_typenum(npy_float) { return NPY_FLOAT; }
inline NPY_TYPES get_typenum(npy_double) { return NPY_DOUBLE; }
//inline NPY_TYPES get_typenum(npy_longdouble) { return NPY_LONGDOUBLE; }
inline NPY_TYPES get_typenum(npy_cfloat) { return NPY_CFLOAT; }
inline NPY_TYPES get_typenum(npy_cdouble) { return NPY_CDOUBLE; }
inline NPY_TYPES get_typenum(npy_clongdouble) { return NPY_CLONGDOUBLE; }
inline NPY_TYPES get_typenum(std::complex<float>) { return NPY_CFLOAT; }
inline NPY_TYPES get_typenum(std::complex<double>) { return NPY_CDOUBLE; }
inline NPY_TYPES get_typenum(std::complex<long double>) { return NPY_CLONGDOUBLE; }
inline NPY_TYPES get_typenum(boost::python::object) { return NPY_OBJECT; }
inline NPY_TYPES get_typenum(boost::python::handle<>) { return NPY_OBJECT; }
/* NPY_STRING, NPY_UNICODE unsupported for now */
template <class T>
inline bool is_storage_compatible(PyObject *ary) {
/* This piece of code works around the fact that 'int' and
* 'long int' are the same on 32-bit machines, which can lead
* to typenum mismatches. Therefore, for integers, we only
* compare size and signedness.
*
* Also, bool and the chars are storage-compatible usually.
*/
NPY_TYPES typenum = NPY_TYPES(PyArray_TYPE(ary));
if (boost::is_integral<T>::value && PyArray_ISINTEGER(ary)) {
return (sizeof(T) == PyArray_ITEMSIZE(ary)
&& bool(boost::is_signed<T>::value)
== bool(PyArray_ISSIGNED(ary)));
}
else if (typenum == NPY_BOOL && (
boost::is_same<T, signed char>::value ||
boost::is_same<T, unsigned char>::value)) {
return (sizeof(T) == PyArray_ITEMSIZE(ary)
&& bool(boost::is_signed<T>::value)
== bool(PyArray_ISSIGNED(ary)));
}
else
return typenum == get_typenum(T());
}
/** \brief ublas storage array compatible with numpy
*
* A Storage is a variable-size container whose elements are arranged in a strict linear order.
* The numpy_array is a unbounded storage array.
* The unbounded array is similar to a std::vector in that in can grow in
* size beyond any fixed bound
*/
template <class T>
class numpy_array {
private:
// Life support for the numpy array.
boost::python::handle<> m_numpy_array;
public:
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T value_type;
typedef const T& const_reference;
typedef T& reference;
typedef const T* const_pointer;
typedef T* pointer;
typedef const_pointer const_iterator;
typedef pointer iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
/// \brief Construction and destruction
numpy_array(){}
BOOST_UBLAS_INLINE
numpy_array(size_type n) {
npy_intp dims[] = { n };
m_numpy_array = boost::python::handle<>(PyArray_SimpleNew(1, dims, get_typenum(T())));
}
BOOST_UBLAS_INLINE
numpy_array(int ndim_, const npy_intp *dims_) {
m_numpy_array = boost::python::handle<>(
PyArray_SimpleNew(
ndim_,
const_cast<npy_intp *>(dims_),
get_typenum(T())));
}
BOOST_UBLAS_INLINE
numpy_array(size_type n, const value_type &v) {
npy_intp dims[] = { n };
if(n) {
m_numpy_array = boost::python::handle<>(PyArray_SimpleNew(1, dims, get_typenum(T())));
std::fill(begin(), end(), v);
}
}
/* MISSING
Range constructor X(i, j)
i and j are Input Iterators whose value type is convertible to T X
*/
numpy_array(const boost::python::handle<> &obj): m_numpy_array(obj) {
if(!obj.get())
return;
if(obj.get() == Py_None) {
m_numpy_array = boost::python::handle<>();
return;
}
if(!PyArray_Check(obj.get()))
PYUBLAS_PYERROR(TypeError, "argument is not a numpy array");
if(!is_storage_compatible<T>(obj.get()))
PYUBLAS_PYERROR(TypeError, "argument is numpy array of wrong type");
if(!PyArray_CHKFLAGS(obj.get(), NPY_ALIGNED))
PYUBLAS_PYERROR(ValueError, "argument array is not aligned");
if(PyArray_CHKFLAGS(obj.get(), NPY_NOTSWAPPED))
PYUBLAS_PYERROR(ValueError, "argument array does not have native endianness");
if(PyArray_ITEMSIZE(obj.get()) != sizeof(T))
PYUBLAS_PYERROR(ValueError, "itemsize does not match size of target type");
}
numpy_array copy() const {
boost::python::handle<> cp(PyArray_NewCopy(
reinterpret_cast<PyArrayObject *>(m_numpy_array.get()), NPY_ANYORDER));
return numpy_array(cp);
}
private:
void resize_internal(size_type new_size, value_type init, bool preserve = true) {
size_type old_size;
if (m_numpy_array.get())
old_size = size();
else {
preserve = false;
old_size = 0;
}
if (new_size != old_size)
{
npy_intp dims[] = { new_size };
boost::python::handle<> new_array = boost::python::handle<>(
PyArray_SimpleNew(1, dims, get_typenum(T())));
pointer new_data = reinterpret_cast<T *>(
PyArray_DATA(new_array.get()));
if (preserve)
{
std::copy(data(), data() + std::min(new_size, old_size), new_data);
std::fill(new_data + std::min(new_size, old_size), new_data + new_size, init);
}
m_numpy_array = new_array;
}
}
public:
void resize (size_type size) {
resize_internal (size, value_type(), false);
}
void resize (size_type size, value_type init) {
resize_internal (size, init, true);
}
size_type size() const {
if (!is_valid())
return 0;
if(ndim() != 0) {
return end()-begin();
}
else
return 1;
}
// metadata
bool is_valid() const { return m_numpy_array.get(); }
size_type ndim() const { return PyArray_NDIM(m_numpy_array.get()); }
const npy_intp *dims() const { return PyArray_DIMS(m_numpy_array.get()); }
const npy_intp dim(npy_intp i) const { return PyArray_DIM(m_numpy_array.get(), i); }
const npy_intp *strides() const { return PyArray_STRIDES(m_numpy_array.get()); }
const npy_intp stride(npy_intp i) const { return PyArray_STRIDE(m_numpy_array.get(), i); }
npy_intp itemsize() const { return sizeof(T); }
bool writable() const { return PyArray_ISWRITEABLE(m_numpy_array.get()); }
// shape manipulation
void reshape(int ndim_, const npy_intp *dims_, NPY_ORDER order=NPY_CORDER) {
PyArray_Dims d = { const_cast<npy_intp *>(dims_), ndim_ };
m_numpy_array = boost::python::handle<>(
PyArray_Newshape((PyArrayObject *) m_numpy_array.get(), &d, order));
}
// Raw data access
T *data() {
return reinterpret_cast<T*>(PyArray_DATA(m_numpy_array.get()));
}
const T *data() const {
return reinterpret_cast<const T *>(PyArray_DATA(m_numpy_array.get()));
}
// Element access
const_reference operator [] (size_type i) const {
BOOST_UBLAS_CHECK(i < size(), boost::numeric::ublas::bad_index());
return begin()[i];
}
reference operator [] (size_type i) {
BOOST_UBLAS_CHECK(i < size(), boost::numeric::ublas::bad_index());
return begin()[i];
}
// Assignment
numpy_array &operator=(const numpy_array &a) {
m_numpy_array = a.m_numpy_array;
return *this;
}
numpy_array &assign_temporary(numpy_array &a) {
m_numpy_array = a.m_numpy_array;
return *this;
}
// Swapping
void swap(numpy_array &a) {
if (this != &a)
std::swap(m_numpy_array, a.m_numpy_array);
}
friend void swap(numpy_array &a1, numpy_array &a2) {
a1.swap (a2);
}
protected:
npy_intp max_pos_stride_index() const {
npy_intp current_idx = -1;
npy_intp current_max = 0;
for (unsigned i = 0; i < ndim(); ++i) {
npy_intp si = stride(i);
if (si > current_max) {
current_max = si;
current_idx = i;
}
}
return current_idx;
}
public:
const_iterator begin() const {
const_iterator result = data();
for (unsigned i = 0; i < ndim(); ++i) {
const npy_intp si = stride(i)/npy_intp(sizeof(T));
const npy_intp di = dim(i);
if (si < 0 && di)
result += si*(di-1);
}
return result;
}
const_iterator end() const {
const npy_intp mpsi = max_pos_stride_index();
if (mpsi != -1) {
const npy_intp mps = stride(mpsi)/npy_intp(sizeof(T));
return data() + mps*dim(mpsi);
}
else
return data()+1;
}
iterator begin() {return const_cast<iterator>(const_cast<numpy_array const *>(this)->begin());}
iterator end() {return const_cast<iterator>(const_cast<numpy_array const *>(this)->end());}
// Reverse iterators
const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
reverse_iterator rbegin() { return reverse_iterator(end()); }
reverse_iterator rend () { return reverse_iterator(begin()); }
// Data accessors
const boost::python::handle<> handle() const {
if(is_valid())
return m_numpy_array;
else
return boost::python::handle<>(boost::python::borrowed(Py_None));
}
boost::python::handle<> to_python() const {return handle();}
};
template <class OCat, class T>
typename numpy_array<T>::size_type get_array_size1(numpy_array<T> const &ary) {
typedef numpy_array<T> mat_type;
if (PyArray_NDIM(ary.handle().get()) != 2)
throw std::runtime_error("ndarray->matrix converteee has dimension != 2");
if (PyArray_STRIDE(ary.handle().get(), 1) == PyArray_ITEMSIZE(ary.handle().get())) {
// row-major
if (!is_row_major(OCat()))
throw std::runtime_error("input array is not row-major (like the target type)");
if (!PyArray_CHKFLAGS(ary.handle().get(), NPY_C_CONTIGUOUS))
throw std::runtime_error("ndarray->matrix converteee is not C-contiguous");
}
else if (PyArray_STRIDE(ary.handle().get(), 0) == PyArray_ITEMSIZE(ary.handle().get())) {
// column-major
if (is_row_major(OCat()))
throw std::runtime_error("input array is not column-major (like the target type)");
if (!PyArray_CHKFLAGS(ary.handle().get(), NPY_F_CONTIGUOUS))
throw std::runtime_error("ndarray->matrix converteee is not F-contiguous");
}
else
throw std::runtime_error("input array is does not have dimension with stride==1");
return PyArray_DIM(ary.handle().get(), 0);
}
template <class T>
typename numpy_array<T>::size_type get_array_size2(numpy_array<T> const &ary) {
// checking is done in size1()
return PyArray_DIM(ary.handle().get(), 1);
}
}}}
#endif // __NUMPY_ARRAY_UBLAS_HPP__
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
#include<time.h>
clock_t cstart, cend;
double cpu_time_used;
using namespace std;
struct AvlNode
{
AvlNode* left;
AvlNode* right;
int data;
int height;
int count;
};
void trav_inorder(AvlNode *tree);
AvlNode* GetNewNode(int);
AvlNode* Insert(AvlNode*,int);
AvlNode* Delete(AvlNode*,int);
int inorder(AvlNode*,int);
int height(AvlNode*);
int Count(AvlNode*);
AvlNode* rotateright(AvlNode*);
AvlNode* rotateleft(AvlNode*);
AvlNode* LR(AvlNode*);
AvlNode* RL(AvlNode*);
int BalanceFactor(AvlNode* );
bool Search(AvlNode*,int);
int main(int argc, char * argv[])
{
//ios_base::sync_with_stdio(false);
//cin.tie(NULL);
AvlNode* root = NULL;
int n,m;
//cin>>n;
// cin>>m;
int k,res,l;
ifstream inFile,outFile,Files;
int x;
string s;
cout<<"Enter Filename:-\n";
cin>>s;
inFile.open(s);
int numberofvalue;
cout<<"\nEnter number of values to insert or search or delete from file:-\n";
cin>>numberofvalue;
int mm=0;
cstart = clock();
while (inFile >> x) {
if(mm==numberofvalue)
{
break;
}
// cout<<x;
root=Insert(root,x);
mm=mm+1;
}
cstart = clock()-cstart;
double time_taken = ((double)cstart)/CLOCKS_PER_SEC;
printf("My function took %f seconds to insert! \n", time_taken);
int ss=0;
Files.open(s);
cstart = clock();
while (Files >> x)
{
if(ss==numberofvalue)
{
break;
}
// np = create_node(x);
Search(root, x);
//cout<<"element deleted"<<i;
ss=ss+1;
// i++;
// cout<<y;
}
cstart = clock()-cstart;
time_taken = ((double)cstart)/CLOCKS_PER_SEC;
printf("My function took %f seconds to search! \n", time_taken);
mm=0;
outFile.open(s);
cstart = clock();
while (outFile >> x)
{
if(mm==numberofvalue)
{
break;
}
// np = create_node(x);
Delete(root, x);
//cout<<"element deleted"<<i;
mm=mm+1;
// i++;
}
cstart = clock()-cstart;
time_taken = ((double)cstart)/CLOCKS_PER_SEC;
printf("My function took %f seconds to delete! \n", time_taken);
// while(n--)
// {
// cin>>k;
// root=Insert(root,k);
// }
while(m--)
{
int q,a;
cout<<"\nPress 1 space number to insert \nPress 2 space number to search \nPress 3 space number to delete: ";
cin>>q>>a;
switch(q)
{
case 1:
root=Insert(root,a);
break;
case 2:
if(Search(root,a)==true)
cout<<"1"<<endl;
else
cout<<"0"<<endl;
break;
case 3:
l=inorder(root,1);
cout<<l<<endl;
root=Delete(root,l);
break;
default:
break;
}
}
// trav_inorder(root);
return 0;
}
int height(AvlNode* T)
{
int lheight,rheight;
if(T==NULL)
return 0;
if(T->left==NULL)
lheight=0;
else
lheight=1+T->left->height;
if(T->right==NULL)
rheight=0;
else
rheight=1+T->right->height;
if(lheight>rheight)
return lheight;
else
return rheight;
}
int Count(AvlNode* T)
{
if(T==NULL)
return 0;
else if(T->left==NULL && T->right==NULL)
T->count=1;
else if(T->left==NULL)
T->count=1+T->right->count;
else if(T->right==NULL)
T->count=1+T->left->count;
else
T->count=1+T->left->count+T->right->count;
return T->count;
}
int BalanceFactor(AvlNode* T)
{
int lheight,rheight;
if(T==NULL)
return 0;
if(T->left==NULL)
lheight=0;
else
lheight=1+T->left->height;
if(T->right==NULL)
rheight=0;
else
rheight=1+T->right->height;
return lheight-rheight;
}
AvlNode* rotateleft(AvlNode *x)
{
AvlNode *y;
y=x->right;
x->right=y->left;
y->left=x;
x->height=height(x);
x->count=Count(x);
y->height=height(y);
y->count=Count(y);
return y;
}
AvlNode* rotateright(AvlNode *x)
{
AvlNode *y;
y=x->left;
x->left=y->right;
y->right=x;
x->height=height(x);
x->count=Count(x);
y->height=height(y);
y->count=Count(y);
return y;
}
AvlNode* LR(AvlNode* T)
{
T->left=rotateleft(T->left);
T=rotateright(T);
return T;
}
AvlNode* RL(AvlNode* T)
{
T->right=rotateright(T->right);
T=rotateleft(T);
return T;
}
AvlNode* GetNewNode(int data)
{
AvlNode* newNode = new AvlNode();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// To insert data in BST, returns address of root node
AvlNode* Insert(AvlNode* root,int data)
{
if(root == NULL)
{ // empty tree
root = GetNewNode(data);
}
else if(data > root->data) // insert in right subtree
{
root->right=Insert(root->right,data);
if(BalanceFactor(root)==-2)
{
if(data >root->right->data)
root=rotateleft(root);
else
root=RL(root);
}
}
else if(data<root->data)
{
root->left=Insert(root->left,data);
if(BalanceFactor(root)==2)
{
if(data < root->left->data)
root=rotateright(root);
else
root=LR(root);
}
}
root->height=height(root);
root->count=Count(root);
return root;
}
AvlNode * Delete(AvlNode *root,int x)
{
AvlNode *p;
if(root==NULL)
{
return NULL;
}
else if(x > root->data) // insert in right subtree
{
root->right=Delete(root->right,x);
if(BalanceFactor(root)==2)
{
if(BalanceFactor(root->left)>=0)
root=rotateright(root);
else
root=LR(root);
}
}
else if(x<root->data)
{
root->left=Delete(root->left,x);
if(BalanceFactor(root)==-2) //Rebalancing
{
if(BalanceFactor(root->right)<=0)
root=rotateleft(root);
else
root=RL(root);
}
}
else
{
if(root->right!=NULL) //data to be deleted is found
{
p=root->right; //delete its inorder succesor
while(p->left!= NULL)
p=p->left;
root->data=p->data;
root->right=Delete(root->right,root->data);
if(BalanceFactor(root)==2) //Rebalancing
{
if(BalanceFactor(root->left)>=0)
root=rotateright(root);
else
root=LR(root);
}
}
else
return(root->left);
}
root->height=height(root);
root->count=Count(root);
return root;
}
int inorder(AvlNode* root,int k)
{
AvlNode* current = root;
if(root==NULL)
{
return 1;
}
if(k==Count(current->left)+1)
{
return current->data;
}
else if(k>Count(current->left))
{
k=k-Count(current->left)-1;
return inorder(current->right,k);
}
else
{
return inorder(current->left,k);
}
}
void trav_inorder(AvlNode *tree)
{
if (tree == NULL)
return;
trav_inorder (tree->left);
cout<<tree->data<<" ";
trav_inorder (tree->right);
}
bool Search(AvlNode* root,int data)
{
if(root == NULL)
{
return false;
}
else if(root->data == data)
{
return true;
}
else if(data <= root->data)
{
return Search(root->left,data);
}
else
{
return Search(root->right,data);
}
}
|
#include "api_v1_String.h"
using namespace api::v1;
using namespace std;
//add definition of your processing function here
void String::split_string(
const HttpRequestPtr& req,
function<void (const HttpResponsePtr &)> &&callback,
string str,
string delimiter
) const {
size_t last = 0;
size_t next = 0;
Json::Value result_arr;
while ((next = str.find(delimiter, last)) != string::npos) {
result_arr.append(str.substr(last, next - last));
last = next + delimiter.length();
}
result_arr.append(str.substr(last));
Json::Value ret;
ret["split_string"] = result_arr;
auto resp = HttpResponse::newHttpJsonResponse(ret);
callback(resp);
}
|
/*
* Copyright 2016-2017 Flatiron Institute, Simons Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PRVFILEDOWNLOAD_H
#define PRVFILEDOWNLOAD_H
#include <QMutex>
#include <QString>
#include <QThread>
#include <QTime>
namespace PrvFileDownload {
class Downloader : public QThread {
public:
//input
QString source_url;
QString destination_file_name;
int size = 0; //optional, if known
//output
bool success = false;
QString error;
void run();
double elapsed_msec();
int num_bytes_downloaded();
private:
QMutex m_mutex;
int m_num_bytes_downloaded = 0;
QTime m_timer;
};
class PrvParallelDownloader : public QThread {
public:
//input
QString source_url; //must be prv protocol
QString destination_file_name;
int size = 0; //mandatory
int num_threads = 10;
//output
bool success = false;
QString error;
void run();
double elapsed_msec();
int num_bytes_downloaded();
private:
QMutex m_mutex;
QTime m_timer;
int m_num_bytes_downloaded = 0;
};
}
#endif // PRVFILEDOWNLOAD_H
|
/***************************************************************************
* Filename : ImGuiBuild.cpp
* Name : Ori Lazar
* Date : 29/10/2019
* Description : Build version file includes and defines for imgui layer to function
with the multi-window branch.
.---.
.'_:___".
|__ --==|
[ ] :[|
|__| I=[|
/ / ____|
|-/.____.'
/___\ /___\
***************************************************************************/
#include "expch.h"
#define IMGUI_IMPL_OPENGL_LOADER_GLAD
#include <examples/imgui_impl_opengl3.cpp>
#include <examples/imgui_impl_glfw.cpp>
|
/*
* Copyright (c) 2006-2016 RDA Microelectronics, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(AFX_SCREENDLG_H__04374C66_0C7E_4820_8A59_2598D4776A21__INCLUDED_)
#define AFX_SCREENDLG_H__04374C66_0C7E_4820_8A59_2598D4776A21__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// ScreenDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CScreenDlg dialog
class CScreenDlg : public CDialog
{
// Construction
public:
void RedrawScreen();
CScreenDlg(CWnd* pParent = NULL); // standard constructor
BOOL m_needRedraw;
float m_zoom;
// Dialog Data
//{{AFX_DATA(CScreenDlg)
enum { IDD = IDD_DIALOG_SCREEN };
CStatic m_screen;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CScreenDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CScreenDlg)
afx_msg void OnPaint();
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnSize(UINT nType, int cx, int cy);
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SCREENDLG_H__04374C66_0C7E_4820_8A59_2598D4776A21__INCLUDED_)
|
#ifndef WORKER_H
#define WORKER_H
#include "employee.h"
#include <qfile.h>
#include <qtextstream.h>
#include <qlist.h>
/**
* @brief Класс Рабочий
*/
class Worker : public Employee
{
public:
/**
* @brief Конструктор класса Worker
* @param fio фамилия и инициалы рабочего
* @param uniqueNumber идентификатор рабочего
* @param login логин рабочего
* @param password пароль рабочего
* @param department отдел, в котором работает рабочий
*/
Worker(QString fio, size_t uniqueNumber,
QString login, QString password, QString department);
~Worker();
/**
* @brief Возвращает название задачи
* @return Название задачи
*/
QString getTaskName();
/**
* @brief Читает из файла tasks.txt
*/
void readTasks();
/**
* @brief Сохраняет отчёт о работнике в текстовый файл
*/
void saveTasks();
/**
* @brief Изменение состояния задач в выполнено
* @param Название задачи
*/
void taskDone(const QString& _task); // 2
private:
//! Список задач по отделам и общий список задач
QList<taskie> tasksDep, tasksAll;
};
#endif // WORKER_H
|
#include<bits/stdc++.h>
using namespace std;
char str[100005];
int main() {
gets(str);
int len = strlen(str);
for(int i = len - 1; i >= 0; i--) {
if(str[i] == ' ') {
for(int j = i + 1; j < len && str[j] != ' '; j++)
cout << str[j];
cout << ' ';
} else if(i == 0) {
for(int j = i; j < len && str[j] != ' '; j++)
cout << str[j];
}
}
return 0;
}
|
#include "mgtools_Motion.hpp"
#include <tuple>
#include <numeric>
#include <fstream>
#include <iostream>
#include "cpptools_Files.hpp"
#include "cpptools_Logger.hpp"
#include "cpptools_Strings.hpp"
#include "cpptools_Timer.hpp"
#include "gltools_Loader.hpp"
#include "Settings.hpp"
namespace imog {
// * Helpers
// Determine the folder for plots and create if not exists
std::string Motion::plotFolder() {
std::string _folder = Settings::plotDir;
if (!Files::pathExists(_folder)) {
#if _WIN64
auto winPath = Files::pathToWin(_folder);
auto winCmd = std::string("mkdir " + winPath + " >nul 2>&1");
system(winCmd.c_str());
#else
auto nixCmd = std::string("mkdir -p " + _folder);
system(nixCmd.c_str());
#endif
}
if (!Files::pathExists(_folder)) {
_folder = "";
LOGE("Couldn't use gived path to store plot data.");
}
return _folder;
}
// * Frame methods
// ====================================================================== //
// ====================================================================== //
// Sum rotations of frame
// ====================================================================== //
glm::vec3 Frame::value() const {
glm::vec3 RT = this->translation * glm::vec3{0.f, 2.f, 0.f};
glm::vec3 RR = this->rotations.at(0) * glm::vec3{1.f, 0.f, 1.f};
glm::vec3 JR{0.f};
for (const auto& rot : this->rotations) JR += rot;
return RT + RR + (JR - this->rotations.at(0));
}
// ====================================================================== //
// ====================================================================== //
// Lerp frame A to frame B at alpha point
// ====================================================================== //
Frame Frame::lerpOne(const Frame& f2, float alpha, bool alsoLerpRoot) const {
Frame f;
f.translation = glm::mix(this->translation, f2.translation, alpha);
try {
auto rootFront = Math::rotToVec(this->rotations[0]);
auto rootY = glm::degrees(
glm::orientedAngle(Math::unitVecZ, rootFront, Math::unitVecY));
for (auto i = 0u; i < this->rotations.size(); ++i) {
if (!alsoLerpRoot && i == 0u) {
f.rotations.push_back(this->rotations[i]);
continue;
}
auto newRot = glm::mix(this->rotations[i], f2.rotations[i], alpha);
if (i == 0u) { newRot = rootY * Math::unitVecY; }
f.rotations.push_back(newRot);
}
} catch (std::exception&) {
LOGE("F1 and F2 doesn't have the same number of Joints?")
}
return f;
}
// ====================================================================== //
// ====================================================================== //
// Lerp from frame A to frame B
// ====================================================================== //
std::vector<Frame> Frame::lerpTransition(const Frame& f2,
uint steps,
bool alsoLerpRoot) const {
std::vector<Frame> lerpFrames;
if (steps < 1u) return lerpFrames;
float alphaStep = 1.0f / glm::clamp((float)steps, 2.f, 100.f);
for (auto alpha = 0.1f; alpha <= 1.0f; alpha += alphaStep) {
auto frame = this->lerpOne(f2, alpha, alsoLerpRoot);
lerpFrames.push_back(frame);
}
return lerpFrames;
}
// * Motion methods
// ====================================================================== //
// ====================================================================== //
// 'Constructor'
// ====================================================================== //
std::shared_ptr<Motion> Motion::create(const std::string& name,
const std::string& filepath,
loopMode lm,
uint steps,
bool alsoLerpRoot) {
auto m = loader::BVH(filepath);
Timer timer("Preprocessing \"" + name + "\"");
m->name = name;
m->m_maxStep = 0u;
// === SETUP DATA ===
float minTX, minTY, minTZ;
minTX = minTY = minTZ = std::numeric_limits<float>::max();
// === Iter 1 : Get data and Set undependent ===
for (auto i = 1u; i < m->frames.size(); ++i) {
auto ft = m->frames.at(i).translation;
// Get Max distance
if (i < m->frames.size() - 2u) {
auto step = glm::distance(m->frames.at(i + 1u).translation, ft);
if (step > m->m_maxStep) m->m_maxStep = step;
}
// Get mins positions
if (ft.x < minTX) minTX = ft.x;
if (ft.y < minTY) minTY = ft.y;
if (ft.z < minTZ) minTZ = ft.z;
}
// === Iter 2 : Set dependent data ===
for (auto i = 1u; i < m->frames.size(); ++i) {
// T back to 0
m->frames.at(i).translation.x -= minTX;
m->frames.at(i).translation.y -= minTY;
m->frames.at(i).translation.z -= minTZ;
}
// === CLEAN ===
// === Remove T-Pose ===
m->frames.erase(m->frames.begin());
if (lm == loopMode::none) return m;
// === Get low errror frames of animation to generate a loop ===
if (lm == loopMode::shortLoop) {
uint B, E;
uint nFrames = m->frames.size();
uint limitA = nFrames / 2.f;
uint limitB = nFrames - limitA;
float auxDiff = std::numeric_limits<float>::max();
for (auto f1 = 0u; f1 < limitA; ++f1) {
auto f1Val = m->frames.at(f1).value();
for (auto f2 = limitB; f2 < nFrames; ++f2) {
auto f2Val = m->frames.at(f2).value();
auto diff = glm::compAdd(glm::abs(f1Val - f2Val));
if (diff < auxDiff) { std::tie(auxDiff, B, E) = {diff, f1, f2}; }
}
}
// Clean based on obtained frames
std::vector<Frame> auxFrames;
auxFrames.reserve(E);
for (auto f = B; f < E; ++f) { auxFrames.push_back(m->frames.at(f)); }
m->frames = auxFrames; // Store
}
// === Lerp: gen loop ===
auto first = m->frames.front();
auto last = m->frames.back();
for (const auto& nF : last.lerpTransition(first, steps, alsoLerpRoot)) {
m->frames.push_back(nF);
}
// === Force look forward ===
for (auto i = 0u; i < m->frames.size(); ++i) {
// Get Y
Transform t1;
t1.rot = m->frames.at(i).rotations.at(0);
auto flipX = [&]() {
bool isNegX = t1.front().x < 0.f;
bool shouldBeFixed = (lm == loopMode::loopAndLockX);
return (isNegX && shouldBeFixed) ? -1.f : 1.f;
}();
auto newY = Math::unitVecY * flipX;
newY *= glm::orientedAngle(t1.front(), Math::unitVecZ, Math::unitVecY);
newY = glm::degrees(newY);
// Rot to look forward
Transform t2;
t2.rot = newY;
float x, y, z;
glm::extractEulerAngleXYZ(t2.asMatrix() * t1.asMatrix(), x, y, z);
// Store
m->frames.at(i).rotations.at(0) = glm::degrees(glm::vec3{x, y, z});
}
return m;
}
// ====================================================================== //
// ====================================================================== //
// Mix any motion with other and get a new animation
// that conect both smoothly
// ====================================================================== //
Motion::mixMap Motion::mix(const std::shared_ptr<Motion>& m2) {
// @lambda for transitions creation
auto createTransitionMotion = [&](uint idxF1, uint idxF2) {
auto mo = std::make_shared<Motion>();
mo->joints = this->joints;
mo->timeStep = (this->timeStep + m2->timeStep) * 0.5f;
auto f1 = this->frames.at(idxF1);
auto f2 = m2->frames.at(idxF2);
for (const auto& nF : f1.lerpTransition(f2, 10u)) {
mo->frames.push_back(nF);
}
return mo;
};
//---
// for heat map visualization
auto _prefix = plotFolder() + this->name + "_" + m2->name;
std::ofstream heatmap(_prefix + ".hm");
std::ofstream refFrames(_prefix + ".ref");
//---
mixMap mm;
{
uint auxF2 = 0;
float auxDiff = std::numeric_limits<float>::infinity();
for (auto f1 = 0u; f1 < this->frames.size(); f1++) {
auxF2 = 0;
auxDiff = std::numeric_limits<float>::infinity();
auto f1Value = this->frames.at(f1).value();
for (auto f2 = 0u; f2 < m2->frames.size(); f2++) {
auto f2Value = m2->frames.at(f2).value();
float diff = glm::compAdd(glm::abs(f1Value - f2Value));
if (diff < auxDiff) { std::tie(auxDiff, auxF2) = {diff, f2}; }
// Write to heatmap
(f2 < m2->frames.size() - 1) ? heatmap << diff << " "
: heatmap << diff << "\n";
}
// Write to ref frames. For mark winner frames on heatmap
refFrames << f1 << " " << auxF2 << "\n";
// Insert winner frames and its transition on the map
auto tMo = createTransitionMotion(f1, auxF2);
mm.insert({f1, {auxF2, tMo}});
}
}
return mm;
}
// ====================================================================== //
// ====================================================================== //
// Minor methods
// ====================================================================== //
float Motion::maxStep() const { return m_maxStep; }
bool Motion::isMix() { return Strings::contains(this->name, "_"); }
Frame Motion::linkedFrame(uint frameIdx, float alpha) const {
Frame f;
if (!this->linked) return f;
auto factor = (float)linked->frames.size() / (float)frames.size();
// Get errors with 'ceilf' (get out-of-range values). Using 'floorf' instead.
auto cf = floorf(frameIdx * factor);
return frames.at(cf).lerpOne(linked->frames.at(cf), alpha);
}
} // namespace imog
|
#include <iostream>
#include<time.h>
using namespace std;
int prime(int n)
{
if (n <= 1)
return 0;
else if (n <= 3)
return 1;
else if (n % 2 == 0 || n % 3 == 0)
return 0;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return 0;
return 1;
}
int main()
{
clock_t start,end;
double cpu_time_used;
int n;
cout<<"Enter a number to check-"<<endl;
cin>>n;
start=clock();
if(prime(n)==1)
{
cout<<"Yes "<<n<<" is a prime number"<<endl;
}
else
cout<<"No "<<n<<" is not a prime number"<<endl;
end=clock();
cpu_time_used=((double)(end-start))/CLOCKS_PER_SEC;
cout<<"Time complexity of the algorithm :- "<<cpu_time_used<<endl;
return 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Graphics::Printing3D {
struct Printing3DBufferDescription;
}
namespace Windows::Graphics::Printing3D {
using Printing3DBufferDescription = ABI::Windows::Graphics::Printing3D::Printing3DBufferDescription;
}
namespace ABI::Windows::Graphics::Printing3D {
struct IPrint3DManager;
struct IPrint3DManagerStatics;
struct IPrint3DTask;
struct IPrint3DTaskCompletedEventArgs;
struct IPrint3DTaskRequest;
struct IPrint3DTaskRequestedEventArgs;
struct IPrint3DTaskSourceChangedEventArgs;
struct IPrint3DTaskSourceRequestedArgs;
struct IPrinting3D3MFPackage;
struct IPrinting3D3MFPackageStatics;
struct IPrinting3DBaseMaterial;
struct IPrinting3DBaseMaterialGroup;
struct IPrinting3DBaseMaterialGroupFactory;
struct IPrinting3DBaseMaterialStatics;
struct IPrinting3DColorMaterial;
struct IPrinting3DColorMaterial2;
struct IPrinting3DColorMaterialGroup;
struct IPrinting3DColorMaterialGroupFactory;
struct IPrinting3DComponent;
struct IPrinting3DComponentWithMatrix;
struct IPrinting3DCompositeMaterial;
struct IPrinting3DCompositeMaterialGroup;
struct IPrinting3DCompositeMaterialGroup2;
struct IPrinting3DCompositeMaterialGroupFactory;
struct IPrinting3DFaceReductionOptions;
struct IPrinting3DMaterial;
struct IPrinting3DMesh;
struct IPrinting3DMeshVerificationResult;
struct IPrinting3DModel;
struct IPrinting3DModel2;
struct IPrinting3DModelTexture;
struct IPrinting3DMultiplePropertyMaterial;
struct IPrinting3DMultiplePropertyMaterialGroup;
struct IPrinting3DMultiplePropertyMaterialGroupFactory;
struct IPrinting3DTexture2CoordMaterial;
struct IPrinting3DTexture2CoordMaterialGroup;
struct IPrinting3DTexture2CoordMaterialGroup2;
struct IPrinting3DTexture2CoordMaterialGroupFactory;
struct IPrinting3DTextureResource;
struct Print3DTaskSourceRequestedHandler;
struct Print3DManager;
struct Print3DTask;
struct Print3DTaskCompletedEventArgs;
struct Print3DTaskRequest;
struct Print3DTaskRequestedEventArgs;
struct Print3DTaskSourceChangedEventArgs;
struct Print3DTaskSourceRequestedArgs;
struct Printing3D3MFPackage;
struct Printing3DBaseMaterial;
struct Printing3DBaseMaterialGroup;
struct Printing3DColorMaterial;
struct Printing3DColorMaterialGroup;
struct Printing3DComponent;
struct Printing3DComponentWithMatrix;
struct Printing3DCompositeMaterial;
struct Printing3DCompositeMaterialGroup;
struct Printing3DFaceReductionOptions;
struct Printing3DMaterial;
struct Printing3DMesh;
struct Printing3DMeshVerificationResult;
struct Printing3DModel;
struct Printing3DModelTexture;
struct Printing3DMultiplePropertyMaterial;
struct Printing3DMultiplePropertyMaterialGroup;
struct Printing3DTexture2CoordMaterial;
struct Printing3DTexture2CoordMaterialGroup;
struct Printing3DTextureResource;
}
namespace Windows::Graphics::Printing3D {
struct Print3DTaskSourceRequestedHandler;
struct IPrint3DManager;
struct IPrint3DManagerStatics;
struct IPrint3DTask;
struct IPrint3DTaskCompletedEventArgs;
struct IPrint3DTaskRequest;
struct IPrint3DTaskRequestedEventArgs;
struct IPrint3DTaskSourceChangedEventArgs;
struct IPrint3DTaskSourceRequestedArgs;
struct IPrinting3D3MFPackage;
struct IPrinting3D3MFPackageStatics;
struct IPrinting3DBaseMaterial;
struct IPrinting3DBaseMaterialGroup;
struct IPrinting3DBaseMaterialGroupFactory;
struct IPrinting3DBaseMaterialStatics;
struct IPrinting3DColorMaterial;
struct IPrinting3DColorMaterial2;
struct IPrinting3DColorMaterialGroup;
struct IPrinting3DColorMaterialGroupFactory;
struct IPrinting3DComponent;
struct IPrinting3DComponentWithMatrix;
struct IPrinting3DCompositeMaterial;
struct IPrinting3DCompositeMaterialGroup;
struct IPrinting3DCompositeMaterialGroup2;
struct IPrinting3DCompositeMaterialGroupFactory;
struct IPrinting3DFaceReductionOptions;
struct IPrinting3DMaterial;
struct IPrinting3DMesh;
struct IPrinting3DMeshVerificationResult;
struct IPrinting3DModel;
struct IPrinting3DModel2;
struct IPrinting3DModelTexture;
struct IPrinting3DMultiplePropertyMaterial;
struct IPrinting3DMultiplePropertyMaterialGroup;
struct IPrinting3DMultiplePropertyMaterialGroupFactory;
struct IPrinting3DTexture2CoordMaterial;
struct IPrinting3DTexture2CoordMaterialGroup;
struct IPrinting3DTexture2CoordMaterialGroup2;
struct IPrinting3DTexture2CoordMaterialGroupFactory;
struct IPrinting3DTextureResource;
struct Print3DManager;
struct Print3DTask;
struct Print3DTaskCompletedEventArgs;
struct Print3DTaskRequest;
struct Print3DTaskRequestedEventArgs;
struct Print3DTaskSourceChangedEventArgs;
struct Print3DTaskSourceRequestedArgs;
struct Printing3D3MFPackage;
struct Printing3DBaseMaterial;
struct Printing3DBaseMaterialGroup;
struct Printing3DColorMaterial;
struct Printing3DColorMaterialGroup;
struct Printing3DComponent;
struct Printing3DComponentWithMatrix;
struct Printing3DCompositeMaterial;
struct Printing3DCompositeMaterialGroup;
struct Printing3DFaceReductionOptions;
struct Printing3DMaterial;
struct Printing3DMesh;
struct Printing3DMeshVerificationResult;
struct Printing3DModel;
struct Printing3DModelTexture;
struct Printing3DMultiplePropertyMaterial;
struct Printing3DMultiplePropertyMaterialGroup;
struct Printing3DTexture2CoordMaterial;
struct Printing3DTexture2CoordMaterialGroup;
struct Printing3DTextureResource;
}
namespace Windows::Graphics::Printing3D {
template <typename T> struct impl_IPrint3DManager;
template <typename T> struct impl_IPrint3DManagerStatics;
template <typename T> struct impl_IPrint3DTask;
template <typename T> struct impl_IPrint3DTaskCompletedEventArgs;
template <typename T> struct impl_IPrint3DTaskRequest;
template <typename T> struct impl_IPrint3DTaskRequestedEventArgs;
template <typename T> struct impl_IPrint3DTaskSourceChangedEventArgs;
template <typename T> struct impl_IPrint3DTaskSourceRequestedArgs;
template <typename T> struct impl_IPrinting3D3MFPackage;
template <typename T> struct impl_IPrinting3D3MFPackageStatics;
template <typename T> struct impl_IPrinting3DBaseMaterial;
template <typename T> struct impl_IPrinting3DBaseMaterialGroup;
template <typename T> struct impl_IPrinting3DBaseMaterialGroupFactory;
template <typename T> struct impl_IPrinting3DBaseMaterialStatics;
template <typename T> struct impl_IPrinting3DColorMaterial;
template <typename T> struct impl_IPrinting3DColorMaterial2;
template <typename T> struct impl_IPrinting3DColorMaterialGroup;
template <typename T> struct impl_IPrinting3DColorMaterialGroupFactory;
template <typename T> struct impl_IPrinting3DComponent;
template <typename T> struct impl_IPrinting3DComponentWithMatrix;
template <typename T> struct impl_IPrinting3DCompositeMaterial;
template <typename T> struct impl_IPrinting3DCompositeMaterialGroup;
template <typename T> struct impl_IPrinting3DCompositeMaterialGroup2;
template <typename T> struct impl_IPrinting3DCompositeMaterialGroupFactory;
template <typename T> struct impl_IPrinting3DFaceReductionOptions;
template <typename T> struct impl_IPrinting3DMaterial;
template <typename T> struct impl_IPrinting3DMesh;
template <typename T> struct impl_IPrinting3DMeshVerificationResult;
template <typename T> struct impl_IPrinting3DModel;
template <typename T> struct impl_IPrinting3DModel2;
template <typename T> struct impl_IPrinting3DModelTexture;
template <typename T> struct impl_IPrinting3DMultiplePropertyMaterial;
template <typename T> struct impl_IPrinting3DMultiplePropertyMaterialGroup;
template <typename T> struct impl_IPrinting3DMultiplePropertyMaterialGroupFactory;
template <typename T> struct impl_IPrinting3DTexture2CoordMaterial;
template <typename T> struct impl_IPrinting3DTexture2CoordMaterialGroup;
template <typename T> struct impl_IPrinting3DTexture2CoordMaterialGroup2;
template <typename T> struct impl_IPrinting3DTexture2CoordMaterialGroupFactory;
template <typename T> struct impl_IPrinting3DTextureResource;
template <typename T> struct impl_Print3DTaskSourceRequestedHandler;
}
namespace Windows::Graphics::Printing3D {
enum class Print3DTaskCompletion
{
Abandoned = 0,
Canceled = 1,
Failed = 2,
Slicing = 3,
Submitted = 4,
};
enum class Print3DTaskDetail
{
Unknown = 0,
ModelExceedsPrintBed = 1,
UploadFailed = 2,
InvalidMaterialSelection = 3,
InvalidModel = 4,
ModelNotManifold = 5,
InvalidPrintTicket = 6,
};
enum class Printing3DBufferFormat
{
Unknown = 0,
R32G32B32A32Float = 2,
R32G32B32A32UInt = 3,
R32G32B32Float = 6,
R32G32B32UInt = 7,
Printing3DDouble = 500,
Printing3DUInt = 501,
};
enum class Printing3DMeshVerificationMode
{
FindFirstError = 0,
FindAllErrors = 1,
};
enum class Printing3DModelUnit
{
Meter = 0,
Micron = 1,
Millimeter = 2,
Centimeter = 3,
Inch = 4,
Foot = 5,
};
enum class Printing3DObjectType
{
Model = 0,
Support = 1,
Others = 2,
};
enum class Printing3DTextureEdgeBehavior
{
None = 0,
Wrap = 1,
Mirror = 2,
Clamp = 3,
};
}
}
|
#ifndef CONTINUITYMANAGER_H
#define CONTINUITYMANAGER_H
#include "enumController.h"
#include "Blogpost.h"
struct Date{unsigned short int day;
monthsEnum month;
unsigned short int year;};
struct DailyArticleGroup{articles art1;
articles art2;
articles art3;};
/*At least try to keep this one in a consistent coding style, yeah? */
class ContinuityManager
{
public:
ContinuityManager();
ContinuityManager(GameWindow* winPointer);
void Update();
void Post(Blogpost& post);
void ProgressToNextDay();
//ACCESORS
unsigned short int getNotoriety();
unsigned short int getNDay();
unsigned int getFollowers();
unsigned int getViews();
unsigned getBlogListSize();
Date getDate();
Blogpost* getBlogPostP(int i = 0);
DailyArticleGroup getArtGroup();
//MUTATORS
void changeNotoriety(unsigned short int a = 0);
void changeFollowers(unsigned int a = 0);
private:
//GAME WINDOW POINTER
GameWindow* gameWindowP = 0;
void render();
void addViews();
void generateArticles();
void saveGameState();
void generateArticleGroup();
bool checkNotoriety();
std::vector<Blogpost> vBlogList;
Date Date= {14,MAY,2024}; //DEFAULT VALUES ARE FOR DAY 1
DailyArticleGroup ArtGroup= {a_facebookAvatar,a_norBorders,a_ukEmbargo}; //DEFAULT VALUES ARE FOR DAY 1
unsigned int nFollowers = 1000;
unsigned short int nNotoriety = 0;
unsigned short int nDay = 1;
unsigned short int nThresholdsReached = 0;
const unsigned NOTORIETY_THRESHOLD_HATE_LEVEL_1 = 100;
const unsigned NOTORIETY_THRESHOLD_HATE_LEVEL_2 = 200;
const unsigned NOTORIETY_THRESHOLD_POLICE_EMAIL_1 = 500;
const unsigned NOTORIETY_THRESHOLD_POLICE_EMAIL_2 = 1000; //FINAL WARNING BEFORE BEING ARRESTED
const unsigned NOTORIETY_THRESHOLD_ARREST = 2000;
const unsigned NOTORIETY_THRESHOLD_DAY_X = 1500;
};
#endif // CONTINUITYMANAGER_H
|
/****************************************************************************
**
** Copyright (C) 2009 Du Hui.
**
****************************************************************************/
#ifndef COMCONFIGDIALOG_H
#define COMCONFIGDIALOG_H
#include <QtGui/QDialog>
#include "qserialcomm.h"
namespace Ui {
class comConfigDialog;
}
class comConfigDialog : public QDialog {
Q_OBJECT
public:
comConfigDialog( const QString & commPort, QWidget *parent = 0);
~comConfigDialog();
void accept();
void reject();
const PORTPROPERTY & property()
{
return m_CommProperty;
}
private slots:
void setBaudRate(QString value);
void setDataBits(int value);
void setParity(int value);
void setStopBits(int value);
void setFlowControl(int value);
protected:
void changeEvent(QEvent *e);
private:
Ui::comConfigDialog *m_ui;
QString m_CommPort;
PORTPROPERTY m_CommProperty;
};
#endif // COMCONFIGDIALOG_H
|
#ifndef KLASA_LISTAPRZEDMIOTOW_HPP
#define KLASA_LISTAPRZEDMIOTOW_HPP
/*Plik Klasa_ListaPrzedmiotow.h zawiera:
- deklaracja klasy ListaPrzedmiotow*/
//Import plikow naglowkowych
//Import bibliotek
//#include <iostream>
//#include <string>
//#include <vector>
//#include <fstream>
//using std::cout;
//using std::cin;
//#include "Jadro_programu.hpp"
//extern class Przedmiot;
//extern class ListaZamowien;
class ListaPrzedmiotow {
/* Klasa odpowiadajaca za obsluge bazy danych dostepnych przedmiotow */
public: static std::vector<Przedmiot> Lista; //Kolekcja pelniaca role bazy danych przedmiotow
protected: std::fstream Plik_Lista; //Obiekt obslugujacy plik z baza danych przedmiotow
protected: std::string Plik_Lista_Nazwa = "Lista_Przedmiotow.bin"; //Lancuch przechowujacy nazwe pliku z baza danych przedmiotow
//////////////////////////////////////////////////////////////////////////////////////////
/*KONSTRUKTOR*/
public: ListaPrzedmiotow();
public: void menu();
protected: void wczytajdane();
protected: void zapiszzmiany();
public: static void wyswietlliste();
protected: std::vector<Przedmiot>::iterator znajdz(int id_przedmiotu);
protected: void dodajprzedmiot();
protected: void usunprzedmiot();
//
//FUNKCJE POMOCNICZE (NIE WIADOMO CZY BEDA UZYTE)
//
public: static std::string getNazwaPrzedmiotu(int indeks);
public: static std::string getPoziomPrzedmiotu(int indeks);
public: static int getCenaPrzedmiotu(int indeks);
public: static bool czyistniejrekord(int indeks);
};
#endif
|
#include "kmp.h"
KMP::KMP(std::string haystack_, std::string needle_){
needle = needle_;
haystack = haystack_;
}
std::vector<size_t> KMP::knuthMorrisPrattTable(){
std::vector<size_t> initTable(needle.size() + 1, -1);
for(size_t index = 1; index <= needle.size(); index++){
size_t position = initTable[index - 1];
while(position != -1 && needle[position] != needle[index - 1]){
position = initTable[position];
}
initTable[index] = position + 1;
}
return initTable;
}
std::vector<size_t> KMP::search(){
std::vector<size_t> matches;
std::vector<size_t> table;
table = knuthMorrisPrattTable();
size_t haystackIndex = 0;
size_t needleIndex = 0;
size_t haystackSize = haystack.size();
size_t needleSize = needle.size();
while(haystackIndex < haystackSize){
while(needleIndex != -1 && (needleIndex == needleSize || needle[needleIndex] != haystack[haystackIndex])){
needleIndex = table[needleIndex];
}
needleIndex++;
haystackIndex++;
if(needleIndex == needleSize){
matches.push_back(haystackIndex - needleSize);
}
}
return matches;
}
|
#include <Arduino.h>
//DS18B20 probe libraries
#include <OneWire.h>
#include <DallasTemperature.h>
//TFT screen libraries
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <XPT2046_Touchscreen.h>
#include <WiFi.h>
//Webserver libraries
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
float targetMashTemp;
float currentMashTemp;
float offsetMashTemp = 1;
// Pin donde se conecta el bus 1-Wire del DS18B20
const int pinDataDQ = 15;
// Instancia a las clases OneWire y DallasTemperature
OneWire oneWireObject(pinDataDQ);
DallasTemperature sensorDS18B20(&oneWireObject);
#define TFT_CS 14 //for D32 Pro
#define TFT_DC 27 //for D32 Pro
#define TFT_RST 33 //for D32 Pro
#define TS_CS 12 //for D32 Pro
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
//XPT2046_Touchscreen ts(TS_CS);
// 'Outlined_brew-pot', 100x100px
const unsigned char brewPot100 [] PROGMEM = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0f, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xff,
0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xe0, 0x00, 0x00, 0x00, 0xff, 0xe0,
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x7e, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0xff, 0x80, 0x00, 0x00, 0x00, 0x3f, 0xe6, 0x0e, 0x00,
0x00, 0x00, 0x1f, 0x86, 0x03, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x06, 0x1f, 0x80, 0x00, 0x00, 0x3d,
0xc6, 0x00, 0x00, 0x0f, 0xfe, 0x00, 0x00, 0x06, 0x3b, 0xc0, 0x00, 0x00, 0x30, 0xe6, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x06, 0x70, 0xc0, 0x00, 0x00, 0x38, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x06, 0x61, 0xc0, 0x00, 0x00, 0x3c, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xc3,
0xc0, 0x00, 0x00, 0x0e, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00, 0x00,
0x07, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x0e, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00,
0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00,
0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x03,
0x0c, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x04, 0x02, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x08, 0x01, 0x00, 0x00, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x11, 0x00, 0x80, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x10, 0x80, 0x80, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00,
0x10, 0xe0, 0x80, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x10, 0x60, 0x80,
0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x10, 0x60, 0x80, 0x00, 0x06, 0x00,
0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
0x00, 0x06, 0x00, 0x00, 0x18, 0x00, 0x80, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00,
0x00, 0x08, 0x01, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x04, 0x02,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x03, 0x8c, 0x00, 0x00, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xc0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x00, 0x01, 0xe0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x07, 0xe0, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0x00, 0x00, 0x07, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff,
0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xff, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
// 'icon_fireprevention', 100x100px
const unsigned char noFire100 [] PROGMEM = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x1f, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x7f, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff,
0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x7f, 0xff, 0xc0, 0x00, 0x3f, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xfe, 0x00,
0x00, 0x03, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xf0, 0x00, 0x00, 0x00, 0xff,
0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x3f, 0xfe, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0f, 0xff, 0x80, 0x00, 0x80, 0x00, 0x0f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
0x1f, 0xfe, 0x00, 0x01, 0x80, 0x00, 0x07, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xfc, 0x80,
0x01, 0xc0, 0x00, 0x01, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xfc, 0x80, 0x01, 0xc0, 0x00,
0x00, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xfe, 0x00, 0x01, 0xc0, 0x00, 0x00, 0x7f, 0xf0,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x3f, 0xf0, 0x00, 0x00, 0x00,
0x00, 0xff, 0xff, 0x80, 0x03, 0xe0, 0x00, 0x00, 0x1f, 0xf8, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff,
0xc0, 0x01, 0xe0, 0x00, 0x00, 0x0f, 0xfc, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xe0, 0x01, 0xf0,
0x00, 0x00, 0x07, 0xfc, 0x00, 0x00, 0x00, 0x03, 0xfe, 0x7f, 0xf0, 0x01, 0xf0, 0x00, 0x00, 0x03,
0xfe, 0x00, 0x00, 0x00, 0x07, 0xfc, 0x3f, 0xf9, 0xc1, 0xf8, 0x00, 0x00, 0x03, 0xfe, 0x00, 0x00,
0x00, 0x07, 0xfd, 0x9f, 0xfc, 0xf1, 0xfc, 0x80, 0x00, 0x01, 0xff, 0x00, 0x00, 0x00, 0x0f, 0xf8,
0x0f, 0xfe, 0x79, 0xfc, 0xe0, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x0f, 0xf0, 0x07, 0xff, 0x3d,
0xfe, 0x70, 0x00, 0x00, 0xff, 0x80, 0x00, 0x00, 0x1f, 0xf0, 0x03, 0xff, 0x9f, 0xff, 0x70, 0x00,
0x00, 0x7f, 0x80, 0x00, 0x00, 0x1f, 0xe0, 0x01, 0xff, 0xcf, 0xff, 0xf8, 0x00, 0x00, 0x7f, 0x80,
0x00, 0x00, 0x1f, 0xe0, 0x00, 0xff, 0xe7, 0xff, 0xf8, 0x00, 0x00, 0x3f, 0xc0, 0x00, 0x00, 0x3f,
0xe0, 0x00, 0x7f, 0xf3, 0xff, 0xfc, 0x00, 0x00, 0x3f, 0xc0, 0x00, 0x00, 0x3f, 0xc0, 0x00, 0x3f,
0xf9, 0xff, 0xfc, 0x00, 0x00, 0x3f, 0xc0, 0x00, 0x00, 0x3f, 0xc0, 0x00, 0x1f, 0xfc, 0xff, 0xfc,
0x00, 0x00, 0x1f, 0xe0, 0x00, 0x00, 0x3f, 0xc0, 0x00, 0x0f, 0xfe, 0x7f, 0xfe, 0x00, 0x00, 0x1f,
0xe0, 0x00, 0x00, 0x7f, 0x80, 0x00, 0x07, 0xff, 0x3f, 0xfe, 0x00, 0x00, 0x1f, 0xe0, 0x00, 0x00,
0x7f, 0x80, 0x00, 0x03, 0xff, 0x9f, 0xfe, 0x40, 0x00, 0x1f, 0xe0, 0x00, 0x00, 0x7f, 0x80, 0x00,
0x09, 0xff, 0xcf, 0xfe, 0x60, 0x00, 0x0f, 0xe0, 0x00, 0x00, 0x7f, 0x80, 0x00, 0x04, 0xff, 0xe7,
0xfe, 0x70, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x7f, 0x80, 0x00, 0x06, 0x7f, 0xf3, 0xfe, 0x70, 0x00,
0x0f, 0xf0, 0x00, 0x00, 0x7f, 0x80, 0x00, 0x07, 0x3f, 0xf9, 0xff, 0x70, 0x00, 0x0f, 0xf0, 0x00,
0x00, 0x7f, 0x80, 0x00, 0x07, 0x9f, 0xfc, 0xff, 0xf8, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x7f, 0x80,
0x00, 0x07, 0xcf, 0xfe, 0x7f, 0xf8, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x7f, 0x80, 0x00, 0x07, 0xe7,
0xff, 0x3f, 0xf8, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x7f, 0x80, 0x07, 0xc7, 0xf3, 0xff, 0x9f, 0xf8,
0x00, 0x0f, 0xf0, 0x00, 0x00, 0x7f, 0x80, 0x01, 0xf7, 0xf9, 0xff, 0xcf, 0xf0, 0x00, 0x0f, 0xf0,
0x00, 0x00, 0x7f, 0x80, 0x00, 0xff, 0xfc, 0xff, 0xe7, 0xf0, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x7f,
0x80, 0x00, 0x7f, 0xfe, 0x7f, 0xf3, 0xf0, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x7f, 0x80, 0x00, 0x7f,
0xff, 0x3f, 0xf9, 0xf4, 0x00, 0x0f, 0xe0, 0x00, 0x00, 0x7f, 0x80, 0x00, 0x3f, 0xff, 0x9f, 0xfc,
0xfe, 0x00, 0x1f, 0xe0, 0x00, 0x00, 0x7f, 0x80, 0x00, 0x3f, 0xff, 0xcf, 0xfe, 0x7e, 0x00, 0x1f,
0xe0, 0x00, 0x00, 0x3f, 0xc0, 0x00, 0x3f, 0xff, 0xe7, 0xff, 0x3e, 0x00, 0x1f, 0xe0, 0x00, 0x00,
0x3f, 0xc0, 0x00, 0x3f, 0xff, 0xf3, 0xff, 0x9e, 0x00, 0x1f, 0xe0, 0x00, 0x00, 0x3f, 0xc0, 0x00,
0x7f, 0xff, 0xf9, 0xff, 0xce, 0x00, 0x3f, 0xe0, 0x00, 0x00, 0x3f, 0xc0, 0x00, 0x7f, 0xff, 0xfc,
0xff, 0xe6, 0x00, 0x3f, 0xc0, 0x00, 0x00, 0x1f, 0xe0, 0x00, 0x7f, 0xff, 0x70, 0x7f, 0xf2, 0x00,
0x3f, 0xc0, 0x00, 0x00, 0x1f, 0xe0, 0x00, 0x7f, 0xfe, 0x31, 0x3f, 0xf8, 0x00, 0x7f, 0xc0, 0x00,
0x00, 0x1f, 0xf0, 0x00, 0x7f, 0xde, 0x01, 0x1f, 0xfc, 0x00, 0x7f, 0x80, 0x00, 0x00, 0x0f, 0xf0,
0x00, 0x7f, 0x8e, 0x00, 0x0f, 0xfe, 0x00, 0xff, 0x80, 0x00, 0x00, 0x0f, 0xf8, 0x00, 0x7f, 0x8e,
0x00, 0x27, 0xff, 0x00, 0xff, 0x80, 0x00, 0x00, 0x0f, 0xf8, 0x00, 0x7f, 0x86, 0x00, 0x03, 0xff,
0x81, 0xff, 0x00, 0x00, 0x00, 0x07, 0xfc, 0x00, 0x7f, 0x87, 0x00, 0x01, 0xff, 0xc1, 0xff, 0x00,
0x00, 0x00, 0x07, 0xfe, 0x00, 0x3f, 0x83, 0x00, 0x0c, 0xff, 0xe3, 0xfe, 0x00, 0x00, 0x00, 0x03,
0xfe, 0x00, 0x3f, 0xc0, 0x00, 0x1e, 0x7f, 0xf7, 0xfe, 0x00, 0x00, 0x00, 0x01, 0xff, 0x00, 0x3f,
0xc0, 0x00, 0x1f, 0x3f, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x01, 0xff, 0x80, 0x1f, 0xe0, 0x00, 0x3f,
0x9f, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0xff, 0xc0, 0x1f, 0xe0, 0x00, 0x7f, 0xcf, 0xff, 0xf8,
0x00, 0x00, 0x00, 0x00, 0x7f, 0xe0, 0x0f, 0xf0, 0x01, 0xff, 0xe7, 0xff, 0xf0, 0x00, 0x00, 0x00,
0x00, 0x7f, 0xf0, 0x07, 0xf8, 0x03, 0xff, 0x83, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xf8,
0x03, 0xfe, 0x1f, 0xfe, 0x09, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xfc, 0x01, 0xff, 0xff,
0xfc, 0x03, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0x00, 0x7f, 0xff, 0xe0, 0x07, 0xff,
0x80, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0x80, 0x07, 0xff, 0x00, 0x1f, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0x03, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x7f, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0xff, 0xf8, 0x00, 0x00, 0x01, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00,
0x00, 0x0f, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xf0, 0x00, 0xff, 0xff,
0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x03, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xff, 0xff,
0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
// 'pngtree-vector-bone-fire-icon-png-image_3760510', 100x100px
const unsigned char fire100 [] PROGMEM = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfc, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1f, 0xff, 0xc0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff,
0xc0, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xc1, 0xc0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xc3, 0xc0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xc7, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xcf, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff,
0xff, 0xdf, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xdf, 0xc0,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x07, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87,
0xff, 0xfb, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8f, 0xff, 0xf3, 0xff,
0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8f, 0xff, 0xc3, 0xff, 0xe0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xcf, 0xff, 0x83, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0xcf, 0xff, 0x03, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0xcf, 0xff, 0x03, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xe7, 0xfe, 0x03,
0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xe7, 0xfe, 0x01, 0xff, 0xf0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xf3, 0xfc, 0x01, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0xfb, 0xfc, 0x00, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0xff, 0x3c, 0x00, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0x1c,
0x00, 0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0x0c, 0x00, 0x3f, 0xf8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x04, 0x00, 0x3f, 0xf8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x1f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0x00, 0x00, 0x1f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f,
0x00, 0x00, 0x0f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x0d,
0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x0d, 0xf0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x04, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x00, 0x08, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00,
0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0xc0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0xfe, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0xff, 0x80, 0x00, 0x03, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xf8,
0x00, 0x1f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff,
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0x9f, 0xff, 0x9f, 0xff, 0xff, 0xe0,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x1f, 0xff, 0x8f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00,
0x00, 0xc3, 0xff, 0xfc, 0x1f, 0xff, 0x83, 0xff, 0xfc, 0x30, 0x00, 0x00, 0x00, 0x00, 0xc1, 0xff,
0xf8, 0x1f, 0xff, 0x81, 0xff, 0xf8, 0x30, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xf0, 0x1f, 0xff,
0xc0, 0x7f, 0xf0, 0x10, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x7f, 0xe0, 0x1f, 0xff, 0xc0, 0x3f, 0xe0,
0x30, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7f, 0xc0, 0x1f, 0xff, 0xc0, 0x1f, 0xe0, 0x20, 0x00, 0x00,
0x00, 0x00, 0x40, 0x3f, 0x00, 0x1e, 0x01, 0xe0, 0x0f, 0xe0, 0x20, 0x00, 0x00, 0x00, 0x00, 0x20,
0x3e, 0x00, 0x1c, 0x00, 0xe0, 0x07, 0xc0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x30, 0x3c, 0x00, 0x1c,
0x00, 0x60, 0x03, 0xc0, 0x40, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x00, 0x18, 0x00, 0x60, 0x01,
0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x18, 0x70, 0x00, 0x0c, 0x00, 0x40, 0x00, 0xe1, 0x80, 0x00,
0x00, 0x00, 0x00, 0x0f, 0xe0, 0x00, 0x06, 0x01, 0xc0, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0xc0, 0x00, 0x03, 0xff, 0x80, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
#define relayPin 13
String relayStatus = "OFF";
// For WiFi connection
const char* ssid = "xxx";
const char* password = "yyy";
AsyncWebServer server(80);
const char* PARAM_INPUT_1 = "targetTemp";
const char* PARAM_INPUT_2 = "offsetTemp";
// HTML web page to handle 2 input fields (targetTemp, offsetTemp)
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html><head>
<title>ESP Input Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head><body>
<form action="/get">
targetTemp: <input type="text" name="targetTemp">
<input type="submit" value="Submit">
</form><br>
<form action="/get">
offsetTemp: <input type="text" name="offsetTemp">
<input type="submit" value="Submit">
</form>
</body></html>)rawliteral";
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
void wifiConnect(){
// Start: Connect to Wi-Fi network
Serial.println("WiFi not connected.");
Serial.println();
Serial.print("Connecting to...");
Serial.println(ssid);
WiFi.begin(ssid, password);
//Removing the while loop to avoid unnecesary waiting. If necessary WiFi will be reconnected in loop()
//while (WiFi.status() != WL_CONNECTED) {
//delay(500);
//Serial.print(".");
//}
Serial.println("");
Serial.println("Wi-Fi connected successfully");
Serial.print("IP address: ");
Serial.print(WiFi.localIP());
// End: Connect to Wi-Fi network
}
void setup() {
// put your setup code here, to run once:
// Serial port communication
Serial.begin(9600);
// Iniciamos el bus 1-Wire
sensorDS18B20.begin();
//TFT initialize
tft.begin();
tft.setRotation(0);
pinMode(relayPin, OUTPUT);
wifiConnect();
// Start: Connect to Wi-Fi network
//Serial.println();
//Serial.println();
//Serial.print("Connecting to...");
//Serial.println(ssid);
//
//WiFi.begin(ssid, password);
//
//while (WiFi.status() != WL_CONNECTED) {
//delay(500);
//Serial.print(".");
//}
//Serial.println("");
//Serial.println("Wi-Fi connected successfully");
//Serial.print("IP address: ");
//Serial.print(WiFi.localIP());
// End: Connect to Wi-Fi network
// Send web page with input fields to client
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html);
});
// Send a GET request to <ESP_IP>/get?targetTemp=<inputMessage>
server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
String inputParam;
// GET targetTemp value on <ESP_IP>/get?targetTemp=<inputMessage>
if (request->hasParam(PARAM_INPUT_1)) {
inputMessage = request->getParam(PARAM_INPUT_1)->value();
targetMashTemp = inputMessage.toFloat();
inputParam = PARAM_INPUT_1;
}
// GET offsetTemp value on <ESP_IP>/get?offsetTemp=<inputMessage>
else if (request->hasParam(PARAM_INPUT_2)) {
inputMessage = request->getParam(PARAM_INPUT_2)->value();
offsetMashTemp = inputMessage.toFloat();
inputParam = PARAM_INPUT_2;
}
else {
inputMessage = "No message sent";
inputParam = "none";
}
Serial.println(inputMessage);
Serial.println(inputParam);
request->send(200, "text/html", "HTTP GET request sent to your ESP on input field ("
+ inputParam + ") with value: " + inputMessage +
"<br><a href=\"/\">Return to Home Page</a>");
});
server.onNotFound(notFound);
server.begin();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
wifiConnect()
}
tft.fillScreen(ILI9341_BLACK);
yield();
tft.setCursor(0, 0);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
// put your main code here, to run repeatedly:
// Mandamos comandos para toma de temperatura a los sensores
Serial.println("Sending request to sensor");
sensorDS18B20.requestTemperatures();
//tft.println("Sending request to sensor");
// Leemos y mostramos los datos del sensor DS18B20
currentMashTemp = sensorDS18B20.getTempCByIndex(0);
Serial.print("DS18B20 sensor temperature: ");
Serial.print(currentMashTemp);
Serial.println(" C");
tft.println("DS18B20 sensor temp: ");
tft.setTextSize(3);
tft.print(currentMashTemp);
tft.print((char)247); //Display degree symbol
tft.println("C");
tft.setTextSize(2);
tft.println("");
tft.setTextColor(ILI9341_YELLOW);
tft.println("Target mash temp: ");
tft.println("");
tft.setTextSize(3);
tft.print(targetMashTemp);
tft.print((char)247); //Display degree symbol
tft.println("C");
tft.println("");
tft.setTextSize(2);
tft.setTextColor(ILI9341_GREEN);
tft.print("Temp offset: ");
tft.print(offsetMashTemp);
tft.print((char)247); //Display degree symbol
tft.println("C");
tft.setTextSize(1);
tft.println("");
tft.setTextSize(2);
if ((currentMashTemp + offsetMashTemp) < targetMashTemp){
tft.setTextColor(ILI9341_GREEN);
digitalWrite(relayPin, HIGH);
relayStatus = "ON";
}
if (currentMashTemp >= targetMashTemp){
tft.setTextColor(ILI9341_RED);
digitalWrite(relayPin, LOW);
relayStatus = "OFF";
}
tft.print("Relay status: ");
tft.println(relayStatus);
tft.setTextSize(1);
tft.println("");
tft.setTextSize(2);
tft.setTextColor(ILI9341_GREEN);
tft.print("IP/URL:");
tft.print(WiFi.localIP());
if (relayStatus == "OFF"){
tft.drawBitmap(15, 220, noFire100, 100, 100, ILI9341_WHITE); // x1,y1,filename,width,height,color
} else {
tft.drawBitmap(15, 220, fire100, 100, 100, ILI9341_WHITE); // x1,y1,filename,width,height,color
}
tft.drawBitmap(120, 220, brewPot100, 100, 100, ILI9341_WHITE); // x1,y1,filename,width,height,color
delay(5000);
}
|
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define ll long long
using namespace std;
typedef tuple<ll, ll, ll> tp;
typedef pair<ll, ll> pr;
const ll MOD = 1000000007;
const ll INF = 1e18;
template <typename T> void print(const T &t) {
std::copy(t.cbegin(), t.cend(),
std::ostream_iterator<typename T::value_type>(std::cout, " "));
cout << endl;
}
template <typename T> void print2d(const T &t) {
std::for_each(t.cbegin(), t.cend(), print<typename T::value_type>);
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin.exceptions(cin.failbit);
ll n;
cin >> n;
ll count = 0;
map<ll, set<ll>> m;
for (ll i = 0; i < n; i++) {
ll x, y;
cin >> x >> y;
m[x].insert(y);
}
set<ll> form;
for (auto it = m.begin(); it != m.end(); it++) {
for (auto it2 = m.begin(); it2 != m.end(); it2++) {
if (it->first == it2->first)
continue;
set<ll> curr = it->second;
set<ll> check = it2->second;
ll currCount = 0;
for (auto s = curr.begin(); s != curr.end(); s++) {
ll currY = *s;
if (check.count(currY)) {
currCount++;
}
}
// cout << currCount << endl;
if (currCount >= 2) {
currCount -= 1;
form.insert(it->first);
form.insert(it2->first);
} else {
currCount = 0;
}
count += currCount;
}
// cout << endl;
}
// cout << endl;
// cout << count << " " << form.size() << endl;
if (form.size()) {
cout << count / 2 << endl;
} else {
cout << 0 << endl;
}
// cout << form.size() << endl;
}
|
#ifndef __FGPlayerWheel_H__
#define __FGPlayerWheel_H__
class FGPlayer;
class FGPlayerWheel : public LivingObject
{
protected:
FGPlayer* m_pPlayer;
public:
FGPlayerWheel();
virtual ~FGPlayerWheel();
virtual void Update(double TimePassed);
void SetAttachedPlayer(FGPlayer* aPlayer);
virtual void ApplyDamage(int damage);
virtual void BeginCollision(b2Fixture* fixtureCollided, b2Fixture* fixtureCollidedAgainst, GameObject* objectCollidedagainst, b2Vec2 collisionNormal, b2Vec2 contactPoint, bool touching);
virtual void EndCollision(b2Fixture* fixtureCollided, b2Fixture* fixtureCollidedAgainst, GameObject* objectCollidedagainst, b2Vec2 collisionNormal, b2Vec2 contactPoint, bool touching);
};
#endif
|
/**
*
* @file MultipleIK.hpp
* @author Naoki Takahashi
*
**/
#pragma once
#include "InverseProblemSolverBase.hpp"
#include "../Parameters.hpp"
#include "../ControlPointMap.hpp"
namespace Kinematics {
namespace InverseProblemSolvers {
template <typename Scalar>
class MultipleIK : public InverseProblemSolverBase {
protected :
using ParametersPtr = typename Parameters<Scalar>::Ptr;
using ControlPointMapPtr = typename ControlPointMap<Scalar>::Ptr;
public :
using InverseProblemSolverBase::ModelPtr;
using Ptr = std::unique_ptr<MultipleIK>;
MultipleIK(ModelPtr &);
virtual ~MultipleIK();
virtual bool compute() = 0;
virtual bool compute(const Quantity::JointAngle<Scalar> &) = 0;
void register_map(ControlPointMapPtr &);
void register_parameters(ParametersPtr &);
protected :
ParametersPtr parameters;
ControlPointMapPtr control_point_map;
};
}
}
|
#include "physics\Singularity.Physics.h"
namespace Singularity
{
namespace Extensions
{
class CharacterController : public Singularity::Physics::Collider
{
DECLARE_OBJECT_TYPE;
private:
#pragma region Variables
Vector3 m_kVelocity;
Vector3 m_kSize;
Vector3 m_kCenter;
float m_fSlopeLimit;
float m_fStepOffset;
bool m_bDetectCollisions;
#pragma endregion
public:
#pragma region Properties
Vector3& Get_Center();
void Set_Center(const Vector3& value);
Vector3& Get_Size();
void Set_Size(const Vector3& value);
#pragma endregion
#pragma region Constructors and Finalizers
CharacterController(String name = "", Vector3 center = Vector3(0,0,0), Vector3 size = Vector3(1,1,1))
:Collider(name), m_kCenter(center), m_kSize(size) { }
~CharacterController() { }
#pragma endregion
#pragma region Methods
void SimpleMove(Vector3 speed);
void Move(Vector3 motion);
#pragma endregion
};
//#include "physics\BoxCollider.inc"
}
}
|
/**
* // This is the MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* class MountainArray {
* public:
* int get(int index);
* int length();
* };
*/
class Solution {
public:
int findInMountainArray(int target, MountainArray &mountainArr) {
int n = mountainArr.length();
int highest = getHighest(mountainArr, n);
int left = 0, right = highest;
while (left < right) {
int mid = left + (right - left) / 2;
if (mountainArr.get(mid) < target) left = mid + 1; // '<'
else right = mid;
}
if (mountainArr.get(left) == target) return left;
left = highest, right = n - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (mountainArr.get(mid) > target) left = mid + 1; // '>'
else right = mid;
}
if (mountainArr.get(left) == target) return left;
return -1;
}
int getHighest(MountainArray & mountainArr, int n) {
int left = 0, right = n - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) left = mid + 1;
else right = mid;
}
return left;
}
};
|
#include <card.h>
#include <vector>
#include <stdlib.h>
#include <ctime>
using namespace std;
class Deck{
public:
Deck(bool type, int jokers, int many){
if(type){ //merges organized decks together
for(int i = 0; i < many; i++){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 13; k++){
deck.push_back(j+1, i);
}
}
for(int j = 0; j < jokers; j++){
deck.push_back(14, 4);
}
}
cardsLeft = many * 52 + jokers;
}
else{
cardsLeft = many * 52 + jokers; //counter the total number of cards
for(int i = 0; i < many; i++){ //makes all the decks
for(int j = 0; j < 4; j++){
for(int k = 0; k < 13; k++){
deck.push_back(j+1, i);
}
}
for(int j = 0; j < jokers; j++){
deck.push_back(14, 4);
}
}
//basic randomizer implemented
srand(time(0));
for(int i = 0; i < cardsLeft; i++){
int r = i + (rand() % (cardsLeft - i));
swap(deck[i], deck[r]);
}
}
}
void reshuffle_cur(){
srand(time(0));
for(int i = 0; i < cardsLeft; i++){
int r = i + (rand() % (cardsLeft - i));
swap(deck[i], deck[r]);
}
}
void reshuffle(){
cardsLeft = cardsLeft + discard.size();
vector<Card> newDeck;
newDeck.reserve(cardsLeft);
newDeck.insert(newDeck.end(), deck.begin(), deck.end());
newDeck.insert(newDeck.end(), discard.begin(), discard.end());
deck = newDeck;
reshuffle_cur();
} // reshuffles entire deck
Card draw(){
cardsLeft--;
Card res = deck[0];
discard.push_back(res);
deck.erase(0);
return res;
}
vector<Card> drawMulti(int n){
vector<Card> res;
res.reserve(n);
for(int i = 0; i < n; i++){
res.insert(i, draw());
}
return res;
}
void add_card(Card a){
deck.push_back(a);
cardsLeft++;
}
private:
vector<Card> deck;
vector<Card> discard;
int cardsLeft;
}
|
//-----------------------------------------------------------------------------
// Perimeter Map Compiler
// Copyright (c) 2005, Don Reba
// 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 Don Reba nor the names of his contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#pragma once
#pragma warning(disable: 4100)
#pragma warning(disable: 4702)
#pragma warning(disable: 4355)
#pragma warning(disable: 4512)
#pragma warning(disable: 4189)
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#define _WIN32_WINDOWS 0x0401 // require Win98 or NT 4 at minimum
// Windows Header Files:
#include <windows.h>
#include <windowsx.h>
#include <Commdlg.h>
#include <shlwapi.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#include <crtdbg.h>
#include <time.h>
// some necessary STL
#include <string>
typedef std::basic_string<char> string;
typedef std::basic_string<wchar_t> wstring;
typedef std::basic_string<TCHAR> tstring;
typedef std::basic_stringstream <TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > tstringstream;
typedef std::basic_istringstream<TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > tistringstream;
typedef std::basic_ostringstream<TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > tostringstream;
#include <vector>
using std::vector;
// third party libraries
#include "..\..\include\bzlib\bzlib.h"
#include "..\..\include\FreeImage\FreeImagePlus.h"
#include "..\..\include\jasper\jasper.h"
#include "..\..\include\tinyxml\tinyxml.h"
#include "..\..\include\tinyxpath\xpath_processor.h"
#include "..\..\include\FastDelegate\FastDelegate.h"
namespace fd = fastdelegate;
// project-wide utilites
#include "util.h"
#include "foreach.h"
// useful typedefs and definitions
#define ri_cast reinterpret_cast
typedef unsigned int uint;
typedef unsigned long ulong;
typedef unsigned short ushort;
// extremely annoying definitions
#undef min
#undef max
// project-wide constants
const uint prm_player_count = 4;
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a;
cin>>a;
bool f = 1, f1 = 0;
for(int i=a.length()-1; i>=0; i--)
{
if(a[i]>='a' && a[i]<='z')
{
if(!i)
{
f1 = 1;
break;
}
f = 0;
break;
}
}
if(f)
{
for(int i=0; i<a.length(); i++)
{
if(a[i]>='A' && a[i]<='Z') a[i] += 'a'-'A';
}
if(f1) a[0] -= 'a'-'A';
}
cout<<a<<endl;
}
|
//具体类
class BinarySplitter:public ISplitter
{
};
class TxtSplitter:public ISplitter
{
};
class PictureSplitter:public ISplitter
{
};
class VideoSplitter:public ISplitter
{
};
//具体工厂
class BinarySplitterFactory:public SplitterFactory
{
public:
virtual ISplitter* createSplitter()
{
return new BinarySplitter();
}
}
class TxtSplitter:public SplitterFactory
{
public:
virtual ISplitter* createSplitter()
{
return new TxtSplitter();
}
}
class PictureSplitter:public SplitterFactory
{
public:
virtual ISplitter* createSplitter()
{
return new PictureSplitter();
}
}
class VideoSplitter:public SplitterFactory
{
public:
virtual ISplitter* createSplitter()
{
return new VideoSplitter();
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define REP(i, init, n) for(int i = (int)(init); i < (int)(n); i++)
#define vi vector<int>
#define vl vector<long>
#define vvi vector<vector<int>>
#define vvl vector<vector<long>>
#define pint pair<int, int>
#define plong pair<long, long>
int main() {
int N, M, X;
cin>>N>>M>>X;
vi C(N);
vvi A(N, vi(M));
REP(i, 0, N){
cin >> C[i];
REP(j, 0, M){
cin >> A[i][j];
}
}
int count = (1<<N);
int min_price = __INT_MAX__;
vi bitA(N);
REP(i, 0, count){
int bit = i;
REP(j, 0, N){
bitA[j] = bit % 2;
bit = (bit >> 1);
//cout << bitA[j] << " ";
}
//cout << endl;
vi sum(M, 0);
int price = 0;
REP(j, 0, N){
if(bitA[j]){
REP(k, 0, M){
sum[k] += A[j][k];
}
price += C[j];
}
}
bool match = true;
REP(k, 0, M){
if(sum[k] < X) match = false;
}
if(match) min_price = min(price, min_price);
}
if(min_price == __INT_MAX__) min_price = -1;
cout << min_price << endl;
}
|
/* In questo codice si prova a capire quando
* viene chiata una funzione costante in caso
* di overload */
#include <iostream>
namespace N{
class C{
public:
C(int x = 0);
//funzione non costante
int& get();
//funzione costante
//funzioni costanti hanno senso se si ritorna un riferimento (o puntatore) e non una copia
const int& get() const;
private:
int m_x;
};
C::C(int x) : m_x(x) {}
int& C::get() {
std::cout << "Non const called\n";
return m_x;
}
const int& C::get() const {
std::cout << "Const called\n";
return m_x;
}
}//namespace N
int main()
{
N::C c1(1);
const N::C c2(2);
//anche se assegnato a una constante viene chiamata la funzione non costante
const int cx = c1.get();
//la funzione costante viene chiamata se l'oggetto è costante
int vx = c2.get();
std::cout << c2.get() << " " << cx << " " << ++vx << '\n';
return 0;
}
/* La risoluzione dell'overload non avviene guardando il tipo di ritorno
* ma solo il nome della funzione e il tipo e numero dei parametri.
* In questo caso la chiamata di funzione quindi può essere decisa solo
* in base all'oggetto chiamante. Quindi se l'oggetto è costante, verrà
* chiamata la funzione costante e viceversa.
*/
|
/**
* @author Levi Armstrong
* @date January 1, 2016
*
* @copyright Copyright (c) 2016, Southwest Research Institute
*
* @license Software License Agreement (Apache License)\n
* \n
* 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\n
* \n
* http://www.apache.org/licenses/LICENSE-2.0\n
* \n
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ROSPROJECTPLUGIN_H
#define ROSPROJECTPLUGIN_H
#include <extensionsystem/iplugin.h>
#include <QObject>
#include <QAction>
namespace ProjectExplorer {
class Project;
class Node;
}
namespace ROSProjectManager {
namespace Internal {
class ROSProjectPlugin : public ExtensionSystem::IPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QtCreatorPlugin" FILE "ROSProjectManager.json")
public:
bool initialize(const QStringList &arguments, QString *errorString) override;
void extensionsInitialized() override {}
private slots:
/**
* @brief This will reload the project include directories.
*
* If libraries are add to a CMakeList.txt this must me called so
* the proper include directories get add to the cpp model.
*/
void reloadProjectIncludeDirectories();
/**
* @brief This will remove the selected FolderNode in the project tree.
*/
void removeProjectDirectory();
private:
/**
* @brief This creates a built-in ROS Cpp code style.
*/
void createCppCodeStyle();
};
} // namespace Internal
} // namespace ROSProjectManager
#endif // ROSPROJECTPLUGIN_H
|
#include <iostream>
#include<bitset>
#include<vector>
using namespace std;
int main() {
// your code goes here
unsigned int n,m;
cin>>n;
cin>>m;
vector<bitset<501>> v;
for(int i=0;i<n;i++)
{
string str;
cin>>str;
bitset<501> b(str);
v.push_back(b);
}
unsigned int max=0,ct=0;
for(int i=0;i<n-1;i++)
{
for(int j=i;j<n;j++)
{
unsigned int t1=(v[i]|v[j]).count();
if(max<t1)
{
max=t1;
ct=1;
}
else
if(max==t1)
{
ct++;
}
}
}
cout<<max<<endl;
cout<<ct<<endl;
return 0;
}
|
/// \file fake_turtle.cpp
/// \brief A kinematics simulation of a differential drive robot using DiffDrive class
/// Publisher: joint_states (sensor_msgs/JointStates): Publish joint states message
///
/// Subscriber: cmd_vel (geometry_msgs/Twist): Subscribe to cmd_vel and get Twist message
#include<ros/ros.h>
#include<ros/console.h>
#include<geometry_msgs/Twist.h>
#include<sensor_msgs/JointState.h>
#include<iostream>
#include<rigid2d/rigid2d.hpp>
#include<rigid2d/diff_drive.hpp>
// define global variables
static std::string left_wheel_joint, right_wheel_joint; // joint names
static rigid2d::Twist2D cmd; // commanded twist
static bool flag; // callback flag
/// \brief updates the body twist of the robot
/// \param msg - twist msg
void twistCallback(const geometry_msgs::Twist::ConstPtr &msg)
{
cmd.vx = msg->linear.x;
cmd.vy = msg->linear.y; // no y component shoule be 0
cmd.w = msg->angular.z;
flag = true;
}
int main(int argc, char** argv)
{
// initiate fake_turtle node
ros::init(argc, argv, "fake_turtle");
ros::NodeHandle nh_("~"); // private node handler
ros::NodeHandle nh; // public node handler
// initiate twist subscriber
ros::Subscriber twist_sub = nh.subscribe("cmd_vel",10,twistCallback);
// initiate joint publisher
ros::Publisher joint_pub = nh.advertise<sensor_msgs::JointState>("joint_states",10);
float wheel_base, wheel_radius;
// read parameters
nh.getParam("/left_wheel_joint", left_wheel_joint);
nh.getParam("/right_wheel_joint",right_wheel_joint);
nh.getParam("/wheel_base", wheel_base);
nh.getParam("/wheel_radius",wheel_radius);
// login info
ROS_INFO("left_wheel_joint: %s", left_wheel_joint.c_str());
ROS_INFO("right_wheel_joint: %s", right_wheel_joint.c_str());
ROS_INFO("wheel_base: %f",wheel_base);
ROS_INFO("wheel_radius: %f", wheel_radius);
ROS_INFO("successfully launched the fake_turtle node!");
// check if flag is received
flag = false;
// assume robot pose starts at (0,0,0)
rigid2d::Pose2D pose;
pose.theta = 0.0;
pose.x = 0.0;
pose.y = 0.0;
// diff_drive
rigid2d::DiffDrive diffDrive(pose,wheel_base,wheel_radius);
// define fixed frequency
int freq = 10; //Hz
ros::Rate loop_rat(freq);
// Timing
ros::Time cur_time, last_time;
cur_time = ros::Time::now();
last_time = ros::Time::now();
while (nh.ok())
{
ros::spinOnce();
cur_time = ros::Time::now();
// received message
if (flag)
{
// scaled twist based on frequency
rigid2d::Twist2D new_cmd;
new_cmd.vx = cmd.vx * 1.0 / freq;
new_cmd.vy = 0.0;
new_cmd.w = cmd.w * 1.0 / freq;
// feedforward control
diffDrive.feedforward(new_cmd);
// wheel ecnoders
rigid2d:: WheelEncoders enc;
enc = diffDrive.getEncoders();
// joint_state
sensor_msgs::JointState joint_state;
joint_state.header.stamp = cur_time;
joint_state.name.push_back(left_wheel_joint);
joint_state.name.push_back(right_wheel_joint);
// pose
joint_state.position.push_back(enc.left);
joint_state.position.push_back(enc.right);
flag = false;
// publish joint state
joint_pub.publish(joint_state);
}
last_time = cur_time;
loop_rat.sleep();
}
return 0;
}
/// end file
|
/*Generic SVGA handling*/
/*This is intended to be used by another SVGA driver, and not as a card in it's own right*/
#include <stdlib.h>
#include "ibm.h"
#include "mem.h"
#include "video.h"
#include "vid_svga.h"
#include "vid_svga_render.h"
#include "io.h"
#include "timer.h"
#define svga_output 0
void svga_doblit(int y1, int y2, int wx, int wy, svga_t *svga);
extern uint8_t edatlookup[4][4];
uint8_t svga_rotate[8][256];
/*Primary SVGA device. As multiple video cards are not yet supported this is the
only SVGA device.*/
static svga_t *svga_pri;
bool svga_on(void *p)
{
svga_t *svga = (svga_t*)p;
return svga->scrblank == 0 && svga->hdisp >= 128;
}
int svga_get_vtotal(void *p)
{
svga_t *svga = (svga_t*)p;
int v = svga->vtotal;
if (svga->crtc[0x17] & 4)
v *= 2;
return v;
}
void *svga_get_object(void)
{
return svga_pri;
}
svga_t *svga_get_pri()
{
return svga_pri;
}
void svga_set_override(svga_t *svga, int val)
{
if (svga->override && !val)
svga->fullchange = changeframecount;
svga->override = val;
}
void svga_out(uint16_t addr, uint8_t val, void *p)
{
svga_t *svga = (svga_t *)p;
int c;
uint8_t o;
// printf("OUT SVGA %03X %02X %04X:%04X\n",addr,val,CS,pc);
switch (addr)
{
case 0x3C0:
if (!svga->attrff)
{
svga->attraddr = val & 31;
if ((val & 0x20) != svga->attr_palette_enable)
{
svga->fullchange = 3;
svga->attr_palette_enable = val & 0x20;
svga_recalctimings(svga);
}
}
else
{
if ((svga->attraddr == 0x13) && (svga->attrregs[0x13] != val))
svga->fullchange = changeframecount;
svga->attrregs[svga->attraddr & 31] = val;
if (svga->attraddr < 16)
svga->fullchange = changeframecount;
if (svga->attraddr == 0x10 || svga->attraddr == 0x14 || svga->attraddr < 0x10)
{
for (c = 0; c < 16; c++)
{
if (svga->attrregs[0x10] & 0x80) svga->egapal[c] = (svga->attrregs[c] & 0xf) | ((svga->attrregs[0x14] & 0xf) << 4);
else svga->egapal[c] = (svga->attrregs[c] & 0x3f) | ((svga->attrregs[0x14] & 0xc) << 4);
}
}
if (svga->attraddr == 0x10)
svga_recalctimings(svga);
if (svga->attraddr == 0x12)
{
if ((val & 0xf) != svga->plane_mask)
svga->fullchange = changeframecount;
svga->plane_mask = val & 0xf;
}
}
svga->attrff ^= 1;
break;
case 0x3C2:
svga->miscout = val;
svga->vidclock = val & 4;// printf("3C2 write %02X\n",val);
io_removehandlerx(0x03a0, 0x0020, svga->video_in, NULL, NULL, svga->video_out, NULL, NULL, svga->p);
if (!(val & 1))
io_sethandlerx(0x03a0, 0x0020, svga->video_in, NULL, NULL, svga->video_out, NULL, NULL, svga->p);
svga_recalctimings(svga);
break;
case 0x3C4:
svga->seqaddr = val;
break;
case 0x3C5:
if (svga->seqaddr > 0xf) return;
o = svga->seqregs[svga->seqaddr & 0xf];
svga->seqregs[svga->seqaddr & 0xf] = val;
if (o != val && (svga->seqaddr & 0xf) == 1)
svga_recalctimings(svga);
switch (svga->seqaddr & 0xf)
{
case 1:
if (svga->scrblank && !(val & 0x20))
svga->fullchange = 3;
svga->scrblank = (svga->scrblank & ~0x20) | (val & 0x20);
svga_recalctimings(svga);
break;
case 2:
svga->writemask = val & 0xf;
break;
case 3:
svga->charsetb = (((val >> 2) & 3) * 0x10000) + 2;
svga->charseta = ((val & 3) * 0x10000) + 2;
if (val & 0x10)
svga->charseta += 0x8000;
if (val & 0x20)
svga->charsetb += 0x8000;
break;
case 4:
svga->chain2_write = !(val & 4);
svga->chain4 = val & 8;
svga->fast = ((svga->gdcreg[8] == 0xff || svga->gdcreg[8] == 0) && !(svga->gdcreg[3] & 0x18) && !svga->gdcreg[1]) &&
((svga->chain4 && svga->packed_chain4) || svga->fb_only);
break;
}
break;
case 0x3c6:
svga->dac_mask = val;
break;
case 0x3C7:
svga->dac_read = val;
svga->dac_pos = 0;
break;
case 0x3C8:
svga->dac_write = val;
svga->dac_read = val - 1;
svga->dac_pos = 0;
break;
case 0x3C9:
svga->dac_status = 0;
svga->fullchange = changeframecount;
switch (svga->dac_pos)
{
case 0:
svga->dac_r = val;
svga->dac_pos++;
break;
case 1:
svga->dac_g = val;
svga->dac_pos++;
break;
case 2:
svga->vgapal[svga->dac_write].r = svga->dac_r;
svga->vgapal[svga->dac_write].g = svga->dac_g;
svga->vgapal[svga->dac_write].b = val;
if (svga->ramdac_type == RAMDAC_8BIT)
svga->pallook[svga->dac_write] = makecol32(svga->vgapal[svga->dac_write].r, svga->vgapal[svga->dac_write].g, svga->vgapal[svga->dac_write].b);
else
svga->pallook[svga->dac_write] = makecol32((svga->vgapal[svga->dac_write].r & 0x3f) * 4, (svga->vgapal[svga->dac_write].g & 0x3f) * 4, (svga->vgapal[svga->dac_write].b & 0x3f) * 4);
if (svga->swaprb)
svga->pallook[svga->dac_write] = ((svga->pallook[svga->dac_write] >> 16) & 0xff) | ((svga->pallook[svga->dac_write] & 0xff) << 16) | (svga->pallook[svga->dac_write] & 0x00ff00);
svga->dac_pos = 0;
svga->dac_write = (svga->dac_write + 1) & 255;
break;
}
break;
case 0x3CE:
svga->gdcaddr = val;
break;
case 0x3CF:
o = svga->gdcreg[svga->gdcaddr & 15];
switch (svga->gdcaddr & 15)
{
case 2: svga->colourcompare=val; break;
case 4: svga->readplane=val&3; break;
case 5:
svga->writemode = val & 3;
svga->readmode = val & 8;
svga->chain2_read = val & 0x10;
break;
case 6:
// pclog("svga_out recalcmapping %p\n", svga);
if ((svga->gdcreg[6] & 0xc) != (val & 0xc))
{
// pclog("Write mapping %02X\n", val);
switch (val&0xC)
{
case 0x0: /*128k at A0000*/
mem_mapping_set_addrx(&svga->mapping, 0xa0000, 0x20000);
svga->banked_mask = 0xffff;
break;
case 0x4: /*64k at A0000*/
mem_mapping_set_addrx(&svga->mapping, 0xa0000, 0x10000);
svga->banked_mask = 0xffff;
break;
case 0x8: /*32k at B0000*/
mem_mapping_set_addrx(&svga->mapping, 0xb0000, 0x08000);
svga->banked_mask = 0x7fff;
break;
case 0xC: /*32k at B8000*/
mem_mapping_set_addrx(&svga->mapping, 0xb8000, 0x08000);
svga->banked_mask = 0x7fff;
break;
}
}
break;
case 7: svga->colournocare=val; break;
}
svga->gdcreg[svga->gdcaddr & 15] = val;
svga->fast = (svga->gdcreg[8] == 0xff && !(svga->gdcreg[3] & 0x18) && !svga->gdcreg[1]) &&
((svga->chain4 && svga->packed_chain4) || svga->fb_only);
if (((svga->gdcaddr & 15) == 5 && (val ^ o) & 0x70) || ((svga->gdcaddr & 15) == 6 && (val ^ o) & 1))
svga_recalctimings(svga);
break;
}
}
uint8_t svga_in(uint16_t addr, void *p)
{
svga_t *svga = (svga_t *)p;
uint8_t temp;
// if (addr!=0x3da) pclog("Read port %04X\n",addr);
switch (addr)
{
case 0x3C0:
return svga->attraddr | svga->attr_palette_enable;
case 0x3C1:
return svga->attrregs[svga->attraddr];
case 0x3c2:
if ((svga->vgapal[0].r + svga->vgapal[0].g + svga->vgapal[0].b) >= 0x50)
temp = 0;
else
temp = 0x10;
return temp;
case 0x3C4:
return svga->seqaddr;
case 0x3C5:
return svga->seqregs[svga->seqaddr & 0xF];
case 0x3c6: return svga->dac_mask;
case 0x3c7: return svga->dac_status;
case 0x3c8: return svga->dac_write;
case 0x3c9:
svga->dac_status = 3;
switch (svga->dac_pos)
{
case 0:
svga->dac_pos++;
if (svga->ramdac_type == RAMDAC_8BIT)
return svga->vgapal[svga->dac_read].r;
return svga->vgapal[svga->dac_read].r & 0x3f;
case 1:
svga->dac_pos++;
if (svga->ramdac_type == RAMDAC_8BIT)
return svga->vgapal[svga->dac_read].g;
return svga->vgapal[svga->dac_read].g & 0x3f;
case 2:
svga->dac_pos=0;
svga->dac_read = (svga->dac_read + 1) & 255;
if (svga->ramdac_type == RAMDAC_8BIT)
return svga->vgapal[(svga->dac_read - 1) & 255].b;
return svga->vgapal[(svga->dac_read - 1) & 255].b & 0x3f;
}
break;
case 0x3CC:
return svga->miscout;
case 0x3CE:
return svga->gdcaddr;
case 0x3CF:
return svga->gdcreg[svga->gdcaddr & 0xf];
case 0x3DA:
svga->attrff = 0;
if (svga->cgastat & 0x01)
svga->cgastat &= ~0x30;
else
svga->cgastat ^= 0x30;
return svga->cgastat;
}
// printf("Bad EGA read %04X %04X:%04X\n",addr,cs>>4,pc);
return 0xFF;
}
void svga_set_ramdac_type(svga_t *svga, int type)
{
int c;
if (svga->ramdac_type != type)
{
svga->ramdac_type = type;
for (c = 0; c < 256; c++)
{
if (svga->ramdac_type == RAMDAC_8BIT)
svga->pallook[c] = makecol32(svga->vgapal[c].r, svga->vgapal[c].g, svga->vgapal[c].b);
else
svga->pallook[c] = makecol32((svga->vgapal[c].r & 0x3f) * 4, (svga->vgapal[c].g & 0x3f) * 4, (svga->vgapal[c].b & 0x3f) * 4);
if (svga->swaprb)
svga->pallook[svga->dac_write] = ((svga->pallook[svga->dac_write] >> 16) & 0xff) | ((svga->pallook[svga->dac_write] & 0xff) << 16) | (svga->pallook[svga->dac_write] & 0x00ff00);
}
}
}
void svga_recalctimings(svga_t *svga)
{
double crtcconst;
double _dispontime, _dispofftime, disptime;
int text = 0;
svga->vtotal = svga->crtc[6];
svga->dispend = svga->crtc[0x12];
svga->vsyncstart = svga->crtc[0x10];
svga->split = svga->crtc[0x18];
svga->vblankstart = svga->crtc[0x15];
if (svga->crtc[7] & 1)
svga->vtotal |= 0x100;
if (svga->crtc[7] & 0x20)
svga->vtotal |= 0x200;
svga->vtotal += 2;
if (svga->crtc[7] & 2)
svga->dispend |= 0x100;
if (svga->crtc[7] & 0x40)
svga->dispend |= 0x200;
svga->dispend++;
if (svga->crtc[7] & 4)
svga->vsyncstart |= 0x100;
if (svga->crtc[7] & 0x80)
svga->vsyncstart |= 0x200;
svga->vsyncstart++;
if (svga->crtc[7] & 0x10)
svga->split|=0x100;
if (svga->crtc[9] & 0x40)
svga->split|=0x200;
svga->split++;
if (svga->crtc[7] & 0x08)
svga->vblankstart |= 0x100;
if (svga->crtc[9] & 0x20)
svga->vblankstart |= 0x200;
svga->vblankstart++;
svga->hdisp = svga->crtc[1] - ((svga->crtc[5] & 0x60) >> 5);
svga->hdisp++;
svga->htotal = svga->crtc[0];
svga->htotal += 6; /*+6 is required for Tyrian*/
svga->rowoffset = svga->crtc[0x13];
svga->clock = (svga->vidclock) ? VGACONST2 : VGACONST1;
svga->lowres = svga->attrregs[0x10] & 0x40;
svga->horizontal_linedbl = 0;
svga->interlace = 0;
svga->ma_latch = ((svga->crtc[0xc] << 8) | svga->crtc[0xd]) + ((svga->crtc[8] & 0x60) >> 5);
svga->ca_adj = 0;
svga->rowcount = svga->crtc[9] & 31;
svga->linedbl = svga->crtc[9] & 0x80;
svga->hdisp_time = svga->hdisp;
svga->render = svga_render_blank;
if (!(svga->gdcreg[6] & 1) && !(svga->attrregs[0x10] & 1)) /*Text mode*/
{
if (svga->seqregs[1] & 8) /*40 column*/
{
svga->render = svga_render_text_40;
svga->hdisp *= (svga->seqregs[1] & 1) ? 16 : 18;
} else
{
svga->render = svga_render_text_80;
svga->hdisp *= (svga->seqregs[1] & 1) ? 8 : 9;
}
svga->hdisp_old = svga->hdisp;
text = 1;
}
else
{
svga->hdisp *= (svga->seqregs[1] & 8) ? 16 : 8;
svga->hdisp_old = svga->hdisp;
switch (svga->gdcreg[5] & 0x60)
{
case 0x00: /*16 colours*/
if (svga->seqregs[1] & 8) /*Low res (320)*/
svga->render = svga_render_4bpp_lowres;
else
svga->render = svga_render_4bpp_highres;
break;
case 0x20: /*4 colours*/
if (svga->seqregs[1] & 8) /*Low res (320)*/
svga->render = svga_render_2bpp_lowres;
else
svga->render = svga_render_2bpp_highres;
break;
case 0x40: case 0x60: /*256+ colours*/
switch (svga->bpp)
{
case 8:
if (svga->lowres)
svga->render = svga_render_8bpp_lowres;
else
svga->render = svga_render_8bpp_highres;
break;
case 15:
if (svga->lowres)
svga->render = svga_render_15bpp_lowres;
else
svga->render = svga_render_15bpp_highres;
break;
case 16:
if (svga->lowres)
svga->render = svga_render_16bpp_lowres;
else
svga->render = svga_render_16bpp_highres;
break;
case 24:
if (svga->lowres)
svga->render = svga_render_24bpp_lowres;
else
svga->render = svga_render_24bpp_highres;
break;
case 32:
if (svga->lowres)
svga->render = svga_render_32bpp_lowres;
else
svga->render = svga_render_32bpp_highres;
break;
}
break;
}
}
//pclog("svga_render %08X : %08X %08X %08X %08X %08X %i %i %02X %i %i\n", svga_render, svga_render_text_40, svga_render_text_80, svga_render_8bpp_lowres, svga_render_8bpp_highres, svga_render_blank, scrblank,gdcreg[6]&1,gdcreg[5]&0x60,bpp,seqregs[1]&8);
svga->char_width = (svga->seqregs[1] & 1) ? 8 : 9;
if (svga->recalctimings_ex)
svga->recalctimings_ex(svga);
if (svga->vblankstart < svga->dispend)
svga->dispend = svga->vblankstart;
if (!text) {
if (!svga->lowres) {
if (svga->render == svga_render_2bpp_lowres)
svga->render = svga_render_2bpp_highres;
if (svga->render == svga_render_4bpp_lowres)
svga->render = svga_render_4bpp_highres;
if (svga->render == svga_render_8bpp_lowres)
svga->render = svga_render_8bpp_highres;
if (svga->render == svga_render_15bpp_lowres)
svga->render = svga_render_15bpp_highres;
if (svga->render == svga_render_16bpp_lowres)
svga->render = svga_render_16bpp_highres;
if (svga->render == svga_render_24bpp_lowres)
svga->render = svga_render_24bpp_highres;
if (svga->render == svga_render_32bpp_lowres)
svga->render = svga_render_32bpp_highres;
}
if (svga->horizontal_linedbl) {
if (svga->render == svga_render_2bpp_highres)
svga->render = svga_render_2bpp_lowres;
if (svga->render == svga_render_4bpp_highres)
svga->render = svga_render_4bpp_lowres;
if (svga->render == svga_render_8bpp_highres)
svga->render = svga_render_8bpp_lowres;
if (svga->render == svga_render_15bpp_highres)
svga->render = svga_render_15bpp_lowres;
if (svga->render == svga_render_16bpp_highres)
svga->render = svga_render_16bpp_lowres;
if (svga->render == svga_render_24bpp_highres)
svga->render = svga_render_24bpp_lowres;
if (svga->render == svga_render_32bpp_highres)
svga->render = svga_render_32bpp_lowres;
}
if (svga->swaprb) {
if (svga->render == svga_render_24bpp_lowres)
svga->render = svga_render_24bpp_lowres_swaprb;
if (svga->render == svga_render_24bpp_highres)
svga->render = svga_render_24bpp_highres_swaprb;
if (svga->render == svga_render_32bpp_lowres)
svga->render = svga_render_32bpp_lowres_swaprb;
if (svga->render == svga_render_32bpp_highres)
svga->render = svga_render_32bpp_highres_swaprb;
}
}
crtcconst = svga->clock * svga->char_width;
disptime = svga->htotal;
_dispontime = svga->hdisp_time;
// printf("Disptime %f dispontime %f hdisp %i\n",disptime,dispontime,crtc[1]*8);
if (svga->seqregs[1] & 8) { disptime *= 2; _dispontime *= 2; }
_dispofftime = disptime - _dispontime;
_dispontime *= crtcconst;
_dispofftime *= crtcconst;
svga->dispontime = (uint64_t)_dispontime;
svga->dispofftime = (uint64_t)_dispofftime;
if (svga->dispontime < TIMER_USEC)
svga->dispontime = TIMER_USEC;
if (svga->dispofftime < TIMER_USEC)
svga->dispofftime = TIMER_USEC;
svga_recalc_remap_func(svga);
/* printf("SVGA horiz total %i display end %i vidclock %f\n",svga->crtc[0],svga->crtc[1],svga->clock);
printf("SVGA vert total %i display end %i max row %i vsync %i\n",svga->vtotal,svga->dispend,(svga->crtc[9]&31)+1,svga->vsyncstart);
printf("total %f on %i cycles off %i cycles frame %i sec %i %02X\n",disptime*crtcconst,svga->dispontime,svga->dispofftime,(svga->dispontime+svga->dispofftime)*svga->vtotal,(svga->dispontime+svga->dispofftime)*svga->vtotal*70,svga->seqregs[1]);
pclog("svga->render %08X\n", svga->render);*/
}
extern int cyc_total;
int svga_poll(void *p)
{
svga_t *svga = (svga_t *)p;
int x;
int eod = 0;
if (!svga->linepos)
{
// if (!(vc & 15)) pclog("VC %i %i\n", vc, GetTickCount());
if (svga->displine == svga->hwcursor_latch.y && svga->hwcursor_latch.ena)
{
svga->hwcursor_on = svga->hwcursor.ysize - svga->hwcursor_latch.yoff;
if (svga->hwcursor_on < 0)
svga->hwcursor_on = 0;
svga->hwcursor_oddeven = 0;
}
if (svga->displine == svga->hwcursor_latch.y+1 && svga->hwcursor_latch.ena && svga->interlace)
{
svga->hwcursor_on = svga->hwcursor.ysize - svga->hwcursor_latch.yoff;
if (svga->hwcursor_on < 0)
svga->hwcursor_on = 0;
svga->hwcursor_oddeven = 1;
}
if (svga->displine == svga->overlay_latch.y && svga->overlay_latch.ena)
{
svga->overlay_on = svga->overlay_latch.ysize - svga->overlay_latch.yoff;
svga->overlay_oddeven = 0;
}
if (svga->displine == svga->overlay_latch.y+1 && svga->overlay_latch.ena && svga->interlace)
{
svga->overlay_on = svga->overlay_latch.ysize - svga->overlay_latch.yoff;
svga->overlay_oddeven = 1;
}
#ifndef UAE
timer_advance_u64(&svga->timer, svga->dispofftime);
#endif
// if (output) printf("Display off %f\n",vidtime);
svga->cgastat |= 1;
svga->linepos = 1;
if (svga->dispon)
{
svga->hdisp_on=1;
svga->ma &= svga->vram_display_mask;
if (svga->firstline == 4000)
{
svga->firstline = svga->displine;
video_wait_for_buffer();
}
if (svga->hwcursor_on || svga->overlay_on)
svga->changedvram[svga->ma >> 12] = svga->changedvram[(svga->ma >> 12) + 1] = svga->interlace ? 3 : 2;
if (!svga->override)
svga->render(svga);
if (svga->overlay_on)
{
if (!svga->override)
svga->overlay_draw(svga, svga->displine);
svga->overlay_on--;
if (svga->overlay_on && svga->interlace)
svga->overlay_on--;
}
if (svga->hwcursor_on)
{
if (!svga->override)
svga->hwcursor_draw(svga, svga->displine);
svga->hwcursor_on--;
if (svga->hwcursor_on && svga->interlace)
svga->hwcursor_on--;
}
if (svga->lastline < svga->displine)
svga->lastline = svga->displine;
}
// pclog("%03i %06X %06X\n",displine,ma,vrammask);
svga->displine++;
if (svga->interlace)
svga->displine++;
if ((svga->cgastat & 8) && ((svga->displine & 15) == (svga->crtc[0x11] & 15)) && svga->vslines)
{
// printf("Vsync off at line %i\n",displine);
svga->cgastat &= ~8;
}
svga->vslines++;
if (svga->displine > 3500)
svga->displine = 0;
// pclog("Col is %08X %08X %08X %i %i %08X\n",((uint32_t *)buffer32->line[displine])[320],((uint32_t *)buffer32->line[displine])[321],((uint32_t *)buffer32->line[displine])[322],
// displine, vc, ma);
}
else
{
// pclog("VC %i ma %05X\n", svga->vc, svga->ma);
#ifndef UAE
timer_advance_u64(&svga->timer, svga->dispontime);
#endif
// if (output) printf("Display on %f\n",vidtime);
if (svga->dispon)
svga->cgastat &= ~1;
svga->hdisp_on = 0;
svga->linepos = 0;
if (svga->sc == (svga->crtc[11] & 31))
svga->con = 0;
if (svga->dispon)
{
if (svga->linedbl && !svga->linecountff)
{
svga->linecountff = 1;
svga->ma = svga->maback;
}
else if (svga->sc == svga->rowcount)
{
svga->linecountff = 0;
svga->sc = 0;
svga->maback += (svga->rowoffset << 3);
if (svga->interlace)
svga->maback += (svga->rowoffset << 3);
svga->maback &= svga->vram_display_mask;
svga->ma = svga->maback;
}
else
{
svga->linecountff = 0;
svga->sc++;
svga->sc &= 31;
svga->ma = svga->maback;
}
}
svga->hsync_divisor = !svga->hsync_divisor;
if (svga->hsync_divisor && (svga->crtc[0x17] & 4))
return eod;
svga->vc++;
svga->vc &= 2047;
if (svga->vc == svga->split)
{
int ret = 1;
if (svga->line_compare)
ret = svga->line_compare(svga);
if (ret)
{
// pclog("VC split\n");
svga->ma = svga->maback = 0;
svga->sc = 0;
if (svga->attrregs[0x10] & 0x20)
svga->scrollcache = 0;
}
}
if (svga->vc == svga->dispend)
{
if (svga->vblank_start)
svga->vblank_start(svga);
// pclog("VC dispend\n");
svga->dispon=0;
if (svga->crtc[10] & 0x20) svga->cursoron = 0;
else svga->cursoron = svga->blink & 16;
if (!(svga->gdcreg[6] & 1) && !(svga->blink & 15))
svga->fullchange = 2;
svga->blink++;
for (x = 0; x < ((svga->vram_mask+1) >> 12); x++)
{
if (svga->changedvram[x])
svga->changedvram[x]--;
}
// memset(changedvram,0,2048);
if (svga->fullchange)
svga->fullchange--;
}
if (svga->vc == svga->vsyncstart)
{
int wx, wy;
// pclog("VC vsync %i %i\n", svga->firstline_draw, svga->lastline_draw);
svga->dispon=0;
svga->cgastat |= 8;
x = svga->hdisp;
if (svga->interlace && !svga->oddeven) svga->lastline++;
if (svga->interlace && svga->oddeven) svga->firstline--;
wx = x;
wy = svga->lastline - svga->firstline;
if (!svga->override)
svga_doblit(svga->firstline_draw, svga->lastline_draw + 1, wx, wy, svga);
readflash = 0;
svga->firstline = 4000;
svga->lastline = 0;
svga->firstline_draw = 4000;
svga->lastline_draw = 0;
svga->oddeven ^= 1;
changeframecount = svga->interlace ? 3 : 2;
svga->vslines = 0;
if (svga->interlace && svga->oddeven) svga->ma = svga->maback = svga->ma_latch + (svga->rowoffset << 1) + ((svga->crtc[5] & 0x60) >> 5);
else svga->ma = svga->maback = svga->ma_latch + ((svga->crtc[5] & 0x60) >> 5);
svga->ca = ((svga->crtc[0xe] << 8) | svga->crtc[0xf]) + ((svga->crtc[0xb] & 0x60) >> 5) + svga->ca_adj;
svga->ma <<= 2;
svga->maback <<= 2;
svga->ca <<= 2;
if (!svga->video_res_override)
{
svga->video_res_x = wx;
svga->video_res_y = wy + 1;
if (!(svga->gdcreg[6] & 1) && !(svga->attrregs[0x10] & 1)) /*Text mode*/
{
svga->video_res_x /= svga->char_width;
svga->video_res_y /= (svga->crtc[9] & 31) + 1;
svga->video_bpp = 0;
} else
{
if (svga->crtc[9] & 0x80)
svga->video_res_y /= 2;
if (!(svga->crtc[0x17] & 2))
svga->video_res_y *= 4;
else if (!(svga->crtc[0x17] & 1))
svga->video_res_y *= 2;
svga->video_res_y /= (svga->crtc[9] & 31) + 1;
if (svga->render == svga_render_8bpp_lowres ||
svga->render == svga_render_15bpp_lowres ||
svga->render == svga_render_16bpp_lowres ||
svga->render == svga_render_24bpp_lowres ||
svga->render == svga_render_32bpp_lowres) {
if (svga->horizontal_linedbl)
svga->video_res_x *= 2;
else
svga->video_res_x /= 2;
}
switch (svga->gdcreg[5] & 0x60)
{
case 0x00: svga->video_bpp = 4; break;
case 0x20: svga->video_bpp = 2; break;
case 0x40: case 0x60: svga->video_bpp = svga->bpp; break;
}
}
}
// if (svga_interlace && oddeven) ma=maback=ma+(svga_rowoffset<<2);
// pclog("Addr %08X vson %03X vsoff %01X %02X %02X %02X %i %i\n",ma,svga_vsyncstart,crtc[0x11]&0xF,crtc[0xD],crtc[0xC],crtc[0x33], svga_interlace, oddeven);
if (svga->vsync_callback)
svga->vsync_callback(svga);
eod = 1;
}
if (svga->vc == svga->vtotal)
{
// pclog("VC vtotal\n");
// printf("Frame over at line %i %i %i %i\n",displine,vc,svga_vsyncstart,svga_dispend);
svga->vc = 0;
svga->sc = svga->crtc[8] & 0x1f;
svga->dispon = 1;
svga->displine = (svga->interlace && svga->oddeven) ? 1 : 0;
svga->scrollcache = svga->attrregs[0x13] & 7;
svga->linecountff = 0;
svga->hwcursor_on = 0;
svga->hwcursor_latch = svga->hwcursor;
svga->overlay_on = 0;
svga->overlay_latch = svga->overlay;
// pclog("Latch HWcursor addr %08X\n", svga_hwcursor_latch.addr);
// pclog("ADDR %08X\n",hwcursor_addr);
}
if (svga->sc == (svga->crtc[10] & 31))
svga->con = 1;
}
// printf("2 %i\n",svga_vsyncstart);
//pclog("svga_poll %i %i %i %i %i %i %i\n", ins, svga->dispofftime, svga->dispontime, svga->vidtime, cyc_total, svga->linepos, svga->vc);
return eod;
}
void svga_setvram(void *p, uint8_t *vram)
{
svga_t* svga = (svga_t*)p;
svga->vram = vram;
}
int svga_init(svga_t *svga, void *p, int memsize,
void (*recalctimings_ex)(struct svga_t *svga),
uint8_t (*video_in) (uint16_t addr, void *p),
void (*video_out)(uint16_t addr, uint8_t val, void *p),
void (*hwcursor_draw)(struct svga_t *svga, int displine),
void (*overlay_draw)(struct svga_t *svga, int displine))
{
int c, d, e;
svga->p = p;
for (c = 0; c < 256; c++)
{
e = c;
for (d = 0; d < 8; d++)
{
svga_rotate[d][c] = e;
e = (e >> 1) | ((e & 1) ? 0x80 : 0);
}
}
svga->readmode = 0;
svga->crtcreg_mask = 0x3f;
svga->crtc[0] = 63;
svga->crtc[6] = 255;
svga->dispontime = 1000ull << 32;
svga->dispofftime = 1000ull << 32;
svga->bpp = 8;
#ifdef UAE
extern void *pcem_getvram(int);
svga->vram = (uint8_t*)pcem_getvram(memsize);
#else
svga->vram = (uint8_t*)malloc(memsize);
#endif
svga->vram_max = memsize;
svga->vram_display_mask = memsize - 1;
svga->vram_mask = memsize - 1;
svga->decode_mask = 0x7fffff;
svga->changedvram = (uint8_t*)malloc(/*(memsize >> 12) << 1*/0x1000000 >> 12);
svga->recalctimings_ex = recalctimings_ex;
svga->video_in = video_in;
svga->video_out = video_out;
svga->hwcursor_draw = hwcursor_draw;
svga->overlay_draw = overlay_draw;
svga->hwcursor.ysize = 64;
svga->ksc5601_english_font_type = 0;
svga_recalctimings(svga);
mem_mapping_addx(&svga->mapping, 0xa0000, 0x20000, svga_read, svga_readw, svga_readl, svga_write, svga_writew, svga_writel, NULL, MEM_MAPPING_EXTERNAL, svga);
#ifndef UAE
timer_add(&svga->timer, svga_poll, svga, 1);
#endif
svga_pri = svga;
svga->ramdac_type = RAMDAC_6BIT;
return 0;
}
void svga_close(svga_t *svga)
{
free(svga->changedvram);
#ifndef UAE
free(svga->vram);
#endif
svga_pri = NULL;
}
void svga_write(uint32_t addr, uint8_t val, void *p)
{
svga_t *svga = (svga_t *)p;
uint8_t vala, valb, valc, vald, wm = svga->writemask;
int writemask2 = svga->writemask;
#if 0
egawrites++;
cycles -= video_timing_write_b;
cycles_lost += video_timing_write_b;
if (svga_output) pclog("Writeega %06X ",addr);
#endif
addr &= svga->banked_mask;
addr += svga->write_bank;
if (!(svga->gdcreg[6] & 1)) svga->fullchange=2;
if ((svga->chain4 && svga->packed_chain4) || svga->fb_only)
{
writemask2=1<<(addr&3);
addr&=~3;
}
else if (svga->chain4)
{
writemask2 = 1 << (addr & 3);
addr &= ~3;
addr = ((addr & 0xfffc) << 2) | ((addr & 0x30000) >> 14) | (addr & ~0x3ffff);
}
else if (svga->chain2_write)
{
writemask2 &= ~0xa;
if (addr & 1)
writemask2 <<= 1;
addr &= ~1;
addr <<= 2;
}
else
{
addr<<=2;
}
addr &= svga->decode_mask;
if (addr >= svga->vram_max)
return;
addr &= svga->vram_mask;
// if (svga_output) pclog("%08X (%i, %i) %02X %i %i %i %02X\n", addr, addr & 1023, addr >> 10, val, writemask2, svga->writemode, svga->chain4, svga->gdcreg[8]);
svga->changedvram[addr >> 12] = changeframecount;
switch (svga->writemode)
{
case 1:
if (writemask2 & 1) svga->vram[addr] = svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = svga->ld;
break;
case 0:
if (svga->gdcreg[3] & 7)
val = svga_rotate[svga->gdcreg[3] & 7][val];
if (svga->gdcreg[8] == 0xff && !(svga->gdcreg[3] & 0x18) && (!svga->gdcreg[1] || svga->set_reset_disabled))
{
if (writemask2 & 1) svga->vram[addr] = val;
if (writemask2 & 2) svga->vram[addr | 0x1] = val;
if (writemask2 & 4) svga->vram[addr | 0x2] = val;
if (writemask2 & 8) svga->vram[addr | 0x3] = val;
}
else
{
if (svga->gdcreg[1] & 1) vala = (svga->gdcreg[0] & 1) ? 0xff : 0;
else vala = val;
if (svga->gdcreg[1] & 2) valb = (svga->gdcreg[0] & 2) ? 0xff : 0;
else valb = val;
if (svga->gdcreg[1] & 4) valc = (svga->gdcreg[0] & 4) ? 0xff : 0;
else valc = val;
if (svga->gdcreg[1] & 8) vald = (svga->gdcreg[0] & 8) ? 0xff : 0;
else vald = val;
switch (svga->gdcreg[3] & 0x18)
{
case 0: /*Set*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | (svga->la & ~svga->gdcreg[8]);
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | (svga->lb & ~svga->gdcreg[8]);
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | (svga->lc & ~svga->gdcreg[8]);
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | (svga->ld & ~svga->gdcreg[8]);
break;
case 8: /*AND*/
if (writemask2 & 1) svga->vram[addr] = (vala | ~svga->gdcreg[8]) & svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb | ~svga->gdcreg[8]) & svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc | ~svga->gdcreg[8]) & svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald | ~svga->gdcreg[8]) & svga->ld;
break;
case 0x10: /*OR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | svga->ld;
break;
case 0x18: /*XOR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) ^ svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) ^ svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) ^ svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) ^ svga->ld;
break;
}
// pclog("- %02X %02X %02X %02X %08X\n",vram[addr],vram[addr|0x1],vram[addr|0x2],vram[addr|0x3],addr);
}
break;
case 2:
if (!(svga->gdcreg[3] & 0x18) && (!svga->gdcreg[1] || svga->set_reset_disabled))
{
if (writemask2 & 1) svga->vram[addr] = (((val & 1) ? 0xff : 0) & svga->gdcreg[8]) | (svga->la & ~svga->gdcreg[8]);
if (writemask2 & 2) svga->vram[addr | 0x1] = (((val & 2) ? 0xff : 0) & svga->gdcreg[8]) | (svga->lb & ~svga->gdcreg[8]);
if (writemask2 & 4) svga->vram[addr | 0x2] = (((val & 4) ? 0xff : 0) & svga->gdcreg[8]) | (svga->lc & ~svga->gdcreg[8]);
if (writemask2 & 8) svga->vram[addr | 0x3] = (((val & 8) ? 0xff : 0) & svga->gdcreg[8]) | (svga->ld & ~svga->gdcreg[8]);
}
else
{
vala = ((val & 1) ? 0xff : 0);
valb = ((val & 2) ? 0xff : 0);
valc = ((val & 4) ? 0xff : 0);
vald = ((val & 8) ? 0xff : 0);
switch (svga->gdcreg[3] & 0x18)
{
case 0: /*Set*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | (svga->la & ~svga->gdcreg[8]);
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | (svga->lb & ~svga->gdcreg[8]);
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | (svga->lc & ~svga->gdcreg[8]);
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | (svga->ld & ~svga->gdcreg[8]);
break;
case 8: /*AND*/
if (writemask2 & 1) svga->vram[addr] = (vala | ~svga->gdcreg[8]) & svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb | ~svga->gdcreg[8]) & svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc | ~svga->gdcreg[8]) & svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald | ~svga->gdcreg[8]) & svga->ld;
break;
case 0x10: /*OR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | svga->ld;
break;
case 0x18: /*XOR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) ^ svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) ^ svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) ^ svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) ^ svga->ld;
break;
}
}
break;
case 3:
if (svga->gdcreg[3] & 7)
val = svga_rotate[svga->gdcreg[3] & 7][val];
wm = svga->gdcreg[8];
svga->gdcreg[8] &= val;
vala = (svga->gdcreg[0] & 1) ? 0xff : 0;
valb = (svga->gdcreg[0] & 2) ? 0xff : 0;
valc = (svga->gdcreg[0] & 4) ? 0xff : 0;
vald = (svga->gdcreg[0] & 8) ? 0xff : 0;
switch (svga->gdcreg[3] & 0x18)
{
case 0: /*Set*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | (svga->la & ~svga->gdcreg[8]);
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | (svga->lb & ~svga->gdcreg[8]);
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | (svga->lc & ~svga->gdcreg[8]);
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | (svga->ld & ~svga->gdcreg[8]);
break;
case 8: /*AND*/
if (writemask2 & 1) svga->vram[addr] = (vala | ~svga->gdcreg[8]) & svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb | ~svga->gdcreg[8]) & svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc | ~svga->gdcreg[8]) & svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald | ~svga->gdcreg[8]) & svga->ld;
break;
case 0x10: /*OR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | svga->ld;
break;
case 0x18: /*XOR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) ^ svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) ^ svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) ^ svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) ^ svga->ld;
break;
}
svga->gdcreg[8] = wm;
break;
}
}
uint8_t svga_read(uint32_t addr, void *p)
{
svga_t *svga = (svga_t *)p;
uint8_t temp, temp2, temp3, temp4;
uint32_t latch_addr;
int readplane = svga->readplane;
#if 0
cycles -= video_timing_read_b;
cycles_lost += video_timing_read_b;
egareads++;
// pclog("Readega %06X ",addr);
#endif
addr &= svga->banked_mask;
addr += svga->read_bank;
latch_addr = (addr << 2) & svga->decode_mask;
// pclog("%05X %i %04X:%04X %02X %02X %i\n",addr,svga->chain4,CS,pc, vram[addr & 0x7fffff], vram[(addr << 2) & 0x7fffff], svga->readmode);
// pclog("%i\n", svga->readmode);
if ((svga->chain4 && svga->packed_chain4) || svga->fb_only)
{
addr &= svga->decode_mask;
if (addr >= svga->vram_max)
return 0xff;
latch_addr = addr & svga->vram_mask & ~3;
svga->la = svga->vram[latch_addr];
svga->lb = svga->vram[latch_addr | 0x1];
svga->lc = svga->vram[latch_addr | 0x2];
svga->ld = svga->vram[latch_addr | 0x3];
return svga->vram[addr & svga->vram_mask];
}
else if (svga->chain4)
{
readplane = addr & 3;
addr = ((addr & 0xfffc) << 2) | ((addr & 0x30000) >> 14) | (addr & ~0x3ffff);
}
else if (svga->chain2_read)
{
readplane = (readplane & 2) | (addr & 1);
addr &= ~1;
addr <<= 2;
}
else
addr<<=2;
addr &= svga->decode_mask;
if (latch_addr >= svga->vram_max)
{
svga->la = svga->lb = svga->lc = svga->ld = 0xff;
}
else
{
latch_addr &= svga->vram_mask;
svga->la = svga->vram[latch_addr];
svga->lb = svga->vram[latch_addr | 0x1];
svga->lc = svga->vram[latch_addr | 0x2];
svga->ld = svga->vram[latch_addr | 0x3];
}
if (addr >= svga->vram_max)
return 0xff;
addr &= svga->vram_mask;
if (svga->readmode)
{
temp = svga->la;
temp ^= (svga->colourcompare & 1) ? 0xff : 0;
temp &= (svga->colournocare & 1) ? 0xff : 0;
temp2 = svga->lb;
temp2 ^= (svga->colourcompare & 2) ? 0xff : 0;
temp2 &= (svga->colournocare & 2) ? 0xff : 0;
temp3 = svga->lc;
temp3 ^= (svga->colourcompare & 4) ? 0xff : 0;
temp3 &= (svga->colournocare & 4) ? 0xff : 0;
temp4 = svga->ld;
temp4 ^= (svga->colourcompare & 8) ? 0xff : 0;
temp4 &= (svga->colournocare & 8) ? 0xff : 0;
return ~(temp | temp2 | temp3 | temp4);
}
//pclog("Read %02X %04X %04X\n",vram[addr|svga->readplane],addr,svga->readplane);
return svga->vram[addr | readplane];
}
void svga_write_linear(uint32_t addr, uint8_t val, void *p)
{
svga_t *svga = (svga_t *)p;
uint8_t vala, valb, valc, vald, wm = svga->writemask;
int writemask2 = svga->writemask;
#if 0
cycles -= video_timing_write_b;
cycles_lost += video_timing_write_b;
egawrites++;
if (svga_output) pclog("Write LFB %08X %02X ", addr, val);
#endif
if (!(svga->gdcreg[6] & 1))
svga->fullchange = 2;
if ((svga->chain4 && svga->packed_chain4) || svga->fb_only)
{
writemask2=1<<(addr&3);
addr&=~3;
}
else if (svga->chain4)
{
writemask2 = 1 << (addr & 3);
addr = ((addr & 0xfffc) << 2) | ((addr & 0x30000) >> 14) | (addr & ~0x3ffff);
}
else if (svga->chain2_write)
{
writemask2 &= ~0xa;
if (addr & 1)
writemask2 <<= 1;
addr &= ~1;
addr <<= 2;
}
else
{
addr<<=2;
}
addr &= svga->decode_mask;
if (addr >= svga->vram_max)
return;
addr &= svga->vram_mask;
// if (svga_output) pclog("%08X\n", addr);
svga->changedvram[addr >> 12]=changeframecount;
switch (svga->writemode)
{
case 1:
if (writemask2 & 1) svga->vram[addr] = svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = svga->ld;
break;
case 0:
if (svga->gdcreg[3] & 7)
val = svga_rotate[svga->gdcreg[3] & 7][val];
if (svga->gdcreg[8] == 0xff && !(svga->gdcreg[3] & 0x18) && (!svga->gdcreg[1] || svga->set_reset_disabled))
{
if (writemask2 & 1) svga->vram[addr] = val;
if (writemask2 & 2) svga->vram[addr | 0x1] = val;
if (writemask2 & 4) svga->vram[addr | 0x2] = val;
if (writemask2 & 8) svga->vram[addr | 0x3] = val;
}
else
{
if (svga->gdcreg[1] & 1) vala = (svga->gdcreg[0] & 1) ? 0xff : 0;
else vala = val;
if (svga->gdcreg[1] & 2) valb = (svga->gdcreg[0] & 2) ? 0xff : 0;
else valb = val;
if (svga->gdcreg[1] & 4) valc = (svga->gdcreg[0] & 4) ? 0xff : 0;
else valc = val;
if (svga->gdcreg[1] & 8) vald = (svga->gdcreg[0] & 8) ? 0xff : 0;
else vald = val;
switch (svga->gdcreg[3] & 0x18)
{
case 0: /*Set*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | (svga->la & ~svga->gdcreg[8]);
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | (svga->lb & ~svga->gdcreg[8]);
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | (svga->lc & ~svga->gdcreg[8]);
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | (svga->ld & ~svga->gdcreg[8]);
break;
case 8: /*AND*/
if (writemask2 & 1) svga->vram[addr] = (vala | ~svga->gdcreg[8]) & svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb | ~svga->gdcreg[8]) & svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc | ~svga->gdcreg[8]) & svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald | ~svga->gdcreg[8]) & svga->ld;
break;
case 0x10: /*OR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | svga->ld;
break;
case 0x18: /*XOR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) ^ svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) ^ svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) ^ svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) ^ svga->ld;
break;
}
// pclog("- %02X %02X %02X %02X %08X\n",vram[addr],vram[addr|0x1],vram[addr|0x2],vram[addr|0x3],addr);
}
break;
case 2:
if (!(svga->gdcreg[3] & 0x18) && (!svga->gdcreg[1] || svga->set_reset_disabled))
{
if (writemask2 & 1) svga->vram[addr] = (((val & 1) ? 0xff : 0) & svga->gdcreg[8]) | (svga->la & ~svga->gdcreg[8]);
if (writemask2 & 2) svga->vram[addr | 0x1] = (((val & 2) ? 0xff : 0) & svga->gdcreg[8]) | (svga->lb & ~svga->gdcreg[8]);
if (writemask2 & 4) svga->vram[addr | 0x2] = (((val & 4) ? 0xff : 0) & svga->gdcreg[8]) | (svga->lc & ~svga->gdcreg[8]);
if (writemask2 & 8) svga->vram[addr | 0x3] = (((val & 8) ? 0xff : 0) & svga->gdcreg[8]) | (svga->ld & ~svga->gdcreg[8]);
}
else
{
vala = ((val & 1) ? 0xff : 0);
valb = ((val & 2) ? 0xff : 0);
valc = ((val & 4) ? 0xff : 0);
vald = ((val & 8) ? 0xff : 0);
switch (svga->gdcreg[3] & 0x18)
{
case 0: /*Set*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | (svga->la & ~svga->gdcreg[8]);
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | (svga->lb & ~svga->gdcreg[8]);
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | (svga->lc & ~svga->gdcreg[8]);
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | (svga->ld & ~svga->gdcreg[8]);
break;
case 8: /*AND*/
if (writemask2 & 1) svga->vram[addr] = (vala | ~svga->gdcreg[8]) & svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb | ~svga->gdcreg[8]) & svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc | ~svga->gdcreg[8]) & svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald | ~svga->gdcreg[8]) & svga->ld;
break;
case 0x10: /*OR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | svga->ld;
break;
case 0x18: /*XOR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) ^ svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) ^ svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) ^ svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) ^ svga->ld;
break;
}
}
break;
case 3:
if (svga->gdcreg[3] & 7)
val = svga_rotate[svga->gdcreg[3] & 7][val];
wm = svga->gdcreg[8];
svga->gdcreg[8] &= val;
vala = (svga->gdcreg[0] & 1) ? 0xff : 0;
valb = (svga->gdcreg[0] & 2) ? 0xff : 0;
valc = (svga->gdcreg[0] & 4) ? 0xff : 0;
vald = (svga->gdcreg[0] & 8) ? 0xff : 0;
switch (svga->gdcreg[3] & 0x18)
{
case 0: /*Set*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | (svga->la & ~svga->gdcreg[8]);
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | (svga->lb & ~svga->gdcreg[8]);
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | (svga->lc & ~svga->gdcreg[8]);
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | (svga->ld & ~svga->gdcreg[8]);
break;
case 8: /*AND*/
if (writemask2 & 1) svga->vram[addr] = (vala | ~svga->gdcreg[8]) & svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb | ~svga->gdcreg[8]) & svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc | ~svga->gdcreg[8]) & svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald | ~svga->gdcreg[8]) & svga->ld;
break;
case 0x10: /*OR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) | svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) | svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) | svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) | svga->ld;
break;
case 0x18: /*XOR*/
if (writemask2 & 1) svga->vram[addr] = (vala & svga->gdcreg[8]) ^ svga->la;
if (writemask2 & 2) svga->vram[addr | 0x1] = (valb & svga->gdcreg[8]) ^ svga->lb;
if (writemask2 & 4) svga->vram[addr | 0x2] = (valc & svga->gdcreg[8]) ^ svga->lc;
if (writemask2 & 8) svga->vram[addr | 0x3] = (vald & svga->gdcreg[8]) ^ svga->ld;
break;
}
svga->gdcreg[8] = wm;
break;
}
}
uint8_t svga_read_linear(uint32_t addr, void *p)
{
svga_t *svga = (svga_t *)p;
uint8_t temp, temp2, temp3, temp4;
int readplane = svga->readplane;
uint32_t latch_addr = (addr << 2) & svga->decode_mask;
#if 0
cycles -= video_timing_read_b;
cycles_lost += video_timing_read_b;
egareads++;
#endif
if ((svga->chain4 && svga->packed_chain4) || svga->fb_only)
{
addr &= svga->decode_mask;
if (addr >= svga->vram_max)
return 0xff;
return svga->vram[addr & svga->vram_mask];
}
else if (svga->chain4)
{
readplane = addr & 3;
addr = ((addr & 0xfffc) << 2) | ((addr & 0x30000) >> 14) | (addr & ~0x3ffff);
}
else if (svga->chain2_read)
{
readplane = (readplane & 2) | (addr & 1);
addr &= ~1;
addr <<= 2;
}
else
addr<<=2;
addr &= svga->decode_mask;
if (latch_addr >= svga->vram_max)
{
svga->la = svga->lb = svga->lc = svga->ld = 0xff;
}
else
{
latch_addr &= svga->vram_mask;
svga->la = svga->vram[latch_addr];
svga->lb = svga->vram[latch_addr | 0x1];
svga->lc = svga->vram[latch_addr | 0x2];
svga->ld = svga->vram[latch_addr | 0x3];
}
if (addr >= svga->vram_max)
return 0xff;
addr &= svga->vram_mask;
if (svga->readmode)
{
temp = svga->la;
temp ^= (svga->colourcompare & 1) ? 0xff : 0;
temp &= (svga->colournocare & 1) ? 0xff : 0;
temp2 = svga->lb;
temp2 ^= (svga->colourcompare & 2) ? 0xff : 0;
temp2 &= (svga->colournocare & 2) ? 0xff : 0;
temp3 = svga->lc;
temp3 ^= (svga->colourcompare & 4) ? 0xff : 0;
temp3 &= (svga->colournocare & 4) ? 0xff : 0;
temp4 = svga->ld;
temp4 ^= (svga->colourcompare & 8) ? 0xff : 0;
temp4 &= (svga->colournocare & 8) ? 0xff : 0;
return ~(temp | temp2 | temp3 | temp4);
}
//printf("Read %02X %04X %04X\n",vram[addr|svga->readplane],addr,svga->readplane);
return svga->vram[addr | readplane];
}
void svga_doblit(int y1, int y2, int wx, int wy, svga_t *svga)
{
// pclog("svga_doblit start\n");
svga->frames++;
// pclog("doblit %i %i\n", y1, y2);
// pclog("svga_doblit %i %i\n", wx, svga->hdisp);
if (y1 > y2)
{
video_blit_memtoscreen(32, 0, 0, 0, xsize << svga->horizontal_linedbl, ysize);
return;
}
if ((wx!=xsize || wy!=ysize) && !vid_resize)
{
xsize=wx;
ysize=wy+1;
if (xsize<128) xsize=0;
if (ysize<32) ysize=0;
updatewindowsize(xsize, svga->horizontal_linedbl ? 2 : 1, ysize, svga->linedbl ? 2 : 1);
}
if (vid_resize)
{
xsize = wx;
ysize = wy + 1;
}
video_blit_memtoscreen(32, 0, y1, y2, xsize << svga->horizontal_linedbl, ysize);
// pclog("svga_doblit end\n");
}
void svga_writew(uint32_t addr, uint16_t val, void *p)
{
svga_t *svga = (svga_t *)p;
if (!svga->fast)
{
svga_write(addr, val, p);
svga_write(addr + 1, val >> 8, p);
return;
}
#if 0
egawrites += 2;
cycles -= video_timing_write_w;
cycles_lost += video_timing_write_w;
if (svga_output) pclog("svga_writew: %05X ", addr);
#endif
addr = (addr & svga->banked_mask) + svga->write_bank;
addr &= svga->decode_mask;
if (addr >= svga->vram_max)
return;
addr &= svga->vram_mask;
// if (svga_output) pclog("%08X (%i, %i) %04X\n", addr, addr & 1023, addr >> 10, val);
svga->changedvram[addr >> 12] = changeframecount;
*(uint16_t *)&svga->vram[addr] = val;
}
void svga_writel(uint32_t addr, uint32_t val, void *p)
{
svga_t *svga = (svga_t *)p;
if (!svga->fast)
{
svga_write(addr, val, p);
svga_write(addr + 1, val >> 8, p);
svga_write(addr + 2, val >> 16, p);
svga_write(addr + 3, val >> 24, p);
return;
}
egawrites += 4;
cycles -= video_timing_write_l;
cycles_lost += video_timing_write_l;
// if (svga_output) pclog("svga_writel: %05X ", addr);
addr = (addr & svga->banked_mask) + svga->write_bank;
addr &= svga->decode_mask;
if (addr >= svga->vram_max)
return;
addr &= svga->vram_mask;
// if (svga_output) pclog("%08X (%i, %i) %08X\n", addr, addr & 1023, addr >> 10, val);
svga->changedvram[addr >> 12] = changeframecount;
*(uint32_t *)&svga->vram[addr] = val;
}
uint16_t svga_readw(uint32_t addr, void *p)
{
svga_t *svga = (svga_t *)p;
if (!svga->fast)
return svga_read(addr, p) | (svga_read(addr + 1, p) << 8);
#if 0
egareads += 2;
cycles -= video_timing_read_w;
cycles_lost += video_timing_read_w;
#endif
// pclog("Readw %05X ", addr);
addr = (addr & svga->banked_mask) + svga->read_bank;
addr &= svga->decode_mask;
// pclog("%08X %04X\n", addr, *(uint16_t *)&vram[addr]);
if (addr >= svga->vram_max)
return 0xffff;
return *(uint16_t *)&svga->vram[addr & svga->vram_mask];
}
uint32_t svga_readl(uint32_t addr, void *p)
{
svga_t *svga = (svga_t *)p;
if (!svga->fast)
return svga_read(addr, p) | (svga_read(addr + 1, p) << 8) | (svga_read(addr + 2, p) << 16) | (svga_read(addr + 3, p) << 24);
#if 0
egareads += 4;
cycles -= video_timing_read_l;
cycles_lost += video_timing_read_l;
#endif
// pclog("Readl %05X ", addr);
addr = (addr & svga->banked_mask) + svga->read_bank;
addr &= svga->decode_mask;
// pclog("%08X %08X\n", addr, *(uint32_t *)&vram[addr]);
if (addr >= svga->vram_max)
return 0xffffffff;
return *(uint32_t *)&svga->vram[addr & svga->vram_mask];
}
void svga_writew_linear(uint32_t addr, uint16_t val, void *p)
{
svga_t *svga = (svga_t *)p;
if (!svga->fast)
{
svga_write_linear(addr, val, p);
svga_write_linear(addr + 1, val >> 8, p);
return;
}
#if 0
egawrites += 2;
cycles -= video_timing_write_w;
cycles_lost += video_timing_write_w;
if (svga_output) pclog("Write LFBw %08X %04X\n", addr, val);
#endif
addr &= svga->decode_mask;
if (addr >= svga->vram_max)
return;
addr &= svga->vram_mask;
svga->changedvram[addr >> 12] = changeframecount;
*(uint16_t *)&svga->vram[addr] = val;
}
void svga_writel_linear(uint32_t addr, uint32_t val, void *p)
{
svga_t *svga = (svga_t *)p;
if (!svga->fast)
{
svga_write_linear(addr, val, p);
svga_write_linear(addr + 1, val >> 8, p);
svga_write_linear(addr + 2, val >> 16, p);
svga_write_linear(addr + 3, val >> 24, p);
return;
}
#if 0
egawrites += 4;
cycles -= video_timing_write_l;
cycles_lost += video_timing_write_l;
if (svga_output) pclog("Write LFBl %08X %08X\n", addr, val);
#endif
addr &= svga->decode_mask;
if (addr >= svga->vram_max)
return;
addr &= svga->vram_mask;
svga->changedvram[addr >> 12] = changeframecount;
*(uint32_t *)&svga->vram[addr] = val;
}
uint16_t svga_readw_linear(uint32_t addr, void *p)
{
svga_t *svga = (svga_t *)p;
if (!svga->fast)
return svga_read_linear(addr, p) | (svga_read_linear(addr + 1, p) << 8);
#if 0
egareads += 2;
cycles -= video_timing_read_w;
cycles_lost += video_timing_read_w;
#endif
addr &= svga->decode_mask;
if (addr >= svga->vram_max)
return 0xffff;
return *(uint16_t *)&svga->vram[addr & svga->vram_mask];
}
uint32_t svga_readl_linear(uint32_t addr, void *p)
{
svga_t *svga = (svga_t *)p;
if (!svga->fast)
return svga_read_linear(addr, p) | (svga_read_linear(addr + 1, p) << 8) | (svga_read_linear(addr + 2, p) << 16) | (svga_read_linear(addr + 3, p) << 24);
#if 0
egareads += 4;
cycles -= video_timing_read_l;
cycles_lost += video_timing_read_l;
#endif
addr &= svga->decode_mask;
if (addr >= svga->vram_max)
return 0xffffffff;
return *(uint32_t *)&svga->vram[addr & svga->vram_mask];
}
void svga_add_status_info(char *s, int max_len, void *p)
{
svga_t *svga = (svga_t *)p;
char temps[128];
if (svga->chain4) strcpy(temps, "SVGA chained (possibly mode 13h) ");
else strcpy(temps, "SVGA unchained (possibly mode-X) ");
strncat(s, temps, max_len);
if (!svga->video_bpp) strcpy(temps, "SVGA in text mode ");
else sprintf(temps, "SVGA colour depth : %i bpp ", svga->video_bpp);
strncat(s, temps, max_len);
sprintf(temps, "SVGA resolution : %i x %i\n", svga->video_res_x, svga->video_res_y);
strncat(s, temps, max_len);
#if 0
sprintf(temps, "SVGA refresh rate : %i Hz\n\n", svga->frames);
svga->frames = 0;
strncat(s, temps, max_len);
#endif
}
|
#pragma once
namespace Dialogs
{
void Monpac();
void FilterHistory();
void QuickFilter();
void Stages();
}
|
#ifndef SRC_PT_EQ_H
#define SRC_PT_EQ_H
/// @file src/pt/Eq.h
/// @brief Eq のヘッダファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2005-2011 Yusuke Matsunaga
/// All rights reserved.
#include "Constr.h"
BEGIN_NAMESPACE_YM_BB
//////////////////////////////////////////////////////////////////////
/// @class Eq Eq.h "Eq.h"
/// @brief 等式を表すクラス
//////////////////////////////////////////////////////////////////////
class Eq :
public Constr
{
public:
/// @brief コンストラクタ
/// @param[in] file_region ファイル上の位置
/// @param[in] lhs 左辺式
/// @param[in] rhs 右辺式
Eq(const FileRegion& file_region,
PtNode* lhs,
PtNode* rhs);
/// @brief デストラクタ
virtual
~Eq();
public:
/// @brief 式の型を得る.
virtual
tType
type() const;
/// @brief 対応した AIG を作る.
virtual
void
gen_aig(AigMgr& aigmgr,
const vector<Aig>& bvar_array,
ymuint bw,
vector<Aig>& tmp_list);
};
END_NAMESPACE_YM_BB
#endif // SRC_PT_EQ_H
|
#include <characters/wise_man.h>
using namespace lab3::characters;
Wise_Man::Wise_Man(const std::string &name, Place *place)
: Human(name, TYPE_HUMAN, place),
will_tell_about_wizard_(false),
knowledge_(0)
{
this->talk_msgs_ =
{
"The princess is trapped in the Kings Castle."
"You need a good equipment in order to defeat the final monster."
"You should train a bit in the forest in order to gain experience, strength and money."
"When you are ready, you need to open the Kings Castle and defeat the monster. The last time"
" I saw the key was in the Dark Cave, but you will need a good illumination to find it. Good luck!"
};
}
Wise_Man::~Wise_Man()
{}
ActionResult Wise_Man::action(bool display_info)
{
Character* player = this->currentPlace()->getCharacter(NAME_PLAYER);
if(player != nullptr)
{
return talk_to(*player);
}
else
{
return this->read();
}
return EVENT_NULL;
}
ActionResult Wise_Man::talk_to(Character &c)
{
Character::talk_to(c);
if(will_tell_about_wizard_)
{
lab3::utils_io::wait_for_enter();
will_tell_about_wizard_ = false;
return ActionResult(true,EVENT_MENTIONED_WIZARD);
}
return true;
}
void Wise_Man::setTellAboutWizard(bool x)
{
will_tell_about_wizard_ = x;
}
ActionResult Wise_Man::read()
{
this->knowledge_ += WISE_MAN_READ_POINTS;
std::stringstream ss;
ss << "The "<<this->name() << " reads an ancient book. His knowledge is increased up to "<<this->knowledge_<<" points";
lab3::utils_io::print_newline(ss.str());
return true;
}
int Wise_Man::getKnowledgePoints() const { return this->knowledge_;}
|
#include <bits/stdc++.h>
#define ll long long
#define rep(i, x, y) for(int i = x; i <= y; i ++)
#define rrep(i, x, y) for(int i = x; i >= y; i --)
using namespace std;
char s[1000010];
int main()
{
scanf("%s", s + 1);
int len = strlen(s + 1);
ll sum = 0, num = 0;
rrep(i, len, 1)
if(s[i] == '1') sum += (len - num - i), num ++;
if(sum % 3) puts("Alice");
else puts("Bob");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.