text
stringlengths 54
60.6k
|
|---|
<commit_before>#pragma once
#include <vpp/core/image2d.hh>
#include <vpp/draw/draw.hh>
#include <vpp/core/keypoint_trajectory.hh>
#include <iod/sio_utils.hh>
#include <vpp/algorithms/Line_tracker_4_sfm/miscellanous/operations.hh>
#include <opencv2/highgui.hpp>
#include "draw_line_hough.hh"
#include "track.hh"
using namespace vpp;
using namespace cv;
namespace vpp {
void paint_hough_video(std::vector<track>& trs,
image2d<vuchar4>& paint_buffer)
{
// Decrease opacity.
pixel_wise(paint_buffer) | [] (vuchar4& v) {
v[3] *= 0.97;
};
#pragma omp parallel for
for (int i = 0; i < trs.size(); i++)
{
auto& t = trs[i];
if (!t.isAlive() or t.size() == 0) continue;
//if (t.alive() && t.size() > 1)
{
vint2 p1 = t.position_at_frame(t.last_frame()).template cast<int>();
vint2 p2 = t.position_at_frame(t.last_frame() - 1).template cast<int>();
vint2 p3 = t.position_at_frame(t.last_frame() - std::min(t.size() - 1, 10)).template cast<int>();
float speed = (p3 - p1).norm();
vuchar3 pt_color = hsv_to_rgb((M_PI + atan2(p3[0] - p1[0], p3[1] - p1[1])) * 180.f / M_PI,
1.f, 1.f);
float alpha = std::min(1.f, speed / 10);
auto paint = [&] (vint2 x, float a)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
c.template segment<3>(0) = pt_color;
c[3] = 255*1*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
auto paint2 = [&] (vint2 x, float a, int d)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
c.template segment<3>(0) = pt_color;
c[3] = 255*0.7*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
if ((p1 - p3).norm() > 5)
draw::line2d(p1, p2, paint, paint2);
}
}
}
void paint_original_video(std::vector<track>& trs,
image2d<vuchar4>& paint_buffer,int T_theta,
int nrows,int ncols)
{
// Decrease opacity.
pixel_wise(paint_buffer) | [] (vuchar4& v) {
v[3] *= 0.97;
};
#pragma omp parallel for
for (int i = 0; i < trs.size(); i++)
{
auto& t = trs[i];
if (!t.isAlive() or t.size() == 0) continue;
//if (t.alive() && t.size() > 1)
{
vint2 p1 = t.position_at_frame(t.last_frame()).template cast<int>();
vint2 p2 = t.position_at_frame(t.last_frame() - 1).template cast<int>();
vint2 p3 = t.position_at_frame(t.last_frame() - std::min(t.size() - 1, 10)).template cast<int>();
float speed = (p3 - p1).norm();
vuchar3 pt_color = hsv_to_rgb((M_PI + atan2(p3[0] - p1[0], p3[1] - p1[1])) * 180.f / M_PI,
1.f, 1.f);
float alpha = std::min(1.f, speed / 10);
auto paint = [&] (vint2 x, float a)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
//c.template segment<3>(0) = pt_color;
c.template segment<3>(0) = t.color;
c[3] = 255*1*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
auto paint2 = [&] (vint2 x, float a, int d)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
c.template segment<3>(0) = t.color;
c[3] = 255*0.7*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
if ((p1 - p3).norm() > 5)
{
float cosinus,sinus;
vint4 ligne = getLineFromPoint_Fast(p1[0],p1[1],T_theta,nrows,ncols,cosinus,sinus);
draw::line2d(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2);
ligne = getLineFromPoint_Fast(p2[0],p2[1],T_theta,nrows,ncols,cosinus,sinus);
draw::line2d(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2);
/*float cosinus,sinus;
image2d<uchar> grad_img = t.gradient_image_at_frame(t.last_frame());
vint4 ligne = getLineFromPoint_Fast(p1[0],p1[1],T_theta,nrows,ncols,cosinus,sinus);
line2d_hough(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2,grad_img);
ligne = getLineFromPoint_Fast(p2[0],p2[1],T_theta,nrows,ncols,cosinus,sinus);
grad_img = t.gradient_image_at_frame(t.last_frame() - 1);
line2d_hough(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2,grad_img);*/
}
}
}
}
void paint_original_video_particle(std::vector<track>& trs,
image2d<vuchar4>& paint_buffer,int T_theta,
int nrows,int ncols)
{
// Decrease opacity.
pixel_wise(paint_buffer) | [] (vuchar4& v) {
v[3] *= 0.97;
};
//#pragma omp parallel for
for (int i = 0; i < trs.size(); i++)
{
auto& t = trs[i];
if (!t.isAlive() or t.size() == 0) continue;
//if (t.alive() && t.size() > 1)
{
vint2 p1 = t.position_at_frame(t.last_frame()).template cast<int>();
vint2 p2 = t.position_at_frame(t.last_frame() - 1).template cast<int>();
vint2 p3 = t.position_at_frame(t.last_frame() - std::min(t.size() - 1, 10)).template cast<int>();
float speed = (p3 - p1).norm();
vuchar3 pt_color = hsv_to_rgb((M_PI + atan2(p3[0] - p1[0], p3[1] - p1[1])) * 180.f / M_PI,
1.f, 1.f);
float alpha = std::min(1.f, speed / 10);
auto paint = [&] (vint2 x, float a)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
//c.template segment<3>(0) = pt_color;
c.template segment<3>(0) = t.color;
c[3] = 255*1*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
auto paint2 = [&] (vint2 x, float a, int d)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
c.template segment<3>(0) = t.color;
c[3] = 255*0.7*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
if ((p1 - p3).norm() > 5)
{
std::list<vint2> list_p1 = t.list_point_at_frame_image(t.last_frame());
std::list<vint2> list_p2 = t.list_point_at_frame_image(t.last_frame() - 1);
//cout << "here" << endl;
float cosinus,sinus;
vint4 ligne = getLineFromPoint_Fast(p1[0],p1[1],T_theta,nrows,ncols,cosinus,sinus);
line2d_hough_particles(list_p1,vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2);
ligne = getLineFromPoint_Fast(p2[0],p2[1],T_theta,nrows,ncols,cosinus,sinus);
line2d_hough_particles(list_p2,vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2);
/*float cosinus,sinus;
image2d<uchar> grad_img = t.gradient_image_at_frame(t.last_frame());
vint4 ligne = getLineFromPoint_Fast(p1[0],p1[1],T_theta,nrows,ncols,cosinus,sinus);
line2d_hough(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2,grad_img);
ligne = getLineFromPoint_Fast(p2[0],p2[1],T_theta,nrows,ncols,cosinus,sinus);
grad_img = t.gradient_image_at_frame(t.last_frame() - 1);
line2d_hough(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2,grad_img);*/
}
}
}
}
}
<commit_msg>Update painting<commit_after>#pragma once
#include <vpp/core/image2d.hh>
#include <vpp/draw/draw.hh>
#include <vpp/core/keypoint_trajectory.hh>
#include <iod/sio_utils.hh>
#include <vpp/algorithms/Line_tracker_4_sfm/miscellanous/operations.hh>
#include <opencv2/highgui.hpp>
#include "draw_line_hough.hh"
#include "track.hh"
using namespace vpp;
using namespace cv;
namespace vpp {
void paint_hough_video(std::vector<track>& trs,
image2d<vuchar4>& paint_buffer)
{
// Decrease opacity.
pixel_wise(paint_buffer) | [] (vuchar4& v) {
v[3] *= 0.97;
};
#pragma omp parallel for
for (int i = 0; i < trs.size(); i++)
{
auto& t = trs[i];
if (!t.isAlive() or t.size() == 0) continue;
//if (t.alive() && t.size() > 1)
{
vint2 p1 = t.position_at_frame(t.last_frame()).template cast<int>();
vint2 p2 = t.position_at_frame(t.last_frame() - 1).template cast<int>();
vint2 p3 = t.position_at_frame(t.last_frame() - std::min(t.size() - 1, 10)).template cast<int>();
float speed = (p3 - p1).norm();
vuchar3 pt_color = hsv_to_rgb((M_PI + atan2(p3[0] - p1[0], p3[1] - p1[1])) * 180.f / M_PI,
1.f, 1.f);
float alpha = std::min(1.f, speed / 10);
auto paint = [&] (vint2 x, float a)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
c.template segment<3>(0) = pt_color;
c[3] = 255*1*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
auto paint2 = [&] (vint2 x, float a, int d)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
c.template segment<3>(0) = pt_color;
c[3] = 255*0.7*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
if ((p1 - p3).norm() > 5)
draw::line2d(p1, p2, paint, paint2);
}
}
}
void paint_original_video(std::vector<track>& trs,
image2d<vuchar4>& paint_buffer,int T_theta,
int nrows,int ncols)
{
// Decrease opacity.
pixel_wise(paint_buffer) | [] (vuchar4& v) {
v[3] *= 0.97;
};
#pragma omp parallel for
for (int i = 0; i < trs.size(); i++)
{
auto& t = trs[i];
if (!t.isAlive() or t.size() == 0) continue;
//if (t.alive() && t.size() > 1)
{
vint2 p1 = t.position_at_frame(t.last_frame()).template cast<int>();
vint2 p2 = t.position_at_frame(t.last_frame() - 1).template cast<int>();
vint2 p3 = t.position_at_frame(t.last_frame() - std::min(t.size() - 1, 10)).template cast<int>();
float speed = (p3 - p1).norm();
vuchar3 pt_color = hsv_to_rgb((M_PI + atan2(p3[0] - p1[0], p3[1] - p1[1])) * 180.f / M_PI,
1.f, 1.f);
float alpha = std::min(1.f, speed / 10);
auto paint = [&] (vint2 x, float a)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
//c.template segment<3>(0) = pt_color;
c.template segment<3>(0) = t.color;
c[3] = 255*1*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
auto paint2 = [&] (vint2 x, float a, int d)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
c.template segment<3>(0) = t.color;
c[3] = 255*0.7*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
if ((p1 - p3).norm() > 5)
{
float cosinus,sinus;
vint4 ligne = getLineFromPoint_Fast(p1[0],p1[1],T_theta,nrows,ncols,cosinus,sinus);
draw::line2d(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2);
ligne = getLineFromPoint_Fast(p2[0],p2[1],T_theta,nrows,ncols,cosinus,sinus);
draw::line2d(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2);
/*float cosinus,sinus;
image2d<uchar> grad_img = t.gradient_image_at_frame(t.last_frame());
vint4 ligne = getLineFromPoint_Fast(p1[0],p1[1],T_theta,nrows,ncols,cosinus,sinus);
line2d_hough(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2,grad_img);
ligne = getLineFromPoint_Fast(p2[0],p2[1],T_theta,nrows,ncols,cosinus,sinus);
grad_img = t.gradient_image_at_frame(t.last_frame() - 1);
line2d_hough(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2,grad_img);*/
}
}
}
}
void paint_original_video_particle(std::vector<track>& trs,
image2d<vuchar4>& paint_buffer,int T_theta,
int nrows,int ncols)
{
// Decrease opacity.
pixel_wise(paint_buffer) | [] (vuchar4& v) {
v[3] *= 0.97;
};
//#pragma omp parallel for
for (int i = 0; i < trs.size(); i++)
{
auto& t = trs[i];
if (!t.isAlive() or t.size() == 0) continue;
//if (t.alive() && t.size() > 1)
{
vint2 p1 = t.position_at_frame(t.last_frame()).template cast<int>();
vint2 p2 = t.position_at_frame(t.last_frame() - 1).template cast<int>();
vint2 p3 = t.position_at_frame(t.last_frame() - std::min(t.size() - 1, 10)).template cast<int>();
float speed = (p3 - p1).norm();
vuchar3 pt_color = hsv_to_rgb((M_PI + atan2(p3[0] - p1[0], p3[1] - p1[1])) * 180.f / M_PI,
1.f, 1.f);
float alpha = std::min(1.f, speed / 10);
auto paint = [&] (vint2 x, float a)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
//c.template segment<3>(0) = pt_color;
c.template segment<3>(0) = t.color;
c[3] = 255*1*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
auto paint2 = [&] (vint2 x, float a, int d)
{
if (!paint_buffer.has(x)) return;
vuchar4 c;
c.template segment<3>(0) = t.color;
c[3] = 255*0.7*alpha;
vpp::draw::plot_color(paint_buffer, x, c);
};
if ((p1 - p3).norm() > 5)
{
std::list<vint2> list_p1 = t.list_point_at_frame_image(t.last_frame());
std::list<vint2> list_p2 = t.list_point_at_frame_image(t.last_frame() - 1);
//cout << "here" << endl;
float cosinus,sinus;
vint4 ligne = getLineFromPoint_Fast(p1[0],p1[1],T_theta,nrows,ncols,cosinus,sinus);
line2d_hough_particles(list_p1,vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2);
ligne = getLineFromPoint_Fast(p2[0],p2[1],T_theta,nrows,ncols,cosinus,sinus);
line2d_hough_particles(list_p2,vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2);
/*float cosinus,sinus;
image2d<uchar> grad_img = t.gradient_image_at_frame(t.last_frame());
vint4 ligne = getLineFromPoint_Fast(p1[0],p1[1],T_theta,nrows,ncols,cosinus,sinus);
line2d_hough(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2,grad_img);
ligne = getLineFromPoint_Fast(p2[0],p2[1],T_theta,nrows,ncols,cosinus,sinus);
grad_img = t.gradient_image_at_frame(t.last_frame() - 1);
line2d_hough(vint2(ligne[1],ligne[0]), vint2(ligne[3],ligne[2]), paint, paint2,grad_img);*/
}
}
}
}
}
<|endoftext|>
|
<commit_before>/*
===============================================================================
FILE: integercompressor.hpp
CONTENTS:
This compressor provides three different contexts for encoding integer
numbers whose range may lie anywhere between 1 and 31 bits, which is
specified with the SetPrecision function.
The compressor encodes two things:
(1) the number k of miss-predicted low-order bits and
(2) the k-bit number that corrects the missprediction
The k-bit number is usually coded broken in two chunks. The highest
bits are compressed using an arithmetic range table. The lower bits
are stored raw without predicive coding. How many of the higher bits
are compressed can be specified with BITS_HIGH. The default is 8.
PROGRAMMERS:
martin.isenburg@gmail.com
COPYRIGHT:
(c) 2005-2011, Martin Isenburg, LASSO - tools to catch reality
This is free software; you can redistribute and/or modify it under the
terms of the GNU Lesser General Licence as published by the Free Software
Foundation. See the COPYING file for more information.
This software is distributed WITHOUT ANY WARRANTY and without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
CHANGE HISTORY:
10 January 2011 -- licensing change for LGPL release and liblas integration
10 December 2010 -- unified for all entropy coders at Baeckerei Schaefer
31 October 2009 -- switched from the Rangecoder to the Entropycoder
30 September 2005 -- now splitting the corrector into raw and compressed bits
13 July 2005 -- created after returning with many mosquito bites from OBX
===============================================================================
*/
#ifndef INTEGER_COMPRESSOR_H
#define INTEGER_COMPRESSOR_H
#include "entropyencoder.hpp"
#include "entropydecoder.hpp"
class IntegerCompressor
{
public:
// Constructor & Deconstructor
IntegerCompressor(EntropyEncoder* enc, U32 bits=16, U32 contexts=1, U32 bits_high=8, U32 range=0);
IntegerCompressor(EntropyDecoder* dec, U32 bits=16, U32 contexts=1, U32 bits_high=8, U32 range=0);
~IntegerCompressor();
// Manage Compressor
void initCompressor();
void compress(I32 iPred, I32 iReal, U32 context=0);
// Manage Decompressor
void initDecompressor();
I32 decompress(I32 iPred, U32 context=0);
// Get the k corrector bits from the last compress/decompress call
U32 getK() const {return k;};
private:
void writeCorrector(I32 c, EntropyModel* model);
I32 readCorrector(EntropyModel* model);
U32 k;
U32 contexts;
U32 bits_high;
U32 bits;
U32 range;
U32 corr_bits;
U32 corr_range;
I32 corr_min;
I32 corr_max;
EntropyEncoder* enc;
EntropyDecoder* dec;
EntropyModel** mBits;
EntropyModel** mCorrector;
int** corr_histogram;
};
#endif
<commit_msg>fix seeking without chunk table<commit_after>/*
===============================================================================
FILE: integercompressor.hpp
CONTENTS:
This compressor provides three different contexts for encoding integer
numbers whose range may lie anywhere between 1 and 31 bits, which is
specified with the SetPrecision function.
The compressor encodes two things:
(1) the number k of miss-predicted low-order bits and
(2) the k-bit number that corrects the missprediction
The k-bit number is usually coded broken in two chunks. The highest
bits are compressed using an arithmetic range table. The lower bits
are stored raw without predicive coding. How many of the higher bits
are compressed can be specified with bits_high. The default is 8.
PROGRAMMERS:
martin.isenburg@gmail.com
COPYRIGHT:
(c) 2005-2011, Martin Isenburg, LASSO - tools to catch reality
This is free software; you can redistribute and/or modify it under the
terms of the GNU Lesser General Licence as published by the Free Software
Foundation. See the COPYING file for more information.
This software is distributed WITHOUT ANY WARRANTY and without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
CHANGE HISTORY:
10 January 2011 -- licensing change for LGPL release and liblas integration
10 December 2010 -- unified for all entropy coders at Baeckerei Schaefer
31 October 2009 -- switched from the Rangecoder to the Entropycoder
30 September 2005 -- now splitting the corrector into raw and compressed bits
13 July 2005 -- created after returning with many mosquito bites from OBX
===============================================================================
*/
#ifndef INTEGER_COMPRESSOR_HPP
#define INTEGER_COMPRESSOR_HPP
#include "entropyencoder.hpp"
#include "entropydecoder.hpp"
class IntegerCompressor
{
public:
// Constructor & Deconstructor
IntegerCompressor(EntropyEncoder* enc, U32 bits=16, U32 contexts=1, U32 bits_high=8, U32 range=0);
IntegerCompressor(EntropyDecoder* dec, U32 bits=16, U32 contexts=1, U32 bits_high=8, U32 range=0);
~IntegerCompressor();
// Manage Compressor
void initCompressor();
void compress(I32 iPred, I32 iReal, U32 context=0);
// Manage Decompressor
void initDecompressor();
I32 decompress(I32 iPred, U32 context=0);
// Get the k corrector bits from the last compress/decompress call
U32 getK() const {return k;};
private:
void writeCorrector(I32 c, EntropyModel* model);
I32 readCorrector(EntropyModel* model);
U32 k;
U32 contexts;
U32 bits_high;
U32 bits;
U32 range;
U32 corr_bits;
U32 corr_range;
I32 corr_min;
I32 corr_max;
EntropyEncoder* enc;
EntropyDecoder* dec;
EntropyModel** mBits;
EntropyModel** mCorrector;
int** corr_histogram;
};
#endif
<|endoftext|>
|
<commit_before>/**
* @file main.cpp
*
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Mellmann, Heinrich</a>
*/
#include "NaoController.h"
#include <glib.h>
#include <glib-object.h>
#include <signal.h>
//#include <rttools/rtthread.h>
#include <atomic>
using namespace naoth;
std::atomic_int framesSinceCognitionLastSeen;
void got_signal(int t)
{
if(t == SIGTERM) {
std::cout << "shutdown requested by kill signal" << t << std::endl;
} else if(t == SIGSEGV) {
std::cerr << "SEGMENTATION FAULT" << std::endl;
} else {
std::cerr << "catched unknown signal " << t << std::endl;
}
std::cout << "dumping traces" << std::endl;
Trace::getInstance().dump();
//StopwatchManager::getInstance().dump("cognition");
std::cout << "syncing file system..." ;
sync();
std::cout << " finished." << std::endl;
exit(0);
}//end got_signal
// a semaphore for sychronization with the DCM
sem_t* dcm_sem = SEM_FAILED;
/*
// Just some experiments with the RT-Threads
// not used yet
class TestThread : public RtThread
{
public:
TestThread(){}
~TestThread(){}
NaoController* theController;
virtual void *execute()
{
Stopwatch stopwatch;
while(true)
{
theController->callMotion();
if(sem_wait(dcm_sem) == -1)
{
cerr << "lock errno: " << errno << endl;
}
StopwatchManager::getInstance().notifyStop(stopwatch);
StopwatchManager::getInstance().notifyStart(stopwatch);
PLOT("_MotionCycle", stopwatch.lastValue);
}//end while
return NULL;
}
virtual void postExecute(){}
virtual void preExecute(){}
} motionRtThread;
*/
void* motionThreadCallback(void* ref)
{
framesSinceCognitionLastSeen = 0;
NaoController* theController = static_cast<NaoController*> (ref);
//Stopwatch stopwatch;
while(true)
{
if(framesSinceCognitionLastSeen > 4000)
{
std::cerr << std::endl;
std::cerr << "+==================================+" << std::endl;
std::cerr << "| NO MORE MESSAGES FROM COGNITION! |" << std::endl;
std::cerr << "+==================================+" << std::endl;
std::cerr << "dumping traces" << std::endl;
Trace::getInstance().dump();
//StopwatchManager::getInstance().dump("cognition");
#ifndef WIN32
std::cerr << "syncing file system..." ;
sync();
std::cerr << " finished." << std::endl;
#endif
ASSERT(false && "Cognition seems to be dead");
}//end if
framesSinceCognitionLastSeen++;
theController->runMotion();
if(sem_wait(dcm_sem) == -1) {
cerr << "lock errno: " << errno << endl;
}
//stopwatch.stop();
//stopwatch.start();
}//end while
return NULL;
}//end motionThreadCallback
#define TO_STRING_INT(x) #x
#define TO_STRING(x) TO_STRING_INT(x)
int main(int /*argc*/, char **/*argv[]*/)
{
std::cout << "==========================================" << std::endl;
std::cout << "NaoTH compiled on: " << __DATE__ << " at " << __TIME__ << std::endl;
#ifdef REVISION
std::cout << "Revision number: " << TO_STRING(REVISION) << std::endl;
#endif
#ifdef USER_NAME
std::cout << "Owner: " << TO_STRING(USER_NAME) << std::endl;
#endif
#ifdef BRANCH_PATH
std::cout << "Branch path: " << TO_STRING(BRANCH_PATH) << std::endl;
#endif
std::cout << "==========================================\n" << std::endl;
// init glib
g_type_init();
// react on "kill" and segmentation fault
struct sigaction saKill;
memset( &saKill, 0, sizeof(saKill) );
saKill.sa_handler = got_signal;
sigfillset(&saKill.sa_mask);
sigaction(SIGTERM,&saKill,NULL);
struct sigaction saSeg;
memset( &saSeg, 0, sizeof(saSeg) );
saSeg.sa_handler = got_signal;
sigfillset(&saSeg.sa_mask);
sigaction(SIGSEGV,&saSeg,NULL);
int retChDir = chdir("/home/nao");
if(retChDir != 0)
{
std::cerr << "Could not change working directory" << std::endl;
}
// O_CREAT - create a new semaphore if not existing
// open semaphore
if((dcm_sem = sem_open("motion_trigger", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, 0)) == SEM_FAILED)
{
perror("NaoController: sem_open");
exit(-1);
}
// create the controller
NaoController theController;
naoth::init_agent(theController);
// waiting for the first rise of the semaphore
// bevore starting the threads
sem_wait(dcm_sem);
// create the motion thread
// !!we use here a pthread directly, because std::thread doesn't support priorities
pthread_t motionThread;
pthread_create(&motionThread, 0, motionThreadCallback, (void*)&theController);
// set the pririty of the motion thread to 50
sched_param param;
param.sched_priority = 50;
pthread_setschedparam(motionThread, SCHED_FIFO, ¶m);
std::thread cognitionThread = std::thread([&theController]
{
while(true) {
theController.runCognition();
framesSinceCognitionLastSeen = 0;
std::this_thread::yield();
}
});
//if(motionThread != NULL)
{
pthread_join(motionThread, NULL);
}
if(cognitionThread.joinable())
{
cognitionThread.join();
}
return 0;
}//end main
<commit_msg>listen to the SIGINT dump trace only on SIGSEGV (dumping traces is slow and is unnecessary in general)<commit_after>/**
* @file main.cpp
*
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Mellmann, Heinrich</a>
*/
#include "NaoController.h"
#include <glib.h>
#include <glib-object.h>
#include <signal.h>
//#include <rttools/rtthread.h>
#include <atomic>
#include <errno.h>
#define handle_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
using namespace naoth;
std::atomic_int framesSinceCognitionLastSeen;
void got_signal(int t)
{
if(t == SIGTERM || t == SIGINT) {
std::cout << "shutdown requested by kill signal" << t << std::endl;
}
else if(t == SIGSEGV)
{
std::cerr << "SEGMENTATION FAULT" << std::endl;
std::cout << "dumping traces" << std::endl;
Trace::getInstance().dump();
//StopwatchManager::getInstance().dump("cognition");
std::cout << "syncing file system..." ;
sync();
std::cout << " finished." << std::endl;
} else {
std::cerr << "caught unknown signal " << t << std::endl;
}
exit(0);
}//end got_signal
// a semaphore for sychronization with the DCM
sem_t* dcm_sem = SEM_FAILED;
/*
// Just some experiments with the RT-Threads
// not used yet
class TestThread : public RtThread
{
public:
TestThread(){}
~TestThread(){}
NaoController* theController;
virtual void *execute()
{
Stopwatch stopwatch;
while(true)
{
theController->callMotion();
if(sem_wait(dcm_sem) == -1)
{
cerr << "lock errno: " << errno << endl;
}
StopwatchManager::getInstance().notifyStop(stopwatch);
StopwatchManager::getInstance().notifyStart(stopwatch);
PLOT("_MotionCycle", stopwatch.lastValue);
}//end while
return NULL;
}
virtual void postExecute(){}
virtual void preExecute(){}
} motionRtThread;
*/
void* motionThreadCallback(void* ref)
{
framesSinceCognitionLastSeen = 0;
NaoController* theController = static_cast<NaoController*> (ref);
//Stopwatch stopwatch;
while(true)
{
if(framesSinceCognitionLastSeen > 4000)
{
std::cerr << std::endl;
std::cerr << "+==================================+" << std::endl;
std::cerr << "| NO MORE MESSAGES FROM COGNITION! |" << std::endl;
std::cerr << "+==================================+" << std::endl;
std::cerr << "dumping traces" << std::endl;
Trace::getInstance().dump();
//StopwatchManager::getInstance().dump("cognition");
#ifndef WIN32
std::cerr << "syncing file system..." ;
sync();
std::cerr << " finished." << std::endl;
#endif
ASSERT(false && "Cognition seems to be dead");
}//end if
framesSinceCognitionLastSeen++;
theController->runMotion();
if(sem_wait(dcm_sem) == -1) {
cerr << "lock errno: " << errno << endl;
}
//stopwatch.stop();
//stopwatch.start();
}//end while
return NULL;
}//end motionThreadCallback
#define TO_STRING_INT(x) #x
#define TO_STRING(x) TO_STRING_INT(x)
int main(int /*argc*/, char **/*argv[]*/)
{
std::cout << "==========================================" << std::endl;
std::cout << "NaoTH compiled on: " << __DATE__ << " at " << __TIME__ << std::endl;
#ifdef REVISION
std::cout << "Revision number: " << TO_STRING(REVISION) << std::endl;
#endif
#ifdef USER_NAME
std::cout << "Owner: " << TO_STRING(USER_NAME) << std::endl;
#endif
#ifdef BRANCH_PATH
std::cout << "Branch path: " << TO_STRING(BRANCH_PATH) << std::endl;
#endif
std::cout << "==========================================\n" << std::endl;
// init glib
g_type_init();
// react on "kill" and segmentation fault
struct sigaction saKill;
memset( &saKill, 0, sizeof(saKill) );
saKill.sa_handler = got_signal;
sigfillset(&saKill.sa_mask);
sigaction(SIGTERM,&saKill,NULL);
struct sigaction saInt;
memset( &saInt, 0, sizeof(saInt) );
saInt.sa_handler = got_signal;
sigfillset(&saInt.sa_mask);
sigaction(SIGINT,&saInt,NULL);
struct sigaction saSeg;
memset( &saSeg, 0, sizeof(saSeg) );
saSeg.sa_handler = got_signal;
sigfillset(&saSeg.sa_mask);
sigaction(SIGSEGV,&saSeg,NULL);
int retChDir = chdir("/home/nao");
if(retChDir != 0)
{
std::cerr << "Could not change working directory" << std::endl;
}
// O_CREAT - create a new semaphore if not existing
// open semaphore
if((dcm_sem = sem_open("motion_trigger", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, 0)) == SEM_FAILED)
{
perror("NaoController: sem_open");
exit(-1);
}
// create the controller
NaoController theController;
naoth::init_agent(theController);
// waiting for the first rise of the semaphore
// bevore starting the threads
sem_wait(dcm_sem);
// create the motion thread
// !!we use here a pthread directly, because std::thread doesn't support priorities
pthread_t motionThread;
int err = pthread_create(&motionThread, NULL, motionThreadCallback, (void*)&theController);
if (err != 0) {
handle_error_en(err, "create motionThread");
}
// set the pririty of the motion thread to 50
sched_param param;
param.sched_priority = 50;
err = pthread_setschedparam(motionThread, SCHED_FIFO, ¶m);
if (err != 0) {
handle_error_en(err, "set priority motionThread");
}
std::thread cognitionThread = std::thread([&theController]
{
while(true) {
theController.runCognition();
framesSinceCognitionLastSeen = 0;
std::this_thread::yield();
}
});
//if(motionThread != NULL)
{
pthread_join(motionThread, NULL);
}
if(cognitionThread.joinable())
{
cognitionThread.join();
}
exit (0);
}//end main
<|endoftext|>
|
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "open_spiel/games/mfg/crowd_modelling_2d.h"
#include <random>
#include <string>
#include <vector>
#include "open_spiel/abseil-cpp/absl/random/uniform_int_distribution.h"
#include "open_spiel/spiel.h"
#include "open_spiel/tests/basic_tests.h"
namespace open_spiel {
namespace crowd_modelling_2d {
namespace {
namespace testing = open_spiel::testing;
void TestLoad() {
testing::LoadGameTest("mfg_crowd_modelling_2d");
auto game = LoadGame("mfg_crowd_modelling_2d");
SPIEL_CHECK_EQ(game->GetType().dynamics, GameType::Dynamics::kMeanField);
auto state = game->NewInitialState();
auto cloned = state->Clone();
SPIEL_CHECK_EQ(state->ToString(), cloned->ToString());
testing::ChanceOutcomesTest(*game);
}
void TestLoadWithParams() {
auto game = LoadGame(
"mfg_crowd_modelling_2d(size=100,horizon=1000,"
"only_distribution_reward=true)");
auto state = game->NewInitialState();
SPIEL_CHECK_EQ(game->ObservationTensorShape()[0], 1000 + 2 * 100 + 1);
}
void TestLoadWithParams2() {
auto game = LoadGame(
"mfg_crowd_modelling_2d(size=100,horizon=1000,forbidden_states=[0|0;0|1]"
",initial_distribution=[0|2;0|3],initial_distribution_value=[0.5;0.5]"
")");
auto state = game->NewInitialState();
SPIEL_CHECK_EQ(game->ObservationTensorShape()[0], 1000 + 2 * 100 + 1);
}
void TestRandomPlay() {
std::mt19937 rng(7);
// TODO(author15): Should we adapt and use testing::RandomSimTest instead?
auto game = LoadGame("mfg_crowd_modelling_2d(size=10,horizon=20)");
auto state = game->NewInitialState();
int t = 0;
int num_moves = 0;
while (!state->IsTerminal()) {
SPIEL_CHECK_LT(state->MoveNumber(), game->MaxMoveNumber());
SPIEL_CHECK_EQ(state->MoveNumber(), num_moves);
testing::CheckLegalActionsAreSorted(*game, *state);
if (state->CurrentPlayer() == kChancePlayerId) {
auto cloned = state->Clone();
SPIEL_CHECK_EQ(state->ToString(), cloned->ToString());
ActionsAndProbs outcomes = state->ChanceOutcomes();
SPIEL_CHECK_EQ(state->LegalActions().size(), outcomes.size());
Action action = open_spiel::SampleAction(outcomes, rng).first;
state->ApplyAction(action);
++num_moves;
} else if (state->CurrentPlayer() == kMeanFieldPlayerId) {
auto support = state->DistributionSupport();
state->UpdateDistribution(
std::vector<double>(support.size(), 1. / support.size()));
} else {
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
auto cloned = state->Clone();
SPIEL_CHECK_EQ(state->ToString(), cloned->ToString());
std::vector<Action> actions = state->LegalActions();
std::uniform_int_distribution<int> dis(0, actions.size() - 1);
Action action = actions[dis(rng)];
state->ApplyAction(action);
++t;
++num_moves;
}
}
SPIEL_CHECK_EQ(t, 20);
SPIEL_CHECK_EQ(state->MoveNumber(), game->MaxMoveNumber());
SPIEL_CHECK_EQ(state->MoveNumber(), num_moves);
}
void TestReward() {
auto game = LoadGame("mfg_crowd_modelling_2d(size=10,horizon=20)");
auto state = game->NewInitialState();
SPIEL_CHECK_EQ(state->CurrentPlayer(), kChancePlayerId);
state->ApplyAction(55);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
// This expected reward assumes that the game is initialized with
// a uniform state distribution.
SPIEL_CHECK_FLOAT_EQ(state->Rewards()[0], 1. + std::log(100));
SPIEL_CHECK_FLOAT_EQ(state->Returns()[0], 1. + std::log(100));
state->ApplyAction(2);
SPIEL_CHECK_EQ(state->CurrentPlayer(), kChancePlayerId);
SPIEL_CHECK_FLOAT_EQ(state->Rewards()[0], 0.);
SPIEL_CHECK_FLOAT_EQ(state->Returns()[0], 1. + std::log(100));
}
void TestProcess() {
auto split_string_list0 = ProcessStringParam("[]", 5);
SPIEL_CHECK_EQ(split_string_list0.size(), 0);
auto split_string_list1 = ProcessStringParam("[0|0;0|1]", 5);
SPIEL_CHECK_EQ(split_string_list1.size(), 2);
auto split_string_list2 = ProcessStringParam("[0|2;0|3;0|4]", 5);
SPIEL_CHECK_EQ(split_string_list2.size(), 3);
auto split_string_list3 = ProcessStringParam("[0.5;0.5]", 5);
SPIEL_CHECK_EQ(split_string_list3.size(), 2);
}
} // namespace
} // namespace crowd_modelling_2d
} // namespace open_spiel
int main(int argc, char** argv) {
open_spiel::crowd_modelling_2d::TestLoad();
open_spiel::crowd_modelling_2d::TestLoadWithParams();
open_spiel::crowd_modelling_2d::TestLoadWithParams2();
open_spiel::crowd_modelling_2d::TestRandomPlay();
// TODO(perolat): enable TestReward once it works.
// open_spiel::crowd_modelling_2d::TestReward();
open_spiel::crowd_modelling_2d::TestProcess();
}
<commit_msg>Use random simulation for crowd modelling 2d test<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "open_spiel/games/mfg/crowd_modelling_2d.h"
#include <random>
#include <string>
#include <vector>
#include "open_spiel/abseil-cpp/absl/random/uniform_int_distribution.h"
#include "open_spiel/spiel.h"
#include "open_spiel/tests/basic_tests.h"
namespace open_spiel {
namespace crowd_modelling_2d {
namespace {
namespace testing = open_spiel::testing;
void TestLoad() {
testing::LoadGameTest("mfg_crowd_modelling_2d");
auto game = LoadGame("mfg_crowd_modelling_2d");
SPIEL_CHECK_EQ(game->GetType().dynamics, GameType::Dynamics::kMeanField);
auto state = game->NewInitialState();
auto cloned = state->Clone();
SPIEL_CHECK_EQ(state->ToString(), cloned->ToString());
testing::ChanceOutcomesTest(*game);
}
void TestLoadWithParams() {
auto game = LoadGame(
"mfg_crowd_modelling_2d(size=100,horizon=1000,"
"only_distribution_reward=true)");
auto state = game->NewInitialState();
SPIEL_CHECK_EQ(game->ObservationTensorShape()[0], 1000 + 2 * 100 + 1);
}
void TestLoadWithParams2() {
auto game = LoadGame(
"mfg_crowd_modelling_2d(size=100,horizon=1000,forbidden_states=[0|0;0|1]"
",initial_distribution=[0|2;0|3],initial_distribution_value=[0.5;0.5]"
")");
auto state = game->NewInitialState();
SPIEL_CHECK_EQ(game->ObservationTensorShape()[0], 1000 + 2 * 100 + 1);
}
void TestRandomPlay() {
testing::LoadGameTest("mfg_crowd_modelling_2d(size=10,horizon=20)");
testing::RandomSimTest(*LoadGame("mfg_crowd_modelling_2d(size=10,horizon=20)"), 3);
}
void TestReward() {
auto game = LoadGame("mfg_crowd_modelling_2d(size=10,horizon=20)");
auto state = game->NewInitialState();
SPIEL_CHECK_EQ(state->CurrentPlayer(), kChancePlayerId);
state->ApplyAction(55);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
// This expected reward assumes that the game is initialized with
// a uniform state distribution.
SPIEL_CHECK_FLOAT_EQ(state->Rewards()[0], 1. + std::log(100));
SPIEL_CHECK_FLOAT_EQ(state->Returns()[0], 1. + std::log(100));
state->ApplyAction(2);
SPIEL_CHECK_EQ(state->CurrentPlayer(), kChancePlayerId);
SPIEL_CHECK_FLOAT_EQ(state->Rewards()[0], 0.);
SPIEL_CHECK_FLOAT_EQ(state->Returns()[0], 1. + std::log(100));
}
void TestProcess() {
auto split_string_list0 = ProcessStringParam("[]", 5);
SPIEL_CHECK_EQ(split_string_list0.size(), 0);
auto split_string_list1 = ProcessStringParam("[0|0;0|1]", 5);
SPIEL_CHECK_EQ(split_string_list1.size(), 2);
auto split_string_list2 = ProcessStringParam("[0|2;0|3;0|4]", 5);
SPIEL_CHECK_EQ(split_string_list2.size(), 3);
auto split_string_list3 = ProcessStringParam("[0.5;0.5]", 5);
SPIEL_CHECK_EQ(split_string_list3.size(), 2);
}
} // namespace
} // namespace crowd_modelling_2d
} // namespace open_spiel
int main(int argc, char** argv) {
open_spiel::crowd_modelling_2d::TestLoad();
open_spiel::crowd_modelling_2d::TestLoadWithParams();
open_spiel::crowd_modelling_2d::TestLoadWithParams2();
open_spiel::crowd_modelling_2d::TestRandomPlay();
// TODO(perolat): enable TestReward once it works.
// open_spiel::crowd_modelling_2d::TestReward();
open_spiel::crowd_modelling_2d::TestProcess();
}
<|endoftext|>
|
<commit_before>#/** \ingroup kernel
* \{
*
* \file kernel/memory_map.hpp
* \brief This file defines the memory map used by the
* kernel as well as some auxilliary types.
*/
#ifndef H_kernel_memory
#define H_kernel_memory
#include <common/types.hpp>
#include "dynarray.hpp"
#include "debug.hpp"
#include "constants.hpp"
#include <memory_resource>
#include <algorithm>
#include <limits>
namespace UtopiaOS
{
namespace kernel
{
/** \enum memory_type
* \brief Analogous to the UEFI memory type
* but contains only types the kernel
* actually knows about.
*/
enum class memory_type : common::uint32
{
general_purpose,
unusable
};
/** \struct memory_request
* \brief Encapsulates a memory requirement
* \tparam ALIGN Specifies the alignment
*/
template<std::size_t ALIGN>
struct memory_request
{
std::size_t size;
static constexpr std::size_t alignment = ALIGN;
};
/** \brief Aligns a pointer to a given alignment.
* \param[in] ptr The pointer to align
* \param[in] alignment The alignment to meet
* \returns An aligned pointer or 0 if the pointer
* could not be aligned.
*
* The aligned pointer is guaranteed to point to
* an address not smaller than the original pointer.
* It is guaranteed that there is no other aligned
* address in the range [\a ptr, \a return-value].
* If the pointer cannot be aligned, i.e it points
* to an address so large that the next aligned
* address would not fit into the data type,
* 0 is returned.
*
* \warning If \a alignment is not a power of two,
* the behaviour is undefined!
*/
static inline common::uintptr align( common::uintptr ptr, std::size_t alignment )
{
static_assert( std::numeric_limits<common::uintptr>::max() >=
std::numeric_limits<std::size_t>::max(),
"This implementation cannot guarantee to work." );
debug_assert( (alignment % 2) == 0, "alignment has to be a power of two" );
common::un mask = alignment - 1; // ...0000011111...
common::un diff = (ptr & mask);
if( diff == 0 )
return ptr;
return (ptr + alignment - diff);
}
/** \struct memory_descriptor
* \brief Analogous to a UEFI memory descriptor,
* but usable by the kernel. It also has
* a well-defined size.
*
* It is guaranteed that
* (\a start + \a number_of_pages * \a pagesize)
* does not overflow, where \a start is either
* \a physical_start or \a virtual_start
*/
struct memory_descriptor
{
memory_type type;
common::uint64 physical_start;
common::uint64 virtual_start;
common::uint64 number_of_pages;
/** \brief Construct a kernel-usable memory
* descriptor from a UEFI one.
*/
memory_descriptor( const UEFI::memory_descriptor_v1 &uefi_desc );
/** \brief Checks whether the memory described by
* the memory descriptor can be used to
* fulfil a memory request.
* \tparam ALIGN Specifies the alignment
* \returns \a true if the request can be fulfilled
* and \a false otherwise.
*/
template<std::size_t ALIGN>
bool can_meet_request( const memory_request<ALIGN> &request ) const
{
static_assert( std::numeric_limits<common::uintptr>::max() >=
std::numeric_limits<std::size_t>::max(),
"This implementation cannot guarantee to work." );
if( type != memory_type::general_purpose )
return false;
auto aligned_address = align( virtual_start, request.alignment );
common::uintptr request_end = aligned_address + request.size;
if( (request_end - virtual_start) / pagesize <= number_of_pages )
return true;
return false;
}
};
/** \class memory_map
* \brief The memory map used by the kernel
* \tparam Allocator The type of allocator to use
*
* It has some sanity guarantees that UEFI lacks, like:
* - fixed size of descriptors that is known compile-time
* - no overlaps
* - The memory descriptors always describe regions that
* are as large as possible, with lower ones always being
* full in a case of ambiguity.
*/
template<class Allocator>
class memory_map
{
public:
using allocator_type = Allocator;
private:
using desc_array = dynarray<memory_descriptor, allocator_type>;
desc_array descriptors;
/** \brief Convert a uefi memory map to a
* kernel-usable one.
* \param[in] uefi_map The UEFI memory map
* \param[in] The allocator to use
* \returns An array of descriptors with the guarantee
* that they do not overlap.
*/
static desc_array
convert_from_uefi( const UEFI::memory_map &uefi_map, allocator_type &&alloc )
{
desc_array stage1_descriptors( uefi_map.cbegin_v1(),
uefi_map.cend_v1(),
std::forward<allocator_type>( alloc ) );
/** \todo Now remedy all possible overlaps and
* any unnecessary fragmentation
*/
}
public:
/** \brief Returns a memory_request that when fulfilled
* will suffice to convert a UEFI memory map
* to a kernel-usable one.
* \param[in] uefi_map The UEFI memory map
* \returns The memory_request
*/
static memory_request<alignof(memory_descriptor)>
maximum_conversion_requirement( const UEFI::memory_map &uefi_map )
{
return { uefi_map.number_of_descriptors * sizeof(memory_descriptor) };
}
/** \brief Returns a memory_request that when fulfilled
* will suffice to copy the memory map.
* \returns The memory_request
*/
memory_request<alignof(memory_descriptor)> copy_requirement( void ) const
{
return { descriptors.size() * sizeof(memory_descriptor) };
}
/** \brief Constructs a kernel-usable memory map
* from a UEFI memory map.
* \param[in] uefi_map The UEFI memory map
* \param[in] alloc The allocator used to copy the
* memory map. It has to be able to
* allocate at least what is returned
* by \a maximum_conversion_requirement.
*/
memory_map( const UEFI::memory_map &uefi_map, allocator_type &&alloc )
: descriptors( convert_from_uefi( uefi_map,
std::forward<allocator_type>( alloc ) ) )
{}
/** \brief Returns a const iterator to the begin of
* the memory descriptor range.
* \returns A const iterator to the begin of
* the memory descriptor range
*/
typename desc_array::const_iterator cbegin( void ) const
{ return descriptors.cbegin(); }
/** \brief Returns a const iterator to the end of
* the memory descriptor range.
* \returns A const iterator to the end of
* the memory descriptor range
*/
typename desc_array::const_iterator cend( void ) const
{ return descriptors.cend(); }
};
}
}
#endif
/** \} */
<commit_msg>Implemented UEFI memory_descriptor to kernel memory descriptor conversion.<commit_after>#/** \ingroup kernel
* \{
*
* \file kernel/memory_map.hpp
* \brief This file defines the memory map used by the
* kernel as well as some auxilliary types.
*/
#ifndef H_kernel_memory
#define H_kernel_memory
#include <common/types.hpp>
#include "dynarray.hpp"
#include "debug.hpp"
#include "constants.hpp"
#include <memory_resource>
#include <algorithm>
#include <limits>
namespace UtopiaOS
{
namespace kernel
{
/** \enum memory_type
* \brief Analogous to the UEFI memory type
* but contains only types the kernel
* actually knows about.
*/
enum class memory_type : common::uint32
{
general_purpose,
unusable,
invalid
};
/** \struct memory_request
* \brief Encapsulates a memory requirement
* \tparam ALIGN Specifies the alignment
*/
template<std::size_t ALIGN>
struct memory_request
{
std::size_t size;
static constexpr std::size_t alignment = ALIGN;
};
/** \brief Aligns a pointer to a given alignment.
* \param[in] ptr The pointer to align
* \param[in] alignment The alignment to meet
* \returns An aligned pointer or 0 if the pointer
* could not be aligned.
*
* The aligned pointer is guaranteed to point to
* an address not smaller than the original pointer.
* It is guaranteed that there is no other aligned
* address in the range [\a ptr, \a return-value].
* If the pointer cannot be aligned, i.e it points
* to an address so large that the next aligned
* address would not fit into the data type,
* 0 is returned.
*
* \warning If \a alignment is not a power of two,
* the behaviour is undefined!
*/
static inline common::uintptr align( common::uintptr ptr, std::size_t alignment )
{
static_assert( std::numeric_limits<common::uintptr>::max() >=
std::numeric_limits<std::size_t>::max(),
"This implementation cannot guarantee to work." );
debug_assert( (alignment % 2) == 0, "alignment has to be a power of two" );
common::un mask = alignment - 1; // ...0000011111...
common::un diff = (ptr & mask);
if( diff == 0 )
return ptr;
return (ptr + alignment - diff);
}
/** \struct memory_descriptor
* \brief Analogous to a UEFI memory descriptor,
* but usable by the kernel. It also has
* a well-defined size.
*
* It is guaranteed that
* (\a start + \a number_of_pages * \a pagesize)
* does not overflow, where \a start is either
* \a physical_start or \a virtual_start.
* For memory_descriptor with its type set to
* \a memory_type::invalid the contents of the
* other fields are undefined.
*/
struct memory_descriptor
{
memory_type type;
common::uint64 physical_start;
common::uint64 virtual_start;
common::uint64 number_of_pages;
/** \brief Construct a kernel-usable memory
* descriptor from a UEFI one.
*
* \warning If there is an overflow in
* (\a start + \a number_of_pages * \a UEFI::pagesize)
* where \a start is either
* \a physical_start or \a virtual_start
* the memory_type will be set to unusable.
* \warning If the total memory block is smaller than
* the kernel pagesize the type will be set
* to invalid and the other fields are undefined.
* \warning If the kernel pagesize cannot be used to fully
* cover the memory region, the memory region
* will be truncated accordingly.
*/
memory_descriptor( const UEFI::memory_descriptor_v1 &uefi_desc )
: type( uefi_desc.type == UEFI::memory_type::EfiConventionalMemory ?
memory_type::general_purpose : memory_type::unusable ),
physical_start( uefi_desc.physical_start ),
virtual_start( uefi_desc.virtual_start ),
number_of_pages( (uefi_desc.number_of_pages * UEFI::pagesize) / pagesize )
{
if( number_of_pages == 0 )
type = memory_type::invalid;
}
/** \brief Checks whether the memory described by
* the memory descriptor can be used to
* fulfil a memory request.
* \tparam ALIGN Specifies the alignment
* \returns \a true if the request can be fulfilled
* and \a false otherwise.
*/
template<std::size_t ALIGN>
bool can_meet_request( const memory_request<ALIGN> &request ) const
{
static_assert( std::numeric_limits<common::uintptr>::max() >=
std::numeric_limits<std::size_t>::max(),
"This implementation cannot guarantee to work." );
if( type != memory_type::general_purpose )
return false;
auto aligned_address = align( virtual_start, request.alignment );
common::uintptr request_end = aligned_address + request.size;
if( (request_end - virtual_start) / pagesize <= number_of_pages )
return true;
return false;
}
};
/** \class memory_map
* \brief The memory map used by the kernel
* \tparam Allocator The type of allocator to use
*
* It has some sanity guarantees that UEFI lacks, like:
* - fixed size of descriptors that is known compile-time
* - no overlaps
* - The memory descriptors always describe regions that
* are as large as possible, with lower ones always being
* full in a case of ambiguity.
*/
template<class Allocator>
class memory_map
{
public:
using allocator_type = Allocator;
private:
using desc_array = dynarray<memory_descriptor, allocator_type>;
desc_array descriptors;
/** \brief Convert a uefi memory map to a
* kernel-usable one.
* \param[in] uefi_map The UEFI memory map
* \param[in] The allocator to use
* \returns An array of descriptors with the guarantee
* that they do not overlap.
*/
static desc_array
convert_from_uefi( const UEFI::memory_map &uefi_map, allocator_type &&alloc )
{
desc_array stage1_descriptors( uefi_map.cbegin_v1(),
uefi_map.cend_v1(),
std::forward<allocator_type>( alloc ) );
/** \todo Now remedy all possible overlaps and
* any unnecessary fragmentation
*/
}
public:
/** \brief Returns a memory_request that when fulfilled
* will suffice to convert a UEFI memory map
* to a kernel-usable one.
* \param[in] uefi_map The UEFI memory map
* \returns The memory_request
*/
static memory_request<alignof(memory_descriptor)>
maximum_conversion_requirement( const UEFI::memory_map &uefi_map )
{
return { uefi_map.number_of_descriptors * sizeof(memory_descriptor) };
}
/** \brief Returns a memory_request that when fulfilled
* will suffice to copy the memory map.
* \returns The memory_request
*/
memory_request<alignof(memory_descriptor)> copy_requirement( void ) const
{
return { descriptors.size() * sizeof(memory_descriptor) };
}
/** \brief Constructs a kernel-usable memory map
* from a UEFI memory map.
* \param[in] uefi_map The UEFI memory map
* \param[in] alloc The allocator used to copy the
* memory map. It has to be able to
* allocate at least what is returned
* by \a maximum_conversion_requirement.
*/
memory_map( const UEFI::memory_map &uefi_map, allocator_type &&alloc )
: descriptors( convert_from_uefi( uefi_map,
std::forward<allocator_type>( alloc ) ) )
{}
/** \brief Returns a const iterator to the begin of
* the memory descriptor range.
* \returns A const iterator to the begin of
* the memory descriptor range
*/
typename desc_array::const_iterator cbegin( void ) const
{ return descriptors.cbegin(); }
/** \brief Returns a const iterator to the end of
* the memory descriptor range.
* \returns A const iterator to the end of
* the memory descriptor range
*/
typename desc_array::const_iterator cend( void ) const
{ return descriptors.cend(); }
};
}
}
#endif
/** \} */
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <libport/format.hh>
#include <libport/lexical-cast.hh>
#include <kernel/uvalue-cast.hh>
#include <urbi/object/cxx-conversions.hh>
#include <urbi/object/float.hh>
#include <urbi/object/global.hh>
#include <urbi/object/list.hh>
#include <urbi/object/string.hh>
#include <object/symbols.hh>
#include <object/uvar.hh>
#include <runner/raise.hh>
#include <urbi/uvalue.hh>
urbi::UDataType uvalue_type(const object::rObject& o)
{
CAPTURE_GLOBAL(Binary);
if (object::rUValue bv = o->as<object::UValue>())
return bv->value_get().type;
if (o->as<object::Float>())
return urbi::DATA_DOUBLE;
if (o->as<object::String>())
return urbi::DATA_STRING;
if (o->as<object::List>())
return urbi::DATA_LIST;
if (is_a(o, Binary))
return urbi::DATA_BINARY;
if (o == object::void_class)
return urbi::DATA_VOID;
return urbi::DATA_OBJECT;
}
urbi::UValue uvalue_cast(const object::rObject& o)
{
CAPTURE_GLOBAL(Binary);
CAPTURE_GLOBAL(UObject);
CAPTURE_GLOBAL(UVar);
urbi::UValue res;
if (object::rUValue bv = o->as<object::UValue>())
return bv->value_get();
if (object::rFloat f = o->as<object::Float>())
res = f->value_get();
else if (object::rString s = o->as<object::String>())
res = s->value_get();
else if (object::rList s = o->as<object::List>())
{
res.type = urbi::DATA_LIST;
res.list = new urbi::UList;
object::List::value_type& t = o.cast<object::List>()->value_get();
foreach (const object::rObject& co, t)
res.list->array.push_back(new urbi::UValue(uvalue_cast(co)));
}
else if (is_a(o, Binary))
{
const std::string& data =
o->slot_get(SYMBOL(data))->as<object::String>()->value_get();
const std::string& keywords =
o->slot_get(SYMBOL(keywords))->
as<object::String>()->value_get();
std::list<urbi::BinaryData> l;
l.push_back(urbi::BinaryData(const_cast<char*>(data.c_str()),
data.size()));
std::list<urbi::BinaryData>::const_iterator i = l.begin();
res.type = urbi::DATA_BINARY;
res.binary = new urbi::UBinary();
res.binary->parse(
(boost::lexical_cast<std::string>(data.size()) +
" " + keywords + '\n').c_str(), 0, l, i);
}
else if (is_a(o, UObject))
{
res = o->slot_get(SYMBOL(__uobjectName))->as<object::String>()
->value_get();
}
else if (is_a(o, UVar))
{
res =
o->slot_get(SYMBOL(ownerName))->as<object::String>()->value_get()
+ "."
+ o->slot_get(SYMBOL(initialName))->as<object::String>()->value_get();
}
else // We could not find how to cast this value
{
const object::rString& rs =
o->slot_get(SYMBOL(type))->as<object::String>();
runner::raise_argument_type_error
(0, rs, object::to_urbi(SYMBOL(LT_exportable_SP_object_GT)),
object::to_urbi(SYMBOL(cast)));
}
return res;
}
object::rObject
object_cast(const urbi::UValue& v)
{
object::rObject res;
switch(v.type)
{
case urbi::DATA_DOUBLE:
return new object::Float(v.val);
break;
case urbi::DATA_STRING:
return new object::String(*v.stringValue);
break;
case urbi::DATA_LIST:
{
object::rList l = new object::List();
foreach (urbi::UValue *cv, v.list->array)
l->value_get().push_back(object_cast(*cv));
res = l;
break;
}
case urbi::DATA_BINARY:
{
CAPTURE_GLOBAL(Binary);
res = new object::Object();
res->proto_add(Binary);
std::string msg = v.binary->getMessage();
// Trim it.
if (!msg.empty() && msg[0] == ' ')
msg = msg.substr(1, msg.npos);
res->slot_set(SYMBOL(keywords),
new object::String(msg));
res->slot_set(SYMBOL(data),
new object::String
(std::string(static_cast<char*>(v.binary->common.data),
v.binary->common.size)));
}
break;
case urbi::DATA_VOID:
res = object::void_class;
break;
default:
static boost::format m("<external data with type %1%>");
runner::raise_argument_type_error
(0, object::to_urbi((m % v.type).str()),
object::Object::proto,
object::to_urbi(SYMBOL(backcast)));
}
return res;
}
<commit_msg>Accept booleans as bound UObjects methods arguments.<commit_after>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <libport/format.hh>
#include <libport/lexical-cast.hh>
#include <kernel/uvalue-cast.hh>
#include <urbi/object/cxx-conversions.hh>
#include <urbi/object/float.hh>
#include <urbi/object/global.hh>
#include <urbi/object/list.hh>
#include <urbi/object/string.hh>
#include <object/symbols.hh>
#include <object/uvar.hh>
#include <runner/raise.hh>
#include <urbi/uvalue.hh>
urbi::UDataType uvalue_type(const object::rObject& o)
{
CAPTURE_GLOBAL(Binary);
if (object::rUValue bv = o->as<object::UValue>())
return bv->value_get().type;
if (o->as<object::Float>())
return urbi::DATA_DOUBLE;
if (o->as<object::String>())
return urbi::DATA_STRING;
if (o->as<object::List>())
return urbi::DATA_LIST;
if (is_a(o, Binary))
return urbi::DATA_BINARY;
if (o == object::void_class)
return urbi::DATA_VOID;
return urbi::DATA_OBJECT;
}
urbi::UValue uvalue_cast(const object::rObject& o)
{
CAPTURE_GLOBAL(Binary);
CAPTURE_GLOBAL(UObject);
CAPTURE_GLOBAL(UVar);
urbi::UValue res;
if (object::rUValue bv = o->as<object::UValue>())
return bv->value_get();
else if (object::rFloat f = o->as<object::Float>())
res = f->value_get();
else if (o == object::true_class)
res = 1;
else if (o == object::false_class)
res = 0;
else if (object::rString s = o->as<object::String>())
res = s->value_get();
else if (object::rList s = o->as<object::List>())
{
res.type = urbi::DATA_LIST;
res.list = new urbi::UList;
object::List::value_type& t = o.cast<object::List>()->value_get();
foreach (const object::rObject& co, t)
res.list->array.push_back(new urbi::UValue(uvalue_cast(co)));
}
else if (is_a(o, Binary))
{
const std::string& data =
o->slot_get(SYMBOL(data))->as<object::String>()->value_get();
const std::string& keywords =
o->slot_get(SYMBOL(keywords))->
as<object::String>()->value_get();
std::list<urbi::BinaryData> l;
l.push_back(urbi::BinaryData(const_cast<char*>(data.c_str()),
data.size()));
std::list<urbi::BinaryData>::const_iterator i = l.begin();
res.type = urbi::DATA_BINARY;
res.binary = new urbi::UBinary();
res.binary->parse(
(boost::lexical_cast<std::string>(data.size()) +
" " + keywords + '\n').c_str(), 0, l, i);
}
else if (is_a(o, UObject))
{
res = o->slot_get(SYMBOL(__uobjectName))->as<object::String>()
->value_get();
}
else if (is_a(o, UVar))
{
res =
o->slot_get(SYMBOL(ownerName))->as<object::String>()->value_get()
+ "."
+ o->slot_get(SYMBOL(initialName))->as<object::String>()->value_get();
}
else // We could not find how to cast this value
{
const object::rString& rs =
o->slot_get(SYMBOL(type))->as<object::String>();
runner::raise_argument_type_error
(0, rs, object::to_urbi(SYMBOL(LT_exportable_SP_object_GT)),
object::to_urbi(SYMBOL(cast)));
}
return res;
}
object::rObject
object_cast(const urbi::UValue& v)
{
object::rObject res;
switch(v.type)
{
case urbi::DATA_DOUBLE:
return new object::Float(v.val);
break;
case urbi::DATA_STRING:
return new object::String(*v.stringValue);
break;
case urbi::DATA_LIST:
{
object::rList l = new object::List();
foreach (urbi::UValue *cv, v.list->array)
l->value_get().push_back(object_cast(*cv));
res = l;
break;
}
case urbi::DATA_BINARY:
{
CAPTURE_GLOBAL(Binary);
res = new object::Object();
res->proto_add(Binary);
std::string msg = v.binary->getMessage();
// Trim it.
if (!msg.empty() && msg[0] == ' ')
msg = msg.substr(1, msg.npos);
res->slot_set(SYMBOL(keywords),
new object::String(msg));
res->slot_set(SYMBOL(data),
new object::String
(std::string(static_cast<char*>(v.binary->common.data),
v.binary->common.size)));
}
break;
case urbi::DATA_VOID:
res = object::void_class;
break;
default:
static boost::format m("<external data with type %1%>");
runner::raise_argument_type_error
(0, object::to_urbi((m % v.type).str()),
object::Object::proto,
object::to_urbi(SYMBOL(backcast)));
}
return res;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <string>
#include "util/sstream.h"
#include "kernel/environment.h"
#include "kernel/type_checker.h"
#include "library/kernel_serializer.h"
#include "library/scoped_ext.h"
#include "library/reducible.h"
#include "library/attribute_manager.h"
namespace lean {
struct reducibility_attribute_data : public attr_data {
reducible_status m_status;
reducibility_attribute_data() {}
reducibility_attribute_data(reducible_status status) : m_status(status) {}
virtual unsigned hash() const override {
return static_cast<unsigned>(m_status);
}
void write(serializer & s) const {
s << static_cast<char>(m_status);
}
void read(deserializer & d) {
char c;
d >> c;
m_status = static_cast<reducible_status>(c);
}
};
template class typed_attribute<reducibility_attribute_data>;
typedef typed_attribute<reducibility_attribute_data> reducibility_attribute;
static reducibility_attribute const & get_reducibility_attribute() {
return static_cast<reducibility_attribute const &>(get_system_attribute("reducibility"));
}
class proxy_attribute : public basic_attribute {
private:
reducible_status m_status;
public:
proxy_attribute(char const * id, char const * descr, reducible_status m_status) : basic_attribute(id, descr),
m_status(m_status) {}
virtual attr_data_ptr get_untyped(environment const & env, name const & n) const override {
if (auto data = get_reducibility_attribute().get(env, n)) {
if (data->m_status == m_status)
return attr_data_ptr(new attr_data);
}
return {};
}
virtual environment set(environment const & env, io_state const & ios, name const & n,
unsigned prio, bool persistent) const override {
declaration const & d = env.get(n);
if (!d.is_definition())
throw exception(sstream() << "invalid reducible command, '" << n << "' is not a definition");
return get_reducibility_attribute().set(env, ios, n, prio, {m_status}, persistent);
}
virtual environment unset(environment, io_state const &, name const &, bool) const override {
throw exception(sstream() << "cannot remove attribute [" << get_name() << "]");
}
virtual void get_instances(environment const & env, buffer<name> & r) const override {
buffer<name> tmp;
get_reducibility_attribute().get_instances(env, tmp);
for (name const & n : tmp)
if (is_instance(env, n))
r.push_back(n);
}
virtual unsigned get_fingerprint(environment const & env) const override {
return get_reducibility_attribute().get_fingerprint(env);
}
};
void initialize_reducible() {
register_system_attribute(reducibility_attribute("reducibility", "internal attribute for storing reducibility"));
register_system_attribute(proxy_attribute("reducible", "reducible", reducible_status::Reducible));
register_system_attribute(proxy_attribute("semireducible", "semireducible", reducible_status::Semireducible));
register_system_attribute(proxy_attribute("irreducible", "irreducible", reducible_status::Irreducible));
register_incompatible("reducible", "semireducible");
register_incompatible("reducible", "irreducible");
register_incompatible("semireducible", "irreducible");
}
void finalize_reducible() {
}
environment set_reducible(environment const & env, name const & n, reducible_status s, bool persistent) {
return get_reducibility_attribute().set(env, get_dummy_ios(), n, LEAN_DEFAULT_PRIORITY, {s}, persistent);
}
reducible_status get_reducible_status(environment const & env, name const & n) {
auto data = get_reducibility_attribute().get(env, n);
if (data)
return data->m_status;
return reducible_status::Semireducible;
}
name_predicate mk_not_reducible_pred(environment const & env) {
return [=](name const & n) { // NOLINT
return get_reducible_status(env, n) != reducible_status::Reducible;
};
}
name_predicate mk_irreducible_pred(environment const & env) {
return [=](name const & n) { // NOLINT
return get_reducible_status(env, n) == reducible_status::Irreducible;
};
}
old_type_checker_ptr mk_type_checker(environment const & env, reducible_behavior rb) {
switch (rb) {
case UnfoldReducible:
return mk_type_checker(env, mk_not_reducible_pred(env));
case UnfoldSemireducible:
return mk_type_checker(env, mk_irreducible_pred(env));
}
lean_unreachable();
}
old_type_checker_ptr mk_opaque_type_checker(environment const & env) {
return mk_type_checker(env, [](name const &) { return true; });
}
}
<commit_msg>refactor(library/reducible): rename proxy_attribute to reducibility_proxy_attribute<commit_after>/*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <string>
#include "util/sstream.h"
#include "kernel/environment.h"
#include "kernel/type_checker.h"
#include "library/kernel_serializer.h"
#include "library/scoped_ext.h"
#include "library/reducible.h"
#include "library/attribute_manager.h"
namespace lean {
struct reducibility_attribute_data : public attr_data {
reducible_status m_status;
reducibility_attribute_data() {}
reducibility_attribute_data(reducible_status status) : m_status(status) {}
virtual unsigned hash() const override {
return static_cast<unsigned>(m_status);
}
void write(serializer & s) const {
s << static_cast<char>(m_status);
}
void read(deserializer & d) {
char c;
d >> c;
m_status = static_cast<reducible_status>(c);
}
};
template class typed_attribute<reducibility_attribute_data>;
typedef typed_attribute<reducibility_attribute_data> reducibility_attribute;
static reducibility_attribute const & get_reducibility_attribute() {
return static_cast<reducibility_attribute const &>(get_system_attribute("reducibility"));
}
class reducibility_proxy_attribute : public basic_attribute {
private:
reducible_status m_status;
public:
reducibility_proxy_attribute(char const * id, char const * descr, reducible_status m_status):
basic_attribute(id, descr), m_status(m_status) {}
virtual attr_data_ptr get_untyped(environment const & env, name const & n) const override {
if (auto data = get_reducibility_attribute().get(env, n)) {
if (data->m_status == m_status)
return attr_data_ptr(new attr_data);
}
return {};
}
virtual environment set(environment const & env, io_state const & ios, name const & n,
unsigned prio, bool persistent) const override {
declaration const & d = env.get(n);
if (!d.is_definition())
throw exception(sstream() << "invalid reducible command, '" << n << "' is not a definition");
return get_reducibility_attribute().set(env, ios, n, prio, {m_status}, persistent);
}
virtual environment unset(environment, io_state const &, name const &, bool) const override {
throw exception(sstream() << "cannot remove attribute [" << get_name() << "]");
}
virtual void get_instances(environment const & env, buffer<name> & r) const override {
buffer<name> tmp;
get_reducibility_attribute().get_instances(env, tmp);
for (name const & n : tmp)
if (is_instance(env, n))
r.push_back(n);
}
virtual unsigned get_fingerprint(environment const & env) const override {
return get_reducibility_attribute().get_fingerprint(env);
}
};
void initialize_reducible() {
register_system_attribute(reducibility_attribute("reducibility", "internal attribute for storing reducibility"));
register_system_attribute(reducibility_proxy_attribute("reducible", "reducible", reducible_status::Reducible));
register_system_attribute(reducibility_proxy_attribute("semireducible", "semireducible", reducible_status::Semireducible));
register_system_attribute(reducibility_proxy_attribute("irreducible", "irreducible", reducible_status::Irreducible));
register_incompatible("reducible", "semireducible");
register_incompatible("reducible", "irreducible");
register_incompatible("semireducible", "irreducible");
}
void finalize_reducible() {
}
environment set_reducible(environment const & env, name const & n, reducible_status s, bool persistent) {
return get_reducibility_attribute().set(env, get_dummy_ios(), n, LEAN_DEFAULT_PRIORITY, {s}, persistent);
}
reducible_status get_reducible_status(environment const & env, name const & n) {
auto data = get_reducibility_attribute().get(env, n);
if (data)
return data->m_status;
return reducible_status::Semireducible;
}
name_predicate mk_not_reducible_pred(environment const & env) {
return [=](name const & n) { // NOLINT
return get_reducible_status(env, n) != reducible_status::Reducible;
};
}
name_predicate mk_irreducible_pred(environment const & env) {
return [=](name const & n) { // NOLINT
return get_reducible_status(env, n) == reducible_status::Irreducible;
};
}
old_type_checker_ptr mk_type_checker(environment const & env, reducible_behavior rb) {
switch (rb) {
case UnfoldReducible:
return mk_type_checker(env, mk_not_reducible_pred(env));
case UnfoldSemireducible:
return mk_type_checker(env, mk_irreducible_pred(env));
}
lean_unreachable();
}
old_type_checker_ptr mk_opaque_type_checker(environment const & env) {
return mk_type_checker(env, [](name const &) { return true; });
}
}
<|endoftext|>
|
<commit_before>/*
В программе ввести и инициализировать массив структур, каждая из которых
описывает материальную точку. Элементы структурного типа: координаты и
массы частиц, а также расстояния от центра масс до всех точек набора.
Окончание ввода - ннулевое значение массы точки.
Общая масса системы точек M = sum_{i} m_i, где под m_i обозначена масса
отдельных точек.
Координаты центра масс: x_c = sum_{i} (x_i * m_i) / M,
y_c = sum_{i} (y_i * m_i) / M, z_c = sum_{i} (z_i * m_i) / M
(x_i, y_i, z_i) - координаты отдельных точек.
Расстояние до центра масс определяется как:
r_i = sqrt( (x_i - x_c)^2 + (y_i - y_c)^2 + (z_i - z_c)^2 )
Версия для С++, но с использованием realloc / free для выделение памяти под массив простых структур.
*/
#include <iostream>
#include <cstdlib>
#include <clocale> // установка вывода русских букв в командную строку (больше нужна для Windows OS)
#include <cmath>
using namespace std;
struct MassPoint {
double coord[3];
double mass;
};
struct PointSet {
struct MassPoint m_point;
double distance;
};
int main(int argc, char *argv[])
{
setlocale(LC_ALL, "RUS");
int i, count = 0;
double rx, ry, rz;
struct PointSet mass_center = { {0., 0., 0., 0.}, 0. };
struct PointSet next_point;
struct PointSet *p_array = nullptr;
cout << "Введите точки (порядок ввода: масса, координата x, координата y, координата z).\nПоставьте 0 в качестве массы для прекращения задания точек" << endl;
while ( true ) {
cout << "Точка номер " << (count + 1) << endl << "\tмасса: ";
cin >> next_point.m_point.mass;
if ( next_point.m_point.mass < 0.0000000001 )
break;
cout << "\tкоординаты (3 значения через пробел): ";
cin >> next_point.m_point.coord[0] >> next_point.m_point.coord[1] >> next_point.m_point.coord[2];
count++;
p_array = (struct PointSet *) realloc(p_array, count * sizeof(struct PointSet));
if (p_array == nullptr) {
cerr << "Проблема с выделением дополнительно памяти\n";
return -1;
}
p_array[count - 1] = next_point;
mass_center.m_point.mass += next_point.m_point.mass;
mass_center.m_point.coord[0] += next_point.m_point.coord[0] * next_point.m_point.mass;
mass_center.m_point.coord[1] += next_point.m_point.coord[1] * next_point.m_point.mass;
mass_center.m_point.coord[2] += next_point.m_point.coord[2] * next_point.m_point.mass;
}
mass_center.m_point.coord[0] /= mass_center.m_point.mass;
mass_center.m_point.coord[1] /= mass_center.m_point.mass;
mass_center.m_point.coord[2] /= mass_center.m_point.mass;
cout << "Итоги." << endl;
cout << "Центр масс: " << endl;
cout << "\tмасса = " << mass_center.m_point.mass << ", координаты = {" << mass_center.m_point.coord[0] <<
", " << mass_center.m_point.coord[1] <<
", " << mass_center.m_point.coord[2] << "}" << endl;
cout << "\nВведённые точки:" << endl;
for (i = 0; i < count; i++) {
rx = p_array[i].m_point.coord[0] - mass_center.m_point.coord[0];
ry = p_array[i].m_point.coord[1] - mass_center.m_point.coord[1];
rz = p_array[i].m_point.coord[2] - mass_center.m_point.coord[2];
p_array[i].distance = sqrt(rx*rx + ry*ry + rz*rz);
cout << "Точка номер " << i + 1 << ", координаты: {" << p_array[i].m_point.coord[0] <<
", " << p_array[i].m_point.coord[1] <<
", " << p_array[i].m_point.coord[2] <<
"}\n\tмасса = " << p_array[i].m_point.mass << ", расстояние до ц.м. = " << p_array[i].distance << endl;
}
free(p_array);
return 0;
}
<commit_msg>update 9_1.cpp program to use C++ struct variable style<commit_after>/*
В программе ввести и инициализировать массив структур, каждая из которых
описывает материальную точку. Элементы структурного типа: координаты и
массы частиц, а также расстояния от центра масс до всех точек набора.
Окончание ввода - ннулевое значение массы точки.
Общая масса системы точек M = sum_{i} m_i, где под m_i обозначена масса
отдельных точек.
Координаты центра масс: x_c = sum_{i} (x_i * m_i) / M,
y_c = sum_{i} (y_i * m_i) / M, z_c = sum_{i} (z_i * m_i) / M
(x_i, y_i, z_i) - координаты отдельных точек.
Расстояние до центра масс определяется как:
r_i = sqrt( (x_i - x_c)^2 + (y_i - y_c)^2 + (z_i - z_c)^2 )
Версия для С++, но с использованием realloc / free для выделение памяти под массив простых структур.
*/
#include <iostream>
#include <cstdlib>
#include <clocale> // установка вывода русских букв в командную строку (больше нужна для Windows OS)
#include <cmath>
using namespace std;
struct MassPoint {
double coord[3];
double mass;
};
struct PointSet {
struct MassPoint m_point;
double distance;
};
int main(int argc, char *argv[])
{
setlocale(LC_ALL, "RUS");
int i, count = 0;
double rx, ry, rz;
PointSet mass_center = { {0., 0., 0., 0.}, 0. };
PointSet next_point;
PointSet *p_array = nullptr;
cout << "Введите точки (порядок ввода: масса, координата x, координата y, координата z).\nПоставьте 0 в качестве массы для прекращения задания точек" << endl;
while ( true ) {
cout << "Точка номер " << (count + 1) << endl << "\tмасса: ";
cin >> next_point.m_point.mass;
if ( next_point.m_point.mass < 0.0000000001 )
break;
cout << "\tкоординаты (3 значения через пробел): ";
cin >> next_point.m_point.coord[0] >> next_point.m_point.coord[1] >> next_point.m_point.coord[2];
count++;
p_array = (struct PointSet *) realloc(p_array, count * sizeof(struct PointSet));
if (p_array == nullptr) {
cerr << "Проблема с выделением дополнительно памяти\n";
return -1;
}
p_array[count - 1] = next_point;
mass_center.m_point.mass += next_point.m_point.mass;
mass_center.m_point.coord[0] += next_point.m_point.coord[0] * next_point.m_point.mass;
mass_center.m_point.coord[1] += next_point.m_point.coord[1] * next_point.m_point.mass;
mass_center.m_point.coord[2] += next_point.m_point.coord[2] * next_point.m_point.mass;
}
mass_center.m_point.coord[0] /= mass_center.m_point.mass;
mass_center.m_point.coord[1] /= mass_center.m_point.mass;
mass_center.m_point.coord[2] /= mass_center.m_point.mass;
cout << "Итоги." << endl;
cout << "Центр масс: " << endl;
cout << "\tмасса = " << mass_center.m_point.mass << ", координаты = {" << mass_center.m_point.coord[0] <<
", " << mass_center.m_point.coord[1] <<
", " << mass_center.m_point.coord[2] << "}" << endl;
cout << "\nВведённые точки:" << endl;
for (i = 0; i < count; i++) {
rx = p_array[i].m_point.coord[0] - mass_center.m_point.coord[0];
ry = p_array[i].m_point.coord[1] - mass_center.m_point.coord[1];
rz = p_array[i].m_point.coord[2] - mass_center.m_point.coord[2];
p_array[i].distance = sqrt(rx*rx + ry*ry + rz*rz);
cout << "Точка номер " << i + 1 << ", координаты: {" << p_array[i].m_point.coord[0] <<
", " << p_array[i].m_point.coord[1] <<
", " << p_array[i].m_point.coord[2] <<
"}\n\tмасса = " << p_array[i].m_point.mass << ", расстояние до ц.м. = " << p_array[i].distance << endl;
}
free(p_array);
return 0;
}
<|endoftext|>
|
<commit_before>/* * This file is part of meego-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* If you have questions regarding the use of this file, please contact
* Nokia at directui@nokia.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "reactionmappainter.h"
#include "reactionmappainter_p.h"
#include <mplainwindow.h>
#include <mreactionmap.h>
#include <mscene.h>
#include "reactionmappaintable.h"
// ReactionMapPainterPrivate......................................................
ReactionMapPainterPrivate::ReactionMapPainterPrivate()
{
repaintTimer.setSingleShot(true);
connect(&repaintTimer, SIGNAL(timeout()), this, SLOT(repaint()));
}
void ReactionMapPainterPrivate::addWidget(ReactionMapPaintable &widget)
{
connect(&widget.signalForwarder, SIGNAL(requestRepaint()),
this, SLOT(requestRepaint()), Qt::UniqueConnection);
connect(&widget.signalForwarder, SIGNAL(requestClear()),
this, SLOT(clear()), Qt::UniqueConnection);
widgets.push_back(&widget);
}
void ReactionMapPainterPrivate::removeWidget(const ReactionMapPaintable &widget)
{
const int pos(widgets.indexOf(const_cast<ReactionMapPaintable*>(&widget)));
if (pos >= 0) {
widgets.remove(pos);
}
}
void ReactionMapPainterPrivate::clear()
{
const QList<QGraphicsView *> views = MPlainWindow::instance()->scene()->views();
// Draw invisible color to all reaction maps
foreach (QGraphicsView *view, views) {
MReactionMap *reactionMap = MReactionMap::instance(view);
if (reactionMap) {
reactionMap->setDrawingValue(MReactionMap::Transparent, MReactionMap::Transparent);
reactionMap->setTransform(QTransform());
reactionMap->fillRectangle(0, 0, reactionMap->width(), reactionMap->height());
}
}
}
void ReactionMapPainterPrivate::requestRepaint()
{
if (repaintTimer.isActive())
return;
// The reaction map painting is queued because if it is scheduled too early then
// the widget geometries are not ready yet and wrong reaction maps will be
// painted.
repaintTimer.start(30);
}
void ReactionMapPainterPrivate::repaint()
{
const QList<QGraphicsView *> views = MPlainWindow::instance()->scene()->views();
clear();
// Draw all reaction maps
foreach (QGraphicsView *view, views) {
MReactionMap *reactionMap = MReactionMap::instance(view);
if (!reactionMap) {
continue;
}
// Draw the first full-screen and paintable widget and go to the
// next reaction map
bool fullScreenWidget = false;
foreach (ReactionMapPaintable *widget, widgets) {
if (widget->isFullScreen() && widget->isPaintable())
{
widget->paintReactionMap(reactionMap, view);
fullScreenWidget = true;
break;
}
}
// Don't draw non-fullscreen widgets and go to the next reaction map
if (fullScreenWidget)
continue;
// Draw the non-fullscreen and paintable widgets
foreach (ReactionMapPaintable *widget, widgets) {
if (widget->isPaintable()) {
widget->paintReactionMap(reactionMap, view);
}
}
}
}
// ReactionMapPainter.............................................................
ReactionMapPainter *ReactionMapPainter::singleton = 0;
ReactionMapPainter::ReactionMapPainter()
: d_ptr(new ReactionMapPainterPrivate)
{
}
ReactionMapPainter::~ReactionMapPainter()
{
delete d_ptr;
}
void ReactionMapPainter::createInstance()
{
Q_ASSERT(!singleton);
if (!singleton) {
singleton = new ReactionMapPainter();
}
}
void ReactionMapPainter::destroyInstance()
{
Q_ASSERT(singleton);
delete singleton;
singleton = 0;
}
void ReactionMapPainter::addWidget(ReactionMapPaintable &widget)
{
Q_D(ReactionMapPainter);
d->addWidget(widget);
}
void ReactionMapPainter::removeWidget(const ReactionMapPaintable &widget)
{
Q_D(ReactionMapPainter);
d->removeWidget(widget);
}
void ReactionMapPainter::clear()
{
Q_D(ReactionMapPainter);
d->clear();
}
void ReactionMapPainter::repaint()
{
Q_D(ReactionMapPainter);
d->requestRepaint();
}
<commit_msg>Fixes: ReactionMapPainter was not honoring CONFIG+=noreactionmap<commit_after>/* * This file is part of meego-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* If you have questions regarding the use of this file, please contact
* Nokia at directui@nokia.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "reactionmappainter.h"
#include "reactionmappainter_p.h"
#include <mplainwindow.h>
#ifdef HAVE_REACTIONMAP
#include <mreactionmap.h>
#endif
#include <mscene.h>
#include "reactionmappaintable.h"
// ReactionMapPainterPrivate......................................................
ReactionMapPainterPrivate::ReactionMapPainterPrivate()
{
repaintTimer.setSingleShot(true);
connect(&repaintTimer, SIGNAL(timeout()), this, SLOT(repaint()));
}
void ReactionMapPainterPrivate::addWidget(ReactionMapPaintable &widget)
{
connect(&widget.signalForwarder, SIGNAL(requestRepaint()),
this, SLOT(requestRepaint()), Qt::UniqueConnection);
connect(&widget.signalForwarder, SIGNAL(requestClear()),
this, SLOT(clear()), Qt::UniqueConnection);
widgets.push_back(&widget);
}
void ReactionMapPainterPrivate::removeWidget(const ReactionMapPaintable &widget)
{
const int pos(widgets.indexOf(const_cast<ReactionMapPaintable*>(&widget)));
if (pos >= 0) {
widgets.remove(pos);
}
}
void ReactionMapPainterPrivate::clear()
{
#ifndef HAVE_REACTIONMAP
return;
#else
const QList<QGraphicsView *> views = MPlainWindow::instance()->scene()->views();
// Draw invisible color to all reaction maps
foreach (QGraphicsView *view, views) {
MReactionMap *reactionMap = MReactionMap::instance(view);
if (reactionMap) {
reactionMap->setDrawingValue(MReactionMap::Transparent, MReactionMap::Transparent);
reactionMap->setTransform(QTransform());
reactionMap->fillRectangle(0, 0, reactionMap->width(), reactionMap->height());
}
}
#endif
}
void ReactionMapPainterPrivate::requestRepaint()
{
if (repaintTimer.isActive())
return;
// The reaction map painting is queued because if it is scheduled too early then
// the widget geometries are not ready yet and wrong reaction maps will be
// painted.
repaintTimer.start(30);
}
void ReactionMapPainterPrivate::repaint()
{
#ifndef HAVE_REACTIONMAP
return;
#else
const QList<QGraphicsView *> views = MPlainWindow::instance()->scene()->views();
clear();
// Draw all reaction maps
foreach (QGraphicsView *view, views) {
MReactionMap *reactionMap = MReactionMap::instance(view);
if (!reactionMap) {
continue;
}
// Draw the first full-screen and paintable widget and go to the
// next reaction map
bool fullScreenWidget = false;
foreach (ReactionMapPaintable *widget, widgets) {
if (widget->isFullScreen() && widget->isPaintable())
{
widget->paintReactionMap(reactionMap, view);
fullScreenWidget = true;
break;
}
}
// Don't draw non-fullscreen widgets and go to the next reaction map
if (fullScreenWidget)
continue;
// Draw the non-fullscreen and paintable widgets
foreach (ReactionMapPaintable *widget, widgets) {
if (widget->isPaintable()) {
widget->paintReactionMap(reactionMap, view);
}
}
}
#endif
}
// ReactionMapPainter.............................................................
ReactionMapPainter *ReactionMapPainter::singleton = 0;
ReactionMapPainter::ReactionMapPainter()
: d_ptr(new ReactionMapPainterPrivate)
{
}
ReactionMapPainter::~ReactionMapPainter()
{
delete d_ptr;
}
void ReactionMapPainter::createInstance()
{
Q_ASSERT(!singleton);
if (!singleton) {
singleton = new ReactionMapPainter();
}
}
void ReactionMapPainter::destroyInstance()
{
Q_ASSERT(singleton);
delete singleton;
singleton = 0;
}
void ReactionMapPainter::addWidget(ReactionMapPaintable &widget)
{
Q_D(ReactionMapPainter);
d->addWidget(widget);
}
void ReactionMapPainter::removeWidget(const ReactionMapPaintable &widget)
{
Q_D(ReactionMapPainter);
d->removeWidget(widget);
}
void ReactionMapPainter::clear()
{
Q_D(ReactionMapPainter);
d->clear();
}
void ReactionMapPainter::repaint()
{
Q_D(ReactionMapPainter);
d->requestRepaint();
}
<|endoftext|>
|
<commit_before>//
// Shell
// Sifer Aseph
// Because I can. Doing this to stem my boredom in class or whatevs.
//
#include <iostream>
int main(int argc, const char * argv[]) {
return 0;
}
<commit_msg>shelly<commit_after>//
// Shell
// Sifer Aseph
// Because I can. Doing this to stem my boredom in class or whatevs.
//
#include <iostream>
//
int main(int argc, const char * argv[]) {
// A loop here. Lifetime of shell starts here.
return 0;
}
<|endoftext|>
|
<commit_before>
#include "pmlc/util/math/bignum.h"
#include <boost/math/common_factor_rt.hpp>
namespace pmlc::util::math {
Integer Floor(const Rational &x) {
if (x < 0) {
return (numerator(x) - denominator(x) + 1) / denominator(x);
} else {
return numerator(x) / denominator(x);
}
}
Integer Ceil(const Rational &x) {
return Floor(Rational(numerator(x) - 1, denominator(x))) + 1;
}
int ToInteger(const Rational &x) {
if (Floor(x) != Ceil(x)) {
throw std::runtime_error("Non-integer rational.");
}
return static_cast<int>(Floor(x));
}
Rational FracPart(const Rational &x) { return x - Floor(x); }
Integer Abs(const Integer &x) {
if (x < 0) {
return -x;
}
return x;
}
Rational Abs(const Rational &x) {
if (x < 0) {
return -x;
}
return x;
}
Rational Reduce(const Rational &v, const Rational &m) {
return v - Floor(v / m) * m;
}
Integer XGCD(const Integer &a, const Integer &b, Integer &x,
Integer &y) { // NOLINT(runtime/references)
if (b == 0) {
x = 1;
y = 0;
return a;
}
Integer x1;
Integer gcd = XGCD(b, a % b, x1, x);
y = x1 - (a / b) * x;
if (gcd < 0) {
gcd *= -1;
x *= -1;
y *= -1;
}
return gcd;
}
Rational XGCD(const Rational &a, const Rational &b, Integer &x,
Integer &y) { // NOLINT(runtime/references)
Integer m = boost::math::lcm(denominator(a), denominator(b));
Rational o;
o = Rational(XGCD(numerator(a * m), numerator(b * m), x, y), m);
if (o < 0) {
o *= -1;
x *= -1;
y *= -1;
}
return o;
}
Rational GCD(const Rational &a, const Rational &b) {
Integer m = boost::math::lcm(denominator(a), denominator(b));
Integer g = boost::math::gcd(numerator(a * m), numerator(b * m));
return Rational(g, m);
}
Integer GCD(const Integer &a, const Integer &b) {
return boost::math::gcd(a, b);
}
Integer LCM(const Integer &a, const Integer &b) {
return boost::math::lcm(a, b);
}
Integer Min(const Integer &a, const Integer &b) {
if (a < b)
return a;
else
return b;
}
Rational Min(const Rational &a, const Rational &b) {
if (a < b)
return a;
else
return b;
}
Integer Max(const Integer &a, const Integer &b) {
if (a < b)
return b;
else
return a;
}
Rational Max(const Rational &a, const Rational &b) {
if (a < b)
return b;
else
return a;
}
Integer RatDiv(const Rational &a, const Rational &b,
Rational &r) { // NOLINT(runtime/references)
Integer q = Floor(a / b);
r = a - q * b;
return q;
}
} // namespace pmlc::util::math
<commit_msg>Update deprecated header loc (#1420)<commit_after>
#include "pmlc/util/math/bignum.h"
#include <boost/integer/common_factor_rt.hpp>
namespace pmlc::util::math {
Integer Floor(const Rational &x) {
if (x < 0) {
return (numerator(x) - denominator(x) + 1) / denominator(x);
} else {
return numerator(x) / denominator(x);
}
}
Integer Ceil(const Rational &x) {
return Floor(Rational(numerator(x) - 1, denominator(x))) + 1;
}
int ToInteger(const Rational &x) {
if (Floor(x) != Ceil(x)) {
throw std::runtime_error("Non-integer rational.");
}
return static_cast<int>(Floor(x));
}
Rational FracPart(const Rational &x) { return x - Floor(x); }
Integer Abs(const Integer &x) {
if (x < 0) {
return -x;
}
return x;
}
Rational Abs(const Rational &x) {
if (x < 0) {
return -x;
}
return x;
}
Rational Reduce(const Rational &v, const Rational &m) {
return v - Floor(v / m) * m;
}
Integer XGCD(const Integer &a, const Integer &b, Integer &x,
Integer &y) { // NOLINT(runtime/references)
if (b == 0) {
x = 1;
y = 0;
return a;
}
Integer x1;
Integer gcd = XGCD(b, a % b, x1, x);
y = x1 - (a / b) * x;
if (gcd < 0) {
gcd *= -1;
x *= -1;
y *= -1;
}
return gcd;
}
Rational XGCD(const Rational &a, const Rational &b, Integer &x,
Integer &y) { // NOLINT(runtime/references)
Integer m = boost::math::lcm(denominator(a), denominator(b));
Rational o;
o = Rational(XGCD(numerator(a * m), numerator(b * m), x, y), m);
if (o < 0) {
o *= -1;
x *= -1;
y *= -1;
}
return o;
}
Rational GCD(const Rational &a, const Rational &b) {
Integer m = boost::math::lcm(denominator(a), denominator(b));
Integer g = boost::math::gcd(numerator(a * m), numerator(b * m));
return Rational(g, m);
}
Integer GCD(const Integer &a, const Integer &b) {
return boost::math::gcd(a, b);
}
Integer LCM(const Integer &a, const Integer &b) {
return boost::math::lcm(a, b);
}
Integer Min(const Integer &a, const Integer &b) {
if (a < b)
return a;
else
return b;
}
Rational Min(const Rational &a, const Rational &b) {
if (a < b)
return a;
else
return b;
}
Integer Max(const Integer &a, const Integer &b) {
if (a < b)
return b;
else
return a;
}
Rational Max(const Rational &a, const Rational &b) {
if (a < b)
return b;
else
return a;
}
Integer RatDiv(const Rational &a, const Rational &b,
Rational &r) { // NOLINT(runtime/references)
Integer q = Floor(a / b);
r = a - q * b;
return q;
}
} // namespace pmlc::util::math
<|endoftext|>
|
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file defines helper routines for XLA compilation.
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include <string>
#include "absl/synchronization/notification.h"
#include "absl/types/span.h"
#include "tensorflow/compiler/tf2xla/lib/util.h"
#include "tensorflow/compiler/tf2xla/literal_util.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_executable_run_options.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/framework/collective.h"
#include "tensorflow/core/framework/device.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/stream_executor/stream.h"
namespace tensorflow {
xla::XlaOp XlaHelpers::Zero(xla::XlaBuilder* b, DataType data_type) {
xla::PrimitiveType type;
TF_CHECK_OK(DataTypeToPrimitiveType(data_type, &type));
return xla::ConstantLiteral(b, xla::LiteralUtil::Zero(type));
}
xla::XlaOp XlaHelpers::One(xla::XlaBuilder* b, DataType data_type) {
xla::PrimitiveType type;
TF_CHECK_OK(DataTypeToPrimitiveType(data_type, &type));
return xla::ConstantLiteral(b, xla::LiteralUtil::One(type));
}
xla::XlaOp XlaHelpers::IntegerLiteral(xla::XlaBuilder* b, DataType data_type,
int64_t value) {
xla::PrimitiveType type;
TF_CHECK_OK(DataTypeToPrimitiveType(data_type, &type));
return ::tensorflow::IntegerLiteral(b, type, value);
}
xla::XlaOp XlaHelpers::FloatLiteral(xla::XlaBuilder* b, DataType data_type,
double value) {
xla::PrimitiveType type;
TF_CHECK_OK(DataTypeToPrimitiveType(data_type, &type));
return ::tensorflow::FloatLiteral(b, type, value);
}
/* static */ Status XlaHelpers::ReshapeLiteral(
const xla::Literal& input, absl::Span<const int64_t> dimensions,
xla::Literal* output) {
if (input.shape().IsTuple()) {
return errors::InvalidArgument("ReshapeLiteral does not support tuples.");
}
xla::Shape shape =
xla::ShapeUtil::MakeShape(input.shape().element_type(), dimensions);
int64_t elements_before = xla::ShapeUtil::ElementsIn(input.shape());
int64_t elements_after = xla::ShapeUtil::ElementsIn(shape);
if (elements_before != elements_after) {
return errors::InvalidArgument(
"Shapes before and after ReshapeLiteral have different numbers of "
"elements.");
}
*output = input.Clone();
output->mutable_shape_do_not_use()->Swap(&shape);
return OkStatus();
}
Status XlaHelpers::OneHot(xla::XlaBuilder* builder, int64_t depth, int axis,
DataType index_type, const TensorShape& indices_shape,
const xla::XlaOp& indices, const xla::XlaOp& on_value,
const xla::XlaOp& off_value, xla::XlaOp* one_hot) {
// Broadcast the linspace constant across the indices along the new axis,
// and test equality at each position.
std::vector<int64_t> broadcast_dims(indices_shape.dims());
std::iota(broadcast_dims.begin(), broadcast_dims.begin() + axis, 0);
std::iota(broadcast_dims.begin() + axis, broadcast_dims.end(), axis + 1);
TensorShape output_shape = indices_shape;
output_shape.InsertDim(axis, depth);
xla::Shape iota_shape;
TF_RETURN_IF_ERROR(
TensorShapeToXLAShape(index_type, output_shape, &iota_shape));
// Selects the user-provided off_value and on_value values.
*one_hot = xla::Select(
xla::Eq(indices, xla::Iota(builder, iota_shape, axis), broadcast_dims),
xla::Broadcast(on_value, output_shape.dim_sizes()),
xla::Broadcast(off_value, output_shape.dim_sizes()));
return OkStatus();
}
DataType XlaHelpers::SumAccumulationType(const DataType& dtype) {
// Upcast 16 bit sum reductions to 32 bit to reduce the precision loss from
// repeated floating point additions.
if (dtype == DT_BFLOAT16 || dtype == DT_HALF) {
return DT_FLOAT;
}
// Upcast small integer types to 32 bit to avoid overflow.
if (dtype == DT_INT8 || dtype == DT_INT16) {
return DT_INT32;
}
if (dtype == DT_UINT8 || dtype == DT_UINT16) {
return DT_UINT32;
}
return dtype;
}
xla::XlaOp XlaHelpers::ConvertElementType(const xla::XlaOp& operand,
const DataType new_element_type) {
xla::PrimitiveType convert_to;
TF_CHECK_OK(DataTypeToPrimitiveType(new_element_type, &convert_to));
return xla::ConvertElementType(operand, convert_to);
}
XlaHelpers::ShapeRepresentationFn IdentityShapeRepresentationFn() {
return [](const TensorShape& shape, DataType dtype, bool use_fast_memory,
XlaLayoutPreference layout_preference) -> StatusOr<xla::Shape> {
xla::Shape xla_shape;
TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dtype, shape, &xla_shape));
return xla_shape;
};
}
Status ResolveDeviceAssignment(
OpKernelContext* ctx,
const XlaCompilationResult::CollectiveInfo& collective_info,
xla::ExecutableRunOptions& run_options,
xla::DeviceAssignment& device_assignment,
xla::gpu::GpuExecutableRunOptions& gpu_options) {
// TODO(nnigania): workaround for b/199436990
static const int kTimeoutSeconds = 1000;
if (ctx->collective_executor() == nullptr) {
return errors::InvalidArgument(
"CollectiveExecutor is required but not available");
}
auto params = core::RefCountPtr<CollectiveParams>(new CollectiveParams());
params->name = "xla-reduction-compilation";
params->group.device_type =
DeviceType{static_cast<Device*>(ctx->device())->device_type()};
params->group.group_size = collective_info.group_size;
params->group.group_key = collective_info.group_key;
params->instance.type = REDUCTION_COLLECTIVE;
params->instance.impl_details.communication_hint = "nccl";
params->instance.impl_details.timeout_seconds = kTimeoutSeconds;
params->instance.impl_details.collective_name = "NcclReduce";
// TODO(cheshire): Avoid passing a dummy shape, TF runtime does not resolve
// devices otherwise.
params->instance.shape = TensorShape({1});
Status st;
absl::Notification n;
ctx->collective_executor()->CompleteParamsAsync(
ctx->device()->attributes(), params.get(), ctx->cancellation_manager(),
[&](const Status& s) {
st = s;
n.Notify();
});
if (!n.WaitForNotificationWithTimeout(absl::Seconds(kTimeoutSeconds))) {
return errors::InvalidArgument("Timeout reached");
}
TF_RETURN_IF_ERROR(st);
VLOG(5) << "Using collective params to resolve device assignment: "
<< params->ToString();
// Identify the physical device associated with each replica.
device_assignment = xla::DeviceAssignment(params->group.group_size, 1);
for (int device_idx = 0; device_idx < params->group.group_size;
device_idx++) {
const DeviceAttributes& device = params->group.members[device_idx].device;
if (device.xla_global_id() == -1) {
if (params->group.device_type == DEVICE_TPU) {
return errors::InvalidArgument(
absl::StrCat("No global ID was set for TPU device ", device.name(),
". Try initializing the TPU system, e.g. "
"`tf.tpu.experimental.initialize_tpu_system()`."));
} else if (params->group.device_type == DEVICE_GPU) {
return errors::Internal(
absl::StrCat("No global ID was set for ", device.name(),
". This is unexpected, please file a bug."));
} else {
// TODO(b/194942685): Implement CPU collectives.
return errors::Unimplemented(
absl::StrCat("Collectives are not yet implemented for ",
params->group.device_type.type_string(),
" devices when compiling with XLA. Attempted to "
"compile a collective running on",
device.name(),
". Please comment on b/194942685 or "
"file a new bug if you don't have access."));
}
}
VLOG(2) << "Assigning physical id " << device.xla_global_id()
<< " for replica " << device_idx << " (" << device.name() << ")";
device_assignment(device_idx, 0) = device.xla_global_id();
}
VLOG(5) << "Generated device assignment: " << device_assignment.ToString();
if (params->group.device_type == DEVICE_GPU) {
// For GPU collectives, `xla_global_id`s are arbitrary integers, and XLA
// requires a mapping from local device IDs to global device IDs.
const DeviceMgr* device_mgr = ctx->function_library()->device_mgr();
std::vector<xla::GlobalDeviceId> global_device_ids(
device_mgr->NumDeviceType(params->group.device_type.type_string()));
for (int device_idx = 0; device_idx < params->group.group_size;
device_idx++) {
const DeviceAttributes& device_attributes =
params->group.members[device_idx].device;
Device* resolved_device = nullptr;
Status lookup_status =
device_mgr->LookupDevice(device_attributes.name(), &resolved_device);
if (lookup_status.ok()) {
// This is a local device, so include it in the mapping.
const DeviceBase::AcceleratorDeviceInfo* accelerator_device_info =
resolved_device->tensorflow_accelerator_device_info();
global_device_ids[accelerator_device_info->stream->parent()
->device_ordinal()] =
device_attributes.xla_global_id();
}
}
gpu_options.set_gpu_global_device_ids(global_device_ids);
}
const std::string& communicator_key =
params->group.runtime_details.communicator_key;
gpu_options.set_nccl_unique_id_callback(
[=](const xla::gpu::NcclCliqueKey& key) { return communicator_key; });
run_options.set_device_assignment(&device_assignment);
run_options.set_gpu_executable_run_options(&gpu_options);
return OkStatus();
}
} // end namespace tensorflow
<commit_msg>Log the collective parameters used by ResolveDeviceAssignment.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file defines helper routines for XLA compilation.
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include <string>
#include "absl/synchronization/notification.h"
#include "absl/types/span.h"
#include "tensorflow/compiler/tf2xla/lib/util.h"
#include "tensorflow/compiler/tf2xla/literal_util.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_executable_run_options.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/framework/collective.h"
#include "tensorflow/core/framework/device.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/stream_executor/stream.h"
namespace tensorflow {
xla::XlaOp XlaHelpers::Zero(xla::XlaBuilder* b, DataType data_type) {
xla::PrimitiveType type;
TF_CHECK_OK(DataTypeToPrimitiveType(data_type, &type));
return xla::ConstantLiteral(b, xla::LiteralUtil::Zero(type));
}
xla::XlaOp XlaHelpers::One(xla::XlaBuilder* b, DataType data_type) {
xla::PrimitiveType type;
TF_CHECK_OK(DataTypeToPrimitiveType(data_type, &type));
return xla::ConstantLiteral(b, xla::LiteralUtil::One(type));
}
xla::XlaOp XlaHelpers::IntegerLiteral(xla::XlaBuilder* b, DataType data_type,
int64_t value) {
xla::PrimitiveType type;
TF_CHECK_OK(DataTypeToPrimitiveType(data_type, &type));
return ::tensorflow::IntegerLiteral(b, type, value);
}
xla::XlaOp XlaHelpers::FloatLiteral(xla::XlaBuilder* b, DataType data_type,
double value) {
xla::PrimitiveType type;
TF_CHECK_OK(DataTypeToPrimitiveType(data_type, &type));
return ::tensorflow::FloatLiteral(b, type, value);
}
/* static */ Status XlaHelpers::ReshapeLiteral(
const xla::Literal& input, absl::Span<const int64_t> dimensions,
xla::Literal* output) {
if (input.shape().IsTuple()) {
return errors::InvalidArgument("ReshapeLiteral does not support tuples.");
}
xla::Shape shape =
xla::ShapeUtil::MakeShape(input.shape().element_type(), dimensions);
int64_t elements_before = xla::ShapeUtil::ElementsIn(input.shape());
int64_t elements_after = xla::ShapeUtil::ElementsIn(shape);
if (elements_before != elements_after) {
return errors::InvalidArgument(
"Shapes before and after ReshapeLiteral have different numbers of "
"elements.");
}
*output = input.Clone();
output->mutable_shape_do_not_use()->Swap(&shape);
return OkStatus();
}
Status XlaHelpers::OneHot(xla::XlaBuilder* builder, int64_t depth, int axis,
DataType index_type, const TensorShape& indices_shape,
const xla::XlaOp& indices, const xla::XlaOp& on_value,
const xla::XlaOp& off_value, xla::XlaOp* one_hot) {
// Broadcast the linspace constant across the indices along the new axis,
// and test equality at each position.
std::vector<int64_t> broadcast_dims(indices_shape.dims());
std::iota(broadcast_dims.begin(), broadcast_dims.begin() + axis, 0);
std::iota(broadcast_dims.begin() + axis, broadcast_dims.end(), axis + 1);
TensorShape output_shape = indices_shape;
output_shape.InsertDim(axis, depth);
xla::Shape iota_shape;
TF_RETURN_IF_ERROR(
TensorShapeToXLAShape(index_type, output_shape, &iota_shape));
// Selects the user-provided off_value and on_value values.
*one_hot = xla::Select(
xla::Eq(indices, xla::Iota(builder, iota_shape, axis), broadcast_dims),
xla::Broadcast(on_value, output_shape.dim_sizes()),
xla::Broadcast(off_value, output_shape.dim_sizes()));
return OkStatus();
}
DataType XlaHelpers::SumAccumulationType(const DataType& dtype) {
// Upcast 16 bit sum reductions to 32 bit to reduce the precision loss from
// repeated floating point additions.
if (dtype == DT_BFLOAT16 || dtype == DT_HALF) {
return DT_FLOAT;
}
// Upcast small integer types to 32 bit to avoid overflow.
if (dtype == DT_INT8 || dtype == DT_INT16) {
return DT_INT32;
}
if (dtype == DT_UINT8 || dtype == DT_UINT16) {
return DT_UINT32;
}
return dtype;
}
xla::XlaOp XlaHelpers::ConvertElementType(const xla::XlaOp& operand,
const DataType new_element_type) {
xla::PrimitiveType convert_to;
TF_CHECK_OK(DataTypeToPrimitiveType(new_element_type, &convert_to));
return xla::ConvertElementType(operand, convert_to);
}
XlaHelpers::ShapeRepresentationFn IdentityShapeRepresentationFn() {
return [](const TensorShape& shape, DataType dtype, bool use_fast_memory,
XlaLayoutPreference layout_preference) -> StatusOr<xla::Shape> {
xla::Shape xla_shape;
TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dtype, shape, &xla_shape));
return xla_shape;
};
}
Status ResolveDeviceAssignment(
OpKernelContext* ctx,
const XlaCompilationResult::CollectiveInfo& collective_info,
xla::ExecutableRunOptions& run_options,
xla::DeviceAssignment& device_assignment,
xla::gpu::GpuExecutableRunOptions& gpu_options) {
// TODO(nnigania): workaround for b/199436990
static const int kTimeoutSeconds = 1000;
if (ctx->collective_executor() == nullptr) {
return errors::InvalidArgument(
"CollectiveExecutor is required but not available");
}
auto params = core::RefCountPtr<CollectiveParams>(new CollectiveParams());
params->name = "xla-reduction-compilation";
params->group.device_type =
DeviceType{static_cast<Device*>(ctx->device())->device_type()};
params->group.group_size = collective_info.group_size;
params->group.group_key = collective_info.group_key;
params->instance.type = REDUCTION_COLLECTIVE;
params->instance.impl_details.communication_hint = "nccl";
params->instance.impl_details.timeout_seconds = kTimeoutSeconds;
params->instance.impl_details.collective_name = "NcclReduce";
// TODO(cheshire): Avoid passing a dummy shape, TF runtime does not resolve
// devices otherwise.
params->instance.shape = TensorShape({1});
VLOG(5) << "Using collective params to resolve device assignment: "
<< params->ToString();
Status st;
absl::Notification n;
ctx->collective_executor()->CompleteParamsAsync(
ctx->device()->attributes(), params.get(), ctx->cancellation_manager(),
[&](const Status& s) {
st = s;
n.Notify();
});
if (!n.WaitForNotificationWithTimeout(absl::Seconds(kTimeoutSeconds))) {
return errors::InvalidArgument("Timeout reached");
}
TF_RETURN_IF_ERROR(st);
VLOG(5) << "Collective params completed: " << params->ToString();
// Identify the physical device associated with each replica.
device_assignment = xla::DeviceAssignment(params->group.group_size, 1);
for (int device_idx = 0; device_idx < params->group.group_size;
device_idx++) {
const DeviceAttributes& device = params->group.members[device_idx].device;
if (device.xla_global_id() == -1) {
if (params->group.device_type == DEVICE_TPU) {
return errors::InvalidArgument(
absl::StrCat("No global ID was set for TPU device ", device.name(),
". Try initializing the TPU system, e.g. "
"`tf.tpu.experimental.initialize_tpu_system()`."));
} else if (params->group.device_type == DEVICE_GPU) {
return errors::Internal(
absl::StrCat("No global ID was set for ", device.name(),
". This is unexpected, please file a bug."));
} else {
// TODO(b/194942685): Implement CPU collectives.
return errors::Unimplemented(
absl::StrCat("Collectives are not yet implemented for ",
params->group.device_type.type_string(),
" devices when compiling with XLA. Attempted to "
"compile a collective running on",
device.name(),
". Please comment on b/194942685 or "
"file a new bug if you don't have access."));
}
}
VLOG(2) << "Assigning physical id " << device.xla_global_id()
<< " for replica " << device_idx << " (" << device.name() << ")";
device_assignment(device_idx, 0) = device.xla_global_id();
}
VLOG(5) << "Generated device assignment: " << device_assignment.ToString();
if (params->group.device_type == DEVICE_GPU) {
// For GPU collectives, `xla_global_id`s are arbitrary integers, and XLA
// requires a mapping from local device IDs to global device IDs.
const DeviceMgr* device_mgr = ctx->function_library()->device_mgr();
std::vector<xla::GlobalDeviceId> global_device_ids(
device_mgr->NumDeviceType(params->group.device_type.type_string()));
for (int device_idx = 0; device_idx < params->group.group_size;
device_idx++) {
const DeviceAttributes& device_attributes =
params->group.members[device_idx].device;
Device* resolved_device = nullptr;
Status lookup_status =
device_mgr->LookupDevice(device_attributes.name(), &resolved_device);
if (lookup_status.ok()) {
// This is a local device, so include it in the mapping.
const DeviceBase::AcceleratorDeviceInfo* accelerator_device_info =
resolved_device->tensorflow_accelerator_device_info();
global_device_ids[accelerator_device_info->stream->parent()
->device_ordinal()] =
device_attributes.xla_global_id();
}
}
gpu_options.set_gpu_global_device_ids(global_device_ids);
}
const std::string& communicator_key =
params->group.runtime_details.communicator_key;
gpu_options.set_nccl_unique_id_callback(
[=](const xla::gpu::NcclCliqueKey& key) { return communicator_key; });
run_options.set_device_assignment(&device_assignment);
run_options.set_gpu_executable_run_options(&gpu_options);
return OkStatus();
}
} // end namespace tensorflow
<|endoftext|>
|
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) 2010 Kitware 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.commontk.org/LICENSE
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.
=========================================================================*/
/// Qt includes
#include <QColor>
#include <QDebug>
#include <QLinearGradient>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <QtGlobal>
#include <QVariant>
/// CTK includes
#include "ctkTransferFunction.h"
#include "ctkTransferFunctionGradientItem.h"
#include "ctkTransferFunctionRepresentation.h"
#include "ctkTransferFunctionScene.h"
//-----------------------------------------------------------------------------
class ctkTransferFunctionGradientItemPrivate
{
public:
ctkTransferFunctionGradientItemPrivate();
bool Mask;
};
//-----------------------------------------------------------------------------
ctkTransferFunctionGradientItemPrivate::ctkTransferFunctionGradientItemPrivate()
{
this->Mask = true;
}
//-----------------------------------------------------------------------------
ctkTransferFunctionGradientItem::ctkTransferFunctionGradientItem(QGraphicsItem* parentGraphicsItem)
:ctkTransferFunctionItem(parentGraphicsItem)
, d_ptr(new ctkTransferFunctionGradientItemPrivate)
{
}
//-----------------------------------------------------------------------------
ctkTransferFunctionGradientItem::ctkTransferFunctionGradientItem(
ctkTransferFunction* transferFunction, QGraphicsItem* parentItem)
:ctkTransferFunctionItem(transferFunction, parentItem)
{
}
//-----------------------------------------------------------------------------
ctkTransferFunctionGradientItem::~ctkTransferFunctionGradientItem()
{
}
//-----------------------------------------------------------------------------
void ctkTransferFunctionGradientItem::paint(
QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
if (this->transferFunction()->count() <= 0)
{
return;
}
//ctkTransferFunctionScene* tfScene = dynamic_cast<ctkTransferFunctionScene*>(this->scene());
//Q_ASSERT(tfScene);
ctkTransferFunctionRepresentation* tfRep = this->transferFunction()->representation();
const QGradient& gradient = tfRep->gradient();
if ( this->mask() )
{
QPainterPath closedPath = tfRep->curve();
QRectF position = this->rect();
// link to last point
closedPath.lineTo(position.x() + position.width(), position.y() + position.height());
// link to first point
closedPath.lineTo(position.x(), position.y() + position.height());
//Don,t need to close because automatic
QPen pen(QColor(255, 255, 255, 191), 1);
pen.setCosmetic(true);
painter->setPen(pen);
painter->setBrush(gradient);
painter->drawPath(closedPath);
}
else
{
painter->fillRect(this->rect(), gradient);
}
}
//-----------------------------------------------------------------------------
bool ctkTransferFunctionGradientItem::mask() const
{
Q_D( const ctkTransferFunctionGradientItem );
return d->Mask;
}
//-----------------------------------------------------------------------------
void ctkTransferFunctionGradientItem::setMask( bool mask )
{
Q_D( ctkTransferFunctionGradientItem );
d->Mask = mask;
}
<commit_msg>BUG: ctkTransferFunctionViewTest* were crashing because of an uninitialized<commit_after>/*=========================================================================
Library: CTK
Copyright (c) 2010 Kitware 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.commontk.org/LICENSE
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.
=========================================================================*/
/// Qt includes
#include <QColor>
#include <QDebug>
#include <QLinearGradient>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <QtGlobal>
#include <QVariant>
/// CTK includes
#include "ctkTransferFunction.h"
#include "ctkTransferFunctionGradientItem.h"
#include "ctkTransferFunctionRepresentation.h"
#include "ctkTransferFunctionScene.h"
//-----------------------------------------------------------------------------
class ctkTransferFunctionGradientItemPrivate
{
public:
ctkTransferFunctionGradientItemPrivate();
bool Mask;
};
//-----------------------------------------------------------------------------
ctkTransferFunctionGradientItemPrivate::ctkTransferFunctionGradientItemPrivate()
{
this->Mask = true;
}
//-----------------------------------------------------------------------------
ctkTransferFunctionGradientItem::ctkTransferFunctionGradientItem(QGraphicsItem* parentGraphicsItem)
:ctkTransferFunctionItem(parentGraphicsItem)
, d_ptr(new ctkTransferFunctionGradientItemPrivate)
{
}
//-----------------------------------------------------------------------------
ctkTransferFunctionGradientItem::ctkTransferFunctionGradientItem(
ctkTransferFunction* transferFunction, QGraphicsItem* parentItem)
:ctkTransferFunctionItem(transferFunction, parentItem)
, d_ptr(new ctkTransferFunctionGradientItemPrivate)
{
}
//-----------------------------------------------------------------------------
ctkTransferFunctionGradientItem::~ctkTransferFunctionGradientItem()
{
}
//-----------------------------------------------------------------------------
void ctkTransferFunctionGradientItem::paint(
QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
if (this->transferFunction()->count() <= 0)
{
return;
}
//ctkTransferFunctionScene* tfScene = dynamic_cast<ctkTransferFunctionScene*>(this->scene());
//Q_ASSERT(tfScene);
ctkTransferFunctionRepresentation* tfRep = this->transferFunction()->representation();
const QGradient& gradient = tfRep->gradient();
if ( this->mask() )
{
QPainterPath closedPath = tfRep->curve();
QRectF position = this->rect();
// link to last point
closedPath.lineTo(position.x() + position.width(), position.y() + position.height());
// link to first point
closedPath.lineTo(position.x(), position.y() + position.height());
//Don,t need to close because automatic
QPen pen(QColor(255, 255, 255, 191), 1);
pen.setCosmetic(true);
painter->setPen(pen);
painter->setBrush(gradient);
painter->drawPath(closedPath);
}
else
{
painter->fillRect(this->rect(), gradient);
}
}
//-----------------------------------------------------------------------------
bool ctkTransferFunctionGradientItem::mask() const
{
Q_D( const ctkTransferFunctionGradientItem );
return d->Mask;
}
//-----------------------------------------------------------------------------
void ctkTransferFunctionGradientItem::setMask( bool mask )
{
Q_D( ctkTransferFunctionGradientItem );
d->Mask = mask;
}
<|endoftext|>
|
<commit_before>#include "Analysis.hh"
#include "G4UnitsTable.hh"
#include "globals.hh"
#include "G4RunManager.hh"
#include "G4Material.hh"
#include "G4HCofThisEvent.hh"
#include "G4Event.hh"
#include "G4ThreeVector.hh"
#ifdef USE_MPI
#include "G4MPImanager.hh"
#include <stdio.h>
#endif
#include "HistoManager.hh"
Analysis* Analysis::singleton = 0;
/**
* Analysis
*
* Creates an Analysis object
*/
Analysis::Analysis(){
}
/**
* Initilize the analysis manager
*
* Creates a new HistoManager
*/
void Analysis::Initilize(){
fHistoManager = new HistoManager();
}
/**
* Cleaning up the analysis manager
*
* Deleting the HistoManager
*/
void Analysis::CleanUp(){
delete fHistoManager;
}
Analysis::~Analysis(){
}
/**
* PrepareNewRun
*
* @brief - called before each run.
* There is no need to update the geometry because the geometry
* is fixed during a run.
*/
void Analysis::PrepareNewRun(const G4Run* ){
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
#ifdef USE_MPI
if ( analysisManager->IsActive() ) {
// Creating a filename based on the rank
G4int rank = G4MPImanager::GetManager()-> GetRank();
char str[64];
sprintf(str, "-%03d", rank);
G4String fname = analysisManager->GetFileName() + G4String(str);
analysisManager->OpenFile(fname);
}
#else
if ( analysisManager->IsActive() ) {
analysisManager->OpenFile();
}
#endif
}
/**
* PrepareNewEvent
*
* @brief - Called before each event
* The energy deposition per slice is initialzed per event
*/
void Analysis::PrepareNewEvent(const G4Event* ){
// Initialize energy deposition to zero
nOPDetEvent = 0.0;
nOPAbsEvent = 0.0;
}
/**
* EndOfEvent
*
* @param G4Event* event
*/
void Analysis::EndOfEvent(const G4Event* event){
G4VHitsCollection *hc;
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
// Iterating through the hit collection to accumulate the energy deposition
G4int numHitColl = event->GetHCofThisEvent()->GetNumberOfCollections();
for(G4int hitItter = 0; hitItter < numHitColl; hitItter++){
// Itterating through the hit collection
hc = event->GetHCofThisEvent()->GetHC(hitItter);
nOPDetEvent += hc->GetSize();
}
// Adding to the run accumulation only events with deposit energy
if (nOPAbsEvent > 0.0){
analysisManager->FillH1(2,nOPDetEvent);
analysisManager->FillH1(1,nOPAbsEvent);
}
}
/**
* EndOfRun
*
* Called at the end of a run, which summerizes the run
*/
void Analysis::EndOfRun(const G4Run* ){
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
// Print some output
G4cout<<"\tAverage Energy Deposited: "
<< G4BestUnit(analysisManager->GetH1(1)->mean(),"Energy")
<< " +/- " << G4BestUnit(analysisManager->GetH1(1)->rms(),"Energy")
<< "\n\tAverage Number of Optical Photons: "
<< analysisManager->GetH1(2)->mean()
<< " +/- " << analysisManager->GetH1(2)->rms()
<< G4endl;
//save histograms
if ( analysisManager->IsActive() ) {
analysisManager->Write();
analysisManager->CloseFile();
}
}
/**
* Sets the number of optical photons generated
*/
void Analysis::SetNumOpticalPhotonsGenerated(G4int numPhotons){
nOPAbsEvent = numPhotons;
}
<commit_msg>Changed units on output<commit_after>#include "Analysis.hh"
#include "G4UnitsTable.hh"
#include "globals.hh"
#include "G4RunManager.hh"
#include "G4Material.hh"
#include "G4HCofThisEvent.hh"
#include "G4Event.hh"
#include "G4ThreeVector.hh"
#ifdef USE_MPI
#include "G4MPImanager.hh"
#include <stdio.h>
#endif
#include "HistoManager.hh"
Analysis* Analysis::singleton = 0;
/**
* Analysis
*
* Creates an Analysis object
*/
Analysis::Analysis(){
}
/**
* Initilize the analysis manager
*
* Creates a new HistoManager
*/
void Analysis::Initilize(){
fHistoManager = new HistoManager();
}
/**
* Cleaning up the analysis manager
*
* Deleting the HistoManager
*/
void Analysis::CleanUp(){
delete fHistoManager;
}
Analysis::~Analysis(){
}
/**
* PrepareNewRun
*
* @brief - called before each run.
* There is no need to update the geometry because the geometry
* is fixed during a run.
*/
void Analysis::PrepareNewRun(const G4Run* ){
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
#ifdef USE_MPI
if ( analysisManager->IsActive() ) {
// Creating a filename based on the rank
G4int rank = G4MPImanager::GetManager()-> GetRank();
char str[64];
sprintf(str, "-%03d", rank);
G4String fname = analysisManager->GetFileName() + G4String(str);
analysisManager->OpenFile(fname);
}
#else
if ( analysisManager->IsActive() ) {
analysisManager->OpenFile();
}
#endif
}
/**
* PrepareNewEvent
*
* @brief - Called before each event
* The energy deposition per slice is initialzed per event
*/
void Analysis::PrepareNewEvent(const G4Event* ){
// Initialize energy deposition to zero
nOPDetEvent = 0.0;
nOPAbsEvent = 0.0;
}
/**
* EndOfEvent
*
* @param G4Event* event
*/
void Analysis::EndOfEvent(const G4Event* event){
G4VHitsCollection *hc;
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
// Iterating through the hit collection to accumulate the energy deposition
G4int numHitColl = event->GetHCofThisEvent()->GetNumberOfCollections();
for(G4int hitItter = 0; hitItter < numHitColl; hitItter++){
// Itterating through the hit collection
hc = event->GetHCofThisEvent()->GetHC(hitItter);
nOPDetEvent += hc->GetSize();
}
// Adding to the run accumulation only events with deposit energy
if (nOPAbsEvent > 0.0){
analysisManager->FillH1(2,nOPDetEvent);
analysisManager->FillH1(1,nOPAbsEvent);
}
}
/**
* EndOfRun
*
* Called at the end of a run, which summerizes the run
*/
void Analysis::EndOfRun(const G4Run* ){
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
// Print some output
G4cout<<"\tAverage Number of Optical Photons Created: "
<< analysisManager->GetH1(1)->mean()
<< " +/- " << analysisManager->GetH1(1)->rms()
<< "\n\tAverage Number of Optical Photons Detected: "
<< analysisManager->GetH1(2)->mean()
<< " +/- " << analysisManager->GetH1(2)->rms()
<< G4endl;
//save histograms
if ( analysisManager->IsActive() ) {
analysisManager->Write();
analysisManager->CloseFile();
}
}
/**
* Sets the number of optical photons generated
*/
void Analysis::SetNumOpticalPhotonsGenerated(G4int numPhotons){
nOPAbsEvent = numPhotons;
}
<|endoftext|>
|
<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
Redistribution and use of HOOMD-blue, in source and binary forms, with or
without modification, are permitted, provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of HOOMD-blue's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR
ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
// $Id$
// $URL$
// Maintainer: askeys
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
#include "FIREEnergyMinimizerGPU.h"
#include "FIREEnergyMinimizerGPU.cuh"
#include "TwoStepNVEGPU.h"
// windows feels the need to #define min and max
#ifdef WIN32
#undef min
#undef max
#endif
/*! \file FIREEnergyMinimizerGPU.h
\brief Contains code for the FIREEnergyMinimizerGPU class
*/
/*! \param sysdef SystemDefinition this method will act on. Must not be NULL.
\param group The group of particles this integration method is to work on
\param dt Default step size
\post The method is constructed with the given particle data and a NULL profiler.
*/
FIREEnergyMinimizerGPU::FIREEnergyMinimizerGPU(boost::shared_ptr<SystemDefinition> sysdef, boost::shared_ptr<ParticleGroup> group, Scalar dt)
: FIREEnergyMinimizer(sysdef, group, dt, false)
{
// only one GPU is supported
if (exec_conf.gpu.size() != 1)
{
cerr << endl << "***Error! Creating a FIREEnergyMinimizer with 0 or more than one GPUs" << endl << endl;
throw std::runtime_error("Error initializing FIREEnergyMinimizer");
}
// allocate the sum arrays
GPUArray<float> sum(1, m_pdata->getExecConf());
m_sum.swap(sum);
GPUArray<float> sum3(3, m_pdata->getExecConf());
m_sum3.swap(sum3);
// initialize the partial sum arrays
m_block_size = 256; //128;
unsigned int group_size = m_group->getIndexArray().getNumElements();
m_num_blocks = group_size / m_block_size + 1;
GPUArray<float> partial_sum1(m_num_blocks, m_pdata->getExecConf());
m_partial_sum1.swap(partial_sum1);
GPUArray<float> partial_sum2(m_num_blocks, m_pdata->getExecConf());
m_partial_sum2.swap(partial_sum2);
GPUArray<float> partial_sum3(m_num_blocks, m_pdata->getExecConf());
m_partial_sum3.swap(partial_sum3);
reset();
createIntegrator();
}
void FIREEnergyMinimizerGPU::createIntegrator()
{
// boost::shared_ptr<ParticleSelector> selector_all(new ParticleSelectorTag(m_sysdef, 0, m_pdata->getN()-1));
// boost::shared_ptr<ParticleGroup> group_all(new ParticleGroup(m_sysdef, selector_all));
boost::shared_ptr<TwoStepNVEGPU> integrator(new TwoStepNVEGPU(m_sysdef, m_group));
addIntegrationMethod(integrator);
setDeltaT(m_deltaT);
}
void FIREEnergyMinimizerGPU::reset()
{
m_converged = false;
m_n_since_negative = m_nmin+1;
m_n_since_start = 0;
m_alpha = m_alpha_start;
m_was_reset = true;
vector<gpu_pdata_arrays>& d_pdata = m_pdata->acquireReadWriteGPU();
ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);
unsigned int group_size = m_group->getIndexArray().getNumElements();
exec_conf.gpu[0]->call(bind(gpu_fire_zero_v,
d_pdata[0],
d_index_array.data,
group_size));
m_pdata->release();
setDeltaT(m_deltaT_set);
}
/*! \param timesteps is the iteration number
*/
void FIREEnergyMinimizerGPU::update(unsigned int timesteps)
{
if (m_converged)
return;
IntegratorTwoStep::update(timesteps);
Scalar P(0.0);
Scalar vnorm(0.0);
Scalar fnorm(0.0);
Scalar energy(0.0);
// compute the total energy on the GPU
// CPU version is Scalar energy = computePotentialEnergy(timesteps)/Scalar(group_size);
if (m_prof)
m_prof->push(exec_conf, "FIRE compute total energy");
vector<gpu_pdata_arrays>& d_pdata = m_pdata->acquireReadWriteGPU();
unsigned int group_size = m_group->getIndexArray().getNumElements();
ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);
{
ArrayHandle<Scalar4> d_net_force(m_pdata->getNetForce(), access_location::device, access_mode::read);
ArrayHandle<float> d_partial_sumE(m_partial_sum1, access_location::device, access_mode::overwrite);
ArrayHandle<float> d_sumE(m_sum, access_location::device, access_mode::overwrite);
exec_conf.gpu[0]->call(bind(gpu_fire_compute_sum_pe,
d_pdata[0],
d_index_array.data,
group_size,
d_net_force.data,
d_sumE.data,
d_partial_sumE.data,
m_block_size,
m_num_blocks));
}
ArrayHandle<float> h_sumE(m_sum, access_location::host, access_mode::read);
energy = h_sumE.data[0]/Scalar(group_size);
if (m_prof)
m_prof->pop(exec_conf);
if (m_was_reset)
{
m_was_reset = false;
m_old_energy = energy + Scalar(100000)*m_etol;
}
//sum P, vnorm, fnorm
if (m_prof)
m_prof->push(exec_conf, "FIRE P, vnorm, fnorm");
{
ArrayHandle<float> d_partial_sum_P(m_partial_sum1, access_location::device, access_mode::overwrite);
ArrayHandle<float> d_partial_sum_vsq(m_partial_sum2, access_location::device, access_mode::overwrite);
ArrayHandle<float> d_partial_sum_fsq(m_partial_sum3, access_location::device, access_mode::overwrite);
ArrayHandle<float> d_sum(m_sum3, access_location::device, access_mode::overwrite);
exec_conf.gpu[0]->call(bind(gpu_fire_compute_sum_all,
d_pdata[0],
d_index_array.data,
group_size,
d_sum.data,
d_partial_sum_P.data,
d_partial_sum_vsq.data,
d_partial_sum_fsq.data,
m_block_size,
m_num_blocks));
}
ArrayHandle<float> h_sum(m_sum3, access_location::host, access_mode::read);
P = h_sum.data[0];
vnorm = sqrt(h_sum.data[1]);
fnorm = sqrt(h_sum.data[2]);
if (m_prof)
m_prof->pop(exec_conf);
if ((fnorm/sqrt(Scalar(m_sysdef->getNDimensions()*group_size)) < m_ftol || fabs(energy-m_old_energy) < m_etol) && m_n_since_start >= m_run_minsteps)
{
m_converged = true;
m_pdata->release();
return;
}
//update velocities
if (m_prof)
m_prof->push(exec_conf, "FIRE update velocities");
Scalar invfnorm = 1.0/fnorm;
exec_conf.gpu[0]->call(bind(gpu_fire_update_v,
d_pdata[0],
d_index_array.data,
group_size,
m_alpha,
vnorm,
invfnorm));
if (m_prof)
m_prof->pop(exec_conf);
if (P > Scalar(0.0))
{
m_n_since_negative++;
if (m_n_since_negative > m_nmin)
{
IntegratorTwoStep::setDeltaT(std::min(m_deltaT*m_finc, m_deltaT_max));
m_alpha *= m_falpha;
}
}
else if (P <= Scalar(0.0))
{
IntegratorTwoStep::setDeltaT(m_deltaT*m_fdec);
m_alpha = m_alpha_start;
m_n_since_negative = 0;
if (m_prof)
m_prof->push(exec_conf, "FIRE zero velocities");
exec_conf.gpu[0]->call(bind(gpu_fire_zero_v,
d_pdata[0],
d_index_array.data,
group_size));
if (m_prof)
m_prof->pop(exec_conf);
}
m_n_since_start++;
m_old_energy = energy;
m_pdata->release();
}
void export_FIREEnergyMinimizerGPU()
{
class_<FIREEnergyMinimizerGPU, boost::shared_ptr<FIREEnergyMinimizerGPU>, bases<FIREEnergyMinimizer>, boost::noncopyable>
("FIREEnergyMinimizerGPU", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<ParticleGroup>, Scalar >())
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<commit_msg>FIREEnergyMinimizerGPU now compiles<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
Redistribution and use of HOOMD-blue, in source and binary forms, with or
without modification, are permitted, provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of HOOMD-blue's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR
ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
// $Id$
// $URL$
// Maintainer: askeys
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
#include "FIREEnergyMinimizerGPU.h"
#include "FIREEnergyMinimizerGPU.cuh"
#include "TwoStepNVEGPU.h"
// windows feels the need to #define min and max
#ifdef WIN32
#undef min
#undef max
#endif
/*! \file FIREEnergyMinimizerGPU.h
\brief Contains code for the FIREEnergyMinimizerGPU class
*/
/*! \param sysdef SystemDefinition this method will act on. Must not be NULL.
\param group The group of particles this integration method is to work on
\param dt Default step size
\post The method is constructed with the given particle data and a NULL profiler.
*/
FIREEnergyMinimizerGPU::FIREEnergyMinimizerGPU(boost::shared_ptr<SystemDefinition> sysdef, boost::shared_ptr<ParticleGroup> group, Scalar dt)
: FIREEnergyMinimizer(sysdef, group, dt, false)
{
// only one GPU is supported
if (!exec_conf.isCUDAEnabled())
{
cerr << endl << "***Error! Creating a FIREEnergyMinimizer with CUDA disabled" << endl << endl;
throw std::runtime_error("Error initializing FIREEnergyMinimizer");
}
// allocate the sum arrays
GPUArray<float> sum(1, exec_conf.isCUDAEnabled());
m_sum.swap(sum);
GPUArray<float> sum3(3, exec_conf.isCUDAEnabled());
m_sum3.swap(sum3);
// initialize the partial sum arrays
m_block_size = 256; //128;
unsigned int group_size = m_group->getIndexArray().getNumElements();
m_num_blocks = group_size / m_block_size + 1;
GPUArray<float> partial_sum1(m_num_blocks, exec_conf.isCUDAEnabled());
m_partial_sum1.swap(partial_sum1);
GPUArray<float> partial_sum2(m_num_blocks, exec_conf.isCUDAEnabled());
m_partial_sum2.swap(partial_sum2);
GPUArray<float> partial_sum3(m_num_blocks, exec_conf.isCUDAEnabled());
m_partial_sum3.swap(partial_sum3);
reset();
createIntegrator();
}
void FIREEnergyMinimizerGPU::createIntegrator()
{
// boost::shared_ptr<ParticleSelector> selector_all(new ParticleSelectorTag(m_sysdef, 0, m_pdata->getN()-1));
// boost::shared_ptr<ParticleGroup> group_all(new ParticleGroup(m_sysdef, selector_all));
boost::shared_ptr<TwoStepNVEGPU> integrator(new TwoStepNVEGPU(m_sysdef, m_group));
addIntegrationMethod(integrator);
setDeltaT(m_deltaT);
}
void FIREEnergyMinimizerGPU::reset()
{
m_converged = false;
m_n_since_negative = m_nmin+1;
m_n_since_start = 0;
m_alpha = m_alpha_start;
m_was_reset = true;
vector<gpu_pdata_arrays>& d_pdata = m_pdata->acquireReadWriteGPU();
ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);
unsigned int group_size = m_group->getIndexArray().getNumElements();
gpu_fire_zero_v(d_pdata[0],
d_index_array.data,
group_size);
if (exec_conf.isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_pdata->release();
setDeltaT(m_deltaT_set);
}
/*! \param timesteps is the iteration number
*/
void FIREEnergyMinimizerGPU::update(unsigned int timesteps)
{
if (m_converged)
return;
IntegratorTwoStep::update(timesteps);
Scalar P(0.0);
Scalar vnorm(0.0);
Scalar fnorm(0.0);
Scalar energy(0.0);
// compute the total energy on the GPU
// CPU version is Scalar energy = computePotentialEnergy(timesteps)/Scalar(group_size);
if (m_prof)
m_prof->push(exec_conf, "FIRE compute total energy");
vector<gpu_pdata_arrays>& d_pdata = m_pdata->acquireReadWriteGPU();
unsigned int group_size = m_group->getIndexArray().getNumElements();
ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);
{
ArrayHandle<Scalar4> d_net_force(m_pdata->getNetForce(), access_location::device, access_mode::read);
ArrayHandle<float> d_partial_sumE(m_partial_sum1, access_location::device, access_mode::overwrite);
ArrayHandle<float> d_sumE(m_sum, access_location::device, access_mode::overwrite);
gpu_fire_compute_sum_pe(d_pdata[0],
d_index_array.data,
group_size,
d_net_force.data,
d_sumE.data,
d_partial_sumE.data,
m_block_size,
m_num_blocks);
if (exec_conf.isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
}
ArrayHandle<float> h_sumE(m_sum, access_location::host, access_mode::read);
energy = h_sumE.data[0]/Scalar(group_size);
if (m_prof)
m_prof->pop(exec_conf);
if (m_was_reset)
{
m_was_reset = false;
m_old_energy = energy + Scalar(100000)*m_etol;
}
//sum P, vnorm, fnorm
if (m_prof)
m_prof->push(exec_conf, "FIRE P, vnorm, fnorm");
{
ArrayHandle<float> d_partial_sum_P(m_partial_sum1, access_location::device, access_mode::overwrite);
ArrayHandle<float> d_partial_sum_vsq(m_partial_sum2, access_location::device, access_mode::overwrite);
ArrayHandle<float> d_partial_sum_fsq(m_partial_sum3, access_location::device, access_mode::overwrite);
ArrayHandle<float> d_sum(m_sum3, access_location::device, access_mode::overwrite);
gpu_fire_compute_sum_all(d_pdata[0],
d_index_array.data,
group_size,
d_sum.data,
d_partial_sum_P.data,
d_partial_sum_vsq.data,
d_partial_sum_fsq.data,
m_block_size,
m_num_blocks);
if (exec_conf.isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
}
ArrayHandle<float> h_sum(m_sum3, access_location::host, access_mode::read);
P = h_sum.data[0];
vnorm = sqrt(h_sum.data[1]);
fnorm = sqrt(h_sum.data[2]);
if (m_prof)
m_prof->pop(exec_conf);
if ((fnorm/sqrt(Scalar(m_sysdef->getNDimensions()*group_size)) < m_ftol || fabs(energy-m_old_energy) < m_etol) && m_n_since_start >= m_run_minsteps)
{
m_converged = true;
m_pdata->release();
return;
}
//update velocities
if (m_prof)
m_prof->push(exec_conf, "FIRE update velocities");
Scalar invfnorm = 1.0/fnorm;
gpu_fire_update_v(d_pdata[0],
d_index_array.data,
group_size,
m_alpha,
vnorm,
invfnorm);
if (exec_conf.isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
if (m_prof)
m_prof->pop(exec_conf);
if (P > Scalar(0.0))
{
m_n_since_negative++;
if (m_n_since_negative > m_nmin)
{
IntegratorTwoStep::setDeltaT(std::min(m_deltaT*m_finc, m_deltaT_max));
m_alpha *= m_falpha;
}
}
else if (P <= Scalar(0.0))
{
IntegratorTwoStep::setDeltaT(m_deltaT*m_fdec);
m_alpha = m_alpha_start;
m_n_since_negative = 0;
if (m_prof)
m_prof->push(exec_conf, "FIRE zero velocities");
gpu_fire_zero_v(d_pdata[0],
d_index_array.data,
group_size);
if (exec_conf.isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
if (m_prof)
m_prof->pop(exec_conf);
}
m_n_since_start++;
m_old_energy = energy;
m_pdata->release();
}
void export_FIREEnergyMinimizerGPU()
{
class_<FIREEnergyMinimizerGPU, boost::shared_ptr<FIREEnergyMinimizerGPU>, bases<FIREEnergyMinimizer>, boost::noncopyable>
("FIREEnergyMinimizerGPU", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<ParticleGroup>, Scalar >())
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<|endoftext|>
|
<commit_before>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <CTraitsTest.h>
#include <mrpt/containers/circular_buffer.h>
#include <mrpt/core/common.h>
#include <mrpt/random.h>
#include <gtest/gtest.h>
template class mrpt::CTraitsTest<mrpt::containers::circular_buffer<char>>;
using cb_t = int;
TEST(circular_buffer_tests, EmptyPop)
{
mrpt::containers::circular_buffer<cb_t> cb(10);
cb_t ret;
EXPECT_THROW(cb.pop(ret), std::exception);
}
TEST(circular_buffer_tests, EmptyPopAfterPushes)
{
constexpr size_t LEN = 20;
mrpt::containers::circular_buffer<cb_t> cb(LEN);
for (size_t nWr = 0; nWr < LEN; nWr++)
{
for (size_t i = 0; i < nWr; i++) cb.push(12);
cb_t ret;
for (size_t i = 0; i < nWr; i++) cb.pop(ret);
// The next one must fail:
EXPECT_THROW(cb.pop(ret), std::exception);
}
}
TEST(circular_buffer_tests, RandomWriteAndPeek)
{
constexpr size_t LEN = 20;
mrpt::containers::circular_buffer<cb_t> cb(LEN);
for (size_t iter = 0; iter < 1000; iter++)
{
const size_t nWr =
mrpt::random::getRandomGenerator().drawUniform32bit() % LEN;
for (size_t i = 0; i < nWr; i++) cb.push(i);
cb_t ret;
for (size_t i = 0; i < nWr; i++)
{
ret = cb.peek(i);
EXPECT_EQ(ret, cb_t(i));
}
for (size_t i = 0; i < nWr; i++)
{
cb.pop(ret);
EXPECT_EQ(ret, cb_t(i));
}
}
}
TEST(circular_buffer_tests, RandomWriteManyAndPeek)
{
constexpr size_t LEN = 20;
mrpt::containers::circular_buffer<cb_t> cb(LEN);
std::vector<cb_t> dum_buf;
for (size_t iter = 0; iter < 1000; iter++)
{
const size_t nWr =
1 +
mrpt::random::getRandomGenerator().drawUniform32bit() % (LEN - 1);
dum_buf.resize(nWr);
cb.push_many(&dum_buf[0], nWr);
cb_t ret;
if (iter % 2)
{
for (size_t i = 0; i < nWr; i++) ret = cb.peek(i);
MRPT_UNUSED_PARAM(ret);
}
else
{
cb.peek_many(&dum_buf[0], nWr);
}
if (iter % 3)
{
for (size_t i = 0; i < nWr; i++) cb.pop(ret);
MRPT_UNUSED_PARAM(ret);
}
else
{
cb.pop_many(&dum_buf[0], nWr);
}
}
}
TEST(circular_buffer_tests, RandomWriteAndPeekOverrun)
{
constexpr size_t LEN = 20;
mrpt::containers::circular_buffer<cb_t> cb(LEN);
for (size_t iter = 0; iter < 100; iter++)
{
const size_t nWr =
mrpt::random::getRandomGenerator().drawUniform32bit() % LEN;
for (size_t i = 0; i < nWr; i++) cb.push(i);
cb_t ret;
for (unsigned k = 0; k < 5; k++)
{
EXPECT_ANY_THROW(ret = cb.peek(nWr + k););
}
for (size_t i = 0; i < nWr; i++) cb.pop(ret);
}
}
TEST(circular_buffer_tests, Size)
{
mrpt::containers::circular_buffer<cb_t> cb(10);
for (size_t i = 0; i < cb.capacity() - 1; i++)
{
cb.push(0);
EXPECT_EQ(cb.size(), i + 1);
}
EXPECT_ANY_THROW(cb.push(0));
for (size_t i = 0; i < cb.capacity() - 1; i++)
{
cb.pop();
EXPECT_EQ(cb.size(), cb.capacity() - 2 - i);
}
}
template <typename T>
void impl_WritePeekCheck()
{
constexpr T LEN = 20;
mrpt::containers::circular_buffer<T> cb(LEN + 1);
for (T i = 0; i < LEN; i++) cb.push(i);
std::array<T, LEN> peek_vals;
cb.peek_many(&peek_vals[0], LEN);
for (T i = 0; i < LEN; i++)
EXPECT_EQ(static_cast<int>(peek_vals[i]), static_cast<int>(i));
}
TEST(circular_buffer_tests, WritePeekCheck_uint8_t)
{
impl_WritePeekCheck<uint8_t>();
}
TEST(circular_buffer_tests, WritePeekCheck_uint16_t)
{
impl_WritePeekCheck<uint16_t>();
}
TEST(circular_buffer_tests, WritePeekCheck_uint32_t)
{
impl_WritePeekCheck<uint32_t>();
}
TEST(circular_buffer_tests, WritePeekCheck_uint64_t)
{
impl_WritePeekCheck<uint64_t>();
}
<commit_msg>fix missing include (only for AppleClang)<commit_after>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <CTraitsTest.h>
#include <mrpt/containers/circular_buffer.h>
#include <mrpt/core/common.h>
#include <mrpt/random.h>
#include <array>
#include <gtest/gtest.h>
template class mrpt::CTraitsTest<mrpt::containers::circular_buffer<char>>;
using cb_t = int;
TEST(circular_buffer_tests, EmptyPop)
{
mrpt::containers::circular_buffer<cb_t> cb(10);
cb_t ret;
EXPECT_THROW(cb.pop(ret), std::exception);
}
TEST(circular_buffer_tests, EmptyPopAfterPushes)
{
constexpr size_t LEN = 20;
mrpt::containers::circular_buffer<cb_t> cb(LEN);
for (size_t nWr = 0; nWr < LEN; nWr++)
{
for (size_t i = 0; i < nWr; i++) cb.push(12);
cb_t ret;
for (size_t i = 0; i < nWr; i++) cb.pop(ret);
// The next one must fail:
EXPECT_THROW(cb.pop(ret), std::exception);
}
}
TEST(circular_buffer_tests, RandomWriteAndPeek)
{
constexpr size_t LEN = 20;
mrpt::containers::circular_buffer<cb_t> cb(LEN);
for (size_t iter = 0; iter < 1000; iter++)
{
const size_t nWr =
mrpt::random::getRandomGenerator().drawUniform32bit() % LEN;
for (size_t i = 0; i < nWr; i++) cb.push(i);
cb_t ret;
for (size_t i = 0; i < nWr; i++)
{
ret = cb.peek(i);
EXPECT_EQ(ret, cb_t(i));
}
for (size_t i = 0; i < nWr; i++)
{
cb.pop(ret);
EXPECT_EQ(ret, cb_t(i));
}
}
}
TEST(circular_buffer_tests, RandomWriteManyAndPeek)
{
constexpr size_t LEN = 20;
mrpt::containers::circular_buffer<cb_t> cb(LEN);
std::vector<cb_t> dum_buf;
for (size_t iter = 0; iter < 1000; iter++)
{
const size_t nWr =
1 +
mrpt::random::getRandomGenerator().drawUniform32bit() % (LEN - 1);
dum_buf.resize(nWr);
cb.push_many(&dum_buf[0], nWr);
cb_t ret;
if (iter % 2)
{
for (size_t i = 0; i < nWr; i++) ret = cb.peek(i);
MRPT_UNUSED_PARAM(ret);
}
else
{
cb.peek_many(&dum_buf[0], nWr);
}
if (iter % 3)
{
for (size_t i = 0; i < nWr; i++) cb.pop(ret);
MRPT_UNUSED_PARAM(ret);
}
else
{
cb.pop_many(&dum_buf[0], nWr);
}
}
}
TEST(circular_buffer_tests, RandomWriteAndPeekOverrun)
{
constexpr size_t LEN = 20;
mrpt::containers::circular_buffer<cb_t> cb(LEN);
for (size_t iter = 0; iter < 100; iter++)
{
const size_t nWr =
mrpt::random::getRandomGenerator().drawUniform32bit() % LEN;
for (size_t i = 0; i < nWr; i++) cb.push(i);
cb_t ret;
for (unsigned k = 0; k < 5; k++)
{
EXPECT_ANY_THROW(ret = cb.peek(nWr + k););
}
for (size_t i = 0; i < nWr; i++) cb.pop(ret);
}
}
TEST(circular_buffer_tests, Size)
{
mrpt::containers::circular_buffer<cb_t> cb(10);
for (size_t i = 0; i < cb.capacity() - 1; i++)
{
cb.push(0);
EXPECT_EQ(cb.size(), i + 1);
}
EXPECT_ANY_THROW(cb.push(0));
for (size_t i = 0; i < cb.capacity() - 1; i++)
{
cb.pop();
EXPECT_EQ(cb.size(), cb.capacity() - 2 - i);
}
}
template <typename T>
void impl_WritePeekCheck()
{
constexpr T LEN = 20;
mrpt::containers::circular_buffer<T> cb(LEN + 1);
for (T i = 0; i < LEN; i++) cb.push(i);
std::array<T, LEN> peek_vals;
cb.peek_many(&peek_vals[0], LEN);
for (T i = 0; i < LEN; i++)
EXPECT_EQ(static_cast<int>(peek_vals[i]), static_cast<int>(i));
}
TEST(circular_buffer_tests, WritePeekCheck_uint8_t)
{
impl_WritePeekCheck<uint8_t>();
}
TEST(circular_buffer_tests, WritePeekCheck_uint16_t)
{
impl_WritePeekCheck<uint16_t>();
}
TEST(circular_buffer_tests, WritePeekCheck_uint32_t)
{
impl_WritePeekCheck<uint32_t>();
}
TEST(circular_buffer_tests, WritePeekCheck_uint64_t)
{
impl_WritePeekCheck<uint64_t>();
}
<|endoftext|>
|
<commit_before>/********************************************************************************
LibVideoGfx - video processing library
Copyright (C) 2002 Dirk Farin
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
********************************************************************************/
#include "libvideogfx/graphics/fileio/mpeg.hh"
#include <stdlib.h>
#include <algorithm>
namespace videogfx {
using namespace std;
FileReader_MPEG::FileReader_MPEG()
: d_fh(NULL),
d_next_framenr(0),
d_image_cache_full(false)
{
}
FileReader_MPEG::~FileReader_MPEG()
{
if (d_fh) pclose(d_fh);
}
void FileReader_MPEG::Open(const char* filename)
{
if (d_fh) pclose(d_fh);
char buf[100];
sprintf(buf,"dvdview -L -W - %s",filename);
#ifdef _WIN32
d_fh = popen(buf,"rb");
#else
d_fh = popen(buf,"r");
#endif
}
bool FileReader_MPEG::IsEOF() const
{
if (d_image_cache_full)
return false;
//d_image_cache_full = const_cast<FileReader_MPEG*>(this)->Preload(d_next_image_cache);
d_image_cache_full = Preload(d_next_image_cache);
return !d_image_cache_full;
}
void FileReader_MPEG::SkipToImage(int nr)
{
AssertDescr(nr>=d_next_framenr,"cannot search backwards in MPEG stream (not implemented yet)");
Image<Pixel> dummy;
while (nr>d_next_framenr)
ReadImage(dummy);
}
static int32 Read4(FILE* fh)
{
int32 n=0;
unsigned char c;
fread(&c,1,1,fh); n |= ((int32)c)<<24;
fread(&c,1,1,fh); n |= ((int32)c)<<16;
fread(&c,1,1,fh); n |= ((int32)c)<<8;
fread(&c,1,1,fh); n |= (int32)c;
return n;
}
static int16 Read2(FILE* fh)
{
int16 n=0;
unsigned char c;
fread(&c,1,1,fh); n |= ((int16)c)<<8;
fread(&c,1,1,fh); n |= (int16)c;
return n;
}
static void Skip(FILE* fh,int n)
{
unsigned char c[100];
while (n)
{
int nskip = min(100,n);
fread(&c,nskip,1,fh);
n-=nskip;
}
}
bool FileReader_MPEG::ReadImage(Image<Pixel>& img)
{
if (d_image_cache_full)
{
img = d_next_image_cache;
d_image_cache_full = false;
d_next_image_cache.Release();
d_next_framenr++;
return true;
}
else
{
bool image_read = Preload(img);
return image_read;
}
}
bool FileReader_MPEG::Preload(Image<Pixel>& dest) const
{
int framenr;
framenr=Read4(d_fh);
int w = Read2(d_fh);
int h = Read2(d_fh);
Skip(d_fh,128-4-2-2);
// cerr << "Nr: " << framenr << " width: " << spec.width << " height: " << spec.height << endl;
if (feof(d_fh))
return false;
ImageParam spec = dest.AskParam();
if (spec.width != w || spec.height != h ||
spec.chroma != Chroma_420 ||
spec.colorspace != Colorspace_YUV)
{
spec.chroma = Chroma_420;
spec.colorspace = Colorspace_YUV;
spec.width =w;
spec.height=h;
dest.Create(spec);
}
Pixel*const* yp = dest.AskFrameY();
Pixel*const* up = dest.AskFrameU();
Pixel*const* vp = dest.AskFrameV();
for (int y=0;y<h;y++)
fread(yp[y],w,1,d_fh);
int cw,ch;
spec.AskChromaSizes(cw,ch);
for (int y=0;y<ch;y++)
fread(up[y],cw,1,d_fh);
for (int y=0;y<ch;y++)
fread(vp[y],cw,1,d_fh);
return true;
}
}
<commit_msg>bugfix: seeking forward in mpeg files did not work<commit_after>/********************************************************************************
LibVideoGfx - video processing library
Copyright (C) 2002 Dirk Farin
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
********************************************************************************/
#include "libvideogfx/graphics/fileio/mpeg.hh"
#include <stdlib.h>
#include <algorithm>
namespace videogfx {
using namespace std;
FileReader_MPEG::FileReader_MPEG()
: d_fh(NULL),
d_next_framenr(0),
d_image_cache_full(false)
{
}
FileReader_MPEG::~FileReader_MPEG()
{
if (d_fh) pclose(d_fh);
}
void FileReader_MPEG::Open(const char* filename)
{
if (d_fh) pclose(d_fh);
char buf[100];
sprintf(buf,"dvdview -L -W - %s",filename);
#ifdef _WIN32
d_fh = popen(buf,"rb");
#else
d_fh = popen(buf,"r");
#endif
}
bool FileReader_MPEG::IsEOF() const
{
if (d_image_cache_full)
return false;
//d_image_cache_full = const_cast<FileReader_MPEG*>(this)->Preload(d_next_image_cache);
d_image_cache_full = Preload(d_next_image_cache);
return !d_image_cache_full;
}
void FileReader_MPEG::SkipToImage(int nr)
{
AssertDescr(nr>=d_next_framenr,"cannot search backwards in MPEG stream (not implemented yet)");
Image<Pixel> dummy;
while (nr>d_next_framenr)
ReadImage(dummy);
}
static int32 Read4(FILE* fh)
{
int32 n=0;
unsigned char c;
fread(&c,1,1,fh); n |= ((int32)c)<<24;
fread(&c,1,1,fh); n |= ((int32)c)<<16;
fread(&c,1,1,fh); n |= ((int32)c)<<8;
fread(&c,1,1,fh); n |= (int32)c;
return n;
}
static int16 Read2(FILE* fh)
{
int16 n=0;
unsigned char c;
fread(&c,1,1,fh); n |= ((int16)c)<<8;
fread(&c,1,1,fh); n |= (int16)c;
return n;
}
static void Skip(FILE* fh,int n)
{
unsigned char c[100];
while (n)
{
int nskip = min(100,n);
fread(&c,nskip,1,fh);
n-=nskip;
}
}
bool FileReader_MPEG::ReadImage(Image<Pixel>& img)
{
if (d_image_cache_full)
{
img = d_next_image_cache;
d_image_cache_full = false;
d_next_image_cache.Release();
d_next_framenr++;
return true;
}
else
{
bool image_read = Preload(img);
d_next_framenr++;
return image_read;
}
}
bool FileReader_MPEG::Preload(Image<Pixel>& dest) const
{
int framenr;
framenr=Read4(d_fh);
int w = Read2(d_fh);
int h = Read2(d_fh);
Skip(d_fh,128-4-2-2);
// cerr << "Nr: " << framenr << " width: " << spec.width << " height: " << spec.height << endl;
if (feof(d_fh))
return false;
ImageParam spec = dest.AskParam();
if (spec.width != w || spec.height != h ||
spec.chroma != Chroma_420 ||
spec.colorspace != Colorspace_YUV)
{
spec.chroma = Chroma_420;
spec.colorspace = Colorspace_YUV;
spec.width =w;
spec.height=h;
dest.Create(spec);
}
Pixel*const* yp = dest.AskFrameY();
Pixel*const* up = dest.AskFrameU();
Pixel*const* vp = dest.AskFrameV();
for (int y=0;y<h;y++)
fread(yp[y],w,1,d_fh);
int cw,ch;
spec.AskChromaSizes(cw,ch);
for (int y=0;y<ch;y++)
fread(up[y],cw,1,d_fh);
for (int y=0;y<ch;y++)
fread(vp[y],cw,1,d_fh);
return true;
}
}
<|endoftext|>
|
<commit_before>/*
* CompoundAgent.cpp
* openc2e
*
* Created by Alyssa Milburn on Tue May 25 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
*/
#include "CompoundPart.h"
#include "openc2e.h"
#include "c16Image.h"
#include "SDLBackend.h"
#include "CompoundAgent.h"
creaturesImage *TextEntryPart::caretsprite = 0;
void CompoundPart::render(SDLBackend *renderer, int xoffset, int yoffset) {
renderer->render(getSprite(), getCurrentSprite(), xoffset + x, yoffset + y, is_transparent, transparency);
}
CompoundPart::CompoundPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg,
int _x, int _y, unsigned int _z) {
id = _id;
firstimg = fimg;
x = _x;
y = _y;
zorder = _z;
origsprite = sprite = gallery.getImage(spritefile);
caos_assert(sprite);
pose = 0;
base = 0;
is_transparent = false;
framerate = 1;
framedelay = 0;
parent = p;
}
CompoundPart::~CompoundPart() {
gallery.delImage(origsprite);
if (origsprite != sprite) delete sprite;
}
void CompoundPart::tint(unsigned char r, unsigned char g, unsigned char b, unsigned char rotation, unsigned char swap) {
if (origsprite != sprite) delete sprite;
s16Image *newsprite = new s16Image();
sprite = newsprite;
((duppableImage *)origsprite)->duplicateTo(newsprite);
newsprite->tint(r, g, b, rotation, swap);
}
DullPart::DullPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg, int _x, int _y,
unsigned int _z) : CompoundPart(p, _id, spritefile, fimg, _x, _y, _z) {
}
ButtonPart::ButtonPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg, int _x, int _y,
unsigned int _z, const bytestring &animhover, int msgid, int option) : CompoundPart(p, _id, spritefile, fimg, _x, _y, _z) {
messageid = msgid;
hitopaquepixelsonly = (option == 1);
hoveranimation = animhover;
}
TextPart::TextPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg, int _x, int _y, unsigned int _z, std::string fontsprite)
: CompoundPart(p, _id, spritefile, fimg, _x, _y, _z) {
textsprite = gallery.getImage(fontsprite);
caos_assert(textsprite);
caos_assert(textsprite->numframes() == 224);
leftmargin = 8; topmargin = 8; rightmargin = 8; bottommargin = 8;
linespacing = 0; charspacing = 0;
left_align = false; center_align = false; bottom_align = false; middle_align = false; last_page_scroll = false;
currpage = 0;
recalculateData(); // ie, insert a blank first page
}
TextPart::~TextPart() {
gallery.delImage(textsprite);
}
void TextPart::setText(std::string t) {
text.clear();
// parse and remove the <tint> tagging
for (unsigned int i = 0; i < t.size(); i++) {
if ((t[i] == '<') && (t.size() > i+4))
if ((t[i + 1] == 't') && (t[i + 2] == 'i') && (t[i + 3] == 'n') && (t[i + 4] == 't')) {
i += 5;
std::string tintinfo;
if (t[i] == ' ') i++; // skip initial space, if any
for (; i < t.size(); i++) {
if (t[i] == '>')
break;
tintinfo += t[i];
}
// TODO: handle contents of tintinfo somehow
continue;
}
text += t[i];
}
recalculateData();
}
void TextEntryPart::setText(std::string t) {
TextPart::setText(t);
// place caret at the end of the text
caretline = lines.size() - 1;
caretchar = lines[caretline].text.size();
}
unsigned int calculateScriptId(unsigned int message_id); // from caosVM_agent.cpp, TODO: move into shared file
void TextEntryPart::handleKey(char c) {
// TODO: this is dumb
if (c == 0) { // backspace
if (text.size() == 0) return;
text.erase(text.end() - 1);
caretchar--; // TODO: it's not this simple!
} else if (c == 1) { // return
parent->fireScript(calculateScriptId(messageid), 0); // TODO: is a null FROM correct?
} else {
text += c;
caretchar++; // TODO: it's not this simple!
}
recalculateData();
}
void TextPart::setFormat(int left, int top, int right, int bottom, int line, int _char, bool lefta, bool centera, bool bottoma, bool middlea, bool lastpagescroll) {
leftmargin = left;
topmargin = top;
rightmargin = right;
bottommargin = bottom;
linespacing = line;
charspacing = _char;
left_align = lefta;
center_align = centera;
bottom_align = bottoma;
middle_align = middlea;
last_page_scroll = lastpagescroll;
recalculateData();
}
unsigned int TextPart::calculateWordWidth(std::string word) {
unsigned int x = 0;
for (unsigned int i = 0; i < word.size(); i++) {
if (word[i] < 32) continue; // TODO: replace with space or similar?
int spriteid = word[i] - 32;
x += textsprite->width(spriteid);
if (i != 0) x += charspacing;
}
return x;
}
/*
* Recalculate the data used for rendering the text part.
*/
void TextPart::recalculateData() {
linedata currentdata;
lines.clear();
pages.clear();
pages.push_back(0);
if (text.size() == 0) {
lines.push_back(currentdata); // blank line, so caret is rendered in TextEntryParts
return;
}
unsigned int textwidth = getWidth() - leftmargin - rightmargin;
unsigned int textheight = getHeight() - topmargin - bottommargin;
unsigned int currenty = 0, usedheight = 0;
unsigned int i = 0;
while (i < text.size()) {
bool newline = false;
// first, retrieve a word from the text
std::string word;
for (; i < text.size(); i++) {
if ((text[i] == ' ') || (text[i] == '\n')) {
if (text[i] == '\n') newline = true;
i++;
break;
}
word += text[i];
}
// next, work out whether it fits
unsigned int wordlen = calculateWordWidth(word);
unsigned int spacelen = textsprite->width(0) + charspacing;
unsigned int possiblelen = wordlen;
if (currentdata.text.size() > 0)
possiblelen = wordlen + spacelen;
// TODO: set usedheight as appropriate/needed
usedheight = textsprite->height(0);
if (currentdata.width + possiblelen <= textwidth) {
// the rest of the word fits on the current line, so that's okay.
// add a space if we're not the first word on this line
if (currentdata.text.size() > 0) word = std::string(" ") + word;
currentdata.text += word;
currentdata.width += possiblelen;
} else if (wordlen <= textwidth) {
// the rest of the word doesn't fit on the current line, but does on the next line.
if (currenty + usedheight > textheight) {
currenty = 0;
pages.push_back(lines.size());
} else currenty += usedheight + linespacing;
currentdata.text += " "; // TODO: HACK THINK ABOUT THIS
lines.push_back(currentdata);
currentdata.reset();
currentdata.text += word;
currentdata.width += wordlen;
} else {
// TODO: word is too wide to fit on a single line
// we should output as much as possible and then go backwards
}
// we force a newline here if necessary (ie, if the last char is '\n', except not in the last case)
if ((i < text.size()) && (newline)) {
currenty += usedheight + linespacing;
if (currenty > textheight) {
currenty = 0;
pages.push_back(lines.size());
}
lines.push_back(currentdata);
currentdata.reset();
}
}
if (currentdata.text.size() > 0) {
currenty += usedheight;
if (text[text.size() -1] == ' ') currentdata.text += " "; // TODO: HACK THINK ABOUT THIS
lines.push_back(currentdata);
}
}
void TextPart::render(SDLBackend *renderer, int xoffset, int yoffset, TextEntryPart *caretdata) {
CompoundPart::render(renderer, xoffset + x, yoffset + y);
unsigned int xoff = xoffset + x + leftmargin;
unsigned int yoff = yoffset + y + topmargin;
unsigned int textwidth = getWidth() - leftmargin - rightmargin;
unsigned int textheight = getHeight() - topmargin - bottommargin;
unsigned int currenty = 0, usedheight = 0;
unsigned int startline = pages[currpage];
unsigned int endline = (currpage + 1 < pages.size() ? pages[currpage + 1] : lines.size());
for (unsigned int i = startline; i < endline; i++) {
unsigned int currentx = 0, somex = xoff;
if (center_align)
somex = somex + ((textwidth - lines[i].width) / 2);
for (unsigned int x = 0; x < lines[i].text.size(); x++) {
if (lines[i].text[x] < 32) continue; // TODO: replace with space or similar?
int spriteid = lines[i].text[x] - 32;
renderer->render(textsprite, spriteid, somex + currentx, yoff + currenty, is_transparent, transparency);
if ((caretdata) && (caretdata->caretline == i) && (caretdata->caretchar == x))
caretdata->renderCaret(renderer, somex + currentx, yoff + currenty);
currentx += textsprite->width(spriteid) + charspacing;
}
if ((caretdata) && (caretdata->caretline == i) && (caretdata->caretchar == lines[i].text.size()))
caretdata->renderCaret(renderer, somex + currentx, yoff + currenty);
currenty += textsprite->height(0) + linespacing;
}
}
FixedTextPart::FixedTextPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg, int _x, int _y,
unsigned int _z, std::string fontsprite) : TextPart(p, _id, spritefile, fimg, _x, _y, _z, fontsprite) {
// nothing, hopefully.. :)
}
TextEntryPart::TextEntryPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg, int _x, int _y,
unsigned int _z, unsigned int msgid, std::string fontsprite) : TextPart(p, _id, spritefile, fimg, _x, _y, _z, fontsprite) {
// TODO: hm, this never gets freed..
if (!caretsprite) { caretsprite = gallery.getImage("cursor"); caos_assert(caretsprite); }
caretpose = 0;
caretline = 0;
caretchar = 0;
focused = false;
messageid = msgid;
}
void TextEntryPart::render(SDLBackend *renderer, int xoffset, int yoffset) {
TextPart::render(renderer, xoffset, yoffset, (focused ? this : 0));
}
void TextEntryPart::renderCaret(SDLBackend *renderer, int xoffset, int yoffset) {
// TODO: fudge xoffset/yoffset as required
renderer->render(caretsprite, caretpose, xoffset, yoffset, is_transparent, transparency);
}
void TextEntryPart::tick() {
CompoundPart::tick();
if (focused) {
caretpose++;
if (caretpose == caretsprite->numframes())
caretpose = 0;
}
}
void CompoundPart::tick() {
if (!animation.empty()) {
if (framerate > 1) {
framedelay++;
if (framedelay == framerate + 1)
framedelay = 0;
}
if (framedelay == 0) {
unsigned int f = frameno + 1;
if (f == animation.size()) return;
if (animation[f] == 255) {
if (f == (animation.size() - 1)) f = 0;
else f = animation[f + 1];
}
setFrameNo(f);
}
}
}
/* vim: set noet: */
<commit_msg>change textpart wrapping a little<commit_after>/*
* CompoundAgent.cpp
* openc2e
*
* Created by Alyssa Milburn on Tue May 25 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
*/
#include "CompoundPart.h"
#include "openc2e.h"
#include "c16Image.h"
#include "SDLBackend.h"
#include "CompoundAgent.h"
creaturesImage *TextEntryPart::caretsprite = 0;
void CompoundPart::render(SDLBackend *renderer, int xoffset, int yoffset) {
renderer->render(getSprite(), getCurrentSprite(), xoffset + x, yoffset + y, is_transparent, transparency);
}
CompoundPart::CompoundPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg,
int _x, int _y, unsigned int _z) {
id = _id;
firstimg = fimg;
x = _x;
y = _y;
zorder = _z;
origsprite = sprite = gallery.getImage(spritefile);
caos_assert(sprite);
pose = 0;
base = 0;
is_transparent = false;
framerate = 1;
framedelay = 0;
parent = p;
}
CompoundPart::~CompoundPart() {
gallery.delImage(origsprite);
if (origsprite != sprite) delete sprite;
}
void CompoundPart::tint(unsigned char r, unsigned char g, unsigned char b, unsigned char rotation, unsigned char swap) {
if (origsprite != sprite) delete sprite;
s16Image *newsprite = new s16Image();
sprite = newsprite;
((duppableImage *)origsprite)->duplicateTo(newsprite);
newsprite->tint(r, g, b, rotation, swap);
}
DullPart::DullPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg, int _x, int _y,
unsigned int _z) : CompoundPart(p, _id, spritefile, fimg, _x, _y, _z) {
}
ButtonPart::ButtonPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg, int _x, int _y,
unsigned int _z, const bytestring &animhover, int msgid, int option) : CompoundPart(p, _id, spritefile, fimg, _x, _y, _z) {
messageid = msgid;
hitopaquepixelsonly = (option == 1);
hoveranimation = animhover;
}
TextPart::TextPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg, int _x, int _y, unsigned int _z, std::string fontsprite)
: CompoundPart(p, _id, spritefile, fimg, _x, _y, _z) {
textsprite = gallery.getImage(fontsprite);
caos_assert(textsprite);
caos_assert(textsprite->numframes() == 224);
leftmargin = 8; topmargin = 8; rightmargin = 8; bottommargin = 8;
linespacing = 0; charspacing = 0;
left_align = false; center_align = false; bottom_align = false; middle_align = false; last_page_scroll = false;
currpage = 0;
recalculateData(); // ie, insert a blank first page
}
TextPart::~TextPart() {
gallery.delImage(textsprite);
}
void TextPart::setText(std::string t) {
text.clear();
// parse and remove the <tint> tagging
for (unsigned int i = 0; i < t.size(); i++) {
if ((t[i] == '<') && (t.size() > i+4))
if ((t[i + 1] == 't') && (t[i + 2] == 'i') && (t[i + 3] == 'n') && (t[i + 4] == 't')) {
i += 5;
std::string tintinfo;
if (t[i] == ' ') i++; // skip initial space, if any
for (; i < t.size(); i++) {
if (t[i] == '>')
break;
tintinfo += t[i];
}
// TODO: handle contents of tintinfo somehow
continue;
}
text += t[i];
}
recalculateData();
}
void TextEntryPart::setText(std::string t) {
TextPart::setText(t);
// place caret at the end of the text
caretline = lines.size() - 1;
caretchar = lines[caretline].text.size();
}
unsigned int calculateScriptId(unsigned int message_id); // from caosVM_agent.cpp, TODO: move into shared file
void TextEntryPart::handleKey(char c) {
// TODO: this is dumb
if (c == 0) { // backspace
if (text.size() == 0) return;
text.erase(text.end() - 1);
caretchar--; // TODO: it's not this simple!
} else if (c == 1) { // return
parent->fireScript(calculateScriptId(messageid), 0); // TODO: is a null FROM correct?
} else {
text += c;
caretchar++; // TODO: it's not this simple!
}
recalculateData();
}
void TextPart::setFormat(int left, int top, int right, int bottom, int line, int _char, bool lefta, bool centera, bool bottoma, bool middlea, bool lastpagescroll) {
leftmargin = left;
topmargin = top;
rightmargin = right;
bottommargin = bottom;
linespacing = line;
charspacing = _char;
left_align = lefta;
center_align = centera;
bottom_align = bottoma;
middle_align = middlea;
last_page_scroll = lastpagescroll;
recalculateData();
}
unsigned int TextPart::calculateWordWidth(std::string word) {
unsigned int x = 0;
for (unsigned int i = 0; i < word.size(); i++) {
if (word[i] < 32) continue; // TODO: replace with space or similar?
int spriteid = word[i] - 32;
x += textsprite->width(spriteid);
if (i != 0) x += charspacing;
}
return x;
}
/*
* Recalculate the data used for rendering the text part.
*/
void TextPart::recalculateData() {
linedata currentdata;
lines.clear();
pages.clear();
pages.push_back(0);
if (text.size() == 0) {
lines.push_back(currentdata); // blank line, so caret is rendered in TextEntryParts
return;
}
unsigned int textwidth = getWidth() - leftmargin - rightmargin;
unsigned int textheight = getHeight() - topmargin - bottommargin;
unsigned int currenty = 0, usedheight = 0;
unsigned int i = 0;
while (i < text.size()) {
bool newline = false;
// first, retrieve a word from the text
std::string word;
for (; i < text.size(); i++) {
if ((text[i] == ' ') || (text[i] == '\n')) {
if (text[i] == '\n') newline = true;
i++;
break;
}
word += text[i];
}
// next, work out whether it fits
unsigned int wordlen = calculateWordWidth(word);
unsigned int spacelen = textsprite->width(0) + charspacing;
unsigned int possiblelen = wordlen;
if (currentdata.text.size() > 0)
possiblelen = wordlen + spacelen;
// TODO: set usedheight as appropriate/needed
usedheight = textsprite->height(0);
if (currentdata.width + possiblelen <= textwidth) {
// the rest of the word fits on the current line, so that's okay.
// add a space if we're not the first word on this line
if (currentdata.text.size() > 0) word = std::string(" ") + word;
currentdata.text += word;
currentdata.width += possiblelen;
} else if (wordlen <= textwidth) {
// the rest of the word doesn't fit on the current line, but does on the next line.
if (currenty + usedheight > textheight) {
currenty = 0;
pages.push_back(lines.size());
} else currenty += usedheight + linespacing;
currentdata.text += " "; // TODO: HACK THINK ABOUT THIS
lines.push_back(currentdata);
currentdata.reset();
currentdata.text += word;
currentdata.width += wordlen;
} else {
// TODO: word is too wide to fit on a single line
// we should output as much as possible and then go backwards
}
// we force a newline here if necessary (ie, if the last char is '\n', except not in the last case)
if ((i < text.size()) && (newline)) {
if (currenty + usedheight > textheight) {
currenty = 0;
pages.push_back(lines.size());
} else currenty += usedheight + linespacing;
lines.push_back(currentdata);
currentdata.reset();
}
}
if (currentdata.text.size() > 0) {
currenty += usedheight;
if (text[text.size() -1] == ' ') currentdata.text += " "; // TODO: HACK THINK ABOUT THIS
lines.push_back(currentdata);
}
}
void TextPart::render(SDLBackend *renderer, int xoffset, int yoffset, TextEntryPart *caretdata) {
CompoundPart::render(renderer, xoffset + x, yoffset + y);
unsigned int xoff = xoffset + x + leftmargin;
unsigned int yoff = yoffset + y + topmargin;
unsigned int textwidth = getWidth() - leftmargin - rightmargin;
unsigned int textheight = getHeight() - topmargin - bottommargin;
unsigned int currenty = 0, usedheight = 0;
unsigned int startline = pages[currpage];
unsigned int endline = (currpage + 1 < pages.size() ? pages[currpage + 1] : lines.size());
for (unsigned int i = startline; i < endline; i++) {
unsigned int currentx = 0, somex = xoff;
if (center_align)
somex = somex + ((textwidth - lines[i].width) / 2);
for (unsigned int x = 0; x < lines[i].text.size(); x++) {
if (lines[i].text[x] < 32) continue; // TODO: replace with space or similar?
int spriteid = lines[i].text[x] - 32;
renderer->render(textsprite, spriteid, somex + currentx, yoff + currenty, is_transparent, transparency);
if ((caretdata) && (caretdata->caretline == i) && (caretdata->caretchar == x))
caretdata->renderCaret(renderer, somex + currentx, yoff + currenty);
currentx += textsprite->width(spriteid) + charspacing;
}
if ((caretdata) && (caretdata->caretline == i) && (caretdata->caretchar == lines[i].text.size()))
caretdata->renderCaret(renderer, somex + currentx, yoff + currenty);
currenty += textsprite->height(0) + linespacing;
}
}
FixedTextPart::FixedTextPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg, int _x, int _y,
unsigned int _z, std::string fontsprite) : TextPart(p, _id, spritefile, fimg, _x, _y, _z, fontsprite) {
// nothing, hopefully.. :)
}
TextEntryPart::TextEntryPart(CompoundAgent *p, unsigned int _id, std::string spritefile, unsigned int fimg, int _x, int _y,
unsigned int _z, unsigned int msgid, std::string fontsprite) : TextPart(p, _id, spritefile, fimg, _x, _y, _z, fontsprite) {
// TODO: hm, this never gets freed..
if (!caretsprite) { caretsprite = gallery.getImage("cursor"); caos_assert(caretsprite); }
caretpose = 0;
caretline = 0;
caretchar = 0;
focused = false;
messageid = msgid;
}
void TextEntryPart::render(SDLBackend *renderer, int xoffset, int yoffset) {
TextPart::render(renderer, xoffset, yoffset, (focused ? this : 0));
}
void TextEntryPart::renderCaret(SDLBackend *renderer, int xoffset, int yoffset) {
// TODO: fudge xoffset/yoffset as required
renderer->render(caretsprite, caretpose, xoffset, yoffset, is_transparent, transparency);
}
void TextEntryPart::tick() {
CompoundPart::tick();
if (focused) {
caretpose++;
if (caretpose == caretsprite->numframes())
caretpose = 0;
}
}
void CompoundPart::tick() {
if (!animation.empty()) {
if (framerate > 1) {
framedelay++;
if (framedelay == framerate + 1)
framedelay = 0;
}
if (framedelay == 0) {
unsigned int f = frameno + 1;
if (f == animation.size()) return;
if (animation[f] == 255) {
if (f == (animation.size() - 1)) f = 0;
else f = animation[f + 1];
}
setFrameNo(f);
}
}
}
/* vim: set noet: */
<|endoftext|>
|
<commit_before>#include <typeinfo>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cassert>
#include <vector>
using namespace std;
std::vector<std::string> Tokenize(const std::string& str,
const std::string& delimiters = " \t");
template<typename T>
inline T Scan(const std::string &input)
{
std::stringstream stream(input);
T ret;
stream >> ret;
return ret;
}
class FF
{
public:
vector<string> toks;
string name;
string path;
int index, numFeatures;
FF(const string &line)
{
toks = Tokenize(line, ":");
}
virtual string ffType() const= 0;
};
class LM : public FF
{
friend std::ostream& operator<<(std::ostream&, const LM&);
static int s_index;
public:
string otherArgs;
int order, factor;
LM(const string &line)
:FF(line)
{
numFeatures = 1;
factor = Scan<int>(toks[0]);
order = Scan<int>(toks[1]);
path = toks[2];
int implNum = Scan<int>(toks[3]);
switch (implNum)
{
case 0: name = "SRILM"; break;
case 1: name = "IRSTLM"; break;
case 8: name = "KENLM"; otherArgs = "lazyken=0"; break;
case 9: name = "KENLM"; otherArgs = "lazyken=1"; break;
}
}
string ffType() const
{ return "LM"; }
};
std::ostream& operator<<(std::ostream &out, const LM &model)
{
out << model.name << model.index << " "
<< " order=" << model.order
<< " factor=" << model.factor
<< " path=" << model.path
<< " " << model.otherArgs
<< endl;
return out;
}
class RO : public FF
{
friend std::ostream& operator<<(std::ostream&, const RO&);
static int s_index;
public:
RO(const string &line)
:FF(line)
{
name = "LexicalReordering";
numFeatures = 6;
path = toks[0];
}
string ffType() const
{ return "RO"; }
};
std::ostream& operator<<(std::ostream &out, const RO &model)
{
out << model.name << model.index << " "
<< " path=" << model.path
<< endl;
return out;
}
class Pt : public FF
{
friend std::ostream& operator<<(std::ostream&, const Pt&);
static int s_index;
public:
int numFeatures;
vector<int> inFactor, outFactor;
Pt(const string &line)
:FF(line)
{
index = s_index++;
name = "PhraseModel";
numFeatures = 5;
path = toks[0];
inFactor.push_back(0);
outFactor.push_back(0);
}
string ffType() const
{ return "Pt"; }
};
int Pt::s_index = 0;
ostream& operator<<(ostream& out, const Pt& model)
{
out << model.name << model.index << " "
<< " path=" << model.path
<< endl;
return out;
}
string iniPath;
vector<FF*> ffVec;
void OutputWeights(stringstream &weightStrme, const FF &ff)
{
}
void Output()
{
ofstream strme(iniPath.c_str());
stringstream weightStrme;
weightStrme << "[weight]" << endl;
strme << "[input-factors]" << endl;
strme << "0" << endl;
strme << "[mapping]" << endl;
strme << "0 T 0" << endl;
strme << "[distortion-limit]" << endl;
strme << "6" << endl;
strme << "[feature]" << endl;
for (size_t i = 0; i < ffVec.size(); ++i) {
const FF &ff = *ffVec[i];
strme << ff;
OutputWeights(weightStrme, ff);
}
strme << weightStrme.str();
strme.close();
}
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i) {
string key(argv[i]);
if (key == "-phrase-translation-table") {
++i;
Pt *model = new Pt(argv[i]);
ffVec.push_back(model);
}
else if (key == "-reordering-table") {
++i;
RO *model = new RO(argv[i]);
ffVec.push_back(model);
}
else if (key == "-lm") {
++i;
LM *model = new LM(argv[i]);
ffVec.push_back(model);
}
else if (key == "-config") {
++i;
iniPath = argv[i];
}
}
Output();
}
std::vector<std::string> Tokenize(const std::string& str,
const std::string& delimiters)
{
std::vector<std::string> tokens;
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos) {
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
<commit_msg>create-ini.cpp<commit_after>#include <typeinfo>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cassert>
#include <vector>
using namespace std;
std::vector<std::string> Tokenize(const std::string& str,
const std::string& delimiters = " \t");
template<typename T>
inline T Scan(const std::string &input)
{
std::stringstream stream(input);
T ret;
stream >> ret;
return ret;
}
class FF
{
friend std::ostream& operator<<(std::ostream &out, const FF&);
virtual void Output(std::ostream &out) const = 0;
public:
vector<string> toks;
string name;
string path;
int index, numFeatures;
FF(const string &line)
{
toks = Tokenize(line, ":");
}
virtual string ffType() const= 0;
};
std::ostream& operator<<(std::ostream &out, const FF &model)
{
model.Output(out);
return out;
}
class LM : public FF
{
static int s_index;
void Output(std::ostream &out) const
{
out << name << index << " "
<< " order=" << order
<< " factor=" << factor
<< " path=" << path
<< " " << otherArgs;
}
public:
string otherArgs;
int order, factor;
LM(const string &line)
:FF(line)
{
numFeatures = 1;
factor = Scan<int>(toks[0]);
order = Scan<int>(toks[1]);
path = toks[2];
int implNum = Scan<int>(toks[3]);
switch (implNum)
{
case 0: name = "SRILM"; break;
case 1: name = "IRSTLM"; break;
case 8: name = "KENLM"; otherArgs = "lazyken=0"; break;
case 9: name = "KENLM"; otherArgs = "lazyken=1"; break;
}
}
string ffType() const
{ return "LM"; }
};
class RO : public FF
{
static int s_index;
void Output(std::ostream &out) const
{
out << name << index << " "
<< " path=" << path;
}
public:
RO(const string &line)
:FF(line)
{
name = "LexicalReordering";
numFeatures = 6;
path = toks[0];
}
string ffType() const
{ return "RO"; }
};
class Pt : public FF
{
static int s_index;
void Output(std::ostream &out) const
{
out << name << index << " "
<< " path=" << path;
}
public:
int numFeatures;
vector<int> inFactor, outFactor;
Pt(const string &line)
:FF(line)
{
index = s_index++;
name = "PhraseModel";
numFeatures = 5;
path = toks[0];
inFactor.push_back(0);
outFactor.push_back(0);
}
string ffType() const
{ return "Pt"; }
};
int Pt::s_index = 0;
string iniPath;
vector<FF*> ffVec;
void OutputWeights(stringstream &weightStrme, const FF &ff)
{
}
void Output()
{
ofstream strme(iniPath.c_str());
stringstream weightStrme;
weightStrme << "[weight]" << endl;
strme << "[input-factors]" << endl;
strme << "0" << endl;
strme << "[mapping]" << endl;
strme << "0 T 0" << endl;
strme << "[distortion-limit]" << endl;
strme << "6" << endl;
strme << "[feature]" << endl;
for (size_t i = 0; i < ffVec.size(); ++i) {
const FF &ff = *ffVec[i];
strme << ff << endl;
OutputWeights(weightStrme, ff);
}
strme << weightStrme.str();
strme.close();
}
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i) {
string key(argv[i]);
if (key == "-phrase-translation-table") {
++i;
Pt *model = new Pt(argv[i]);
ffVec.push_back(model);
}
else if (key == "-reordering-table") {
++i;
RO *model = new RO(argv[i]);
ffVec.push_back(model);
}
else if (key == "-lm") {
++i;
LM *model = new LM(argv[i]);
ffVec.push_back(model);
}
else if (key == "-config") {
++i;
iniPath = argv[i];
}
}
Output();
}
std::vector<std::string> Tokenize(const std::string& str,
const std::string& delimiters)
{
std::vector<std::string> tokens;
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos) {
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
<|endoftext|>
|
<commit_before>/**
* @file file_location_benchmark.cc
* @author Rafal Grzeszczuk
* @copyright (C) 2018 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#include "messages/fuse/fileBlock.h"
#include "messages/fuse/fileLocation.h"
#include <boost/random.hpp>
#include <boost/range/irange.hpp>
#include <folly/Benchmark.h>
#include <folly/Foreach.h>
#include <utility>
using namespace one::messages::fuse;
constexpr auto blockSize = 1024; // 1KB
BENCHMARK(benchmarkPutSingleBlock)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkPutHugeBlock)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(
0, blockSize * blockSize * blockSize, FileBlock{" ", " "});
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkPutManyBlocks)
{
auto fileLocation = FileLocation{};
FOR_EACH_RANGE(i, 0, 1000000)
{
fileLocation.putBlock(blockSize * i, blockSize, FileBlock{" ", " "});
}
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkPutBlockRandomly)
{
auto fileLocation = FileLocation{};
auto randomBlockNumber = 0;
BENCHMARK_SUSPEND
{
for (auto i : boost::irange(1, 1024 * 1024))
fileLocation.putBlock(
2 * i * blockSize, blockSize, FileBlock{" ", " "});
}
BENCHMARK_SUSPEND
{
std::time_t now = std::time(0);
boost::random::mt19937 gen{static_cast<std::uint32_t>(now)};
boost::random::uniform_int_distribution<> randomBlock(1, 1024 * 1024);
randomBlockNumber = randomBlock(gen);
}
fileLocation.putBlock(randomBlockNumber, blockSize, FileBlock{" ", " "});
folly::doNotOptimizeAway(fileLocation);
folly::doNotOptimizeAway(randomBlockNumber);
}
BENCHMARK(benchmarkPutManyBlocksRandomly)
{
auto fileLocation = FileLocation{};
auto randomBlockNumber = 0;
BENCHMARK_SUSPEND
{
for (auto i : boost::irange(1, 1024))
fileLocation.putBlock(
i * blockSize, blockSize, FileBlock{" ", " "});
}
FOR_EACH_RANGE(i, 0, 100000)
{
BENCHMARK_SUSPEND
{
std::time_t now = std::time(0);
boost::random::mt19937 gen{static_cast<std::uint32_t>(now)};
boost::random::uniform_int_distribution<> randomBlock(
1, 1024 * 1024);
randomBlockNumber = randomBlock(gen);
}
fileLocation.putBlock(
randomBlockNumber, blockSize, FileBlock{" ", " "});
}
folly::doNotOptimizeAway(fileLocation);
folly::doNotOptimizeAway(randomBlockNumber);
}
BENCHMARK(benchmarkFileBlockCreation)
{
auto fileBlock = FileBlock{" ", " "};
folly::doNotOptimizeAway(fileBlock);
}
BENCHMARK(benchmarkToString)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
}
fileLocation.toString();
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkProgressString)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
}
fileLocation.progressString(blockSize, 10);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkProgressStringLarge)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
FOR_EACH_RANGE(i, 0, 1000000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
fileLocation.progressString(blockSize, 10);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkReplicationProgress)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
}
fileLocation.replicationProgress(blockSize);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkReplicationProgressLarge)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
FOR_EACH_RANGE(i, 0, 1000000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
fileLocation.replicationProgress(blockSize);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkLinearReadReadPrefetch)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
}
fileLocation.linearReadPrefetchThresholdReached(1, 1);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkLinearReadReadPrefetchLarge)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
FOR_EACH_RANGE(i, 0, 1000000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
fileLocation.linearReadPrefetchThresholdReached(1, 1);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkRandomReadReadPrefetch)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
}
fileLocation.randomReadPrefetchThresholdReached(1, 1);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkRandomReadReadPrefetchLarge)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
FOR_EACH_RANGE(i, 0, 1000000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
fileLocation.randomReadPrefetchThresholdReached(1, 1);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkRandomBlocksInRangeAll)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
FOR_EACH_RANGE(i, 0, 1000000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
auto result = fileLocation.blocksInRange(0, 1000000);
folly::doNotOptimizeAway(fileLocation);
folly::doNotOptimizeAway(result);
}
BENCHMARK(benchmarkRandomBlocksInRangeRandom)
{
auto fileLocation = FileLocation{};
auto intervalBegin = 0;
BENCHMARK_SUSPEND
{
std::time_t now = std::time(0);
boost::random::mt19937 gen{static_cast<std::uint32_t>(now)};
boost::random::uniform_int_distribution<> randomBlock(1, 1024 * 1024);
intervalBegin = randomBlock(gen);
FOR_EACH_RANGE(i, 0, 1000000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
auto result = fileLocation.blocksInRange(intervalBegin, 1024);
folly::doNotOptimizeAway(fileLocation);
folly::doNotOptimizeAway(result);
}
int main() { folly::runBenchmarks(); }
<commit_msg>VFS-4515 Added FileLocation::updateInRange microbenchmark<commit_after>/**
* @file file_location_benchmark.cc
* @author Rafal Grzeszczuk
* @copyright (C) 2018 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#include "messages/fuse/fileBlock.h"
#include "messages/fuse/fileLocation.h"
#include <boost/random.hpp>
#include <boost/range/irange.hpp>
#include <folly/Benchmark.h>
#include <folly/Foreach.h>
#include <utility>
using namespace one::messages::fuse;
constexpr auto blockSize = 1024; // 1KB
BENCHMARK(benchmarkPutSingleBlock)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkPutHugeBlock)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(
0, blockSize * blockSize * blockSize, FileBlock{" ", " "});
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkPutManyBlocks)
{
auto fileLocation = FileLocation{};
FOR_EACH_RANGE(i, 0, 1'000'000)
{
fileLocation.putBlock(blockSize * i, blockSize, FileBlock{" ", " "});
}
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkPutBlockRandomly)
{
auto fileLocation = FileLocation{};
auto randomBlockNumber = 0;
BENCHMARK_SUSPEND
{
for (auto i : boost::irange(1, 1024 * 1024))
fileLocation.putBlock(
2 * i * blockSize, blockSize, FileBlock{" ", " "});
std::time_t now = std::time(0);
boost::random::mt19937 gen{static_cast<std::uint32_t>(now)};
boost::random::uniform_int_distribution<> randomBlock(1, 1024 * 1024);
randomBlockNumber = randomBlock(gen);
}
fileLocation.putBlock(randomBlockNumber, blockSize, FileBlock{" ", " "});
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkPutManyBlocksRandomly)
{
auto fileLocation = FileLocation{};
auto randomBlockNumber = 0;
BENCHMARK_SUSPEND
{
for (auto i : boost::irange(1, 1024))
fileLocation.putBlock(
i * blockSize, blockSize, FileBlock{" ", " "});
}
FOR_EACH_RANGE(i, 0, 100'000)
{
BENCHMARK_SUSPEND
{
std::time_t now = std::time(0);
boost::random::mt19937 gen{static_cast<std::uint32_t>(now)};
boost::random::uniform_int_distribution<> randomBlock(
1, 1024 * 1024);
randomBlockNumber = randomBlock(gen);
}
fileLocation.putBlock(
randomBlockNumber, blockSize, FileBlock{" ", " "});
}
folly::doNotOptimizeAway(fileLocation);
folly::doNotOptimizeAway(randomBlockNumber);
}
BENCHMARK(benchmarkFileBlockCreation)
{
auto fileBlock = FileBlock{" ", " "};
folly::doNotOptimizeAway(fileBlock);
}
BENCHMARK(benchmarkToString)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
}
fileLocation.toString();
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkProgressString)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
}
fileLocation.progressString(blockSize, 10);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkProgressStringLarge)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
FOR_EACH_RANGE(i, 0, 1'000'000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
fileLocation.progressString(blockSize, 10);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkReplicationProgress)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
}
fileLocation.replicationProgress(blockSize);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkReplicationProgressLarge)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
FOR_EACH_RANGE(i, 0, 1'000'000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
fileLocation.replicationProgress(blockSize);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkLinearReadReadPrefetch)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
}
fileLocation.linearReadPrefetchThresholdReached(1, 1);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkLinearReadReadPrefetchLarge)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
FOR_EACH_RANGE(i, 0, 1'000'000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
fileLocation.linearReadPrefetchThresholdReached(1, 1);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkRandomReadReadPrefetch)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
fileLocation.putBlock(0, blockSize, FileBlock{" ", " "});
}
fileLocation.randomReadPrefetchThresholdReached(1, 1);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkRandomReadReadPrefetchLarge)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
FOR_EACH_RANGE(i, 0, 1'000'000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
fileLocation.randomReadPrefetchThresholdReached(1, 1);
folly::doNotOptimizeAway(fileLocation);
}
BENCHMARK(benchmarkRandomBlocksInRangeAll)
{
auto fileLocation = FileLocation{};
BENCHMARK_SUSPEND
{
FOR_EACH_RANGE(i, 0, 1'000'000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
auto result = fileLocation.blocksInRange(0, 1'000'000);
folly::doNotOptimizeAway(fileLocation);
folly::doNotOptimizeAway(result);
}
BENCHMARK(benchmarkRandomBlocksInRangeRandom)
{
auto fileLocation = FileLocation{};
auto intervalBegin = 0;
BENCHMARK_SUSPEND
{
std::time_t now = std::time(0);
boost::random::mt19937 gen{static_cast<std::uint32_t>(now)};
boost::random::uniform_int_distribution<> randomBlock(1, 1024 * 1024);
intervalBegin = randomBlock(gen);
FOR_EACH_RANGE(i, 0, 1'000'000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
}
auto result = fileLocation.blocksInRange(intervalBegin, 1024);
folly::doNotOptimizeAway(fileLocation);
folly::doNotOptimizeAway(result);
}
BENCHMARK(benchmarkUpdateBlocksInRangeLarge)
{
auto fileLocation = FileLocation{};
auto fileLocationUpdate = FileLocation{};
auto randomBlockNumber = 0;
BENCHMARK_SUSPEND
{
std::time_t now = std::time(0);
boost::random::mt19937 gen{static_cast<std::uint32_t>(now)};
boost::random::uniform_int_distribution<> randomBlock(1, 1024 * 1024);
FOR_EACH_RANGE(i, 0, 1'000'000)
{
fileLocation.putBlock(
blockSize * i, blockSize, FileBlock{" ", " "});
}
randomBlockNumber = randomBlock(gen);
fileLocationUpdate.putBlock(
randomBlockNumber, 100, FileBlock{" ", " "});
}
fileLocation.updateInRange(
randomBlockNumber, randomBlockNumber + 100, fileLocationUpdate);
folly::doNotOptimizeAway(fileLocation);
}
int main() { folly::runBenchmarks(); }
<|endoftext|>
|
<commit_before>#pragma once
#include "pin.hpp"
enum SpiMode
{
SpiMode0 = 0x00,
SpiMode1 = 0x04,
SpiMode2 = 0x08,
SpiMode3 = 0x0C
};
enum SpiBitOrder
{
SpiLsbFirst,
SpiMsbFirst
};
template <unsigned P_SS>
class Spi
{
public:
Spi() : ss(Output), sclk(Output), mosi(Output), miso(Input)
{
ss.high();
SPCR |= _BV(MSTR);
SPCR |= _BV(SPE);
}
~Spi()
{
SPCR &= ~_BV(SPE);
}
uint8_t transfer(uint8_t byte)
{
SPDR = byte;
while (!(SPSR & (1<<SPIF)));
return SPDR;
}
void setMode(SpiMode m) { SPCR = (SPCR & ~0x0C) | m; }
SpiMode mode() { return SpiMode(SPCR & 0x0C); }
void setBitOrder(SpiBitOrder b) { if (b == SpiLsbFirst) SPCR |= (1<<DORD); else SPCR &= ~(1<<DORD); }
SpiBitOrder bitOrder() { return SPCR & (1<<DORD) ? SpiLsbFirst : SpiMsbFirst; }
private:
Pin<P_SS> ss;
Pin<SCLK> sclk;
Pin<MOSI> mosi;
Pin<MISO> miso;
};
<commit_msg>SPI: Enable device only during transfer.<commit_after>#pragma once
#include "pin.hpp"
enum SpiMode
{
SpiMode0 = 0x00,
SpiMode1 = 0x04,
SpiMode2 = 0x08,
SpiMode3 = 0x0C
};
enum SpiBitOrder
{
SpiLsbFirst,
SpiMsbFirst
};
template <unsigned P_SS>
class Spi
{
public:
Spi() : ss(Output), sclk(Output), mosi(Output), miso(Input)
{
ss.high();
SPCR |= _BV(MSTR);
SPCR |= _BV(SPE);
}
~Spi()
{
SPCR &= ~_BV(SPE);
}
uint8_t transfer(uint8_t byte)
{
ss.low();
SPDR = byte;
while (!(SPSR & (1<<SPIF)));
uint8_t r = SPDR;
ss.high();
return r;
}
void setMode(SpiMode m) { SPCR = (SPCR & ~0x0C) | m; }
SpiMode mode() { return SpiMode(SPCR & 0x0C); }
void setBitOrder(SpiBitOrder b) { if (b == SpiLsbFirst) SPCR |= (1<<DORD); else SPCR &= ~(1<<DORD); }
SpiBitOrder bitOrder() { return SPCR & (1<<DORD) ? SpiLsbFirst : SpiMsbFirst; }
private:
Pin<P_SS> ss;
Pin<SCLK> sclk;
Pin<MOSI> mosi;
Pin<MISO> miso;
};
<|endoftext|>
|
<commit_before>/*
* ASTFactory.cpp
*
* This file is part of the XShaderCompiler project (Copyright (c) 2014-2017 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "ASTFactory.h"
#include "Helper.h"
#include "Exception.h"
#include "Variant.h"
namespace Xsc
{
namespace ASTFactory
{
template <typename T, typename... Args>
std::shared_ptr<T> MakeAST(Args&&... args)
{
return MakeShared<T>(SourcePosition::ignore, std::forward<Args>(args)...);
}
template <typename T, typename Origin, typename... Args>
std::shared_ptr<T> MakeASTWithOrigin(Origin origin, Args&&... args)
{
return MakeShared<T>(origin->area, std::forward<Args>(args)...);
}
/* ----- Make functions ----- */
FunctionCallExprPtr MakeIntrinsicCallExpr(
const Intrinsic intrinsic, const std::string& ident, const TypeDenoterPtr& typeDenoter, const std::vector<ExprPtr>& arguments)
{
auto ast = MakeAST<FunctionCallExpr>();
{
auto funcCall = MakeAST<FunctionCall>();
{
funcCall->varIdent = MakeAST<VarIdent>();
funcCall->varIdent->ident = ident;
funcCall->typeDenoter = typeDenoter;
funcCall->arguments = arguments;
funcCall->intrinsic = intrinsic;
}
ast->call = funcCall;
}
return ast;
}
CastExprPtr MakeCastExpr(const TypeDenoterPtr& typeDenoter, const ExprPtr& valueExpr)
{
auto ast = MakeAST<CastExpr>();
{
ast->typeSpecifier = MakeTypeSpecifier(typeDenoter);
ast->typeSpecifier->area = valueExpr->area;
ast->expr = valueExpr;
}
return ast;
}
CastExprPtr MakeLiteralCastExpr(const TypeDenoterPtr& typeDenoter, const DataType literalType, const std::string& literalValue)
{
return MakeCastExpr(typeDenoter, MakeLiteralExpr(literalType, literalValue));
}
SuffixExprPtr MakeSuffixExpr(const ExprPtr& expr, const VarIdentPtr& varIdent)
{
auto ast = MakeASTWithOrigin<SuffixExpr>(expr);
{
ast->expr = expr;
ast->varIdent = varIdent;
}
return ast;
}
ExprPtr MakeCastOrSuffixCastExpr(const TypeDenoterPtr& typeDenoter, const ExprPtr& valueExpr, const VarIdentPtr& suffixVarIdent)
{
auto castExpr = ASTFactory::MakeCastExpr(typeDenoter, valueExpr);
if (suffixVarIdent)
return MakeSuffixExpr(castExpr, suffixVarIdent);
else
return castExpr;
}
LiteralExprPtr MakeLiteralExpr(const DataType literalType, const std::string& literalValue)
{
auto ast = MakeAST<LiteralExpr>();
{
ast->dataType = literalType;
ast->value = literalValue;
}
return ast;
}
LiteralExprPtr MakeLiteralExpr(const Variant& literalValue)
{
switch (literalValue.Type())
{
case Variant::Types::Bool:
return MakeLiteralExpr(DataType::Bool, std::to_string(literalValue.Bool()));
case Variant::Types::Int:
return MakeLiteralExpr(DataType::Int, std::to_string(literalValue.Int()));
case Variant::Types::Real:
return MakeLiteralExpr(DataType::Float, std::to_string(literalValue.Real()));
}
return MakeLiteralExpr(DataType::Int, "0");
}
AliasDeclStmntPtr MakeBaseTypeAlias(const DataType dataType, const std::string& ident)
{
auto ast = MakeAST<AliasDeclStmnt>();
{
auto aliasDecl = MakeAST<AliasDecl>();
{
aliasDecl->ident = ident;
aliasDecl->typeDenoter = MakeShared<BaseTypeDenoter>(dataType);
aliasDecl->declStmntRef = ast.get();
}
ast->aliasDecls.push_back(aliasDecl);
}
return ast;
}
TypeSpecifierPtr MakeTypeSpecifier(const StructDeclPtr& structDecl)
{
auto ast = MakeAST<TypeSpecifier>();
{
ast->structDecl = structDecl;
ast->typeDenoter = std::make_shared<StructTypeDenoter>(structDecl.get());
}
ast->area = ast->structDecl->area;
return ast;
}
TypeSpecifierPtr MakeTypeSpecifier(const TypeDenoterPtr& typeDenoter)
{
auto ast = MakeAST<TypeSpecifier>();
{
ast->typeDenoter = typeDenoter;
}
return ast;
}
TypeSpecifierPtr MakeTypeSpecifier(const DataType dataType)
{
return MakeTypeSpecifier(MakeShared<BaseTypeDenoter>(dataType));
}
VarDeclStmntPtr MakeVarDeclStmnt(const DataType dataType, const std::string& ident)
{
auto ast = MakeAST<VarDeclStmnt>();
{
ast->typeSpecifier = MakeTypeSpecifier(dataType);
auto varDecl = MakeAST<VarDecl>();
{
varDecl->ident = ident;
varDecl->declStmntRef = ast.get();
}
ast->varDecls.push_back(varDecl);
}
return ast;
}
VarIdentPtr MakeVarIdent(const std::string& ident, AST* symbolRef)
{
auto ast = MakeAST<VarIdent>();
{
ast->ident = ident;
ast->symbolRef = symbolRef;
}
return ast;
}
VarAccessExprPtr MakeVarAccessExpr(const std::string& ident, AST* symbolRef)
{
auto ast = MakeAST<VarAccessExpr>();
{
ast->varIdent = MakeVarIdent(ident, symbolRef);
}
return ast;
}
/*
TODO:
This is currently being used to convert a scalar-to-struct cast expression
into a struct-constructor expression (e.g. "(S)0" -> "S(0, 0, 0)").
This is done by using a list-expression instead of an argument list for the constructor.
This should be changed, because a list-expression is not meant to be used as argument list!
-> see GLSLConverter::VisitCastExpr
*/
#if 1
static ExprPtr MakeConstructorListExprPrimarySingle(const LiteralExprPtr& literalExpr, const TypeDenoterPtr& typeDen)
{
if (auto structTypeDen = typeDen->As<StructTypeDenoter>())
{
if (auto structDecl = structTypeDen->structDeclRef)
{
/* Get the type denoter of all structure members */
std::vector<TypeDenoterPtr> memberTypeDens;
structDecl->CollectMemberTypeDenoters(memberTypeDens);
/* Generate list expression with N copies of the literal (where N is the number of struct members) */
return MakeCastExpr(typeDen, MakeConstructorListExpr(literalExpr, memberTypeDens));
}
}
return literalExpr;
}
static ExprPtr MakeConstructorListExprPrimary(
const LiteralExprPtr& literalExpr,
std::vector<TypeDenoterPtr>::const_iterator typeDensBegin,
std::vector<TypeDenoterPtr>::const_iterator typeDensEnd)
{
if (typeDensBegin + 1 != typeDensEnd)
{
auto ast = MakeAST<ListExpr>();
{
ast->firstExpr = MakeConstructorListExprPrimarySingle(literalExpr, (*typeDensBegin)->Get());
ast->nextExpr = MakeConstructorListExprPrimary(literalExpr, typeDensBegin + 1, typeDensEnd);
}
return ast;
}
else
return MakeConstructorListExprPrimarySingle(literalExpr, (*typeDensBegin)->Get());
}
ExprPtr MakeConstructorListExpr(const LiteralExprPtr& literalExpr, const std::vector<TypeDenoterPtr>& listTypeDens)
{
if (listTypeDens.empty())
return nullptr;
else
return MakeConstructorListExprPrimary(literalExpr, listTypeDens.begin(), listTypeDens.end());
}
#endif
ExprStmntPtr MakeArrayAssignStmnt(VarDecl* varDecl, const std::vector<int>& arrayIndices, const ExprPtr& assignExpr)
{
auto ast = MakeAST<ExprStmnt>();
{
auto expr = MakeAST<VarAccessExpr>();
{
expr->varIdent = MakeVarIdent(varDecl->ident, varDecl);
expr->varIdent->arrayIndices = MakeArrayIndices(arrayIndices);
expr->assignOp = AssignOp::Set;
expr->assignExpr = assignExpr;
}
ast->expr = expr;
}
return ast;
}
ArrayDimensionPtr MakeArrayDimension(int arraySize)
{
auto ast = MakeAST<ArrayDimension>();
{
if (arraySize > 0)
{
ast->expr = MakeLiteralExpr(DataType::Int, std::to_string(arraySize));
ast->size = arraySize;
}
else
{
ast->expr = MakeAST<NullExpr>();
ast->size = 0;
}
}
return ast;
}
/* ----- Make list functions ----- */
std::vector<ExprPtr> MakeArrayIndices(const std::vector<int>& arrayIndices)
{
std::vector<ExprPtr> exprs;
for (auto index : arrayIndices)
exprs.push_back(MakeLiteralExpr(DataType::Int, std::to_string(index)));
return exprs;
}
std::vector<ArrayDimensionPtr> MakeArrayDimensionList(const std::vector<int>& arraySizes)
{
std::vector<ArrayDimensionPtr> arrayDims;
for (auto dim : arraySizes)
arrayDims.push_back(MakeArrayDimension(dim));
return arrayDims;
}
/* ----- Convert functions ----- */
ExprPtr ConvertExprBaseType(const DataType dataType, const ExprPtr& subExpr)
{
if (subExpr->Type() == AST::Types::LiteralExpr && IsScalarType(dataType))
{
/* Convert data type into literal expression */
auto ast = std::static_pointer_cast<LiteralExpr>(subExpr);
{
ast->ConvertDataType(dataType);
}
return ast;
}
else
{
/* Make new cast expression */
auto ast = MakeShared<CastExpr>(subExpr->area);
{
ast->typeSpecifier = MakeTypeSpecifier(MakeShared<BaseTypeDenoter>(dataType));
ast->typeSpecifier->area = subExpr->area;
ast->expr = subExpr;
}
return ast;
}
}
ArrayDimensionPtr ConvertExprToArrayDimension(const ExprPtr& expr)
{
auto ast = MakeAST<ArrayDimension>();
{
if (expr)
{
ast->area = expr->area;
ast->expr = expr;
}
}
return ast;
}
std::vector<ArrayDimensionPtr> ConvertExprListToArrayDimensionList(const std::vector<ExprPtr>& exprs)
{
std::vector<ArrayDimensionPtr> arrayDims;
for (const auto& expr : exprs)
arrayDims.push_back(ConvertExprToArrayDimension(expr));
return arrayDims;
}
} // /namespace ASTFactory
} // /namespace Xsc
// ================================================================================
<commit_msg>Continued with scalar-to-struct cast expression in ASTFactory.<commit_after>/*
* ASTFactory.cpp
*
* This file is part of the XShaderCompiler project (Copyright (c) 2014-2017 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "ASTFactory.h"
#include "Helper.h"
#include "Exception.h"
#include "Variant.h"
namespace Xsc
{
namespace ASTFactory
{
template <typename T, typename... Args>
std::shared_ptr<T> MakeAST(Args&&... args)
{
return MakeShared<T>(SourcePosition::ignore, std::forward<Args>(args)...);
}
template <typename T, typename Origin, typename... Args>
std::shared_ptr<T> MakeASTWithOrigin(Origin origin, Args&&... args)
{
return MakeShared<T>(origin->area, std::forward<Args>(args)...);
}
/* ----- Make functions ----- */
FunctionCallExprPtr MakeIntrinsicCallExpr(
const Intrinsic intrinsic, const std::string& ident, const TypeDenoterPtr& typeDenoter, const std::vector<ExprPtr>& arguments)
{
auto ast = MakeAST<FunctionCallExpr>();
{
auto funcCall = MakeAST<FunctionCall>();
{
funcCall->varIdent = MakeAST<VarIdent>();
funcCall->varIdent->ident = ident;
funcCall->typeDenoter = typeDenoter;
funcCall->arguments = arguments;
funcCall->intrinsic = intrinsic;
}
ast->call = funcCall;
}
return ast;
}
CastExprPtr MakeCastExpr(const TypeDenoterPtr& typeDenoter, const ExprPtr& valueExpr)
{
auto ast = MakeAST<CastExpr>();
{
ast->typeSpecifier = MakeTypeSpecifier(typeDenoter);
ast->typeSpecifier->area = valueExpr->area;
ast->expr = valueExpr;
}
return ast;
}
CastExprPtr MakeLiteralCastExpr(const TypeDenoterPtr& typeDenoter, const DataType literalType, const std::string& literalValue)
{
return MakeCastExpr(typeDenoter, MakeLiteralExpr(literalType, literalValue));
}
SuffixExprPtr MakeSuffixExpr(const ExprPtr& expr, const VarIdentPtr& varIdent)
{
auto ast = MakeASTWithOrigin<SuffixExpr>(expr);
{
ast->expr = expr;
ast->varIdent = varIdent;
}
return ast;
}
ExprPtr MakeCastOrSuffixCastExpr(const TypeDenoterPtr& typeDenoter, const ExprPtr& valueExpr, const VarIdentPtr& suffixVarIdent)
{
auto castExpr = ASTFactory::MakeCastExpr(typeDenoter, valueExpr);
if (suffixVarIdent)
return MakeSuffixExpr(castExpr, suffixVarIdent);
else
return castExpr;
}
LiteralExprPtr MakeLiteralExpr(const DataType literalType, const std::string& literalValue)
{
auto ast = MakeAST<LiteralExpr>();
{
ast->dataType = literalType;
ast->value = literalValue;
}
return ast;
}
LiteralExprPtr MakeLiteralExpr(const Variant& literalValue)
{
switch (literalValue.Type())
{
case Variant::Types::Bool:
return MakeLiteralExpr(DataType::Bool, std::to_string(literalValue.Bool()));
case Variant::Types::Int:
return MakeLiteralExpr(DataType::Int, std::to_string(literalValue.Int()));
case Variant::Types::Real:
return MakeLiteralExpr(DataType::Float, std::to_string(literalValue.Real()));
}
return MakeLiteralExpr(DataType::Int, "0");
}
AliasDeclStmntPtr MakeBaseTypeAlias(const DataType dataType, const std::string& ident)
{
auto ast = MakeAST<AliasDeclStmnt>();
{
auto aliasDecl = MakeAST<AliasDecl>();
{
aliasDecl->ident = ident;
aliasDecl->typeDenoter = MakeShared<BaseTypeDenoter>(dataType);
aliasDecl->declStmntRef = ast.get();
}
ast->aliasDecls.push_back(aliasDecl);
}
return ast;
}
TypeSpecifierPtr MakeTypeSpecifier(const StructDeclPtr& structDecl)
{
auto ast = MakeAST<TypeSpecifier>();
{
ast->structDecl = structDecl;
ast->typeDenoter = std::make_shared<StructTypeDenoter>(structDecl.get());
}
ast->area = ast->structDecl->area;
return ast;
}
TypeSpecifierPtr MakeTypeSpecifier(const TypeDenoterPtr& typeDenoter)
{
auto ast = MakeAST<TypeSpecifier>();
{
ast->typeDenoter = typeDenoter;
}
return ast;
}
TypeSpecifierPtr MakeTypeSpecifier(const DataType dataType)
{
return MakeTypeSpecifier(MakeShared<BaseTypeDenoter>(dataType));
}
VarDeclStmntPtr MakeVarDeclStmnt(const DataType dataType, const std::string& ident)
{
auto ast = MakeAST<VarDeclStmnt>();
{
ast->typeSpecifier = MakeTypeSpecifier(dataType);
auto varDecl = MakeAST<VarDecl>();
{
varDecl->ident = ident;
varDecl->declStmntRef = ast.get();
}
ast->varDecls.push_back(varDecl);
}
return ast;
}
VarIdentPtr MakeVarIdent(const std::string& ident, AST* symbolRef)
{
auto ast = MakeAST<VarIdent>();
{
ast->ident = ident;
ast->symbolRef = symbolRef;
}
return ast;
}
VarAccessExprPtr MakeVarAccessExpr(const std::string& ident, AST* symbolRef)
{
auto ast = MakeAST<VarAccessExpr>();
{
ast->varIdent = MakeVarIdent(ident, symbolRef);
}
return ast;
}
/*
TODO:
This is currently being used to convert a scalar-to-struct cast expression
into a struct-constructor expression (e.g. "(S)0" -> "S(0, 0, 0)").
This is done by using a list-expression instead of an argument list for the constructor.
This should be changed, because a list-expression is not meant to be used as argument list!
-> see GLSLConverter::VisitCastExpr
*/
#if 1
static ExprPtr MakeConstructorListExprPrimarySingle(const LiteralExprPtr& literalExpr, const TypeDenoterPtr& typeDen)
{
if (auto structTypeDen = typeDen->As<StructTypeDenoter>())
{
if (auto structDecl = structTypeDen->structDeclRef)
{
/* Get the type denoter of all structure members */
std::vector<TypeDenoterPtr> memberTypeDens;
structDecl->CollectMemberTypeDenoters(memberTypeDens);
/* Generate list expression with N copies of the literal (where N is the number of struct members) */
return MakeCastExpr(typeDen, MakeConstructorListExpr(literalExpr, memberTypeDens));
}
}
else if (auto baseTypeDen = typeDen->As<BaseTypeDenoter>())
{
if (!baseTypeDen->IsScalar())
{
/* Make a cast expression for this vector or matrix type */
return MakeCastExpr(typeDen, literalExpr);
}
}
return literalExpr;
}
static ExprPtr MakeConstructorListExprPrimary(
const LiteralExprPtr& literalExpr,
std::vector<TypeDenoterPtr>::const_iterator typeDensBegin,
std::vector<TypeDenoterPtr>::const_iterator typeDensEnd)
{
if (typeDensBegin + 1 != typeDensEnd)
{
auto ast = MakeAST<ListExpr>();
{
ast->firstExpr = MakeConstructorListExprPrimarySingle(literalExpr, (*typeDensBegin)->Get());
ast->nextExpr = MakeConstructorListExprPrimary(literalExpr, typeDensBegin + 1, typeDensEnd);
}
return ast;
}
else
return MakeConstructorListExprPrimarySingle(literalExpr, (*typeDensBegin)->Get());
}
ExprPtr MakeConstructorListExpr(const LiteralExprPtr& literalExpr, const std::vector<TypeDenoterPtr>& listTypeDens)
{
if (listTypeDens.empty())
return nullptr;
else
return MakeConstructorListExprPrimary(literalExpr, listTypeDens.begin(), listTypeDens.end());
}
#endif
ExprStmntPtr MakeArrayAssignStmnt(VarDecl* varDecl, const std::vector<int>& arrayIndices, const ExprPtr& assignExpr)
{
auto ast = MakeAST<ExprStmnt>();
{
auto expr = MakeAST<VarAccessExpr>();
{
expr->varIdent = MakeVarIdent(varDecl->ident, varDecl);
expr->varIdent->arrayIndices = MakeArrayIndices(arrayIndices);
expr->assignOp = AssignOp::Set;
expr->assignExpr = assignExpr;
}
ast->expr = expr;
}
return ast;
}
ArrayDimensionPtr MakeArrayDimension(int arraySize)
{
auto ast = MakeAST<ArrayDimension>();
{
if (arraySize > 0)
{
ast->expr = MakeLiteralExpr(DataType::Int, std::to_string(arraySize));
ast->size = arraySize;
}
else
{
ast->expr = MakeAST<NullExpr>();
ast->size = 0;
}
}
return ast;
}
/* ----- Make list functions ----- */
std::vector<ExprPtr> MakeArrayIndices(const std::vector<int>& arrayIndices)
{
std::vector<ExprPtr> exprs;
for (auto index : arrayIndices)
exprs.push_back(MakeLiteralExpr(DataType::Int, std::to_string(index)));
return exprs;
}
std::vector<ArrayDimensionPtr> MakeArrayDimensionList(const std::vector<int>& arraySizes)
{
std::vector<ArrayDimensionPtr> arrayDims;
for (auto dim : arraySizes)
arrayDims.push_back(MakeArrayDimension(dim));
return arrayDims;
}
/* ----- Convert functions ----- */
ExprPtr ConvertExprBaseType(const DataType dataType, const ExprPtr& subExpr)
{
if (subExpr->Type() == AST::Types::LiteralExpr && IsScalarType(dataType))
{
/* Convert data type into literal expression */
auto ast = std::static_pointer_cast<LiteralExpr>(subExpr);
{
ast->ConvertDataType(dataType);
}
return ast;
}
else
{
/* Make new cast expression */
auto ast = MakeShared<CastExpr>(subExpr->area);
{
ast->typeSpecifier = MakeTypeSpecifier(MakeShared<BaseTypeDenoter>(dataType));
ast->typeSpecifier->area = subExpr->area;
ast->expr = subExpr;
}
return ast;
}
}
ArrayDimensionPtr ConvertExprToArrayDimension(const ExprPtr& expr)
{
auto ast = MakeAST<ArrayDimension>();
{
if (expr)
{
ast->area = expr->area;
ast->expr = expr;
}
}
return ast;
}
std::vector<ArrayDimensionPtr> ConvertExprListToArrayDimensionList(const std::vector<ExprPtr>& exprs)
{
std::vector<ArrayDimensionPtr> arrayDims;
for (const auto& expr : exprs)
arrayDims.push_back(ConvertExprToArrayDimension(expr));
return arrayDims;
}
} // /namespace ASTFactory
} // /namespace Xsc
// ================================================================================
<|endoftext|>
|
<commit_before>#include "ViewportWidget.h"
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QCoreApplication>
#include <QMouseEvent>
#include <QPainter>
static const char *vertexShaderSourceCore =
"#version 150\n"
"in vec4 vertex;\n"
"in vec3 normal;\n"
"out vec3 vert;\n"
"out vec3 vertNormal;\n"
"uniform mat4 projMatrix;\n"
"uniform mat4 mvMatrix;\n"
"uniform mat3 normalMatrix;\n"
"void main() {\n"
" vert = vertex.xyz;\n"
" vertNormal = normalMatrix * normal;\n"
" gl_Position = projMatrix * mvMatrix * vertex;\n"
"}\n";
static const char *fragmentShaderSourceCore =
"#version 150\n"
"in highp vec3 vert;\n"
"in highp vec3 vertNormal;\n"
"out highp vec4 fragColor;\n"
"uniform highp vec3 lightPos;\n"
"void main() {\n"
" highp vec3 L = normalize(lightPos - vert);\n"
" highp float NL = max(dot(normalize(vertNormal), L), 0.0);\n"
" highp vec3 color = vec3(0.39, 1.0, 0.0);\n"
" highp vec3 col = clamp(color * 0.2 + color * 0.8 * NL, 0.0, 1.0);\n"
" fragColor = vec4(col, 1.0);\n"
"}\n";
static const char *vertexShaderSource =
"attribute vec4 vertex;\n"
"attribute vec3 normal;\n"
"varying vec3 vert;\n"
"varying vec3 vertNormal;\n"
"uniform mat4 projMatrix;\n"
"uniform mat4 mvMatrix;\n"
"uniform mat3 normalMatrix;\n"
"void main() {\n"
" vert = vertex.xyz;\n"
" vertNormal = normalMatrix * normal;\n"
" gl_Position = projMatrix * mvMatrix * vertex;\n"
"}\n";
static const char *fragmentShaderSource =
"varying highp vec3 vert;\n"
"varying highp vec3 vertNormal;\n"
"uniform highp vec3 lightPos;\n"
"void main() {\n"
" highp vec3 L = normalize(lightPos - vert);\n"
" highp float NL = max(dot(normalize(vertNormal), L), 0.0);\n"
" highp vec3 color = vec3(0.39, 1.0, 0.0);\n"
" highp vec3 col = clamp(color * 0.2 + color * 0.8 * NL, 0.0, 1.0);\n"
" gl_FragColor = vec4(col, 1.0);\n"
"}\n";
ViewportWidget::ViewportWidget(QWidget *parent)
: QOpenGLWidget(parent)
//, mCamTilt(0.0f)
//, mCamOrbit(0.0f)
//, mZoom(3.0f)
, mButtons(Qt::MouseButton::NoButton)
{
mCore = QCoreApplication::arguments().contains(QStringLiteral("--coreprofile"));
// --transparent causes the clear color to be transparent. Therefore, on systems that
// support it, the widget will become transparent apart from the logo.
mTransparent = QCoreApplication::arguments().contains(QStringLiteral("--transparent"));
if (mTransparent)
setAttribute(Qt::WA_TranslucentBackground);
setAutoFillBackground(false);
}
ViewportWidget::~ViewportWidget()
{
Cleanup();
}
QSize ViewportWidget::minimumSizeHint() const
{
return QSize(640, 480);
}
QSize ViewportWidget::sizeHint() const
{
return QSize(1024, 768);
}
void ViewportWidget::Cleanup()
{
makeCurrent();
mVBO.destroy();
mVBO2.destroy();
if (mShaderProgram)
{
delete mShaderProgram;
mShaderProgram = nullptr;
}
doneCurrent();
}
void ViewportWidget::initializeGL()
{
// From the Qt OpenGL example
// In this example the widget's corresponding top-level window can change
// several times during the widget's lifetime. Whenever this happens, the
// QOpenGLWidget's associated context is destroyed and a new one is created.
// Therefore we have to be prepared to clean up the resources on the
// aboutToBeDestroyed() signal, instead of the destructor. The emission of
// the signal will be followed by an invocation of initializeGL() where we
// can recreate all resources.
connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &ViewportWidget::Cleanup);
//initializeOpenGLFunctions();
glClearColor(0.9f, 0.9f, 0.9f, mTransparent ? 0 : 1);
glLineWidth(1.0f);
mShaderProgram = new QOpenGLShaderProgram;
mShaderProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, mCore ? vertexShaderSourceCore : vertexShaderSource);
mShaderProgram->addShaderFromSourceCode(QOpenGLShader::Fragment, mCore ? fragmentShaderSourceCore : fragmentShaderSource);
mShaderProgram->bindAttributeLocation("vertex", 0);
mShaderProgram->bindAttributeLocation("normal", 1);
mShaderProgram->link();
mShaderProgram->bind();
mLocProjectionMatrix = mShaderProgram->uniformLocation("projMatrix");
mLocMvMatrix = mShaderProgram->uniformLocation("mvMatrix");
mLocNormalMatrix = mShaderProgram->uniformLocation("normalMatrix");
mLocLightPosition = mShaderProgram->uniformLocation("lightPos");
// Create a vertex array object. In OpenGL ES 2.0 and OpenGL 2.x
// implementations this is optional and support may not be present
// at all. Nonetheless the below code works in all cases and makes
// sure there is a VAO when one is needed.
mVAO.create();
QOpenGLVertexArrayObject::Binder vaoBinder(&mVAO);
// Setup our vertex buffer object.
mVBO.create();
mVBO.bind();
//m_vbo.allocate(mBasicShape.constData(), mBasicShape.count() * sizeof(GLfloat));
mVBO.allocate(mGridObject.constData(), mGridObject.count() * sizeof(GLfloat));
// Store the vertex attribute bindings for the program.
SetupVertexAttributes(&mVBO);
mVAO2.create();
QOpenGLVertexArrayObject::Binder vaoBinder2(&mVAO2);
mVBO2.create();
mVBO2.bind();
mVBO2.setUsagePattern(QOpenGLBuffer::UsagePattern::DynamicDraw);
mVBO2.allocate(mLineObject.count() * sizeof(GLfloat)); // Allocate without data if intended for dynamic drawing
SetupVertexAttributes(&mVBO2);
//// Light position is fixed.
mShaderProgram->setUniformValue(mLocLightPosition, QVector3D(0, 0, 70));
mShaderProgram->release();
mCamera.SetPosition(QVector3D(5.0f, 3.0f, 4.0f));
}
void ViewportWidget::SetupVertexAttributes(QOpenGLBuffer* vbo)
{
if (!vbo)
return;
vbo->bind();
QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
f->glEnableVertexAttribArray(0);
f->glEnableVertexAttribArray(1);
f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), 0);
f->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), reinterpret_cast<void *>(3 * sizeof(GLfloat)));
vbo->release();
}
//void ViewportWidget::paintEvent(QPaintEvent* paintEvent)
//{
// QPainter painter(this);
// painter.setPen(Qt::blue);
// painter.setFont(QFont("Arial", 24));
// painter.drawText(rect(), Qt::AlignCenter, "Test");
//}
void ViewportWidget::paintGL()
{
DrawGL();
}
void ViewportWidget::DrawGL()
{
QPainter painter(this);
painter.beginNativePainting();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
mWorld.setToIdentity();
//// m_world.rotate(180.0f - (m_xRot / 16.0f), 1, 0, 0);
//// m_world.rotate(m_yRot / 16.0f, 0, 1, 0);
//// m_world.rotate(m_zRot / 16.0f, 0, 0, 1);
////m_world.rotate(mRot / 16.0f, 0, 1, 0);
//m_world.rotate(mRot / 16.0f, 1, 0, 0);
//mWorld.rotate(15.0f, 1, 0, 0);
QMatrix4x4 cameraTransform = mCamera.GetTransform();
QMatrix3x3 normalMatrix = mWorld.normalMatrix();
mShaderProgram->bind();
mShaderProgram->setUniformValue(mLocProjectionMatrix, mProjection);
//mShaderProgram->setUniformValue(mLocMvMatrix, mCamera /** mWorld*/);
mShaderProgram->setUniformValue(mLocMvMatrix, cameraTransform);
mShaderProgram->setUniformValue(mLocNormalMatrix, normalMatrix);
QOpenGLVertexArrayObject::Binder vaoBinder(&mVAO);
glDrawArrays(GL_LINES, 0, mGridObject.vertexCount());
vaoBinder.release();
QOpenGLVertexArrayObject::Binder vaoBinder2(&mVAO2);
mVBO2.bind();
mLineObject.Update(mCamera.GetTiltAxis(), QVector3D(0.0f, 1.0f, 0.0f));
mVBO2.write(0, mLineObject.constData(), mLineObject.count() * sizeof(GLfloat));
mVBO2.release();
mShaderProgram->setUniformValue(mLocProjectionMatrix, mProjection);
//mShaderProgram->setUniformValue(mLocMvMatrix, mCamera /** mWorld*/);
mShaderProgram->setUniformValue(mLocMvMatrix, cameraTransform);
mShaderProgram->setUniformValue(mLocNormalMatrix, normalMatrix);
glDrawArrays(GL_LINES, 0, mLineObject.vertexCount());
vaoBinder2.release();
mShaderProgram->release();
//update(); // force loop
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
painter.endNativePainting();
painter.setPen(Qt::red);
painter.setFont(QFont("Arial", 24));
painter.drawText(rect(), Qt::AlignCenter, "Test");
}
void ViewportWidget::resizeGL(int w, int h)
{
mProjection.setToIdentity();
mProjection.perspective(45.0f, GLfloat(w) / h, 0.001f, 100.0f);
}
void ViewportWidget::mousePressEvent(QMouseEvent *event)
{
printf("Mouse Press\n");
mLastPos = event->pos();
mDragPos = event->pos();
mButtons |= event->buttons();
update();
}
void ViewportWidget::mouseMoveEvent(QMouseEvent *event)
{
float multiplier = 0.1f;
int dx = event->x() - mLastPos.x();
int dy = event->y() - mLastPos.y();
float dragDx = (float)event->x() - (float)mDragPos.x();
float dragDy = (float)event->y() - (float)mDragPos.y();
if (mButtons & Qt::MouseButton::LeftButton)
{
//mCamera.Tilt(multiplier * dy);
//mCamera.Orbit(multiplier * dx);
mCamera.TiltAndOrbit(multiplier * dy, multiplier * dx);
}
else if (mButtons & Qt::MouseButton::MidButton)
{
float kPanMult = 0.1f;
mCamera.Pan(-kPanMult * multiplier * dragDx, kPanMult * multiplier * dragDy);
}
mDragPos = event->pos();
mLastPos = event->pos();
//qDebug("Mouse Move\n");
update();
}
void ViewportWidget::mouseReleaseEvent(QMouseEvent * event)
{
printf("Mouse Release\n");
mButtons &= ~Qt::AllButtons;
update();
}
void ViewportWidget::wheelEvent(QWheelEvent *event)
{
mCamera.Zoom(0.01f * event->delta());
update();
}
<commit_msg>Cleanup<commit_after>#include "ViewportWidget.h"
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QCoreApplication>
#include <QMouseEvent>
#include <QPainter>
static const char *vertexShaderSourceCore =
"#version 150\n"
"in vec4 vertex;\n"
"in vec3 normal;\n"
"out vec3 vert;\n"
"out vec3 vertNormal;\n"
"uniform mat4 projMatrix;\n"
"uniform mat4 mvMatrix;\n"
"uniform mat3 normalMatrix;\n"
"void main() {\n"
" vert = vertex.xyz;\n"
" vertNormal = normalMatrix * normal;\n"
" gl_Position = projMatrix * mvMatrix * vertex;\n"
"}\n";
static const char *fragmentShaderSourceCore =
"#version 150\n"
"in highp vec3 vert;\n"
"in highp vec3 vertNormal;\n"
"out highp vec4 fragColor;\n"
"uniform highp vec3 lightPos;\n"
"void main() {\n"
" highp vec3 L = normalize(lightPos - vert);\n"
" highp float NL = max(dot(normalize(vertNormal), L), 0.0);\n"
" highp vec3 color = vec3(0.39, 1.0, 0.0);\n"
" highp vec3 col = clamp(color * 0.2 + color * 0.8 * NL, 0.0, 1.0);\n"
" fragColor = vec4(col, 1.0);\n"
"}\n";
static const char *vertexShaderSource =
"attribute vec4 vertex;\n"
"attribute vec3 normal;\n"
"varying vec3 vert;\n"
"varying vec3 vertNormal;\n"
"uniform mat4 projMatrix;\n"
"uniform mat4 mvMatrix;\n"
"uniform mat3 normalMatrix;\n"
"void main() {\n"
" vert = vertex.xyz;\n"
" vertNormal = normalMatrix * normal;\n"
" gl_Position = projMatrix * mvMatrix * vertex;\n"
"}\n";
static const char *fragmentShaderSource =
"varying highp vec3 vert;\n"
"varying highp vec3 vertNormal;\n"
"uniform highp vec3 lightPos;\n"
"void main() {\n"
" highp vec3 L = normalize(lightPos - vert);\n"
" highp float NL = max(dot(normalize(vertNormal), L), 0.0);\n"
" highp vec3 color = vec3(0.39, 1.0, 0.0);\n"
" highp vec3 col = clamp(color * 0.2 + color * 0.8 * NL, 0.0, 1.0);\n"
" gl_FragColor = vec4(col, 1.0);\n"
"}\n";
ViewportWidget::ViewportWidget(QWidget *parent)
: QOpenGLWidget(parent)
//, mCamTilt(0.0f)
//, mCamOrbit(0.0f)
//, mZoom(3.0f)
, mButtons(Qt::MouseButton::NoButton)
{
mCore = QCoreApplication::arguments().contains(QStringLiteral("--coreprofile"));
// --transparent causes the clear color to be transparent. Therefore, on systems that
// support it, the widget will become transparent apart from the logo.
mTransparent = QCoreApplication::arguments().contains(QStringLiteral("--transparent"));
if (mTransparent)
setAttribute(Qt::WA_TranslucentBackground);
setAutoFillBackground(false);
}
ViewportWidget::~ViewportWidget()
{
Cleanup();
}
QSize ViewportWidget::minimumSizeHint() const
{
return QSize(640, 480);
}
QSize ViewportWidget::sizeHint() const
{
return QSize(1024, 768);
}
void ViewportWidget::Cleanup()
{
makeCurrent();
mVBO.destroy();
mVBO2.destroy();
if (mShaderProgram)
{
delete mShaderProgram;
mShaderProgram = nullptr;
}
doneCurrent();
}
void ViewportWidget::initializeGL()
{
// From the Qt OpenGL example
// In this example the widget's corresponding top-level window can change
// several times during the widget's lifetime. Whenever this happens, the
// QOpenGLWidget's associated context is destroyed and a new one is created.
// Therefore we have to be prepared to clean up the resources on the
// aboutToBeDestroyed() signal, instead of the destructor. The emission of
// the signal will be followed by an invocation of initializeGL() where we
// can recreate all resources.
connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &ViewportWidget::Cleanup);
//initializeOpenGLFunctions();
glClearColor(0.9f, 0.9f, 0.9f, mTransparent ? 0 : 1);
glLineWidth(1.0f);
mShaderProgram = new QOpenGLShaderProgram;
mShaderProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, mCore ? vertexShaderSourceCore : vertexShaderSource);
mShaderProgram->addShaderFromSourceCode(QOpenGLShader::Fragment, mCore ? fragmentShaderSourceCore : fragmentShaderSource);
mShaderProgram->bindAttributeLocation("vertex", 0);
mShaderProgram->bindAttributeLocation("normal", 1);
mShaderProgram->link();
mShaderProgram->bind();
mLocProjectionMatrix = mShaderProgram->uniformLocation("projMatrix");
mLocMvMatrix = mShaderProgram->uniformLocation("mvMatrix");
mLocNormalMatrix = mShaderProgram->uniformLocation("normalMatrix");
mLocLightPosition = mShaderProgram->uniformLocation("lightPos");
// Create a vertex array object. In OpenGL ES 2.0 and OpenGL 2.x
// implementations this is optional and support may not be present
// at all. Nonetheless the below code works in all cases and makes
// sure there is a VAO when one is needed.
mVAO.create();
QOpenGLVertexArrayObject::Binder vaoBinder(&mVAO);
// Setup our vertex buffer object.
mVBO.create();
mVBO.bind();
//m_vbo.allocate(mBasicShape.constData(), mBasicShape.count() * sizeof(GLfloat));
mVBO.allocate(mGridObject.constData(), mGridObject.count() * sizeof(GLfloat));
// Store the vertex attribute bindings for the program.
SetupVertexAttributes(&mVBO);
mVAO2.create();
QOpenGLVertexArrayObject::Binder vaoBinder2(&mVAO2);
mVBO2.create();
mVBO2.bind();
mVBO2.setUsagePattern(QOpenGLBuffer::UsagePattern::DynamicDraw);
mVBO2.allocate(mLineObject.count() * sizeof(GLfloat)); // Allocate without data if intended for dynamic drawing
SetupVertexAttributes(&mVBO2);
//// Light position is fixed.
mShaderProgram->setUniformValue(mLocLightPosition, QVector3D(0, 0, 70));
mShaderProgram->release();
mCamera.SetPosition(QVector3D(5.0f, 3.0f, 4.0f));
}
void ViewportWidget::SetupVertexAttributes(QOpenGLBuffer* vbo)
{
if (!vbo)
return;
vbo->bind();
QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
f->glEnableVertexAttribArray(0);
f->glEnableVertexAttribArray(1);
f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), 0);
f->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), reinterpret_cast<void *>(3 * sizeof(GLfloat)));
vbo->release();
}
//void ViewportWidget::paintEvent(QPaintEvent* paintEvent)
//{
// QPainter painter(this);
// painter.setPen(Qt::blue);
// painter.setFont(QFont("Arial", 24));
// painter.drawText(rect(), Qt::AlignCenter, "Test");
//}
void ViewportWidget::paintGL()
{
DrawGL();
}
void ViewportWidget::DrawGL()
{
QPainter painter(this);
painter.beginNativePainting();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
mWorld.setToIdentity();
//// m_world.rotate(180.0f - (m_xRot / 16.0f), 1, 0, 0);
//// m_world.rotate(m_yRot / 16.0f, 0, 1, 0);
//// m_world.rotate(m_zRot / 16.0f, 0, 0, 1);
////m_world.rotate(mRot / 16.0f, 0, 1, 0);
//m_world.rotate(mRot / 16.0f, 1, 0, 0);
//mWorld.rotate(15.0f, 1, 0, 0);
QMatrix4x4 cameraTransform = mCamera.GetTransform();
QMatrix3x3 normalMatrix = mWorld.normalMatrix();
mShaderProgram->bind();
mShaderProgram->setUniformValue(mLocProjectionMatrix, mProjection);
//mShaderProgram->setUniformValue(mLocMvMatrix, mCamera /** mWorld*/);
mShaderProgram->setUniformValue(mLocMvMatrix, cameraTransform);
mShaderProgram->setUniformValue(mLocNormalMatrix, normalMatrix);
QOpenGLVertexArrayObject::Binder vaoBinder(&mVAO);
glDrawArrays(GL_LINES, 0, mGridObject.vertexCount());
vaoBinder.release();
QOpenGLVertexArrayObject::Binder vaoBinder2(&mVAO2);
mVBO2.bind();
mLineObject.Update(mCamera.GetTiltAxis(), QVector3D(0.0f, 1.0f, 0.0f));
mVBO2.write(0, mLineObject.constData(), mLineObject.count() * sizeof(GLfloat));
mVBO2.release();
glDrawArrays(GL_LINES, 0, mLineObject.vertexCount());
vaoBinder2.release();
mShaderProgram->release();
//update(); // force loop
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
painter.endNativePainting();
painter.setPen(Qt::red);
painter.setFont(QFont("Arial", 24));
painter.drawText(rect(), Qt::AlignCenter, "Test");
}
void ViewportWidget::resizeGL(int w, int h)
{
mProjection.setToIdentity();
mProjection.perspective(45.0f, GLfloat(w) / h, 0.001f, 100.0f);
}
void ViewportWidget::mousePressEvent(QMouseEvent *event)
{
printf("Mouse Press\n");
mLastPos = event->pos();
mDragPos = event->pos();
mButtons |= event->buttons();
update();
}
void ViewportWidget::mouseMoveEvent(QMouseEvent *event)
{
float multiplier = 0.1f;
int dx = event->x() - mLastPos.x();
int dy = event->y() - mLastPos.y();
float dragDx = (float)event->x() - (float)mDragPos.x();
float dragDy = (float)event->y() - (float)mDragPos.y();
if (mButtons & Qt::MouseButton::LeftButton)
{
//mCamera.Tilt(multiplier * dy);
//mCamera.Orbit(multiplier * dx);
mCamera.TiltAndOrbit(multiplier * dy, multiplier * dx);
}
else if (mButtons & Qt::MouseButton::MidButton)
{
float kPanMult = 0.1f;
mCamera.Pan(-kPanMult * multiplier * dragDx, kPanMult * multiplier * dragDy);
}
mDragPos = event->pos();
mLastPos = event->pos();
//qDebug("Mouse Move\n");
update();
}
void ViewportWidget::mouseReleaseEvent(QMouseEvent * event)
{
printf("Mouse Release\n");
mButtons &= ~Qt::AllButtons;
update();
}
void ViewportWidget::wheelEvent(QWheelEvent *event)
{
mCamera.Zoom(0.01f * event->delta());
update();
}
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_READ_SPATIAL_PARTITION
#define MJOLNIR_READ_SPATIAL_PARTITION
#include <mjolnir/core/UnlimitedGridCellList.hpp>
#include <mjolnir/core/PeriodicGridCellList.hpp>
#include <mjolnir/core/NaivePairCalculation.hpp>
#include <mjolnir/core/VerletList.hpp>
#include <mjolnir/util/make_unique.hpp>
namespace mjolnir
{
template<typename boundaryT, typename traitsT>
struct celllist_dispatcher;
template<typename realT, typename coordT, typename traitsT>
struct celllist_dispatcher<UnlimitedBoundary<realT, coordT>, traitsT>
{
typedef UnlimitedGridCellList<traitsT> type;
typedef realT real_type;
static UnlimitedGridCellList<traitsT>
invoke(const real_type cutoff, const real_type mergin)
{
return UnlimitedGridCellList<traitsT>{cutoff, mergin};
}
};
template<typename realT, typename coordT, typename traitsT>
struct celllist_dispatcher<CubicPeriodicBoundary<realT, coordT>, traitsT>
{
typedef PeriodicGridCellList<traitsT> type;
typedef realT real_type;
static PeriodicGridCellList<traitsT>
invoke(const real_type cutoff, const real_type mergin)
{
return PeriodicGridCellList<traitsT>{cutoff, mergin};
}
};
template<typename partitionT>
partitionT
read_exception_information(const toml::Table& global, partitionT&& sp)
{
const auto& params = global.at("parameters").cast<toml::value_t::Array>();
for(const auto& tab : params)
{
const auto& info = tab.cast<toml::value_t::Table>();
const auto idx = toml::get<std::size_t>(info.at("index"));
sp.chain_index(idx) = toml::get<std::size_t>(info.at("chain"));
for(auto exc : toml::get<std::vector<std::size_t>>(
info.at("except_chains")))
{
sp.except_chains(idx).push_back(exc);
}
for(auto exb : toml::get<std::vector<std::size_t>>(
info.at("except_beads")))
{
sp.except_indices(idx).push_back(exb);
}
}
return sp;
}
template<typename traitsT, typename potentialT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_spatial_partition_for_distance(const toml::Table& global, potentialT&& pot)
{
typedef typename traitsT::real_type real_type;
const auto& sp = global.at("spatial_partition").cast<toml::value_t::Table>();
const auto type = toml::get<std::string>(sp.at("type"));
if(type == "CellList")
{
typedef typename traitsT::boundary_type boundary_type;
typedef typename celllist_dispatcher<boundary_type, traitsT>::type
celllist_type;
const auto co = pot.max_cutoff_length();
const auto mg = toml::get<real_type>(sp.at("mergin"));
return make_unique<GlobalDistanceInteraction<
traitsT, potentialT, celllist_type>>(std::move(pot),
celllist_dispatcher<boundary_type, traitsT>::invoke(co, mg));
}
else if(type == "VerletList")
{
const auto cutoff = pot.max_cutoff_length();
const auto mergin = toml::get<real_type>(sp.at("mergin"));
return make_unique<GlobalDistanceInteraction<
traitsT, potentialT, VerletList<traitsT>>
>(std::move(pot), VerletList<traitsT>{cutoff, mergin});
}
else if(type == "Naive")
{
return make_unique<GlobalDistanceInteraction<
traitsT, potentialT, NaivePairCalculation<traitsT>>
>(std::move(pot), NaivePairCalculation<traitsT>{});
}
else
{
throw std::runtime_error("invalid spatial partition type: " + type);
}
}
template<typename traitsT, typename potentialT>
std::unique_ptr<GlobalInteractionBase<traitT>>
read_spatial_partition_for_externalMU(const toml::Table& global, potentialT&& pot)
{
return make_unique<GlobalExternalInteraction<
traitsT, potentialT, SpatialPartitionForMU<traitsT>>
>(std::move(pot), SpatialPartitionForMU<traitsT>{});
}
}
#endif// MJOLNIR_READ_SPATIAL_PARTITION
<commit_msg>fix traitT -> traitsT<commit_after>#ifndef MJOLNIR_READ_SPATIAL_PARTITION
#define MJOLNIR_READ_SPATIAL_PARTITION
#include <mjolnir/core/UnlimitedGridCellList.hpp>
#include <mjolnir/core/PeriodicGridCellList.hpp>
#include <mjolnir/core/NaivePairCalculation.hpp>
#include <mjolnir/core/VerletList.hpp>
#include <mjolnir/core/SpatialPartitionForMU.hpp>
#include <mjolnir/util/make_unique.hpp>
namespace mjolnir
{
template<typename boundaryT, typename traitsT>
struct celllist_dispatcher;
template<typename realT, typename coordT, typename traitsT>
struct celllist_dispatcher<UnlimitedBoundary<realT, coordT>, traitsT>
{
typedef UnlimitedGridCellList<traitsT> type;
typedef realT real_type;
static UnlimitedGridCellList<traitsT>
invoke(const real_type cutoff, const real_type mergin)
{
return UnlimitedGridCellList<traitsT>{cutoff, mergin};
}
};
template<typename realT, typename coordT, typename traitsT>
struct celllist_dispatcher<CubicPeriodicBoundary<realT, coordT>, traitsT>
{
typedef PeriodicGridCellList<traitsT> type;
typedef realT real_type;
static PeriodicGridCellList<traitsT>
invoke(const real_type cutoff, const real_type mergin)
{
return PeriodicGridCellList<traitsT>{cutoff, mergin};
}
};
template<typename partitionT>
partitionT
read_exception_information(const toml::Table& global, partitionT&& sp)
{
const auto& params = global.at("parameters").cast<toml::value_t::Array>();
for(const auto& tab : params)
{
const auto& info = tab.cast<toml::value_t::Table>();
const auto idx = toml::get<std::size_t>(info.at("index"));
sp.chain_index(idx) = toml::get<std::size_t>(info.at("chain"));
for(auto exc : toml::get<std::vector<std::size_t>>(
info.at("except_chains")))
{
sp.except_chains(idx).push_back(exc);
}
for(auto exb : toml::get<std::vector<std::size_t>>(
info.at("except_beads")))
{
sp.except_indices(idx).push_back(exb);
}
}
return sp;
}
template<typename traitsT, typename potentialT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_spatial_partition_for_distance(const toml::Table& global, potentialT&& pot)
{
typedef typename traitsT::real_type real_type;
const auto& sp = global.at("spatial_partition").cast<toml::value_t::Table>();
const auto type = toml::get<std::string>(sp.at("type"));
if(type == "CellList")
{
typedef typename traitsT::boundary_type boundary_type;
typedef typename celllist_dispatcher<boundary_type, traitsT>::type
celllist_type;
const auto co = pot.max_cutoff_length();
const auto mg = toml::get<real_type>(sp.at("mergin"));
return make_unique<GlobalDistanceInteraction<
traitsT, potentialT, celllist_type>>(std::move(pot),
celllist_dispatcher<boundary_type, traitsT>::invoke(co, mg));
}
else if(type == "VerletList")
{
const auto cutoff = pot.max_cutoff_length();
const auto mergin = toml::get<real_type>(sp.at("mergin"));
return make_unique<GlobalDistanceInteraction<
traitsT, potentialT, VerletList<traitsT>>
>(std::move(pot), VerletList<traitsT>{cutoff, mergin});
}
else if(type == "Naive")
{
return make_unique<GlobalDistanceInteraction<
traitsT, potentialT, NaivePairCalculation<traitsT>>
>(std::move(pot), NaivePairCalculation<traitsT>{});
}
else
{
throw std::runtime_error("invalid spatial partition type: " + type);
}
}
template<typename traitsT, typename potentialT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_spatial_partition_for_externalMU(const toml::Table& global, potentialT&& pot)
{
return make_unique<GlobalExternalInteraction<
traitsT, potentialT, SpatialPartitionForMU<traitsT>>
>(std::move(pot), SpatialPartitionForMU<traitsT>{});
}
}
#endif// MJOLNIR_READ_SPATIAL_PARTITION
<|endoftext|>
|
<commit_before>/*
########## Copyright (C) 2015 Vincenzo Pacella
## ## Distributed under MIT license, see file LICENSE
## ## or <http://opensource.org/licenses/MIT>
## ##
########## ############################################################# shaduzlabs.com #####*/
#include <algorithm>
#include <iostream>
#include <iterator>
#include <catch.hpp>
#include <gfx/displays/LCDDisplay7Segments.h>
//--------------------------------------------------------------------------------------------------
namespace sl
{
namespace cabl
{
template class LCDDisplayBase<19, 1>;
template class LCDDisplay7Segments<19>;
namespace test
{
//--------------------------------------------------------------------------------------------------
TEST_CASE("LCDDisplay7Segments: constructor", "[gfx][displays][LCDDisplay7Segments]")
{
LCDDisplay7Segments<19> display;
CHECK(display.width() == 19);
CHECK(display.height() == 1);
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("LCDDisplay7Segments: set text", "[gfx][displays][LCDDisplay7Segments]")
{
LCDDisplay7Segments<19> display;
{
display.setText("@A text!@", 0, LCDDisplay::Align::Center);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected
= {0, 0, 0, 0, 0, 0, 0x7E, 0, 0xE2, 0xF2, 0, 0xE2, 0, 0, 0, 0, 0, 0, 0};
CHECK(displayData == expected);
display.clear();
}
{
display.setText(" ", 0, LCDDisplay::Align::Left);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
CHECK(displayData == expected);
display.clear();
}
{
display.setText(" ! ? *", 0, LCDDisplay::Align::Left);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
CHECK(displayData == expected);
display.clear();
}
{
display.setText("AAA", 0, LCDDisplay::Align::Left);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected
= {0x7E, 0x7E, 0x7E, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
CHECK(displayData == expected);
display.clear();
}
{
display.setText("AAA", 0, LCDDisplay::Align::Right);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected
= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7E, 0x7E, 0x7E};
CHECK(displayData == expected);
display.clear();
}
{
display.setText("AAA", 0, LCDDisplay::Align::Center);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected
= {0, 0, 0, 0, 0, 0, 0, 0, 0x7E, 0x7E, 0x7E, 0, 0, 0, 0, 0, 0, 0, 0};
CHECK(displayData == expected);
display.clear();
}
}
//--------------------------------------------------------------------------------------------------
} // namespace test
} // namespace cabl
} // namespace sl
<commit_msg>reverted change<commit_after>/*
########## Copyright (C) 2015 Vincenzo Pacella
## ## Distributed under MIT license, see file LICENSE
## ## or <http://opensource.org/licenses/MIT>
## ##
########## ############################################################# shaduzlabs.com #####*/
#include <algorithm>
#include <iostream>
#include <iterator>
#include <catch.hpp>
#include <gfx/displays/LCDDisplay7Segments.h>
//--------------------------------------------------------------------------------------------------
namespace sl
{
namespace cabl
{
namespace test
{
//--------------------------------------------------------------------------------------------------
TEST_CASE("LCDDisplay7Segments: constructor", "[gfx][displays][LCDDisplay7Segments]")
{
LCDDisplay7Segments<19> display;
CHECK(display.width() == 19);
CHECK(display.height() == 1);
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("LCDDisplay7Segments: set text", "[gfx][displays][LCDDisplay7Segments]")
{
LCDDisplay7Segments<19> display;
{
display.setText("@A text!@", 0, LCDDisplay::Align::Center);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected
= {0, 0, 0, 0, 0, 0, 0x7E, 0, 0xE2, 0xF2, 0, 0xE2, 0, 0, 0, 0, 0, 0, 0};
CHECK(displayData == expected);
display.clear();
}
{
display.setText(" ", 0, LCDDisplay::Align::Left);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
CHECK(displayData == expected);
display.clear();
}
{
display.setText(" ! ? *", 0, LCDDisplay::Align::Left);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
CHECK(displayData == expected);
display.clear();
}
{
display.setText("AAA", 0, LCDDisplay::Align::Left);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected
= {0x7E, 0x7E, 0x7E, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
CHECK(displayData == expected);
display.clear();
}
{
display.setText("AAA", 0, LCDDisplay::Align::Right);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected
= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7E, 0x7E, 0x7E};
CHECK(displayData == expected);
display.clear();
}
{
display.setText("AAA", 0, LCDDisplay::Align::Center);
std::vector<uint8_t> displayData(
display.displayData(), display.displayData() + display.dataSize());
std::vector<uint8_t> expected
= {0, 0, 0, 0, 0, 0, 0, 0, 0x7E, 0x7E, 0x7E, 0, 0, 0, 0, 0, 0, 0, 0};
CHECK(displayData == expected);
display.clear();
}
}
//--------------------------------------------------------------------------------------------------
} // namespace test
} // namespace cabl
} // namespace sl
<|endoftext|>
|
<commit_before>#include "Script.hpp"
using namespace Component;
Script::Script(Entity* entity) : SuperComponent(entity) {
}
Json::Value Script::Save() const {
Json::Value component;
return component;
}
void Script::Load(const Json::Value& node) {
}
<commit_msg>Add placeholder value to script component<commit_after>#include "Script.hpp"
using namespace Component;
Script::Script(Entity* entity) : SuperComponent(entity) {
}
Json::Value Script::Save() const {
Json::Value component;
component["placeholderValue"] = "";
return component;
}
void Script::Load(const Json::Value& node) {
}
<|endoftext|>
|
<commit_before>#include "opt_avcall.h"
//#include "../avcall/avcall.h"
//#include "../avcall/mediadevicewatcher.h"
#include "../psimedia/psimedia.h"
//#include "common.h"
//#include "iconwidget.h"
//#include "psioptions.h"
#include "gstprovider.h"
#include "optionaccessinghost.h"
#include "ui_opt_avcall.h"
#include <QComboBox>
#include <QLineEdit>
#include <QList>
class OptAvCallUI : public QWidget, public Ui::OptAvCall {
public:
OptAvCallUI() : QWidget() { setupUi(this); }
};
//----------------------------------------------------------------------------
// OptionsTabAvCall
//----------------------------------------------------------------------------
OptionsTabAvCall::OptionsTabAvCall(PsiMedia::Provider *provider, OptionAccessingHost *optHost, QIcon icon) :
_icon(icon), provider(provider), optHost(optHost)
{
// connect(MediaDeviceWatcher::instance(), &MediaDeviceWatcher::updated, this, [this]() { restoreOptions(); });
}
OptionsTabAvCall::~OptionsTabAvCall() { delete features; }
QWidget *OptionsTabAvCall::widget()
{
if (w)
return nullptr;
w = new OptAvCallUI();
if (!features) {
features = provider->createFeatures();
}
return w;
}
void OptionsTabAvCall::applyOptions()
{
if (!w)
return;
OptAvCallUI *d = static_cast<OptAvCallUI *>(w.data());
/*
PsiOptions::instance()->setOption("options.media.devices.audio-output",
d->cb_audioOutDevice->itemData(d->cb_audioOutDevice->currentIndex()).toString());
PsiOptions::instance()->setOption("options.media.devices.audio-input",
d->cb_audioInDevice->itemData(d->cb_audioInDevice->currentIndex()).toString());
PsiOptions::instance()->setOption("options.media.devices.video-input",
d->cb_videoInDevice->itemData(d->cb_videoInDevice->currentIndex()).toString());
PsiOptions::instance()->setOption("options.media.video-support", d->cb_videoSupport->isChecked());
MediaDeviceWatcher::instance()->updateDefaults();
*/
}
void OptionsTabAvCall::restoreOptions()
{
if (!w)
return;
OptAvCallUI *d = static_cast<OptAvCallUI *>(w.data());
auto devs
= PsiMedia::FeaturesContext::AudioOut | PsiMedia::FeaturesContext::AudioIn | PsiMedia::FeaturesContext::VideoIn;
auto handler = [this, d](const PsiMedia::PFeatures &features) {
d->cb_audioOutDevice->clear();
if (features.audioOutputDevices.isEmpty())
d->cb_audioOutDevice->addItem("<None>", QString());
for (const PsiMedia::PDevice &dev : features.audioOutputDevices)
d->cb_audioOutDevice->addItem(dev.name, dev.id);
d->cb_audioInDevice->clear();
if (features.audioInputDevices.isEmpty())
d->cb_audioInDevice->addItem("<None>", QString());
for (const PsiMedia::PDevice &dev : features.audioInputDevices)
d->cb_audioInDevice->addItem(dev.name, dev.id);
d->cb_videoInDevice->clear();
if (features.videoInputDevices.isEmpty())
d->cb_videoInDevice->addItem("<None>", QString());
for (const PsiMedia::PDevice &dev : features.videoInputDevices)
d->cb_videoInDevice->addItem(dev.name, dev.id);
auto ain = optHost->getPluginOption("audio-input", QString()).toString();
auto aout = optHost->getPluginOption("audio-out", QString()).toString();
auto vin = optHost->getPluginOption("video-input", QString()).toString();
if (!aout.isEmpty())
d->cb_audioOutDevice->setCurrentIndex(d->cb_audioOutDevice->findData(aout));
if (!ain.isEmpty())
d->cb_audioInDevice->setCurrentIndex(d->cb_audioInDevice->findData(ain));
if (!vin.isEmpty())
d->cb_videoInDevice->setCurrentIndex(d->cb_videoInDevice->findData(vin));
if (this->connectDataChanged) {
this->connectDataChanged(w);
// it's a hack to not play with other signals much
this->connectDataChanged = std::function<void(QWidget *)>();
}
};
features->lookup(devs, w, handler);
// features->monitor(devs, w, handler);
}
QByteArray OptionsTabAvCall::id() const { return "avcall"; }
QByteArray OptionsTabAvCall::nextToId() const { return "sound"; }
QByteArray OptionsTabAvCall::parentId() const { return ""; }
QString OptionsTabAvCall::title() const { return QObject::tr("Voice Calling"); }
QIcon OptionsTabAvCall::icon() const { return _icon; }
QString OptionsTabAvCall::desc() const { return QObject::tr("Audio and video device configuration"); }
void OptionsTabAvCall::setCallbacks(std::function<void()> dataChanged, std::function<void(bool)> noDirty,
std::function<void(QWidget *)> connectDataChanged)
{
this->dataChanged = dataChanged;
this->noDirty = noDirty;
this->connectDataChanged = connectDataChanged;
}
<commit_msg>Save/restore select media device settings<commit_after>#include "opt_avcall.h"
//#include "../avcall/avcall.h"
//#include "../avcall/mediadevicewatcher.h"
#include "../psimedia/psimedia.h"
//#include "common.h"
//#include "iconwidget.h"
//#include "psioptions.h"
#include "gstprovider.h"
#include "optionaccessinghost.h"
#include "ui_opt_avcall.h"
#include <QComboBox>
#include <QLineEdit>
#include <QList>
class OptAvCallUI : public QWidget, public Ui::OptAvCall {
public:
OptAvCallUI() : QWidget() { setupUi(this); }
};
//----------------------------------------------------------------------------
// OptionsTabAvCall
//----------------------------------------------------------------------------
OptionsTabAvCall::OptionsTabAvCall(PsiMedia::Provider *provider, OptionAccessingHost *optHost, QIcon icon) :
_icon(icon), provider(provider), optHost(optHost)
{
// connect(MediaDeviceWatcher::instance(), &MediaDeviceWatcher::updated, this, [this]() { restoreOptions(); });
}
OptionsTabAvCall::~OptionsTabAvCall() { delete features; }
QWidget *OptionsTabAvCall::widget()
{
if (w)
return nullptr;
w = new OptAvCallUI();
if (!features) {
features = provider->createFeatures();
}
return w;
}
void OptionsTabAvCall::applyOptions()
{
if (!w)
return;
OptAvCallUI *d = static_cast<OptAvCallUI *>(w.data());
optHost->setPluginOption("devices.audio-output",
d->cb_audioOutDevice->itemData(d->cb_audioOutDevice->currentIndex()).toString());
optHost->setPluginOption("devices.audio-input",
d->cb_audioInDevice->itemData(d->cb_audioInDevice->currentIndex()).toString());
optHost->setPluginOption("devices.video-input",
d->cb_videoInDevice->itemData(d->cb_videoInDevice->currentIndex()).toString());
/*
MediaDeviceWatcher::instance()->updateDefaults();
*/
}
void OptionsTabAvCall::restoreOptions()
{
if (!w)
return;
OptAvCallUI *d = static_cast<OptAvCallUI *>(w.data());
auto devs
= PsiMedia::FeaturesContext::AudioOut | PsiMedia::FeaturesContext::AudioIn | PsiMedia::FeaturesContext::VideoIn;
auto handler = [this, d](const PsiMedia::PFeatures &features) {
d->cb_audioOutDevice->clear();
if (features.audioOutputDevices.isEmpty())
d->cb_audioOutDevice->addItem("<None>", QString());
for (const PsiMedia::PDevice &dev : features.audioOutputDevices)
d->cb_audioOutDevice->addItem(dev.name, dev.id);
d->cb_audioInDevice->clear();
if (features.audioInputDevices.isEmpty())
d->cb_audioInDevice->addItem("<None>", QString());
for (const PsiMedia::PDevice &dev : features.audioInputDevices)
d->cb_audioInDevice->addItem(dev.name, dev.id);
d->cb_videoInDevice->clear();
if (features.videoInputDevices.isEmpty())
d->cb_videoInDevice->addItem("<None>", QString());
for (const PsiMedia::PDevice &dev : features.videoInputDevices)
d->cb_videoInDevice->addItem(dev.name, dev.id);
auto ain = optHost->getPluginOption("devices.audio-input", QString()).toString();
auto aout = optHost->getPluginOption("devices.audio-output", QString()).toString();
auto vin = optHost->getPluginOption("devices.video-input", QString()).toString();
if (!aout.isEmpty())
d->cb_audioOutDevice->setCurrentIndex(d->cb_audioOutDevice->findData(aout));
if (!ain.isEmpty())
d->cb_audioInDevice->setCurrentIndex(d->cb_audioInDevice->findData(ain));
if (!vin.isEmpty())
d->cb_videoInDevice->setCurrentIndex(d->cb_videoInDevice->findData(vin));
if (this->connectDataChanged) {
this->connectDataChanged(w);
// it's a hack to not play with other signals much
this->connectDataChanged = std::function<void(QWidget *)>();
}
};
features->lookup(devs, w, handler);
// features->monitor(devs, w, handler);
}
QByteArray OptionsTabAvCall::id() const { return "avcall"; }
QByteArray OptionsTabAvCall::nextToId() const { return "sound"; }
QByteArray OptionsTabAvCall::parentId() const { return ""; }
QString OptionsTabAvCall::title() const { return QObject::tr("Voice Calling"); }
QIcon OptionsTabAvCall::icon() const { return _icon; }
QString OptionsTabAvCall::desc() const { return QObject::tr("Audio and video device configuration"); }
void OptionsTabAvCall::setCallbacks(std::function<void()> dataChanged, std::function<void(bool)> noDirty,
std::function<void(QWidget *)> connectDataChanged)
{
this->dataChanged = dataChanged;
this->noDirty = noDirty;
this->connectDataChanged = connectDataChanged;
}
<|endoftext|>
|
<commit_before><commit_msg>Entry wall and entry wall sensor position and size adjustments<commit_after><|endoftext|>
|
<commit_before>/*
Copyright (c) 2021 Intel Corporation
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.
*/
#define TBB_PREVIEW_COLLABORATIVE_CALL_ONCE 1
#if _MSC_VER && !defined(__INTEL_COMPILER)
// unreachable code
#pragma warning( push )
#pragma warning( disable: 4702 )
#endif
#if __INTEL_COMPILER && _MSC_VER
#pragma warning(disable : 2586) // decorated name length exceeded, name was truncated
#endif
#include "common/config.h"
// Include first to check missed header dependencies
#include "tbb/collaborative_call_once.h"
#include "common/test.h"
#include "common/exception_handling.h"
#include "common/utils_concurrency_limit.h"
#include "tbb/parallel_invoke.h"
#include "tbb/parallel_reduce.h"
#include "tbb/task_arena.h"
//! \file test_collaborative_call_once.cpp
//! \brief Tests for [preview] functionality
struct increment_functor {
int ct{0};
void operator()() {
ct++;
}
};
struct sum_functor {
int sum{0};
template<typename T>
void operator()(T first_op) {
sum += first_op;
}
template<typename T, typename... Args>
void operator()(T first_op, Args&&... args) {
(*this)(first_op);
(*this)(std::forward<Args>(args)...);
}
};
struct move_only_type {
const int* my_pointer;
move_only_type(move_only_type && other): my_pointer(other.my_pointer){ other.my_pointer=nullptr; }
explicit move_only_type(const int* value): my_pointer(value) {}
};
class call_once_exception : public std::exception {};
template<typename Fn, typename... Args>
void call_once_in_for_loop(std::size_t N, Fn&& body, Args&&... args) {
tbb::collaborative_once_flag flag;
for (std::size_t i = 0; i < N; ++i) {
tbb::collaborative_call_once(flag, std::forward<Fn>(body), std::forward<Args>(args)...);
}
}
template<typename Fn, typename... Args>
void call_once_in_parallel_for(std::size_t N, Fn&& body, Args&&... args) {
tbb::collaborative_once_flag flag;
#if __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
auto stored_pack = tbb::detail::d0::save_pack(std::forward<Args>(args)...);
auto func = [&] { tbb::detail::d0::call(std::forward<Fn>(body), std::move(stored_pack)); };
#endif // __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
tbb::parallel_for(tbb::blocked_range<size_t>(0, N), [&](const tbb::blocked_range<size_t>& range) {
for (size_t i = range.begin(); i != range.end(); ++i) {
#if __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
tbb::collaborative_call_once(flag, func);
#else
tbb::collaborative_call_once(flag, std::forward<Fn>(body), std::forward<Args>(args)...);
#endif //__TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
}
});
}
template<typename Fn, typename... Args>
void call_once_threads(std::size_t N, Fn&& body, Args&&... args) {
tbb::collaborative_once_flag flag;
std::vector<std::thread> threads;
#if __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
auto stored_pack = tbb::detail::d0::save_pack(std::forward<Args>(args)...);
auto func = [&] { tbb::detail::d0::call(std::forward<Fn>(body), std::move(stored_pack)); };
#endif // __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
for (std::size_t i = 0; i < N; ++i)
{
threads.push_back(std::thread([&]() {
#if __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
tbb::collaborative_call_once(flag, func);
#else
tbb::collaborative_call_once(flag, std::forward<Fn>(body), std::forward<Args>(args)...);
#endif // __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
}));
}
for (auto& thread : threads) {
thread.join();
}
}
//! Test for functor to be called only once
//! \brief \ref interface \ref requirement
TEST_CASE("only calls once 1") {
{
increment_functor f;
call_once_in_for_loop(1024, f);
REQUIRE( f.ct == 1);
}
{
increment_functor f;
call_once_in_parallel_for(100, f);
REQUIRE(f.ct == 1);
}
{
increment_functor f;
call_once_threads(utils::get_platform_max_threads(), f);
REQUIRE(f.ct == 1);
}
}
//! Test for functor to be called only once
//! \brief \ref interface \ref requirement
TEST_CASE("only calls once 2") {
{
sum_functor f;
call_once_in_for_loop(1024, f, 1, 2, 3 ,4);
REQUIRE(f.sum == 10);
}
{
sum_functor f;
call_once_in_parallel_for(512, f, 1000, -1000);
REQUIRE(f.sum == 0);
}
{
sum_functor f;
call_once_threads(utils::get_platform_max_threads(), f, 0, -1, -5);
REQUIRE(f.sum == -6);
}
}
//! Test for correct handling move-only arguments
//! \brief \ref interface \ref requirement
TEST_CASE("only calls once - move only argument") {
const int value = 42;
int ready{0};
auto func = [&ready, &value] (move_only_type other) {
REQUIRE(other.my_pointer == &value);
ready++;
};
{
move_only_type mv(&value);
call_once_in_parallel_for(512, func, std::move(mv));
REQUIRE(ready == 1);
REQUIRE(mv.my_pointer == nullptr);
}
{
move_only_type mv(&value);
call_once_threads(utils::get_platform_max_threads(), func, std::move(mv));
REQUIRE(ready == 2);
REQUIRE(mv.my_pointer == nullptr);
}
}
//! Stress test for functor to be called only once
//! \brief \ref interface \ref requirement \ref stress
TEST_CASE("only calls once - stress test") {
#if TBB_TEST_LOW_WORKLOAD
constexpr std::size_t N = 32;
#elif __TBB_x86_32 || __aarch32__ || __ANDROID__
// Some C++ implementations allocate 8MB stacks for std::thread on 32 bit platforms
// that makes impossible to create more than ~500 threads.
// Android has been added to decrease testing time.
constexpr std::size_t N = tbb::detail::d0::max_nfs_size * 2;
#else
constexpr std::size_t N = tbb::detail::d0::max_nfs_size * 4;
#endif
{
increment_functor f;
call_once_threads(N, f);
REQUIRE(f.ct == 1);
}
{
increment_functor f;
utils::SpinBarrier barrier{N};
tbb::collaborative_once_flag flag;
utils::NativeParallelFor(N, [&](std::size_t) {
for (int i = 0; i < 100; ++i) {
REQUIRE(f.ct == i);
barrier.wait([&] {
flag.~collaborative_once_flag();
new (&flag) tbb::collaborative_once_flag{};
});
tbb::collaborative_call_once(flag, f);
}
});
}
}
#if TBB_USE_EXCEPTIONS
//! Test for collaborative_call_once exception handling
//! \brief \ref error_guessing
TEST_CASE("handles exceptions - state reset") {
bool b{ false };
auto setB = [&b]() { b = true; };
auto setBAndCancel = [&b]() {
b = true;
throw call_once_exception{};
};
tbb::collaborative_once_flag flag;
REQUIRE_THROWS_AS(tbb::collaborative_call_once(flag, setBAndCancel), call_once_exception);
REQUIRE(b);
b = false;
REQUIRE_THROWS_AS(tbb::collaborative_call_once(flag, setBAndCancel), call_once_exception);
REQUIRE(b);
b = false;
tbb::collaborative_call_once(flag, setB);
REQUIRE(b);
b = false;
tbb::collaborative_call_once(flag, setB); // Now the call_once flag should be set.
REQUIRE(!b);
b = false;
REQUIRE_NOTHROW(tbb::collaborative_call_once(flag, setBAndCancel)); // Flag still set, so it shouldn't be called.
REQUIRE(!b);
}
//! Stress test for collaborative_call_once exception handling
//! \brief \ref error_guessing \ref stress
TEST_CASE("handles exceptions - stress test") {
#if TBB_TEST_LOW_WORKLOAD
constexpr std::size_t N = 32;
#elif __TBB_x86_32 || __aarch32__ || __ANDROID__
// Some C++ implementations allocate 8MB stacks for std::thread on 32 bit platforms
// that makes impossible to create more than ~500 threads.
// Android has been added to decrease testing time.
constexpr std::size_t N = tbb::detail::d0::max_nfs_size * 2;
#else
constexpr std::size_t N = tbb::detail::d0::max_nfs_size * 4;
#endif
int data{0};
bool run_again{true};
auto throwing_func = [&] {
utils::doDummyWork(10000);
if (data < 100) {
data++;
run_again = true;
throw call_once_exception{};
}
run_again = false;
};
tbb::collaborative_once_flag flag;
utils::NativeParallelFor(N, [&](std::size_t) {
while(run_again) {
try {
tbb::collaborative_call_once(flag, throwing_func);
} catch (const call_once_exception&) {
// We expecting only const call_once_exception&
} catch (...) {
FAIL("Unexpected exception");
}
}
});
REQUIRE(data == 100);
}
#endif
//! Test for multiple help from moonlighting threads
//! \brief \ref interface \ref requirement
TEST_CASE("multiple help") {
std::size_t num_threads = utils::get_platform_max_threads();
utils::SpinBarrier barrier{num_threads};
tbb::collaborative_once_flag flag;
tbb::parallel_for<std::size_t>(0, num_threads, [&](std::size_t) {
barrier.wait();
tbb::collaborative_call_once(flag, [&] {
tbb::parallel_for<std::size_t>(0, num_threads, [&](std::size_t) {
barrier.wait();
});
});
});
}
//! Test for collaborative work from different arenas
//! \brief \ref interface \ref requirement
TEST_CASE("multiple arenas") {
int num_threads = static_cast<int>(utils::get_platform_max_threads());
utils::SpinBarrier barrier(num_threads);
tbb::task_arena a1(num_threads), a2(num_threads);
tbb::collaborative_once_flag flag;
for (auto i = 0; i < num_threads - 1; ++i) {
a1.enqueue([&] {
barrier.wait();
barrier.wait();
tbb::collaborative_call_once(flag, [] {
FAIL("Unreachable code. collaborative_once_flag must be already initialized at this moment");
});
});
}
barrier.wait();
a2.execute([&] {
utils::ConcurrencyTracker ct;
tbb::parallel_for(0, num_threads, [&](int) {
CHECK(utils::ConcurrencyTracker::PeakParallelism() == 1);
});
tbb::collaborative_call_once(flag, [&] {
barrier.wait();
tbb::parallel_for(0, num_threads, [&](int) {
barrier.wait();
});
});
});
}
using FibBuffer = std::vector<std::pair<tbb::collaborative_once_flag, std::uint64_t>>;
std::uint64_t collaborative_recursive_fib(int n, FibBuffer& buffer) {
if (n <= 1) {
return 1;
}
tbb::collaborative_call_once(buffer[n].first, [&]() {
std::uint64_t a, b;
tbb::parallel_invoke([&] { a = collaborative_recursive_fib(n - 2, buffer); },
[&] { b = collaborative_recursive_fib(n - 1, buffer); });
buffer[n].second = a + b;
});
return buffer[n].second;
}
std::uint64_t collaborative_recursive_fib(int n) {
FibBuffer buffer(n);
return collaborative_recursive_fib(n-1, buffer);
}
//! Correctness test for Fibonacci example
//! \brief \ref interface \ref requirement
TEST_CASE("fibonacci example") {
constexpr int N = 93;
constexpr std::uint64_t expected_result = 12200160415121876738ull;
auto collaborative = collaborative_recursive_fib(N);
REQUIRE(collaborative == expected_result);
}
#if _MSC_VER && !defined(__INTEL_COMPILER)
#pragma warning( pop )
#endif
<commit_msg>Fix TSAN errors in collaborative_call_once (#445)<commit_after>/*
Copyright (c) 2021 Intel Corporation
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.
*/
#define TBB_PREVIEW_COLLABORATIVE_CALL_ONCE 1
#if _MSC_VER && !defined(__INTEL_COMPILER)
// unreachable code
#pragma warning( push )
#pragma warning( disable: 4702 )
#endif
#if __INTEL_COMPILER && _MSC_VER
#pragma warning(disable : 2586) // decorated name length exceeded, name was truncated
#endif
#include "common/config.h"
// Include first to check missed header dependencies
#include "tbb/collaborative_call_once.h"
#include "common/test.h"
#include "common/exception_handling.h"
#include "common/utils_concurrency_limit.h"
#include "tbb/parallel_invoke.h"
#include "tbb/parallel_reduce.h"
#include "tbb/task_arena.h"
//! \file test_collaborative_call_once.cpp
//! \brief Tests for [preview] functionality
struct increment_functor {
int ct{0};
void operator()() {
ct++;
}
};
struct sum_functor {
int sum{0};
template<typename T>
void operator()(T first_op) {
sum += first_op;
}
template<typename T, typename... Args>
void operator()(T first_op, Args&&... args) {
(*this)(first_op);
(*this)(std::forward<Args>(args)...);
}
};
struct move_only_type {
const int* my_pointer;
move_only_type(move_only_type && other): my_pointer(other.my_pointer){ other.my_pointer=nullptr; }
explicit move_only_type(const int* value): my_pointer(value) {}
};
class call_once_exception : public std::exception {};
template<typename Fn, typename... Args>
void call_once_in_for_loop(std::size_t N, Fn&& body, Args&&... args) {
tbb::collaborative_once_flag flag;
for (std::size_t i = 0; i < N; ++i) {
tbb::collaborative_call_once(flag, std::forward<Fn>(body), std::forward<Args>(args)...);
}
}
template<typename Fn, typename... Args>
void call_once_in_parallel_for(std::size_t N, Fn&& body, Args&&... args) {
tbb::collaborative_once_flag flag;
#if __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
auto stored_pack = tbb::detail::d0::save_pack(std::forward<Args>(args)...);
auto func = [&] { tbb::detail::d0::call(std::forward<Fn>(body), std::move(stored_pack)); };
#endif // __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
tbb::parallel_for(tbb::blocked_range<size_t>(0, N), [&](const tbb::blocked_range<size_t>& range) {
for (size_t i = range.begin(); i != range.end(); ++i) {
#if __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
tbb::collaborative_call_once(flag, func);
#else
tbb::collaborative_call_once(flag, std::forward<Fn>(body), std::forward<Args>(args)...);
#endif //__TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
}
});
}
template<typename Fn, typename... Args>
void call_once_threads(std::size_t N, Fn&& body, Args&&... args) {
tbb::collaborative_once_flag flag;
std::vector<std::thread> threads;
#if __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
auto stored_pack = tbb::detail::d0::save_pack(std::forward<Args>(args)...);
auto func = [&] { tbb::detail::d0::call(std::forward<Fn>(body), std::move(stored_pack)); };
#endif // __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
for (std::size_t i = 0; i < N; ++i)
{
threads.push_back(std::thread([&]() {
#if __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
tbb::collaborative_call_once(flag, func);
#else
tbb::collaborative_call_once(flag, std::forward<Fn>(body), std::forward<Args>(args)...);
#endif // __TBB_GCC_PARAMETER_PACK_IN_LAMBDAS_BROKEN
}));
}
for (auto& thread : threads) {
thread.join();
}
}
//! Test for functor to be called only once
//! \brief \ref interface \ref requirement
TEST_CASE("only calls once 1") {
{
increment_functor f;
call_once_in_for_loop(1024, f);
REQUIRE( f.ct == 1);
}
{
increment_functor f;
call_once_in_parallel_for(100, f);
REQUIRE(f.ct == 1);
}
{
increment_functor f;
call_once_threads(utils::get_platform_max_threads(), f);
REQUIRE(f.ct == 1);
}
}
//! Test for functor to be called only once
//! \brief \ref interface \ref requirement
TEST_CASE("only calls once 2") {
{
sum_functor f;
call_once_in_for_loop(1024, f, 1, 2, 3 ,4);
REQUIRE(f.sum == 10);
}
{
sum_functor f;
call_once_in_parallel_for(512, f, 1000, -1000);
REQUIRE(f.sum == 0);
}
{
sum_functor f;
call_once_threads(utils::get_platform_max_threads(), f, 0, -1, -5);
REQUIRE(f.sum == -6);
}
}
//! Test for correct handling move-only arguments
//! \brief \ref interface \ref requirement
TEST_CASE("only calls once - move only argument") {
const int value = 42;
int ready{0};
auto func = [&ready, &value] (move_only_type other) {
REQUIRE(other.my_pointer == &value);
ready++;
};
{
move_only_type mv(&value);
call_once_in_parallel_for(512, func, std::move(mv));
REQUIRE(ready == 1);
REQUIRE(mv.my_pointer == nullptr);
}
{
move_only_type mv(&value);
call_once_threads(utils::get_platform_max_threads(), func, std::move(mv));
REQUIRE(ready == 2);
REQUIRE(mv.my_pointer == nullptr);
}
}
//! Stress test for functor to be called only once
//! \brief \ref interface \ref requirement \ref stress
TEST_CASE("only calls once - stress test") {
#if TBB_TEST_LOW_WORKLOAD
constexpr std::size_t N = 32;
#elif __TBB_x86_32 || __aarch32__ || __ANDROID__
// Some C++ implementations allocate 8MB stacks for std::thread on 32 bit platforms
// that makes impossible to create more than ~500 threads.
// Android has been added to decrease testing time.
constexpr std::size_t N = tbb::detail::d0::max_nfs_size * 2;
#else
constexpr std::size_t N = tbb::detail::d0::max_nfs_size * 4;
#endif
{
increment_functor f;
call_once_threads(N, f);
REQUIRE(f.ct == 1);
}
{
increment_functor f;
utils::SpinBarrier barrier{N};
tbb::collaborative_once_flag flag;
utils::NativeParallelFor(N, [&](std::size_t) {
for (int i = 0; i < 100; ++i) {
REQUIRE(f.ct == i);
barrier.wait([&] {
flag.~collaborative_once_flag();
new (&flag) tbb::collaborative_once_flag{};
});
tbb::collaborative_call_once(flag, f);
}
});
}
}
#if TBB_USE_EXCEPTIONS
//! Test for collaborative_call_once exception handling
//! \brief \ref error_guessing
TEST_CASE("handles exceptions - state reset") {
bool b{ false };
auto setB = [&b]() { b = true; };
auto setBAndCancel = [&b]() {
b = true;
throw call_once_exception{};
};
tbb::collaborative_once_flag flag;
REQUIRE_THROWS_AS(tbb::collaborative_call_once(flag, setBAndCancel), call_once_exception);
REQUIRE(b);
b = false;
REQUIRE_THROWS_AS(tbb::collaborative_call_once(flag, setBAndCancel), call_once_exception);
REQUIRE(b);
b = false;
tbb::collaborative_call_once(flag, setB);
REQUIRE(b);
b = false;
tbb::collaborative_call_once(flag, setB); // Now the call_once flag should be set.
REQUIRE(!b);
b = false;
REQUIRE_NOTHROW(tbb::collaborative_call_once(flag, setBAndCancel)); // Flag still set, so it shouldn't be called.
REQUIRE(!b);
}
//! Stress test for collaborative_call_once exception handling
//! \brief \ref error_guessing \ref stress
TEST_CASE("handles exceptions - stress test") {
#if TBB_TEST_LOW_WORKLOAD
constexpr std::size_t N = 32;
#elif __TBB_x86_32 || __aarch32__ || __ANDROID__
// Some C++ implementations allocate 8MB stacks for std::thread on 32 bit platforms
// that makes impossible to create more than ~500 threads.
// Android has been added to decrease testing time.
constexpr std::size_t N = tbb::detail::d0::max_nfs_size * 2;
#else
constexpr std::size_t N = tbb::detail::d0::max_nfs_size * 4;
#endif
int data{0};
std::atomic<bool> run_again{true};
auto throwing_func = [&] {
utils::doDummyWork(10000);
if (data < 100) {
data++;
throw call_once_exception{};
}
run_again = false;
};
tbb::collaborative_once_flag flag;
utils::NativeParallelFor(N, [&](std::size_t) {
while(run_again) {
try {
tbb::collaborative_call_once(flag, throwing_func);
} catch (const call_once_exception&) {
// We expecting only const call_once_exception&
} catch (...) {
FAIL("Unexpected exception");
}
}
});
REQUIRE(data == 100);
}
#endif
//! Test for multiple help from moonlighting threads
//! \brief \ref interface \ref requirement
TEST_CASE("multiple help") {
std::size_t num_threads = utils::get_platform_max_threads();
utils::SpinBarrier barrier{num_threads};
tbb::collaborative_once_flag flag;
tbb::parallel_for<std::size_t>(0, num_threads, [&](std::size_t) {
barrier.wait();
tbb::collaborative_call_once(flag, [&] {
tbb::parallel_for<std::size_t>(0, num_threads, [&](std::size_t) {
barrier.wait();
});
});
});
}
//! Test for collaborative work from different arenas
//! \brief \ref interface \ref requirement
TEST_CASE("multiple arenas") {
int num_threads = static_cast<int>(utils::get_platform_max_threads());
utils::SpinBarrier barrier(num_threads);
tbb::task_arena a1(num_threads), a2(num_threads);
tbb::collaborative_once_flag flag;
for (auto i = 0; i < num_threads - 1; ++i) {
a1.enqueue([&] {
barrier.wait();
barrier.wait();
tbb::collaborative_call_once(flag, [] {
FAIL("Unreachable code. collaborative_once_flag must be already initialized at this moment");
});
});
}
barrier.wait();
a2.execute([&] {
utils::ConcurrencyTracker ct;
tbb::parallel_for(0, num_threads, [&](int) {
CHECK(utils::ConcurrencyTracker::PeakParallelism() == 1);
});
tbb::collaborative_call_once(flag, [&] {
barrier.wait();
tbb::parallel_for(0, num_threads, [&](int) {
barrier.wait();
});
});
});
}
using FibBuffer = std::vector<std::pair<tbb::collaborative_once_flag, std::uint64_t>>;
std::uint64_t collaborative_recursive_fib(int n, FibBuffer& buffer) {
if (n <= 1) {
return 1;
}
tbb::collaborative_call_once(buffer[n].first, [&]() {
std::uint64_t a, b;
tbb::parallel_invoke([&] { a = collaborative_recursive_fib(n - 2, buffer); },
[&] { b = collaborative_recursive_fib(n - 1, buffer); });
buffer[n].second = a + b;
});
return buffer[n].second;
}
std::uint64_t collaborative_recursive_fib(int n) {
FibBuffer buffer(n);
return collaborative_recursive_fib(n-1, buffer);
}
//! Correctness test for Fibonacci example
//! \brief \ref interface \ref requirement
TEST_CASE("fibonacci example") {
constexpr int N = 93;
constexpr std::uint64_t expected_result = 12200160415121876738ull;
auto collaborative = collaborative_recursive_fib(N);
REQUIRE(collaborative == expected_result);
}
#if _MSC_VER && !defined(__INTEL_COMPILER)
#pragma warning( pop )
#endif
<|endoftext|>
|
<commit_before>#include "tensor.h"
#include "device.h"
#include "op_algo.h"
#include "attribute.h"
#include "graph.h"
#include "gradient_helper.h"
#include "../operators/initializer.h"
#include "../operators/basic_arithmetics.h"
#include "../utils/assert.h"
#include <algorithm>
#include <sstream>
namespace mlfe{
//TODO : use thread for _children_modified
struct Tensor::impl{
impl() : _exec_order(0), _ctx("unknown"), _children_modified(true){}
std::vector<Tensor> _parents;
std::vector<Tensor> _children;
int _exec_order;
memory_ptr _mem;
OpAlgoContext _ctx;
std::shared_ptr<OpAlgo> _algo;
std::shared_ptr<Tensor> _gradient;
Attributes _attrs;
std::vector<Tensor> _compute_list;
std::vector<std::shared_ptr<Tensor>> _backward_list;
bool _children_modified;
};
Tensor::Tensor()
: _pimpl(std::make_shared<impl>()){
}
Tensor::Tensor(std::string name)
: Variable(name),
_pimpl(std::make_shared<impl>()){
}
Tensor::Tensor(std::vector<int> shape)
: Variable(shape),
_pimpl(std::make_shared<impl>()){
}
Tensor::~Tensor(){}
std::string Variable::name() const{
return *_name + "_" + std::to_string(_id->Id());
}
void Tensor::add_parent(Tensor p){
_pimpl->_parents.push_back(p);
//p.add_child(*this);
p._pimpl->_children.push_back(*this);
}
void Tensor::add_child(Tensor c){
_pimpl->_children.push_back(c);
//c.add_parent(*this);
c._pimpl->_parents.push_back(*this);
if(c._pimpl->_exec_order > _pimpl->_exec_order){
_pimpl->_exec_order = c._pimpl->_exec_order + 1;
}
}
std::vector<Tensor> Tensor::get_parents() const{
return _pimpl->_parents;
}
std::vector<Tensor> Tensor::get_children() const{
return _pimpl->_children;
}
int Tensor::get_exec_order() const{
return _pimpl->_exec_order;
}
bool Tensor::operator==(const Tensor &v) const{
return _pimpl.get() == v._pimpl.get();
}
void Tensor::eval(){
//compute all children.
if(_pimpl->_children_modified){
for(auto t : _pimpl->_compute_list){
if(t._pimpl->_algo != nullptr){
t._pimpl->_algo->Compute();
}
}
_pimpl->_children_modified = false;
}
}
unsigned int Variable::UniqueID::_next_gen = 0;
void Tensor::add_attr(Attribution attr){
_pimpl->_attrs.SetAttr(attr);
}
template <>
bool Tensor::get_attr<bool>(std::string name){
return _pimpl->_attrs.GetAttr<bool>(name);
}
template <>
int Tensor::get_attr<int>(std::string name){
return _pimpl->_attrs.GetAttr<int>(name);
}
template <>
double Tensor::get_attr<double>(std::string name){
return _pimpl->_attrs.GetAttr<double>(name);
}
template <>
float Tensor::get_attr<float>(std::string name){
return _pimpl->_attrs.GetAttr<float>(name);
}
template <>
std::vector<int> Tensor::get_attr<std::vector<int>>(std::string name){
return _pimpl->_attrs.GetAttr<std::vector<int>>(name);
}
OpAlgoContext Tensor::get_context() const{
return _pimpl->_ctx;
}
memory_ptr Tensor::get_memory() const{
return _pimpl->_mem;
}
void Tensor::backprop(){
if(_pimpl->_backward_list.empty()){
compute_gradient(*this);
}
for(auto &var : _pimpl->_backward_list){
var->eval();
}
}
Tensor Tensor::grad(){
return *_pimpl->_gradient;
}
const void *Tensor::_host_data(){
return _pimpl->_mem->host_data<void>();
}
void *Tensor::_mutable_host_data(){
_pimpl->_children_modified = true;
for(int n = 0; n < _pimpl->_parents.size(); ++n){
_pimpl->_parents[n]._pimpl->_children_modified = true;
}
return _pimpl->_mem->mutable_host_data<void>();
}
const void *Tensor::_device_data(){
return _pimpl->_mem->device_data<void>();
}
void *Tensor::_mutable_device_data(){
_pimpl->_children_modified = true;
for(int n = 0; n < _pimpl->_parents.size(); ++n){
_pimpl->_parents[n]._pimpl->_children_modified = true;
}
return _pimpl->_mem->mutable_device_data<void>();
}
void Tensor::compute_gradient(const Tensor root){
using TensorUmap = std::unordered_map<Tensor, std::vector<Tensor>>;
auto make_ptr = [](Tensor &t){
return std::make_shared<Tensor>(t);
};
TensorUmap dy_collector;
// top-down seuqnce
auto v_list = visit_bfs(root);
// sort by execution order.
std::sort(v_list.begin(), v_list.end(), [](Tensor v1, Tensor v2){
return v1.get_exec_order() > v2.get_exec_order();
});
// root gradient is 1.
dy_collector[root].push_back(functional::constant(1, root.shape()));
// set root gradient.
root._pimpl->_gradient = make_ptr(dy_collector[root][0]);
//run computing all gradients.
for(auto &var : v_list){
if(var._pimpl->_algo != nullptr){
auto op_name = var._pimpl->_algo->get_name();
auto helper = GradientHelperRegistry::Get();
auto op_grad = helper->GetHelper(op_name, nullptr);
//add all partial gradients and propagate down.
auto dy = functional::add_n(dy_collector[var]);
//calculate input's gradients.
auto input_grad = op_grad->compute_gradient(var, dy);
//set current variable's gradient, if a partial gradient exists.
if(dy_collector[var].size() > 1){
var._pimpl->_gradient = make_ptr(dy);
root._pimpl->_backward_list.push_back(var._pimpl->_gradient);
}
// store all input's gradients.
for(int n = 0; n < var.get_children().size(); ++n){
Tensor x = var.get_children()[n];
Tensor x_grad = input_grad[n];
dy_collector[x].push_back(x_grad);
x._pimpl->_gradient = make_ptr(x_grad);
root._pimpl->_backward_list.push_back(x._pimpl->_gradient);
}
}
}
}
Tensor::AssignOpFunctor::AssignOpFunctor(Tensor t, OpAlgoContext ctx){
auto reg = OpAlgoRegistry::Get();
auto dev = get_enabled_device();
std::string op_name = ctx.get_op_name();
std::string full_op_name = "Name:" + op_name + "/Device:";
std::string dev_name = dev->get_device_name();
std::string with_accel = dev_name + "(" + dev->get_accelerator_name() + ")";
t._pimpl->_compute_list = visit_bfs(t);
std::reverse(t._pimpl->_compute_list.begin(),
t._pimpl->_compute_list.end()
);
ctx.add_output(t);
t._pimpl->_ctx = ctx;
if(reg->Has(full_op_name + with_accel)){
t._pimpl->_algo = reg->GetOpAlgo(full_op_name + with_accel, &ctx);
}
else if(reg->Has(full_op_name + dev_name)){
t._pimpl->_algo = reg->GetOpAlgo(full_op_name + dev_name, &ctx);
}
else{
throw std::string(op_name) + " is not supported.";
}
}
namespace functional{
Tensor create_variable(std::vector<int> shape){
Tensor var;
var.reshape(shape);
var._pimpl->_mem = create_memory(var.size() * var.type().size);
return var;
}
Tensor reshape(Tensor x, std::vector<int> shape){
Tensor y;
OpAlgoContext ctx("Reshape");
y.add_child(x);
y._pimpl->_algo = nullptr;
y._pimpl->_gradient = nullptr;
y._pimpl->_ctx = x._pimpl->_ctx;
y._pimpl->_mem = x._pimpl->_mem;
y.reshape(shape);
Tensor::AssignOpFunctor(y, ctx);
return y;
}
void fill(Tensor to, const Tensor from){
copy(from.get_memory(), to.get_memory());
}
} // end namespace functional
} // end namespace mlfe
namespace std{
size_t hash<mlfe::Tensor>::operator()(const mlfe::Tensor &v) const{
return hash<shared_ptr<mlfe::Tensor::impl>>{}(v._pimpl);
}
} // end namespace std
<commit_msg>fix performance drop. fix checking children data modification.<commit_after>#include "tensor.h"
#include "device.h"
#include "op_algo.h"
#include "attribute.h"
#include "graph.h"
#include "gradient_helper.h"
#include "../operators/initializer.h"
#include "../operators/basic_arithmetics.h"
#include "../utils/assert.h"
#include <algorithm>
#include <sstream>
namespace mlfe{
//TODO : use thread for _children_modified
struct Tensor::impl{
impl() : _exec_order(0), _ctx("unknown"), _children_modified(true){}
std::vector<Tensor> _parents;
std::vector<Tensor> _children;
int _exec_order;
memory_ptr _mem;
OpAlgoContext _ctx;
std::shared_ptr<OpAlgo> _algo;
std::shared_ptr<Tensor> _gradient;
Attributes _attrs;
std::vector<Tensor> _compute_list;
std::vector<std::shared_ptr<Tensor>> _backward_list;
bool _children_modified;
};
Tensor::Tensor()
: _pimpl(std::make_shared<impl>()){
}
Tensor::Tensor(std::string name)
: Variable(name),
_pimpl(std::make_shared<impl>()){
}
Tensor::Tensor(std::vector<int> shape)
: Variable(shape),
_pimpl(std::make_shared<impl>()){
}
Tensor::~Tensor(){}
std::string Variable::name() const{
return *_name + "_" + std::to_string(_id->Id());
}
void Tensor::add_parent(Tensor p){
_pimpl->_parents.push_back(p);
//p.add_child(*this);
p._pimpl->_children.push_back(*this);
}
void Tensor::add_child(Tensor c){
_pimpl->_children.push_back(c);
//c.add_parent(*this);
c._pimpl->_parents.push_back(*this);
if(c._pimpl->_exec_order > _pimpl->_exec_order){
_pimpl->_exec_order = c._pimpl->_exec_order + 1;
}
}
std::vector<Tensor> Tensor::get_parents() const{
return _pimpl->_parents;
}
std::vector<Tensor> Tensor::get_children() const{
return _pimpl->_children;
}
int Tensor::get_exec_order() const{
return _pimpl->_exec_order;
}
bool Tensor::operator==(const Tensor &v) const{
return _pimpl.get() == v._pimpl.get();
}
void Tensor::eval(){
//compute all children.
for(auto t : _pimpl->_compute_list){
if(t._pimpl->_algo != nullptr &&
t._pimpl->_children_modified
){
t._pimpl->_algo->Compute();
t._pimpl->_children_modified = false;
for(int n = 0; n < t._pimpl->_parents.size(); ++n){
t._pimpl->_parents[n]._pimpl->_children_modified = true;
}
}
}
}
unsigned int Variable::UniqueID::_next_gen = 0;
void Tensor::add_attr(Attribution attr){
_pimpl->_attrs.SetAttr(attr);
}
template <>
bool Tensor::get_attr<bool>(std::string name){
return _pimpl->_attrs.GetAttr<bool>(name);
}
template <>
int Tensor::get_attr<int>(std::string name){
return _pimpl->_attrs.GetAttr<int>(name);
}
template <>
double Tensor::get_attr<double>(std::string name){
return _pimpl->_attrs.GetAttr<double>(name);
}
template <>
float Tensor::get_attr<float>(std::string name){
return _pimpl->_attrs.GetAttr<float>(name);
}
template <>
std::vector<int> Tensor::get_attr<std::vector<int>>(std::string name){
return _pimpl->_attrs.GetAttr<std::vector<int>>(name);
}
OpAlgoContext Tensor::get_context() const{
return _pimpl->_ctx;
}
memory_ptr Tensor::get_memory() const{
return _pimpl->_mem;
}
void Tensor::backprop(){
if(_pimpl->_backward_list.empty()){
compute_gradient(*this);
}
for(auto &var : _pimpl->_backward_list){
var->eval();
}
}
Tensor Tensor::grad(){
return *_pimpl->_gradient;
}
const void *Tensor::_host_data(){
return _pimpl->_mem->host_data<void>();
}
void *Tensor::_mutable_host_data(){
_pimpl->_children_modified = true;
for(int n = 0; n < _pimpl->_parents.size(); ++n){
_pimpl->_parents[n]._pimpl->_children_modified = true;
}
return _pimpl->_mem->mutable_host_data<void>();
}
const void *Tensor::_device_data(){
return _pimpl->_mem->device_data<void>();
}
void *Tensor::_mutable_device_data(){
_pimpl->_children_modified = true;
for(int n = 0; n < _pimpl->_parents.size(); ++n){
_pimpl->_parents[n]._pimpl->_children_modified = true;
}
return _pimpl->_mem->mutable_device_data<void>();
}
void Tensor::compute_gradient(const Tensor root){
using TensorUmap = std::unordered_map<Tensor, std::vector<Tensor>>;
auto make_ptr = [](Tensor &t){
return std::make_shared<Tensor>(t);
};
TensorUmap dy_collector;
// top-down seuqnce
auto v_list = visit_bfs(root);
// sort by execution order.
std::sort(v_list.begin(), v_list.end(), [](Tensor v1, Tensor v2){
return v1.get_exec_order() > v2.get_exec_order();
});
// root gradient is 1.
dy_collector[root].push_back(functional::constant(1, root.shape()));
// set root gradient.
root._pimpl->_gradient = make_ptr(dy_collector[root][0]);
//run computing all gradients.
for(auto &var : v_list){
if(var._pimpl->_algo != nullptr){
auto op_name = var._pimpl->_algo->get_name();
auto helper = GradientHelperRegistry::Get();
auto op_grad = helper->GetHelper(op_name, nullptr);
//add all partial gradients and propagate down.
auto dy = functional::add_n(dy_collector[var]);
//calculate input's gradients.
auto input_grad = op_grad->compute_gradient(var, dy);
//set current variable's gradient, if a partial gradient exists.
if(dy_collector[var].size() > 1){
var._pimpl->_gradient = make_ptr(dy);
root._pimpl->_backward_list.push_back(var._pimpl->_gradient);
}
// store all input's gradients.
for(int n = 0; n < var.get_children().size(); ++n){
Tensor x = var.get_children()[n];
Tensor x_grad = input_grad[n];
dy_collector[x].push_back(x_grad);
x._pimpl->_gradient = make_ptr(x_grad);
root._pimpl->_backward_list.push_back(x._pimpl->_gradient);
}
}
}
}
Tensor::AssignOpFunctor::AssignOpFunctor(Tensor t, OpAlgoContext ctx){
auto reg = OpAlgoRegistry::Get();
auto dev = get_enabled_device();
std::string op_name = ctx.get_op_name();
std::string full_op_name = "Name:" + op_name + "/Device:";
std::string dev_name = dev->get_device_name();
std::string with_accel = dev_name + "(" + dev->get_accelerator_name() + ")";
t._pimpl->_compute_list = visit_bfs(t);
std::reverse(t._pimpl->_compute_list.begin(),
t._pimpl->_compute_list.end()
);
ctx.add_output(t);
t._pimpl->_ctx = ctx;
if(reg->Has(full_op_name + with_accel)){
t._pimpl->_algo = reg->GetOpAlgo(full_op_name + with_accel, &ctx);
}
else if(reg->Has(full_op_name + dev_name)){
t._pimpl->_algo = reg->GetOpAlgo(full_op_name + dev_name, &ctx);
}
else{
throw std::string(op_name) + " is not supported.";
}
}
namespace functional{
Tensor create_variable(std::vector<int> shape){
Tensor var;
var.reshape(shape);
var._pimpl->_mem = create_memory(var.size() * var.type().size);
return var;
}
Tensor reshape(Tensor x, std::vector<int> shape){
Tensor y;
OpAlgoContext ctx("Reshape");
y.add_child(x);
y._pimpl->_algo = nullptr;
y._pimpl->_gradient = nullptr;
y._pimpl->_ctx = x._pimpl->_ctx;
y._pimpl->_mem = x._pimpl->_mem;
y.reshape(shape);
Tensor::AssignOpFunctor(y, ctx);
return y;
}
void fill(Tensor to, const Tensor from){
copy(from.get_memory(), to.get_memory());
}
} // end namespace functional
} // end namespace mlfe
namespace std{
size_t hash<mlfe::Tensor>::operator()(const mlfe::Tensor &v) const{
return hash<shared_ptr<mlfe::Tensor::impl>>{}(v._pimpl);
}
} // end namespace std
<|endoftext|>
|
<commit_before>
// A game fragment adapted from Andre La Mothe's book
// Ported to GNU/Linux by Antonello Dettori
// The Black Art of 3D Games Programming
// Modified by CJM 24/9/'08 to run without error or warnings:
// Note: this is very old-fashioned code originally written for 16-bit PCs
// INCLUDES ///////////////////////////////////////////////
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <ncurses.h>
#include <time.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
// DEFINES ////////////////////////////////////////////////
#define MAX_X 80 // maximum x position for player
#define SCROLL_POS 24 // the point that scrolling occurs
// PROTOTYPES /////////////////////////////////////////////
void Init_Graphics();
void Set_Color(int fcolor, int bcolor);
void Draw_String(int x, int y, char *string);
// GLOBALS ////////////////////////////////////////////////
int game_running = 1; // state of game, 0=done, 1=run
// FUNCTIONS //////////////////////////////////////////////
void Init_Graphics()
{
// this function initializes the console graphics engine
setlocale(LC_ALL,"uk");
initscr();
cbreak(); /* Line buffering disabled */
keypad(stdscr, TRUE); /* We get F1, F2 etc.. */
noecho(); /* Don't echo() while we do getch */
scrollok(stdscr, TRUE);
curs_set(0); /*Set cursor invisible*/
start_color();
// seed the random number generator with time
srand((unsigned)time(NULL));
} // end Init_Graphics
///////////////////////////////////////////////////////////
void Set_Color(int pairNumber, int foreground, bool isActive, int background=COLOR_BLACK)
{
// Keep an init_pair for every different string in order to not apply the same color to
// everyone of them
init_pair(pairNumber, foreground, background);
if(isActive){
attron(COLOR_PAIR(pairNumber));
} else {
attroff(COLOR_PAIR(pairNumber));
}
} // Set_Color
///////////////////////////////////////////////////////////
void Draw_String(int x, int y, char* string)
{
// this function draws a string at the given x,y
int cursor_pos_x = x;
int cursor_pos_y = y;
// print the string in current color and position
mvaddstr(cursor_pos_y, cursor_pos_x, string);
refresh();
} // end Draw_String
///////////////////////////////////////////////////////////
void Clear_Screen(void)
{
// this function clears the screen
// set color to white on black
// Set_Color(15, 0);
// color_set(COLOR_PAIR(1));
// clear the screen
for (int x = 0; x <= MAX_X; x++){
for (int y = 0; y <= SCROLL_POS; y++){
Draw_String(x, y, "\n");
}
}
refresh();
} // end Clear_Screen
int kbhit()
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
int msleep(unsigned long milisec)
{
//Credits to http://cc.byexamples.com/2007/05/25/nanosleep-is-better-than-sleep-and-usleep/
struct timespec req={0};
time_t sec=(int)(milisec/1000);
milisec=milisec-(sec*1000);
req.tv_sec=sec;
req.tv_nsec=milisec*1000000L;
while(nanosleep(&req,&req)==-1)
continue;
return 1;
}
// MAIN GAME LOOP /////////////////////////////////////////
using namespace std;
int main()
{
char key; // player input data
int player_x = 40; // player's x
int random_color = 0;
// SECTION: initialization
// set up the console text graphics system
Init_Graphics();
// clear the screen
Clear_Screen();
// SECTION: main event loop, this is where all the action
// takes place, the general loop is erase-move-draw
while (game_running)
{
// SECTION: erase all the objects or clear screen
// nothing to erase in our case
// SECTION: get player input
if(kbhit()){
key = getchar();
// is player trying to exit, if so exit
if (key == 27)
game_running = 0;
// is player moving left
if (key == 'a')
player_x--;
// is player moving right
if (key == 'd')
player_x++;
}
// SECTION: game logic and further processing
// make sure player stays on screen
if (++player_x > MAX_X)
player_x = MAX_X;
if (--player_x < 0)
player_x = 0;
// SECTION: draw everything
// draw next star at random position
Set_Color(1, COLOR_WHITE,true);
Draw_String(rand() % MAX_X, SCROLL_POS, ".\n");
Set_Color(1, COLOR_WHITE,false);
// Scroll
scroll(stdscr);
// draw player
random_color = (rand() % 7) + 1;
Set_Color(2, random_color, true);
Draw_String(player_x, 0, "<--*-->");
Set_Color(2, random_color, false);
Draw_String(0, 0, "");
// SECTION: synchronize to a constant frame rate
msleep(45);
} // end while
// SECTION: shutdown and bail
Clear_Screen();
Draw_String(MAX_X/2,SCROLL_POS/2, "G A M E O V E R");
getch();
endwin();
return 0;
} // end main
<commit_msg>Small fix and formatting correction<commit_after>
// A game fragment adapted from Andre La Mothe's book
// Ported to GNU/Linux by Antonello Dettori
// The Black Art of 3D Games Programming
// Modified by CJM 24/9/'08 to run without error or warnings:
// Note: this is very old-fashioned code originally written for 16-bit PCs
// INCLUDES ///////////////////////////////////////////////
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <ncurses.h>
#include <time.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
// DEFINES ////////////////////////////////////////////////
#define MAX_X 80 // maximum x position for player
#define SCROLL_POS 24 // the point that scrolling occurs
// PROTOTYPES /////////////////////////////////////////////
void Init_Graphics();
void Set_Color(int fcolor, int bcolor);
void Draw_String(int x, int y, char *string);
// GLOBALS ////////////////////////////////////////////////
int game_running = 1; // state of game, 0=done, 1=run
// FUNCTIONS //////////////////////////////////////////////
void Init_Graphics()
{
// this function initializes the console graphics engine
setlocale(LC_ALL,"uk");
initscr();
cbreak(); /* Line buffering disabled */
keypad(stdscr, TRUE); /* We get F1, F2 etc.. */
noecho(); /* Don't echo() while we do getch */
scrollok(stdscr, TRUE);
curs_set(0); /*Set cursor invisible*/
start_color();
// seed the random number generator with time
srand((unsigned)time(NULL));
} // end Init_Graphics
///////////////////////////////////////////////////////////
void Set_Color(int pairNumber, int foreground, bool isActive, int background=COLOR_BLACK)
{
// Keep an init_pair for every different string in order to not apply the same color to
// everyone of them
init_pair(pairNumber, foreground, background);
if(isActive){
attron(COLOR_PAIR(pairNumber));
} else {
attroff(COLOR_PAIR(pairNumber));
}
} // Set_Color
///////////////////////////////////////////////////////////
void Draw_String(int x, int y, char* string)
{
// this function draws a string at the given x,y
int cursor_pos_x = x;
int cursor_pos_y = y;
// print the string in current color and position
mvaddstr(cursor_pos_y, cursor_pos_x, string);
refresh();
} // end Draw_String
///////////////////////////////////////////////////////////
void Clear_Screen(void)
{
// this function clears the screen
// set color to white on black
Set_Color(1, COLOR_WHITE, true);
// clear the screen
for (int x = 0; x <= MAX_X; x++){
for (int y = 0; y <= SCROLL_POS; y++){
Draw_String(x, y, "\n");
}
}
Set_Color(1, COLOR_WHITE, false);
refresh();
} // end Clear_Screen
int kbhit()
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
int msleep(unsigned long milisec)
{
//Credits to http://cc.byexamples.com/2007/05/25/nanosleep-is-better-than-sleep-and-usleep/
struct timespec req={0};
time_t sec=(int)(milisec/1000);
milisec=milisec-(sec*1000);
req.tv_sec=sec;
req.tv_nsec=milisec*1000000L;
while(nanosleep(&req,&req)==-1)
continue;
return 1;
}
// MAIN GAME LOOP /////////////////////////////////////////
using namespace std;
int main()
{
char key; // player input data
int player_x = 40; // player's x
int random_color = 0;
// SECTION: initialization
// set up the console text graphics system
Init_Graphics();
// clear the screen
Clear_Screen();
// SECTION: main event loop, this is where all the action
// takes place, the general loop is erase-move-draw
while (game_running)
{
// SECTION: erase all the objects or clear screen
// nothing to erase in our case
// SECTION: get player input
if(kbhit()){
key = getchar();
// is player trying to exit, if so exit
if (key == 27)
game_running = 0;
// is player moving left
if (key == 'a')
player_x--;
// is player moving right
if (key == 'd')
player_x++;
}
// SECTION: game logic and further processing
// make sure player stays on screen
if (++player_x > MAX_X)
player_x = MAX_X;
if (--player_x < 0)
player_x = 0;
// SECTION: draw everything
// draw next star at random position
Set_Color(1, COLOR_WHITE,true);
Draw_String(rand() % MAX_X, SCROLL_POS, ".\n");
Set_Color(1, COLOR_WHITE,false);
// Scroll
scroll(stdscr);
// draw player
random_color = (rand() % 7) + 1;
Set_Color(2, random_color, true);
Draw_String(player_x, 0, "<--*-->");
Set_Color(2, random_color, false);
Draw_String(0, 0, "");
// SECTION: synchronize to a constant frame rate
msleep(45);
} // end while
// SECTION: shutdown and bail
Clear_Screen();
Draw_String(MAX_X/2,SCROLL_POS/2, "G A M E O V E R");
getch();
endwin();
return 0;
} // end main
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 Devin Smith <devin@devinsmith.net>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include "QvdFile.h"
#include "utils/dumphex.h"
struct less_than_bitOffset {
inline bool operator() (const QvdField &field1, const QvdField &field2)
{
return field1.BitOffset < field2.BitOffset;
}
};
bool QvdFile::Load(const char *filename)
{
_fp = fopen(filename, "rb");
if (_fp == NULL) {
return false;
}
if (!parseXmlHeader(filename)) {
return false;
}
if (_eof && _bufLen == 0) {
// XML header parsed but missing symbol table and data.
return false;
}
// The start of the dataPtr might have the ending \r and \n from
// the XML portion, if so skip past that.
char c;
while (_bufLen > 0) {
c = peekByte();
if (c == '\r' || c == '\n' || c == '\0') {
advanceBytes(1);
continue;
}
break;
}
if (_eof && _bufLen == 0) {
// XML header parsed but missing symbol table and data.
return false;
}
fprintf(stdout, "%zu bytes left\n", _bufLen);
parseSymbolAndData();
// First 2 bytes seem to store a type:
// 00 01 - INT
// 00 04 - Text
// 00 05 - Dual INT
//dump_hex(0, _dataPtrStart, _bufLen);
// Read rest of file.
while (!_eof) {
size_t len = readBytes();
printf("Read %zu bytes.\n", len);
}
fclose(_fp);
return true;
}
bool QvdFile::parseSymbolAndData()
{
for (std::vector<QvdField>::iterator it = _hdr.Fields.begin();
it != _hdr.Fields.end(); ++it) {
printf("Parsing symbols for %s, need to read %d symbols\n",
it->FieldName.c_str(), it->NoOfSymbols);
for (unsigned int i = 0; i < it->NoOfSymbols; i++) {
unsigned char typeByte = static_cast<unsigned char>(readByte());
QvdSymbol symbol;
char stringByte;
double d;
symbol.Type = typeByte;
switch (typeByte) {
case 0x01: // INT (4 bytes)
symbol.IntValue = readInt32();
break;
case 0x02: // NUMERIC (double 8 bytes)
// XXX: Not endian safe.
memcpy(&d, _dataPtrStart, 8);
for (int i = 0; i < 8; i++) {
readByte();
}
symbol.DoubleValue = d;
break;
case 0x04: // String value (0 terminated)
while ((stringByte = readByte()) != 0) {
symbol.StringValue += stringByte;
}
break;
case 0x05: // Dual (INT format) 4 bytes, followed by string format.
symbol.IntValue = readInt32();
while ((stringByte = readByte()) != 0) {
symbol.StringValue += stringByte;
}
break;
case 0x06: // DUAL (Double format) 8 bytes followed by string format.
// XXX: Not endian safe.
memcpy(&d, _dataPtrStart, 8);
for (int i = 0; i < 8; i++) {
readByte();
}
symbol.DoubleValue = d;
// Read string.
while ((stringByte = readByte()) != 0) {
symbol.StringValue += stringByte;
}
break;
default:
printf("Unknown byte: 0x%02x\n", typeByte);
}
it->Symbols.push_back(symbol);
}
}
// Sort fields by BitOffset
std::sort(_hdr.Fields.begin(), _hdr.Fields.end(), less_than_bitOffset());
printf("Total number of rows: %d\n", _hdr.NoOfRecords);
size_t rowNumber = 0;
printf("[\n");
printf(" {\n");
if (_bufLen == 0) {
if (!_eof) {
readBytes();
} else {
return 0; // throw an error.
}
}
dump_hex(0, _dataPtrStart, _bufLen);
for (rowNumber = 0; rowNumber < _hdr.NoOfRecords; rowNumber++) {
printf("==== ROW: %d ====\n", (int)rowNumber);
// Read first row now;
for (std::vector<QvdField>::iterator it = _hdr.Fields.begin();
it != _hdr.Fields.end(); ++it) {
if (it->BitWidth > 0) {
printf("Parsing data for %s (%d), need to read %d bits for this field\n",
it->FieldName.c_str(), it->BitOffset, it->BitWidth);
int idx = get_bits_index(it->BitWidth);
if (it->Bias != 0)
idx += it->Bias;
printf("> Index = %d\n", idx);
_hdr.Indices.push_back(idx);
if (idx == -2) {
printf("NULL\n");
continue;
}
if (it->Symbols.size() == 0) {
printf("NULL\n");
continue;
}
QvdSymbol sym = it->Symbols[idx];
switch (sym.Type) {
case 0x01:
printf("%d\n", sym.IntValue);
break;
case 0x02:
printf("%f\n", sym.DoubleValue);
break;
case 0x04:
printf("%s\n", sym.StringValue.c_str());
break;
case 0x05:
printf("%u (%s)\n", (unsigned int)sym.IntValue, sym.StringValue.c_str());
break;
case 0x06:
printf("%f (%s)\n", sym.DoubleValue, sym.StringValue.c_str());
break;
default:
printf("Unknown value\n");
break;
}
}
}
}
printf(" }\n");
printf("]\n");
return true;
}
bool QvdFile::parseXmlHeader(const char *filename)
{
const char *endQvdTableHeader = "</QvdTableHeader>";
xmlParserCtxtPtr ctxt;
ctxt = xmlCreatePushParserCtxt(NULL, NULL, NULL, 0, filename);
// Read XML content of the file.
int done;
do {
size_t len = readBytes();
done = len < sizeof(_buf); // Did we reach end of file?
// Unfortunately the Qvd file format includes an XML based
// header followed by raw binary data.
// We know that it occurs after </QvdTableHeader> so we need
// to scan our read buffer each time to see if we have that tag.
//
// If we do, we alter the length read, set a pointer to the data just
// after the tag and proceed to finish reading the XML portion of the
// file.
char *end;
if ((end = strstr(_buf, endQvdTableHeader)) != NULL) {
end += strlen(endQvdTableHeader);
// For the XML portion, the dataPtrStart marks the end of the XML
// and the start of raw data to be parsed later on.
//
// We treat this as an "End of File" situation for expat.
_dataPtrStart = end;
_bufLen = len;
len = end - _buf;
_bufLen -= len;
done = 1;
}
if (xmlParseChunk(ctxt, _buf, len, done) != 0) {
fprintf(stderr, "An error occurred parsing the XML\n");
return false;
#if 0
fprintf(stderr, "%s at line %lu\n",
XML_ErrorString(XML_GetErrorCode(parser)),
XML_GetCurrentLineNumber(parser));
#endif
}
} while (!done);
if (ctxt->myDoc == NULL || !ctxt->wellFormed) {
// XML header is not well formed.
return false;
}
xmlDoc *doc = ctxt->myDoc; /* the resulting document tree */
xmlNode *root_element = xmlDocGetRootElement(doc);
for (xmlNode *node = root_element; node; node = node->next) {
if (node->type == XML_ELEMENT_NODE &&
strcmp((char *)node->name, "QvdTableHeader") == 0) {
_hdr.ParseXml(node);
}
}
xmlFreeDoc(doc);
xmlFreeParserCtxt(ctxt);
return true;
}
size_t QvdFile::readBytes()
{
size_t len = fread(_buf, 1, sizeof(_buf), _fp);
if (len < sizeof(_buf)) {
_eof = true;
}
_dataPtrStart = _buf;
_bufLen = len;
return len;
}
char QvdFile::readByte()
{
char c;
if (_bufLen == 0) {
if (!_eof) {
readBytes();
} else {
return 0; // throw an error.
}
}
_bufLen--;
c = *_dataPtrStart++;
return c;
}
int QvdFile::get_bits_index(size_t nBits)
{
int i = 0;
if (_bufLen == 0) {
if (!_eof) {
readBytes();
printf("Need to reload\n");
} else {
return 0; // throw an error.
}
}
while (nBits > _bitBufferSz) {
// printf("Requesting %zu bits, but only have %d bits\n", nBits, _bitBufferSz);
unsigned int byte = (unsigned char)*_dataPtrStart++;
// printf("Read byte 0x%02x\n", byte);
byte = byte << _bitBufferSz;
_bitBufferSz += 8;
_bitBuffer += byte;
_bufLen--;
}
// printf("%d\n", _bitBufferSz);
int mask = ((1 << nBits) - 1);
i = (_bitBuffer) & mask;
_bitBuffer = _bitBuffer >> nBits;
_bitBufferSz -= nBits;
return i;
}
//
// Reads 32 bits in Little Endian format.
//
int QvdFile::readInt32()
{
int c;
c = (unsigned char)readByte();
c += (unsigned char)readByte() << 8;
c += (unsigned char)readByte() << 16;
c += (unsigned char)readByte() << 24;
return c;
}
char QvdFile::peekByte()
{
char c;
if (_bufLen == 0) {
if (!_eof) {
readBytes();
} else {
return 0; // throw an error.
}
}
c = *_dataPtrStart;
return c;
}
void QvdFile::advanceBytes(size_t nBytes)
{
if (_bufLen < nBytes) {
if (!_eof) {
readBytes();
} else {
return; // throw an error.
}
}
if (_bufLen < nBytes) {
return; // throw an error.
}
_bufLen -= nBytes;
_dataPtrStart += nBytes;
}
<commit_msg>last index always came out as 0<commit_after>/*
* Copyright (c) 2017 Devin Smith <devin@devinsmith.net>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include "QvdFile.h"
#include "utils/dumphex.h"
struct less_than_bitOffset {
inline bool operator() (const QvdField &field1, const QvdField &field2)
{
return field1.BitOffset < field2.BitOffset;
}
};
bool QvdFile::Load(const char *filename)
{
_fp = fopen(filename, "rb");
if (_fp == NULL) {
return false;
}
if (!parseXmlHeader(filename)) {
return false;
}
if (_eof && _bufLen == 0) {
// XML header parsed but missing symbol table and data.
return false;
}
// The start of the dataPtr might have the ending \r and \n from
// the XML portion, if so skip past that.
char c;
while (_bufLen > 0) {
c = peekByte();
if (c == '\r' || c == '\n' || c == '\0') {
advanceBytes(1);
continue;
}
break;
}
if (_eof && _bufLen == 0) {
// XML header parsed but missing symbol table and data.
return false;
}
fprintf(stdout, "%zu bytes left\n", _bufLen);
parseSymbolAndData();
// First 2 bytes seem to store a type:
// 00 01 - INT
// 00 04 - Text
// 00 05 - Dual INT
//dump_hex(0, _dataPtrStart, _bufLen);
// Read rest of file.
while (!_eof) {
size_t len = readBytes();
printf("Read %zu bytes.\n", len);
}
fclose(_fp);
return true;
}
bool QvdFile::parseSymbolAndData()
{
for (std::vector<QvdField>::iterator it = _hdr.Fields.begin();
it != _hdr.Fields.end(); ++it) {
printf("Parsing symbols for %s, need to read %d symbols\n",
it->FieldName.c_str(), it->NoOfSymbols);
for (unsigned int i = 0; i < it->NoOfSymbols; i++) {
unsigned char typeByte = static_cast<unsigned char>(readByte());
QvdSymbol symbol;
char stringByte;
double d;
symbol.Type = typeByte;
switch (typeByte) {
case 0x01: // INT (4 bytes)
symbol.IntValue = readInt32();
break;
case 0x02: // NUMERIC (double 8 bytes)
// XXX: Not endian safe.
memcpy(&d, _dataPtrStart, 8);
for (int i = 0; i < 8; i++) {
readByte();
}
symbol.DoubleValue = d;
break;
case 0x04: // String value (0 terminated)
while ((stringByte = readByte()) != 0) {
symbol.StringValue += stringByte;
}
break;
case 0x05: // Dual (INT format) 4 bytes, followed by string format.
symbol.IntValue = readInt32();
while ((stringByte = readByte()) != 0) {
symbol.StringValue += stringByte;
}
break;
case 0x06: // DUAL (Double format) 8 bytes followed by string format.
// XXX: Not endian safe.
memcpy(&d, _dataPtrStart, 8);
for (int i = 0; i < 8; i++) {
readByte();
}
symbol.DoubleValue = d;
// Read string.
while ((stringByte = readByte()) != 0) {
symbol.StringValue += stringByte;
}
break;
default:
printf("Unknown byte: 0x%02x\n", typeByte);
}
it->Symbols.push_back(symbol);
}
}
// Sort fields by BitOffset
std::sort(_hdr.Fields.begin(), _hdr.Fields.end(), less_than_bitOffset());
printf("Total number of rows: %d\n", _hdr.NoOfRecords);
size_t rowNumber = 0;
printf("[\n");
printf(" {\n");
if (_bufLen == 0) {
if (!_eof) {
readBytes();
} else {
return 0; // throw an error.
}
}
dump_hex(0, _dataPtrStart, _bufLen);
for (rowNumber = 0; rowNumber < _hdr.NoOfRecords; rowNumber++) {
printf("==== ROW: %d ====\n", (int)rowNumber);
// Read first row now;
for (std::vector<QvdField>::iterator it = _hdr.Fields.begin();
it != _hdr.Fields.end(); ++it) {
if (it->BitWidth > 0) {
printf("Parsing data for %s (%d), need to read %d bits for this field\n",
it->FieldName.c_str(), it->BitOffset, it->BitWidth);
int idx = get_bits_index(it->BitWidth);
if (it->Bias != 0)
idx += it->Bias;
printf("> Index = %d\n", idx);
_hdr.Indices.push_back(idx);
if (idx == -2) {
printf("NULL\n");
continue;
}
if (it->Symbols.size() == 0) {
printf("NULL\n");
continue;
}
QvdSymbol sym = it->Symbols[idx];
switch (sym.Type) {
case 0x01:
printf("%d\n", sym.IntValue);
break;
case 0x02:
printf("%f\n", sym.DoubleValue);
break;
case 0x04:
printf("%s\n", sym.StringValue.c_str());
break;
case 0x05:
printf("%u (%s)\n", (unsigned int)sym.IntValue, sym.StringValue.c_str());
break;
case 0x06:
printf("%f (%s)\n", sym.DoubleValue, sym.StringValue.c_str());
break;
default:
printf("Unknown value\n");
break;
}
}
}
}
printf(" }\n");
printf("]\n");
return true;
}
bool QvdFile::parseXmlHeader(const char *filename)
{
const char *endQvdTableHeader = "</QvdTableHeader>";
xmlParserCtxtPtr ctxt;
ctxt = xmlCreatePushParserCtxt(NULL, NULL, NULL, 0, filename);
// Read XML content of the file.
int done;
do {
size_t len = readBytes();
done = len < sizeof(_buf); // Did we reach end of file?
// Unfortunately the Qvd file format includes an XML based
// header followed by raw binary data.
// We know that it occurs after </QvdTableHeader> so we need
// to scan our read buffer each time to see if we have that tag.
//
// If we do, we alter the length read, set a pointer to the data just
// after the tag and proceed to finish reading the XML portion of the
// file.
char *end;
if ((end = strstr(_buf, endQvdTableHeader)) != NULL) {
end += strlen(endQvdTableHeader);
// For the XML portion, the dataPtrStart marks the end of the XML
// and the start of raw data to be parsed later on.
//
// We treat this as an "End of File" situation for expat.
_dataPtrStart = end;
_bufLen = len;
len = end - _buf;
_bufLen -= len;
done = 1;
}
if (xmlParseChunk(ctxt, _buf, len, done) != 0) {
fprintf(stderr, "An error occurred parsing the XML\n");
return false;
#if 0
fprintf(stderr, "%s at line %lu\n",
XML_ErrorString(XML_GetErrorCode(parser)),
XML_GetCurrentLineNumber(parser));
#endif
}
} while (!done);
if (ctxt->myDoc == NULL || !ctxt->wellFormed) {
// XML header is not well formed.
return false;
}
xmlDoc *doc = ctxt->myDoc; /* the resulting document tree */
xmlNode *root_element = xmlDocGetRootElement(doc);
for (xmlNode *node = root_element; node; node = node->next) {
if (node->type == XML_ELEMENT_NODE &&
strcmp((char *)node->name, "QvdTableHeader") == 0) {
_hdr.ParseXml(node);
}
}
xmlFreeDoc(doc);
xmlFreeParserCtxt(ctxt);
return true;
}
size_t QvdFile::readBytes()
{
size_t len = fread(_buf, 1, sizeof(_buf), _fp);
if (len < sizeof(_buf)) {
_eof = true;
}
_dataPtrStart = _buf;
_bufLen = len;
return len;
}
char QvdFile::readByte()
{
char c;
if (_bufLen == 0) {
if (!_eof) {
readBytes();
} else {
return 0; // throw an error.
}
}
_bufLen--;
c = *_dataPtrStart++;
return c;
}
int QvdFile::get_bits_index(size_t nBits)
{
int i = 0;
if ((_bufLen == 0) && (nBits < _bitBufferSz)) {
if (!_eof) {
readBytes();
printf("Need to reload\n");
} else {
return 0; // throw an error.
}
}
while (nBits > _bitBufferSz) {
// printf("Requesting %zu bits, but only have %d bits\n", nBits, _bitBufferSz);
unsigned int byte = (unsigned char)*_dataPtrStart++;
// printf("Read byte 0x%02x\n", byte);
byte = byte << _bitBufferSz;
_bitBufferSz += 8;
_bitBuffer += byte;
_bufLen--;
}
// printf("%d\n", _bitBufferSz);
int mask = ((1 << nBits) - 1);
i = (_bitBuffer) & mask;
_bitBuffer = _bitBuffer >> nBits;
_bitBufferSz -= nBits;
return i;
}
//
// Reads 32 bits in Little Endian format.
//
int QvdFile::readInt32()
{
int c;
c = (unsigned char)readByte();
c += (unsigned char)readByte() << 8;
c += (unsigned char)readByte() << 16;
c += (unsigned char)readByte() << 24;
return c;
}
char QvdFile::peekByte()
{
char c;
if (_bufLen == 0) {
if (!_eof) {
readBytes();
} else {
return 0; // throw an error.
}
}
c = *_dataPtrStart;
return c;
}
void QvdFile::advanceBytes(size_t nBytes)
{
if (_bufLen < nBytes) {
if (!_eof) {
readBytes();
} else {
return; // throw an error.
}
}
if (_bufLen < nBytes) {
return; // throw an error.
}
_bufLen -= nBytes;
_dataPtrStart += nBytes;
}
<|endoftext|>
|
<commit_before>// Copyright 2014 Vladimir Alyamkin. All Rights Reserved.
#include "Krieger.h"
AKriegerExplosionEffect::AKriegerExplosionEffect(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP)
{
ExplosionLightComponentName = TEXT("ExplosionLight");
PrimaryActorTick.bCanEverTick = true;
ExplosionLight = PCIP.CreateDefaultSubobject<UPointLightComponent>(this, ExplosionLightComponentName);
ExplosionLight->AttenuationRadius = 400.0;
ExplosionLight->Intensity = 500.0f;
ExplosionLight->bUseInverseSquaredFalloff = false;
ExplosionLight->LightColor = FColor(255, 185, 35);
ExplosionLight->CastShadows = false;
ExplosionLight->bVisible = true;
ExplosionLightFadeOut = 0.2f;
}
void AKriegerExplosionEffect::BeginPlay()
{
Super::BeginPlay();
if (ExplosionFX)
{
UGameplayStatics::SpawnEmitterAtLocation(this, ExplosionFX, GetActorLocation(), GetActorRotation());
}
if (ExplosionSound)
{
UGameplayStatics::PlaySoundAtLocation(this, ExplosionSound, GetActorLocation());
}
if (Decal.DecalMaterial)
{
FRotator RandomDecalRotation = SurfaceHit.ImpactNormal.Rotation();
RandomDecalRotation.Roll = FMath::FRandRange(-180.0f, 180.0f);
UGameplayStatics::SpawnDecalAttached(Decal.DecalMaterial, FVector(Decal.DecalSize, Decal.DecalSize, 1.0f),
SurfaceHit.Component.Get(), SurfaceHit.BoneName,
SurfaceHit.ImpactPoint, RandomDecalRotation, EAttachLocation::KeepWorldPosition,
Decal.LifeSpan);
}
}
void AKriegerExplosionEffect::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
const float TimeAlive = GetWorld()->GetTimeSeconds() - CreationTime;
const float TimeRemaining = FMath::Max(0.0f, ExplosionLightFadeOut - TimeAlive);
if (TimeRemaining > 0)
{
const float FadeAlpha = 1.0f - FMath::Square(TimeRemaining / ExplosionLightFadeOut);
UPointLightComponent* DefLight = Cast<UPointLightComponent>(GetClass()->GetDefaultSubobjectByName(ExplosionLightComponentName));
ExplosionLight->SetBrightness(DefLight->Intensity * FadeAlpha);
}
else
{
Destroy();
}
}
<commit_msg>Explosion location fixed<commit_after>// Copyright 2014 Vladimir Alyamkin. All Rights Reserved.
#include "Krieger.h"
AKriegerExplosionEffect::AKriegerExplosionEffect(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP)
{
ExplosionLightComponentName = TEXT("ExplosionLight");
PrimaryActorTick.bCanEverTick = true;
ExplosionLight = PCIP.CreateDefaultSubobject<UPointLightComponent>(this, ExplosionLightComponentName);
ExplosionLight->AttenuationRadius = 400.0;
ExplosionLight->Intensity = 500.0f;
ExplosionLight->bUseInverseSquaredFalloff = false;
ExplosionLight->LightColor = FColor(255, 185, 35);
ExplosionLight->CastShadows = false;
ExplosionLight->bVisible = true;
ExplosionLightFadeOut = 0.2f;
// Don't miss to set root component
RootComponent = ExplosionLight;
}
void AKriegerExplosionEffect::BeginPlay()
{
Super::BeginPlay();
if (ExplosionFX)
{
UGameplayStatics::SpawnEmitterAtLocation(this, ExplosionFX, GetActorLocation(), GetActorRotation());
}
if (ExplosionSound)
{
UGameplayStatics::PlaySoundAtLocation(this, ExplosionSound, GetActorLocation());
}
if (Decal.DecalMaterial)
{
FRotator RandomDecalRotation = SurfaceHit.ImpactNormal.Rotation();
RandomDecalRotation.Roll = FMath::FRandRange(-180.0f, 180.0f);
UGameplayStatics::SpawnDecalAttached(Decal.DecalMaterial, FVector(Decal.DecalSize, Decal.DecalSize, 1.0f),
SurfaceHit.Component.Get(), SurfaceHit.BoneName,
SurfaceHit.ImpactPoint, RandomDecalRotation, EAttachLocation::KeepWorldPosition,
Decal.LifeSpan);
}
}
void AKriegerExplosionEffect::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
const float TimeAlive = GetWorld()->GetTimeSeconds() - CreationTime;
const float TimeRemaining = FMath::Max(0.0f, ExplosionLightFadeOut - TimeAlive);
if (TimeRemaining > 0)
{
const float FadeAlpha = 1.0f - FMath::Square(TimeRemaining / ExplosionLightFadeOut);
UPointLightComponent* DefLight = Cast<UPointLightComponent>(GetClass()->GetDefaultSubobjectByName(ExplosionLightComponentName));
ExplosionLight->SetBrightness(DefLight->Intensity * FadeAlpha);
}
else
{
Destroy();
}
}
<|endoftext|>
|
<commit_before>
#include "UEPyFSlateIcon.h"
#include "Engine/Texture2D.h"
#include "Engine/Engine.h"
static PyObject *py_ue_fslate_icon_get_icon(ue_PyFSlateIcon *self, PyObject * args)
{
return py_ue_new_uscriptstruct(FSlateBrush::StaticStruct(), (uint8*)self->icon.GetIcon());
}
static PyMethodDef ue_PyFSlateIcon_methods[] = {
{ "get_icon", (PyCFunction)py_ue_fslate_icon_get_icon, METH_VARARGS, "" },
{ NULL } /* Sentinel */
};
static PyObject *ue_PyFSlateIcon_str(ue_PyFSlateIcon *self)
{
return PyUnicode_FromFormat("<unreal_engine.SlateIcon {'name': %s}>",
TCHAR_TO_UTF8(*self->icon.GetStyleName().ToString()));
}
static PyTypeObject ue_PyFSlateIconType = {
PyVarObject_HEAD_INIT(NULL, 0)
"unreal_engine.FSlateIcon", /* tp_name */
sizeof(ue_PyFSlateIcon), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
(reprfunc)ue_PyFSlateIcon_str, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"Unreal Engine FSlateIcon", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
ue_PyFSlateIcon_methods, /* tp_methods */
};
static int ue_py_fslate_icon_init(ue_PyFSlateIcon *self, PyObject *args, PyObject *kwargs)
{
char *style_set = nullptr;
char *style = nullptr;
if (!PyArg_ParseTuple(args, "|ss", &style_set, &style))
{
return -1;
}
if (style_set)
{
if (!style)
{
PyErr_SetString(PyExc_ValueError, "you have not specified as style name");
return -1;
}
ISlateStyle const* const foundStyleSet = FSlateStyleRegistry::FindSlateStyle(FName(style_set));
const FSlateBrush * iconBrush = foundStyleSet->GetBrush(style);
FString Path = iconBrush->GetResourceName().ToString();
// Hack to load in the texture resource object of the icon brush in case it hasn't been already loaded
if (!Path.IsEmpty() && iconBrush->GetResourceObject() == nullptr)
{
if (Path.StartsWith(FSlateBrush::UTextureIdentifier()))
{
Path = Path.RightChop(FSlateBrush::UTextureIdentifier().Len());
}
UObject* TextureObject = LoadObject<UTexture2D>(NULL, *Path, NULL, LOAD_None, NULL);
FSlateBrush* Brush = const_cast<FSlateBrush*>(iconBrush);
// Set the texture object to a default texture to prevent constant loading of missing textures
if (!TextureObject)
{
UE_LOG(LogSlate, Warning, TEXT("Error loading loading UTexture from path: %s not found"), *Path);
if (GEngine)
{
TextureObject = GEngine->DefaultTexture;
}
}
else
{
// We do this here because this deprecated system of loading textures will not report references and we dont want the Slate RHI resource manager to manage references
TextureObject->AddToRoot();
}
if (TextureObject)
{
Brush->SetResourceObject(TextureObject);
}
}
new(&self->icon) FSlateIcon(FName(style_set), FName(style));
}
else
{
new(&self->icon) FSlateIcon();
}
return 0;
}
void ue_python_init_fslate_icon(PyObject *ue_module)
{
ue_PyFSlateIconType.tp_new = PyType_GenericNew;
ue_PyFSlateIconType.tp_init = (initproc)ue_py_fslate_icon_init;
if (PyType_Ready(&ue_PyFSlateIconType) < 0)
return;
Py_INCREF(&ue_PyFSlateIconType);
PyModule_AddObject(ue_module, "FSlateIcon", (PyObject *)&ue_PyFSlateIconType);
}
ue_PyFSlateIcon *py_ue_new_fslate_icon(const FSlateIcon slate_icon)
{
ue_PyFSlateIcon *ret = (ue_PyFSlateIcon *)PyObject_New(ue_PyFSlateIcon, &ue_PyFSlateIconType);
ret->icon = slate_icon;
return ret;
}
ue_PyFSlateIcon *py_ue_is_fslate_icon(PyObject *obj)
{
if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyFSlateIconType))
return nullptr;
return (ue_PyFSlateIcon *)obj;
}
<commit_msg>FIX bug with PyFSlateIcon<commit_after>
#include "UEPyFSlateIcon.h"
#include "Engine/Texture2D.h"
#include "Engine/Engine.h"
static PyObject *py_ue_fslate_icon_get_icon(ue_PyFSlateIcon *self, PyObject * args)
{
return py_ue_new_uscriptstruct(FSlateBrush::StaticStruct(), (uint8*)self->icon.GetIcon());
}
static PyMethodDef ue_PyFSlateIcon_methods[] = {
{ "get_icon", (PyCFunction)py_ue_fslate_icon_get_icon, METH_VARARGS, "" },
{ NULL } /* Sentinel */
};
static PyObject *ue_PyFSlateIcon_str(ue_PyFSlateIcon *self)
{
return PyUnicode_FromFormat("<unreal_engine.SlateIcon {'name': %s}>",
TCHAR_TO_UTF8(*self->icon.GetStyleName().ToString()));
}
static PyTypeObject ue_PyFSlateIconType = {
PyVarObject_HEAD_INIT(NULL, 0)
"unreal_engine.FSlateIcon", /* tp_name */
sizeof(ue_PyFSlateIcon), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
(reprfunc)ue_PyFSlateIcon_str, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"Unreal Engine FSlateIcon", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
ue_PyFSlateIcon_methods, /* tp_methods */
};
static int ue_py_fslate_icon_init(ue_PyFSlateIcon *self, PyObject *args, PyObject *kwargs)
{
char *style_set = nullptr;
char *style = nullptr;
if (!PyArg_ParseTuple(args, "|ss", &style_set, &style))
{
return -1;
}
if (style_set)
{
if (!style)
{
PyErr_SetString(PyExc_ValueError, "you have not specified as style name");
return -1;
}
ISlateStyle const* const foundStyleSet = FSlateStyleRegistry::FindSlateStyle(FName(style_set));
FSlateBrush const* iconBrush = foundStyleSet ? foundStyleSet->GetBrush(style) : nullptr;
// Hack to load in the texture resource object of the icon brush in case it hasn't been already loaded
if (iconBrush && iconBrush->HasUObject() == false)
{
FSlateShaderResourceProxy* ResourceProxy = FSlateDataPayload::ResourceManager->GetShaderResource(*iconBrush);
}
else
{
UE_LOG(LogPython, Warning, TEXT("Error loading icon brush from (%s,%s) (styleset,style)"), ANSI_TO_TCHAR(style_set), ANSI_TO_TCHAR(style));
}
new(&self->icon) FSlateIcon(FName(style_set), FName(style));
}
else
{
new(&self->icon) FSlateIcon();
}
return 0;
}
void ue_python_init_fslate_icon(PyObject *ue_module)
{
ue_PyFSlateIconType.tp_new = PyType_GenericNew;
ue_PyFSlateIconType.tp_init = (initproc)ue_py_fslate_icon_init;
if (PyType_Ready(&ue_PyFSlateIconType) < 0)
return;
Py_INCREF(&ue_PyFSlateIconType);
PyModule_AddObject(ue_module, "FSlateIcon", (PyObject *)&ue_PyFSlateIconType);
}
ue_PyFSlateIcon *py_ue_new_fslate_icon(const FSlateIcon slate_icon)
{
ue_PyFSlateIcon *ret = (ue_PyFSlateIcon *)PyObject_New(ue_PyFSlateIcon, &ue_PyFSlateIconType);
ret->icon = slate_icon;
return ret;
}
ue_PyFSlateIcon *py_ue_is_fslate_icon(PyObject *obj)
{
if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyFSlateIconType))
return nullptr;
return (ue_PyFSlateIcon *)obj;
}
<|endoftext|>
|
<commit_before>#include "ReconVarIC.h"
#include "MooseMesh.h"
template<>
InputParameters validParams<ReconVarIC>()
{
InputParameters params = validParams<InitialCondition>();
params.addRequiredParam<UserObjectName>("ebsd_reader", "The EBSDReader GeneralUserObject");
params.addRequiredParam<unsigned int>("crys_num", "Specifies the number of order paraameters to create");
params.addRequiredParam<unsigned int>("grain_num", "Specifies the number of grains in the reconstructed dataset");
params.addRequiredParam<unsigned int>("crys_index", "The index for the current crystal");
return params;
}
ReconVarIC::ReconVarIC(const std::string & name,InputParameters parameters) :
InitialCondition(name, parameters),
_mesh(_fe_problem.mesh()),
_nl(_fe_problem.getNonlinearSystem()),
_ebsd_reader(getUserObject<EBSDReader>("ebsd_reader")),
_op_num(getParam<unsigned int>("crys_num")),
_grain_num(getParam<unsigned int>("grain_num")),
_op_index(getParam<unsigned int>("crys_index"))
{
}
void
ReconVarIC::initialSetup()
{
// Read in EBSD data from user object
// unsigned int n_elem = _mesh.getMesh().n_active_elem();
const MeshBase::element_iterator begin = _mesh.getMesh().active_elements_begin();
const MeshBase::element_iterator end = _mesh.getMesh().active_elements_end();
for (MeshBase::element_iterator el = begin; el != end; ++el)
{
Elem * current_elem = *el;
unsigned int index = current_elem->id();
Point p0 = current_elem->centroid();
const EBSDReader::EBSDPointData & d = _ebsd_reader.getData(p0);
_gp[index].grain = d.grain;
_gp[index].p = d.p;
}
// Calculate centerpoint of each EBSD grain TODO: use Point
_centerpoints.resize(_grain_num);
std::vector<unsigned int> num_pts(_grain_num);
for (unsigned int i = 0; i < _grain_num; i++)
{
_centerpoints[i] = 0.0;
num_pts[i] = 0;
}
for (std::map<unsigned int, GrainPoint>::iterator it = _gp.begin(); it != _gp.end(); ++it)
{
_centerpoints[it->second.grain] += it->second.p;
num_pts[it->second.grain]++;
}
for (unsigned int i = 0; i < _grain_num; i++)
{
if (num_pts[i] == 0) continue;
_centerpoints[i] *= 1.0 / Real(num_pts[i]);
}
// Output error message if number of order parameters is larger than number of grains from EBSD dataset
if (_op_num > _grain_num)
mooseError("ERROR in PolycrystalReducedIC: Number of order parameters (crys_num) can't be larger than the number of grains (grain_num)");
// Assign grains to each order parameter in a way that maximizes distance
_assigned_op.resize(_grain_num);
std::vector<int> min_op_ind;
std::vector<Real> min_op_dist;
min_op_ind.resize(_op_num);
min_op_dist.resize(_op_num);
for (unsigned int grain=0; grain < _grain_num; grain++)
{
// Determine the distance to the closest center assigned to each order parameter
if (grain >= _op_num)
{
// We can set the array to the distances to the grains 0.._op_num-1 (see assignment in the else case)
for (unsigned int i=0; i<_op_num; ++i)
{
min_op_dist[i] = _mesh.minPeriodicDistance(_var.number(), _centerpoints[grain], _centerpoints[i]);
min_op_ind[_assigned_op[i]] = i;
}
// Now check if any of the extra grains are even closer
for (unsigned int i=_op_num; i<grain; ++i)
{
Real dist = _mesh.minPeriodicDistance(_var.number(), _centerpoints[grain], _centerpoints[i]);
if (min_op_dist[_assigned_op[i]] > dist)
{
min_op_dist[_assigned_op[i]] = dist;
min_op_ind[_assigned_op[i]] = i;
}
}
}
else
{
_assigned_op[grain] = grain;
continue;
}
// Assign the current center point to the order parameter that is furthest away.
unsigned int mx_ind = 0;
for (unsigned int i = 1; i < _op_num; i++) // Find index of max
if (min_op_dist[mx_ind] < min_op_dist[i])
mx_ind = i;
_assigned_op[grain] = mx_ind;
}
}
// Note that we are not actually using Point coordinates that get passed in to assign the order parameter.
// By knowing the curent elements index, we can use it's centroid to grab the EBSD grain index
// associated with the point from the EBSDReader user object.
Real
ReconVarIC::value(const Point &)
{
const Point p1 = _current_elem->centroid();
const unsigned int grn_index = _ebsd_reader.getData(p1).grain;;
if (_assigned_op[grn_index] == _op_index)
return 1.0;
else
return 0.0;
}
<commit_msg>Add test for ReconAuxVarICAction, fix bugs (#21)<commit_after>#include "ReconVarIC.h"
#include "MooseMesh.h"
template<>
InputParameters validParams<ReconVarIC>()
{
InputParameters params = validParams<InitialCondition>();
params.addRequiredParam<UserObjectName>("ebsd_reader", "The EBSDReader GeneralUserObject");
params.addRequiredParam<unsigned int>("crys_num", "Specifies the number of order paraameters to create");
params.addRequiredParam<unsigned int>("grain_num", "Specifies the number of grains in the reconstructed dataset");
params.addRequiredParam<unsigned int>("crys_index", "The index for the current crystal");
return params;
}
ReconVarIC::ReconVarIC(const std::string & name,InputParameters parameters) :
InitialCondition(name, parameters),
_mesh(_fe_problem.mesh()),
_nl(_fe_problem.getNonlinearSystem()),
_ebsd_reader(getUserObject<EBSDReader>("ebsd_reader")),
_op_num(getParam<unsigned int>("crys_num")),
_grain_num(getParam<unsigned int>("grain_num")),
_op_index(getParam<unsigned int>("crys_index"))
{
}
void
ReconVarIC::initialSetup()
{
// Read in EBSD data from user object
// unsigned int n_elem = _mesh.getMesh().n_active_elem();
const MeshBase::element_iterator begin = _mesh.getMesh().active_elements_begin();
const MeshBase::element_iterator end = _mesh.getMesh().active_elements_end();
for (MeshBase::element_iterator el = begin; el != end; ++el)
{
Elem * current_elem = *el;
unsigned int index = current_elem->id();
Point p0 = current_elem->centroid();
const EBSDReader::EBSDPointData & d = _ebsd_reader.getData(p0);
_gp[index].grain = d.grain;
_gp[index].p = d.p;
}
// Calculate centerpoint of each EBSD grain
_centerpoints.resize(_grain_num);
std::vector<unsigned int> num_pts(_grain_num);
for (unsigned int i = 0; i < _grain_num; i++)
{
_centerpoints[i] = 0.0;
num_pts[i] = 0;
}
for (std::map<unsigned int, GrainPoint>::iterator it = _gp.begin(); it != _gp.end(); ++it)
{
_centerpoints[it->second.grain] += it->second.p;
num_pts[it->second.grain]++;
}
for (unsigned int i = 0; i < _grain_num; i++)
{
if (num_pts[i] == 0) continue;
_centerpoints[i] *= 1.0 / Real(num_pts[i]);
}
// Output error message if number of order parameters is larger than number of grains from EBSD dataset
if (_op_num > _grain_num)
mooseError("ERROR in PolycrystalReducedIC: Number of order parameters (crys_num) can't be larger than the number of grains (grain_num)");
// Assign grains to each order parameter in a way that maximizes distance
_assigned_op.resize(_grain_num);
std::vector<int> min_op_ind;
std::vector<Real> min_op_dist;
min_op_ind.resize(_op_num);
min_op_dist.resize(_op_num);
for (unsigned int grain=0; grain < _grain_num; grain++)
{
// Determine the distance to the closest center assigned to each order parameter
if (grain >= _op_num)
{
// We can set the array to the distances to the grains 0.._op_num-1 (see assignment in the else case)
for (unsigned int i=0; i<_op_num; ++i)
{
min_op_dist[i] = _mesh.minPeriodicDistance(_var.number(), _centerpoints[grain], _centerpoints[i]);
min_op_ind[_assigned_op[i]] = i;
}
// Now check if any of the extra grains are even closer
for (unsigned int i=_op_num; i<grain; ++i)
{
Real dist = _mesh.minPeriodicDistance(_var.number(), _centerpoints[grain], _centerpoints[i]);
if (min_op_dist[_assigned_op[i]] > dist)
{
min_op_dist[_assigned_op[i]] = dist;
min_op_ind[_assigned_op[i]] = i;
}
}
}
else
{
_assigned_op[grain] = grain;
continue;
}
// Assign the current center point to the order parameter that is furthest away.
unsigned int mx_ind = 0;
for (unsigned int i = 1; i < _op_num; i++) // Find index of max
if (min_op_dist[mx_ind] < min_op_dist[i])
mx_ind = i;
_assigned_op[grain] = mx_ind;
}
}
// Note that we are not actually using Point coordinates that get passed in to assign the order parameter.
// By knowing the curent elements index, we can use it's centroid to grab the EBSD grain index
// associated with the point from the EBSDReader user object.
Real
ReconVarIC::value(const Point &)
{
const Point p1 = _current_elem->centroid();
const unsigned int grn_index = _ebsd_reader.getData(p1).grain;;
if (_assigned_op[grn_index] == _op_index)
return 1.0;
else
return 0.0;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/planning_util.h"
#include <array>
#include <cmath>
#include <memory>
#include <utility>
#include "modules/common/math/integral.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/planning/math/hermite_spline.h"
namespace apollo {
namespace planning {
namespace util {
using common::PathPoint;
using common::SpeedPoint;
using common::TrajectoryPoint;
PathPoint interpolate(const PathPoint &p0, const PathPoint &p1,
const double s) {
double s0 = p0.s();
double s1 = p1.s();
CHECK(s0 <= s && s <= s1);
std::array<double, 2> gx0{{p0.theta(), p0.kappa()}};
std::array<double, 2> gx1{{p1.theta(), p1.kappa()}};
HermiteSpline<double, 3> geometry_spline(gx0, gx1, s0, s1);
auto func_cos_theta = [&geometry_spline](const double s) {
auto theta = geometry_spline.evaluate(0, s);
return std::cos(theta);
};
auto func_sin_theta = [&geometry_spline](const double s) {
auto theta = geometry_spline.evaluate(0, s);
return std::sin(theta);
};
double x =
p0.x() + common::math::IntegrateByGaussLegendre(func_cos_theta, s0, s);
double y =
p0.y() + common::math::IntegrateByGaussLegendre(func_sin_theta, s0, s);
double theta = geometry_spline.evaluate(0, s);
double kappa = geometry_spline.evaluate(1, s);
double dkappa = geometry_spline.evaluate(2, s);
double d2kappa = geometry_spline.evaluate(3, s);
PathPoint p;
p.set_x(x);
p.set_y(y);
p.set_theta(theta);
p.set_kappa(kappa);
p.set_dkappa(dkappa);
p.set_ddkappa(d2kappa);
p.set_s(s);
return p;
}
SpeedPoint interpolate(const SpeedPoint &start, const SpeedPoint &end,
const double weight) {
SpeedPoint speed_point;
speed_point.set_s((1 - weight) * start.s() + weight * end.s());
speed_point.set_t((1 - weight) * start.t() + weight * end.t());
speed_point.set_v((1 - weight) * start.v() + weight * end.v());
speed_point.set_a((1 - weight) * start.a() + weight * end.a());
speed_point.set_da((1 - weight) * start.da() + weight * end.da());
return speed_point;
}
PathPoint interpolate_linear_approximation(const PathPoint &p0,
const PathPoint &p1,
const double s) {
double s0 = p0.s();
double s1 = p1.s();
CHECK(s0 < s1);
PathPoint path_point;
double weight = (s - s0) / (s1 - s0);
double x = (1 - weight) * p0.x() + weight * p1.x();
double y = (1 - weight) * p0.y() + weight * p1.y();
double cos_heading =
(1 - weight) * std::cos(p0.theta()) + weight * std::cos(p1.theta());
double sin_heading =
(1 - weight) * std::sin(p0.theta()) + weight * std::sin(p1.theta());
double theta = std::atan2(sin_heading, cos_heading);
double kappa = (1 - weight) * p0.kappa() + weight * p1.kappa();
double dkappa = (1 - weight) * p0.dkappa() + weight * p1.dkappa();
double ddkappa = (1 - weight) * p0.ddkappa() + weight * p1.ddkappa();
path_point.set_x(x);
path_point.set_y(y);
path_point.set_theta(theta);
path_point.set_kappa(kappa);
path_point.set_dkappa(dkappa);
path_point.set_ddkappa(ddkappa);
path_point.set_s(s);
return path_point;
}
TrajectoryPoint interpolate(const TrajectoryPoint &tp0,
const TrajectoryPoint &tp1, const double t) {
const PathPoint &pp0 = tp0.path_point();
const PathPoint &pp1 = tp1.path_point();
double t0 = tp0.relative_time();
double t1 = tp1.relative_time();
std::array<double, 2> dx0{{tp0.v(), tp0.a()}};
std::array<double, 2> dx1{{tp1.v(), tp1.a()}};
HermiteSpline<double, 3> dynamic_spline(dx0, dx1, t0, t1);
double s0 = 0.0;
auto func_v = [&dynamic_spline](const double t) {
return dynamic_spline.evaluate(0, t);
};
double s1 = common::math::IntegrateByGaussLegendre(func_v, t0, t1);
double s = common::math::IntegrateByGaussLegendre(func_v, t0, t);
double v = dynamic_spline.evaluate(0, t);
double a = dynamic_spline.evaluate(1, t);
std::array<double, 2> gx0{{pp0.theta(), pp0.kappa()}};
std::array<double, 2> gx1{{pp1.theta(), pp1.kappa()}};
HermiteSpline<double, 3> geometry_spline(gx0, gx1, s0, s1);
auto func_cos_theta = [&geometry_spline](const double s) {
auto theta = geometry_spline.evaluate(0, s);
return std::cos(theta);
};
auto func_sin_theta = [&geometry_spline](const double s) {
auto theta = geometry_spline.evaluate(0, s);
return std::sin(theta);
};
double x =
pp0.x() + common::math::IntegrateByGaussLegendre(func_cos_theta, s0, s);
double y =
pp0.y() + common::math::IntegrateByGaussLegendre(func_sin_theta, s0, s);
double theta = geometry_spline.evaluate(0, s);
double kappa = geometry_spline.evaluate(1, s);
double dkappa = geometry_spline.evaluate(2, s);
double d2kappa = geometry_spline.evaluate(3, s);
TrajectoryPoint tp;
tp.set_v(v);
tp.set_a(a);
PathPoint *path_point = tp.mutable_path_point();
path_point->set_x(x);
path_point->set_y(y);
path_point->set_theta(theta);
path_point->set_kappa(kappa);
path_point->set_dkappa(dkappa);
path_point->set_ddkappa(d2kappa);
path_point->set_s(s);
// check the diff of computed s1 and p1.s()?
return tp;
}
TrajectoryPoint interpolate_linear_approximation(const TrajectoryPoint &tp0,
const TrajectoryPoint &tp1,
const double t) {
const PathPoint &pp0 = tp0.path_point();
const PathPoint &pp1 = tp1.path_point();
double t0 = tp0.relative_time();
double t1 = tp1.relative_time();
TrajectoryPoint tp;
tp.set_v(common::math::lerp(tp0.v(), t0, tp1.v(), t1, t));
tp.set_a(common::math::lerp(tp0.a(), t0, tp1.a(), t1, t));
tp.set_relative_time(t);
PathPoint *path_point = tp.mutable_path_point();
path_point->set_x(common::math::lerp(pp0.x(), t0, pp1.x(), t1, t));
path_point->set_y(common::math::lerp(pp0.y(), t0, pp1.y(), t1, t));
path_point->set_theta(
common::math::lerp(pp0.theta(), t0, pp1.theta(), t1, t));
path_point->set_kappa(
common::math::lerp(pp0.kappa(), t0, pp1.kappa(), t1, t));
path_point->set_dkappa(
common::math::lerp(pp0.dkappa(), t0, pp1.dkappa(), t1, t));
path_point->set_ddkappa(
common::math::lerp(pp0.ddkappa(), t0, pp1.ddkappa(), t1, t));
path_point->set_s(common::math::lerp(pp0.s(), t0, pp1.s(), t1, t));
return tp;
}
common::SLPoint interpolate(const common::SLPoint &start,
const common::SLPoint &end, const double weight) {
common::SLPoint point;
double s = start.s() * (1 - weight) + end.s() * weight;
double l = start.l() * (1 - weight) + end.l() * weight;
point.set_s(s);
point.set_l(l);
return point;
}
} // namespace util
} // namespace planning
} // namespace apollo
<commit_msg>Fixed the trajectory point interpolation problem when two points are the same<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/planning_util.h"
#include <array>
#include <cmath>
#include <memory>
#include <utility>
#include "modules/common/math/integral.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/planning/math/hermite_spline.h"
namespace apollo {
namespace planning {
namespace util {
using common::PathPoint;
using common::SpeedPoint;
using common::TrajectoryPoint;
PathPoint interpolate(const PathPoint &p0, const PathPoint &p1,
const double s) {
double s0 = p0.s();
double s1 = p1.s();
CHECK(s0 <= s && s <= s1);
std::array<double, 2> gx0{{p0.theta(), p0.kappa()}};
std::array<double, 2> gx1{{p1.theta(), p1.kappa()}};
HermiteSpline<double, 3> geometry_spline(gx0, gx1, s0, s1);
auto func_cos_theta = [&geometry_spline](const double s) {
auto theta = geometry_spline.evaluate(0, s);
return std::cos(theta);
};
auto func_sin_theta = [&geometry_spline](const double s) {
auto theta = geometry_spline.evaluate(0, s);
return std::sin(theta);
};
double x =
p0.x() + common::math::IntegrateByGaussLegendre(func_cos_theta, s0, s);
double y =
p0.y() + common::math::IntegrateByGaussLegendre(func_sin_theta, s0, s);
double theta = geometry_spline.evaluate(0, s);
double kappa = geometry_spline.evaluate(1, s);
double dkappa = geometry_spline.evaluate(2, s);
double d2kappa = geometry_spline.evaluate(3, s);
PathPoint p;
p.set_x(x);
p.set_y(y);
p.set_theta(theta);
p.set_kappa(kappa);
p.set_dkappa(dkappa);
p.set_ddkappa(d2kappa);
p.set_s(s);
return p;
}
SpeedPoint interpolate(const SpeedPoint &start, const SpeedPoint &end,
const double weight) {
SpeedPoint speed_point;
speed_point.set_s((1 - weight) * start.s() + weight * end.s());
speed_point.set_t((1 - weight) * start.t() + weight * end.t());
speed_point.set_v((1 - weight) * start.v() + weight * end.v());
speed_point.set_a((1 - weight) * start.a() + weight * end.a());
speed_point.set_da((1 - weight) * start.da() + weight * end.da());
return speed_point;
}
PathPoint interpolate_linear_approximation(const PathPoint &p0,
const PathPoint &p1,
const double s) {
double s0 = p0.s();
double s1 = p1.s();
CHECK(s0 < s1);
PathPoint path_point;
double weight = (s - s0) / (s1 - s0);
double x = (1 - weight) * p0.x() + weight * p1.x();
double y = (1 - weight) * p0.y() + weight * p1.y();
double cos_heading =
(1 - weight) * std::cos(p0.theta()) + weight * std::cos(p1.theta());
double sin_heading =
(1 - weight) * std::sin(p0.theta()) + weight * std::sin(p1.theta());
double theta = std::atan2(sin_heading, cos_heading);
double kappa = (1 - weight) * p0.kappa() + weight * p1.kappa();
double dkappa = (1 - weight) * p0.dkappa() + weight * p1.dkappa();
double ddkappa = (1 - weight) * p0.ddkappa() + weight * p1.ddkappa();
path_point.set_x(x);
path_point.set_y(y);
path_point.set_theta(theta);
path_point.set_kappa(kappa);
path_point.set_dkappa(dkappa);
path_point.set_ddkappa(ddkappa);
path_point.set_s(s);
return path_point;
}
TrajectoryPoint interpolate(const TrajectoryPoint &tp0,
const TrajectoryPoint &tp1, const double t) {
if (std::abs(tp0.path_point().s() - tp0.path_point().s()) < 1.0e-4) {
return tp1;
}
const PathPoint &pp0 = tp0.path_point();
const PathPoint &pp1 = tp1.path_point();
double t0 = tp0.relative_time();
double t1 = tp1.relative_time();
std::array<double, 2> dx0{{tp0.v(), tp0.a()}};
std::array<double, 2> dx1{{tp1.v(), tp1.a()}};
HermiteSpline<double, 3> dynamic_spline(dx0, dx1, t0, t1);
double s0 = 0.0;
auto func_v = [&dynamic_spline](const double t) {
return dynamic_spline.evaluate(0, t);
};
double s1 = common::math::IntegrateByGaussLegendre(func_v, t0, t1);
double s = common::math::IntegrateByGaussLegendre(func_v, t0, t);
if (std::abs(tp0.path_point().s() - s1) < 1.0e-4) {
return tp1;
}
double v = dynamic_spline.evaluate(0, t);
double a = dynamic_spline.evaluate(1, t);
std::array<double, 2> gx0{{pp0.theta(), pp0.kappa()}};
std::array<double, 2> gx1{{pp1.theta(), pp1.kappa()}};
HermiteSpline<double, 3> geometry_spline(gx0, gx1, s0, s1);
auto func_cos_theta = [&geometry_spline](const double s) {
auto theta = geometry_spline.evaluate(0, s);
return std::cos(theta);
};
auto func_sin_theta = [&geometry_spline](const double s) {
auto theta = geometry_spline.evaluate(0, s);
return std::sin(theta);
};
double x =
pp0.x() + common::math::IntegrateByGaussLegendre(func_cos_theta, s0, s);
double y =
pp0.y() + common::math::IntegrateByGaussLegendre(func_sin_theta, s0, s);
double theta = geometry_spline.evaluate(0, s);
double kappa = geometry_spline.evaluate(1, s);
double dkappa = geometry_spline.evaluate(2, s);
double d2kappa = geometry_spline.evaluate(3, s);
TrajectoryPoint tp;
tp.set_v(v);
tp.set_a(a);
PathPoint *path_point = tp.mutable_path_point();
path_point->set_x(x);
path_point->set_y(y);
path_point->set_theta(theta);
path_point->set_kappa(kappa);
path_point->set_dkappa(dkappa);
path_point->set_ddkappa(d2kappa);
path_point->set_s(s);
// check the diff of computed s1 and p1.s()?
return tp;
}
TrajectoryPoint interpolate_linear_approximation(const TrajectoryPoint &tp0,
const TrajectoryPoint &tp1,
const double t) {
const PathPoint &pp0 = tp0.path_point();
const PathPoint &pp1 = tp1.path_point();
double t0 = tp0.relative_time();
double t1 = tp1.relative_time();
TrajectoryPoint tp;
tp.set_v(common::math::lerp(tp0.v(), t0, tp1.v(), t1, t));
tp.set_a(common::math::lerp(tp0.a(), t0, tp1.a(), t1, t));
tp.set_relative_time(t);
PathPoint *path_point = tp.mutable_path_point();
path_point->set_x(common::math::lerp(pp0.x(), t0, pp1.x(), t1, t));
path_point->set_y(common::math::lerp(pp0.y(), t0, pp1.y(), t1, t));
path_point->set_theta(
common::math::lerp(pp0.theta(), t0, pp1.theta(), t1, t));
path_point->set_kappa(
common::math::lerp(pp0.kappa(), t0, pp1.kappa(), t1, t));
path_point->set_dkappa(
common::math::lerp(pp0.dkappa(), t0, pp1.dkappa(), t1, t));
path_point->set_ddkappa(
common::math::lerp(pp0.ddkappa(), t0, pp1.ddkappa(), t1, t));
path_point->set_s(common::math::lerp(pp0.s(), t0, pp1.s(), t1, t));
return tp;
}
common::SLPoint interpolate(const common::SLPoint &start,
const common::SLPoint &end, const double weight) {
common::SLPoint point;
double s = start.s() * (1 - weight) + end.s() * weight;
double l = start.l() * (1 - weight) + end.l() * weight;
point.set_s(s);
point.set_l(l);
return point;
}
} // namespace util
} // namespace planning
} // namespace apollo
<|endoftext|>
|
<commit_before>#include <Game/cPlayerManager.h>
#include <Utility/cInput.h>
#include <CameraManager/cCameraManager.h>
#include <Game/cStrategyManager.h>
#include <Game/Strategy/cDrill.h>
#include <Game/cFieldManager.h>
#include <Game/cClientAdapter.h>
void Game::cPlayerManager::playerInstance(std::vector<ci::vec3> positions, const int& player_number, const int& active_player_id, std::vector<int> teams)
{
//
for (int i = 0; i < player_number; i++) {
//ʐMő
if (i == active_player_id) {
players.push_back(std::make_shared<Player::cPlayer>(positions[i], i, true, 0, 0, static_cast<Game::Player::Team>(teams[i])));
//ANeBu[Uɑ
active_player = players[i];
this->active_player_id = active_player_id;
this->active_player_team_id = teams[i];
}
else {
players.push_back(std::make_shared<Player::cPlayer>(positions[i], i, false, 0, 0, static_cast<Game::Player::Team>(teams[i])));
}
}
}
void Game::cPlayerManager::playerDrillMove(const float & delta_time)
{
//CAMERA->shakeCamera(0.1f, 0.1f);
//J̕Ɉړ
active_player->move(CAMERA->getCameraLook() * active_player->getDrillSpeed());
}
void Game::cPlayerManager::playerAttack(const float & delta_time)
{
if (active_player->isDead())return;
if (ENV->pushKey(ci::app::MouseEvent::RIGHT_DOWN))
{
cClientAdapter::getInstance()->sendPlayerAttack(active_player_id, 1);
}
if (ENV->pullKey(ci::app::MouseEvent::RIGHT_DOWN))
{
cClientAdapter::getInstance()->sendPlayerAttack(active_player_id, 2);
}
}
ci::vec3 Game::cPlayerManager::playerNormalMoveKey(const float& delta_time)
{
//vC[̑x
float player_speed = active_player->getSpeed() * delta_time;
ci::vec3 keybord_velocity = ci::vec3(0);
float x_axis = 0;
float z_axis = 0;
//ߗpX^bN
int diagonal = 0;
//Zbg
if (ENV->pressKey(ci::app::KeyEvent::KEY_r)) {
active_player->resetPos();
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_w)) {
z_axis = active_player->getSpeed();
diagonal++;
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_s)) {
z_axis = -active_player->getSpeed();
diagonal++;
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_d)) {
x_axis = -active_player->getSpeed();
diagonal++;
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_a)) {
x_axis = active_player->getSpeed();
diagonal++;
}
keybord_velocity += ci::vec3(z_axis*sin(CAMERA->getCameraAngle().x), 0.0f, z_axis*cos(CAMERA->getCameraAngle().x));
keybord_velocity += ci::vec3(x_axis*cos(CAMERA->getCameraAngle().x), 0.0f, -x_axis*sin(CAMERA->getCameraAngle().x));
if (diagonal >= 2) {
std::sqrtf(keybord_velocity.x);
std::sqrtf(keybord_velocity.z);
}
//WvMověɌĂ
if (ENV->pushKey(ci::app::KeyEvent::KEY_SPACE)) {
active_player->jump(true);
}
return keybord_velocity;
}
ci::vec3 Game::cPlayerManager::playerNormalMovePad(const float & delta_time)
{
ci::vec3 pad_velocity = ci::vec3(0);
float x_axis = -10 * ENV->getPadAxis(0) * delta_time * active_player->getSpeed();
float z_axis = -10 * ENV->getPadAxis(1) * delta_time * active_player->getSpeed();
pad_velocity += ci::vec3(z_axis*sin(CAMERA->getCameraAngle().x), 0.0f, z_axis*cos(CAMERA->getCameraAngle().x));
pad_velocity += ci::vec3(x_axis*cos(CAMERA->getCameraAngle().x), 0.0f, -x_axis*sin(CAMERA->getCameraAngle().x));
return pad_velocity;
}
void Game::cPlayerManager::playerMove(const float & delta_time)
{
//J̃}EXON@OFF
if (ENV->pushKey(ci::app::KeyEvent::KEY_ESCAPE)) {
ENV->setMouseControl(mouse_on);
if (mouse_on == true) {
mouse_on = false;
}
else {
mouse_on = true;
}
}
CAMERA->addCameraAngle(ci::vec2(ENV->getPadAxis(2)*(-0.05f), ENV->getPadAxis(3)*(-0.05f)));
//vC[łJȊOs\
if (active_player->isDead())return;
keyMove(delta_time);
//pbh̎ɍU㏑Ȃ悤ɒ
//padMove(delta_time);
//@풆͓ς
if (active_player->isDrilling()) {
playerDrillMove(delta_time);
}
else {
ci::vec3 buf_axis = ci::vec3(0);
buf_axis += playerNormalMoveKey(delta_time);
buf_axis += playerNormalMovePad(delta_time);
active_player->move(buf_axis);
}
}
void Game::cPlayerManager::padMove(const float & delta_time)
{
//@ L1
if (ENV->isPadPress(ENV->BUTTON_5) &&
Game::Field::WORLD_SIZE.y + 1 > active_player->getPos().y) {
active_player->Drilling(true);
}
//CU R2
active_player->getMainWeapon()->pushCall(ENV->isPadPush(ENV->BUTTON_8));
active_player->getMainWeapon()->pullCall(ENV->isPadPull(ENV->BUTTON_8));
//Tu R1
if (ENV->isPadPush(ENV->BUTTON_7)) {
active_player->useSubWeapon.useWeapon(active_player_id);
}
//Wv X
if (ENV->isPadPush(ENV->BUTTON_1)) {
active_player->jump(true);
}
//_bV
if (ENV->isPadPull(ENV->BUTTON_3)) {
active_player->setDefaultSpeed();
}
if (ENV->isPadPress(ENV->BUTTON_3)) {
active_player->setSpeed(10.0f);
}
//CɃWF@Z
auto cannon = cStrategyManager::getInstance()->getCannons()[static_cast<Player::Team>(active_player->getWhichTeam())];
if (cannon->getAABB().intersects(active_player->getAABB())) {
cannon->receivePlayerGem(active_player->getgems.size(), active_player_id);
active_player->getgems.clear();
}
}
void Game::cPlayerManager::keyMove(const float & delta_time)
{
//@풆true
if (ENV->pressKey(ci::app::MouseEvent::LEFT_DOWN) &&
Game::Field::WORLD_SIZE.y + 1 > active_player->getPos().y) {
active_player->Drilling(true);
}
else {
active_player->Drilling(false);
}
if (ENV->pullKey(ci::app::MouseEvent::LEFT_DOWN)) {
active_player->Drilling(false);
}
//_bV
//304 = Vtg
if (ENV->pullKey(304)) {
active_player->setDefaultSpeed();
}
if (ENV->pushKey(304)) {
active_player->setSpeed(10.0f);
}
//G-BACK
if (ENV->pressKey(ci::app::KeyEvent::KEY_l)) {
active_player->receiveDamage(10.0f, 5);
}
//CɃWF
if (ENV->pressKey(ci::app::KeyEvent::KEY_f)) {
auto cannon = cStrategyManager::getInstance()->getCannons()[static_cast<Player::Team>(active_player->getWhichTeam())];
if (cannon->getAABB().intersects(active_player->getAABB())) {
cannon->receivePlayerGem(active_player->getgems.size(), active_player_id);
active_player->getgems.clear();
}
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_UP)) {
CAMERA->addCameraAngle(ci::vec2(0, 0.05f));
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_DOWN))
CAMERA->addCameraAngle(ci::vec2(0, -0.05f));
if (ENV->pressKey(ci::app::KeyEvent::KEY_RIGHT))
CAMERA->addCameraAngle(ci::vec2(-0.05f, 0));
if (ENV->pressKey(ci::app::KeyEvent::KEY_LEFT))
CAMERA->addCameraAngle(ci::vec2(0.05f, 0));
///////////////////fobNŃCg{𑝂₷
if (ENV->pushKey(ci::app::KeyEvent::KEY_h)) {
active_player->useSubWeapon.addSubWeapon(Game::Weapons::SubWeapon::LIGHT_BOMB);
}
/////////////////ACeg
if (ENV->pushKey(ci::app::KeyEvent::KEY_g)) {
active_player->useSubWeapon.useWeapon(active_player_id);
}
///////////////////
}
void Game::cPlayerManager::killCamera(const float & delta_time)
{
if (!active_player->isDead())return;
if (active_player->getRespawnCount() > 1.5f) {
for (auto& it : players) {
if (active_player->getDamagedId() == it->getPlayerId()) {
CAMERA->refPosition = it->getPos() + ci::vec3(0, 0, 0);
}
}
}
}
void Game::cPlayerManager::setPlayersPosition(std::vector<ci::vec3> positions)
{
for (int i = 0; i < players.size(); i++) {
ci::vec3 vec = positions[i] - players[i]->getPos();
players[i]->move(vec);
}
}
//vC[̃RWXs[h̓RW}l[W
//ɌĂ
void Game::cPlayerManager::playerCollisionAfterUpdate(const float& delta_time)
{
playerAttack(delta_time);
for (auto& it : players) {
it->setColliderSpeed();
it->gemsUpdate(delta_time);
it->weaponUpdae(delta_time);
}
if (!active_player->isDead()) {
CAMERA->refPosition = active_player->getPos() + ci::vec3(0, 0, 0);
}
}
void Game::cPlayerManager::setup(std::vector<ci::vec3> positions, const int& player_number, const int& active_player_id, std::vector<int> teams)
{
playerInstance(positions, player_number, active_player_id, teams);
//|WV̎QƂƃJ̃Y[ݒ
for (auto& it : players) {
it->setup();
}
}
void Game::cPlayerManager::update(const float& delta_time)
{
playerMove(delta_time);
for (auto& it : players) {
it->update(delta_time);
}
killCamera(delta_time);
cClientAdapter::getInstance()->sendPlayer(active_player->getPos(), ci::vec2(active_player->getRotateX(), active_player->getRotateY()));
}
void Game::cPlayerManager::draw()
{
for (auto& it : players) {
it->draw();
}
}
<commit_msg>大砲を近くに行くだけで取れるようにした<commit_after>#include <Game/cPlayerManager.h>
#include <Utility/cInput.h>
#include <CameraManager/cCameraManager.h>
#include <Game/cStrategyManager.h>
#include <Game/Strategy/cDrill.h>
#include <Game/cFieldManager.h>
#include <Game/cClientAdapter.h>
void Game::cPlayerManager::playerInstance(std::vector<ci::vec3> positions, const int& player_number, const int& active_player_id, std::vector<int> teams)
{
//
for (int i = 0; i < player_number; i++) {
//ʐMő
if (i == active_player_id) {
players.push_back(std::make_shared<Player::cPlayer>(positions[i], i, true, 0, 0, static_cast<Game::Player::Team>(teams[i])));
//ANeBu[Uɑ
active_player = players[i];
this->active_player_id = active_player_id;
this->active_player_team_id = teams[i];
}
else {
players.push_back(std::make_shared<Player::cPlayer>(positions[i], i, false, 0, 0, static_cast<Game::Player::Team>(teams[i])));
}
}
}
void Game::cPlayerManager::playerDrillMove(const float & delta_time)
{
//CAMERA->shakeCamera(0.1f, 0.1f);
//J̕Ɉړ
active_player->move(CAMERA->getCameraLook() * active_player->getDrillSpeed());
}
void Game::cPlayerManager::playerAttack(const float & delta_time)
{
if (active_player->isDead())return;
if (ENV->pushKey(ci::app::MouseEvent::RIGHT_DOWN))
{
cClientAdapter::getInstance()->sendPlayerAttack(active_player_id, 1);
}
if (ENV->pullKey(ci::app::MouseEvent::RIGHT_DOWN))
{
cClientAdapter::getInstance()->sendPlayerAttack(active_player_id, 2);
}
}
ci::vec3 Game::cPlayerManager::playerNormalMoveKey(const float& delta_time)
{
//vC[̑x
float player_speed = active_player->getSpeed() * delta_time;
ci::vec3 keybord_velocity = ci::vec3(0);
float x_axis = 0;
float z_axis = 0;
//ߗpX^bN
int diagonal = 0;
//Zbg
if (ENV->pressKey(ci::app::KeyEvent::KEY_r)) {
active_player->resetPos();
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_w)) {
z_axis = active_player->getSpeed();
diagonal++;
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_s)) {
z_axis = -active_player->getSpeed();
diagonal++;
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_d)) {
x_axis = -active_player->getSpeed();
diagonal++;
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_a)) {
x_axis = active_player->getSpeed();
diagonal++;
}
keybord_velocity += ci::vec3(z_axis*sin(CAMERA->getCameraAngle().x), 0.0f, z_axis*cos(CAMERA->getCameraAngle().x));
keybord_velocity += ci::vec3(x_axis*cos(CAMERA->getCameraAngle().x), 0.0f, -x_axis*sin(CAMERA->getCameraAngle().x));
if (diagonal >= 2) {
std::sqrtf(keybord_velocity.x);
std::sqrtf(keybord_velocity.z);
}
//WvMověɌĂ
if (ENV->pushKey(ci::app::KeyEvent::KEY_SPACE)) {
active_player->jump(true);
}
return keybord_velocity;
}
ci::vec3 Game::cPlayerManager::playerNormalMovePad(const float & delta_time)
{
ci::vec3 pad_velocity = ci::vec3(0);
float x_axis = -10 * ENV->getPadAxis(0) * delta_time * active_player->getSpeed();
float z_axis = -10 * ENV->getPadAxis(1) * delta_time * active_player->getSpeed();
pad_velocity += ci::vec3(z_axis*sin(CAMERA->getCameraAngle().x), 0.0f, z_axis*cos(CAMERA->getCameraAngle().x));
pad_velocity += ci::vec3(x_axis*cos(CAMERA->getCameraAngle().x), 0.0f, -x_axis*sin(CAMERA->getCameraAngle().x));
return pad_velocity;
}
void Game::cPlayerManager::playerMove(const float & delta_time)
{
//J̃}EXON@OFF
if (ENV->pushKey(ci::app::KeyEvent::KEY_ESCAPE)) {
ENV->setMouseControl(mouse_on);
if (mouse_on == true) {
mouse_on = false;
}
else {
mouse_on = true;
}
}
CAMERA->addCameraAngle(ci::vec2(ENV->getPadAxis(2)*(-0.05f), ENV->getPadAxis(3)*(-0.05f)));
//vC[łJȊOs\
if (active_player->isDead())return;
keyMove(delta_time);
//pbh̎ɍU㏑Ȃ悤ɒ
//padMove(delta_time);
//@풆͓ς
if (active_player->isDrilling()) {
playerDrillMove(delta_time);
}
else {
ci::vec3 buf_axis = ci::vec3(0);
buf_axis += playerNormalMoveKey(delta_time);
buf_axis += playerNormalMovePad(delta_time);
active_player->move(buf_axis);
}
}
void Game::cPlayerManager::padMove(const float & delta_time)
{
//@ L1
if (ENV->isPadPress(ENV->BUTTON_5) &&
Game::Field::WORLD_SIZE.y + 1 > active_player->getPos().y) {
active_player->Drilling(true);
}
//CU R2
active_player->getMainWeapon()->pushCall(ENV->isPadPush(ENV->BUTTON_8));
active_player->getMainWeapon()->pullCall(ENV->isPadPull(ENV->BUTTON_8));
//Tu R1
if (ENV->isPadPush(ENV->BUTTON_7)) {
active_player->useSubWeapon.useWeapon(active_player_id);
}
//Wv X
if (ENV->isPadPush(ENV->BUTTON_1)) {
active_player->jump(true);
}
//_bV
if (ENV->isPadPull(ENV->BUTTON_3)) {
active_player->setDefaultSpeed();
}
if (ENV->isPadPress(ENV->BUTTON_3)) {
active_player->setSpeed(10.0f);
}
//CɃWF@Z
auto cannon = cStrategyManager::getInstance()->getCannons()[static_cast<Player::Team>(active_player->getWhichTeam())];
if (cannon->getAABB().intersects(active_player->getAABB())) {
cannon->receivePlayerGem(active_player->getgems.size(), active_player_id);
active_player->getgems.clear();
}
}
void Game::cPlayerManager::keyMove(const float & delta_time)
{
//@풆true
if (ENV->pressKey(ci::app::MouseEvent::LEFT_DOWN) &&
Game::Field::WORLD_SIZE.y + 1 > active_player->getPos().y) {
active_player->Drilling(true);
}
else {
active_player->Drilling(false);
}
if (ENV->pullKey(ci::app::MouseEvent::LEFT_DOWN)) {
active_player->Drilling(false);
}
//_bV
//304 = Vtg
if (ENV->pullKey(304)) {
active_player->setDefaultSpeed();
}
if (ENV->pushKey(304)) {
active_player->setSpeed(10.0f);
}
//G-BACK
if (ENV->pressKey(ci::app::KeyEvent::KEY_l)) {
active_player->receiveDamage(10.0f, 5);
}
//CɃWF@Z
auto cannon = cStrategyManager::getInstance()->getCannons()[static_cast<Player::Team>(active_player->getWhichTeam())];
if (cannon->getAABB().intersects(active_player->getAABB())) {
cannon->receivePlayerGem(active_player->getgems.size(), active_player_id);
active_player->getgems.clear();
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_UP)) {
CAMERA->addCameraAngle(ci::vec2(0, 0.05f));
}
if (ENV->pressKey(ci::app::KeyEvent::KEY_DOWN))
CAMERA->addCameraAngle(ci::vec2(0, -0.05f));
if (ENV->pressKey(ci::app::KeyEvent::KEY_RIGHT))
CAMERA->addCameraAngle(ci::vec2(-0.05f, 0));
if (ENV->pressKey(ci::app::KeyEvent::KEY_LEFT))
CAMERA->addCameraAngle(ci::vec2(0.05f, 0));
///////////////////fobNŃCg{𑝂₷
if (ENV->pushKey(ci::app::KeyEvent::KEY_h)) {
active_player->useSubWeapon.addSubWeapon(Game::Weapons::SubWeapon::LIGHT_BOMB);
}
/////////////////ACeg
if (ENV->pushKey(ci::app::KeyEvent::KEY_g)) {
active_player->useSubWeapon.useWeapon(active_player_id);
}
///////////////////
}
void Game::cPlayerManager::killCamera(const float & delta_time)
{
if (!active_player->isDead())return;
if (active_player->getRespawnCount() > 1.5f) {
for (auto& it : players) {
if (active_player->getDamagedId() == it->getPlayerId()) {
CAMERA->refPosition = it->getPos() + ci::vec3(0, 0, 0);
}
}
}
}
void Game::cPlayerManager::setPlayersPosition(std::vector<ci::vec3> positions)
{
for (int i = 0; i < players.size(); i++) {
ci::vec3 vec = positions[i] - players[i]->getPos();
players[i]->move(vec);
}
}
//vC[̃RWXs[h̓RW}l[W
//ɌĂ
void Game::cPlayerManager::playerCollisionAfterUpdate(const float& delta_time)
{
playerAttack(delta_time);
for (auto& it : players) {
it->setColliderSpeed();
it->gemsUpdate(delta_time);
it->weaponUpdae(delta_time);
}
if (!active_player->isDead()) {
CAMERA->refPosition = active_player->getPos() + ci::vec3(0, 0, 0);
}
}
void Game::cPlayerManager::setup(std::vector<ci::vec3> positions, const int& player_number, const int& active_player_id, std::vector<int> teams)
{
playerInstance(positions, player_number, active_player_id, teams);
//|WV̎QƂƃJ̃Y[ݒ
for (auto& it : players) {
it->setup();
}
}
void Game::cPlayerManager::update(const float& delta_time)
{
playerMove(delta_time);
for (auto& it : players) {
it->update(delta_time);
}
killCamera(delta_time);
cClientAdapter::getInstance()->sendPlayer(active_player->getPos(), ci::vec2(active_player->getRotateX(), active_player->getRotateY()));
}
void Game::cPlayerManager::draw()
{
for (auto& it : players) {
it->draw();
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2021 Stanford University, NVIDIA Corporation
*
* 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.
*/
// Realm object metadata base implementation
#include "realm/metadata.h"
#include "realm/event_impl.h"
#include "realm/inst_impl.h"
#include "realm/runtime_impl.h"
namespace Realm {
Logger log_metadata("metadata");
////////////////////////////////////////////////////////////////////////
//
// class MetadataBase
//
MetadataBase::MetadataBase(void)
: state(STATE_INVALID), valid_event(Event::NO_EVENT)
{}
MetadataBase::~MetadataBase(void)
{}
void MetadataBase::mark_valid(NodeSet& early_reqs)
{
// take lock so we can make sure we get a precise list of early requestors
// if there was an event (i.e. an impatient local reqiest), trigger it too
Event to_trigger = Event::NO_EVENT;
{
AutoLock<> a(mutex);
early_reqs = remote_copies;
state = STATE_VALID;
to_trigger = valid_event;
valid_event = Event::NO_EVENT;
}
if(to_trigger.exists())
GenEventImpl::trigger(to_trigger, false /*!poisoned*/);
}
bool MetadataBase::handle_request(int requestor)
{
// just add the requestor to the list of remote nodes with copies, can send
// response if the data is already valid
AutoLock<> a(mutex);
assert(!remote_copies.contains(requestor));
remote_copies.add(requestor);
return is_valid();
}
void MetadataBase::handle_response(void)
{
// update the state, and
// if there was an event, we'll trigger it
Event to_trigger = Event::NO_EVENT;
{
AutoLock<> a(mutex);
switch(state) {
case STATE_REQUESTED:
{
to_trigger = valid_event;
valid_event = Event::NO_EVENT;
state = STATE_VALID;
break;
}
default:
assert(0);
}
}
if(to_trigger.exists())
GenEventImpl::trigger(to_trigger, false /*!poisoned*/);
}
Event MetadataBase::request_data(int owner, ID::IDType id)
{
// early out - valid data need not be re-requested
if(state == STATE_VALID)
return Event::NO_EVENT;
Event e = Event::NO_EVENT;
bool issue_request = false;
{
AutoLock<> a(mutex);
switch(state) {
case STATE_VALID:
{
// possible if the data came in between our early out check
// above and our taking of the lock - nothing more to do
break;
}
case STATE_INVALID:
{
// if the current state is invalid, we'll need to issue a request
state = STATE_REQUESTED;
valid_event = GenEventImpl::create_genevent()->current_event();
e = valid_event;
// actually, no need to issue a request if we're the owner
issue_request = (owner != Network::my_node_id);
break;
}
case STATE_REQUESTED:
{
// request has already been issued, but return the event again
assert(valid_event.exists());
e = valid_event;
break;
}
case STATE_INVALIDATE:
assert(0 && "requesting metadata we've been told is invalid!");
case STATE_CLEANUP:
assert(0 && "requesting metadata in CLEANUP state!");
}
}
if(issue_request) {
ActiveMessage<MetadataRequestMessage> amsg(owner);
amsg->id = id;
amsg.commit();
}
return e;
}
bool MetadataBase::initiate_cleanup(ID::IDType id)
{
NodeSet invals_to_send;
{
AutoLock<> a(mutex);
assert(state == STATE_VALID);
// eagerly invalidate local contents
do_invalidate();
if(remote_copies.empty()) {
state = STATE_INVALID;
} else {
state = STATE_CLEANUP;
invals_to_send = remote_copies;
}
}
// send invalidations outside the locked section
if(invals_to_send.empty())
return true;
ActiveMessage<MetadataInvalidateMessage> amsg(invals_to_send);
amsg->id = id;
amsg.commit();
// can't free object until we receive all the acks
return false;
}
void MetadataBase::handle_invalidate(void)
{
AutoLock<> a(mutex);
switch(state) {
case STATE_VALID:
{
// was valid, now invalid (up to app to make sure no races exist)
state = STATE_INVALID;
do_invalidate();
break;
}
case STATE_REQUESTED:
{
// hopefully rare case where invalidation passes response to initial request
state = STATE_INVALIDATE;
break;
}
default:
assert(0);
}
}
bool MetadataBase::handle_inval_ack(int sender)
{
bool last_copy;
{
AutoLock<> a(mutex);
assert(remote_copies.contains(sender));
remote_copies.remove(sender);
last_copy = remote_copies.empty();
}
return last_copy;
}
////////////////////////////////////////////////////////////////////////
//
// class MetadataRequestMessage
//
/*static*/ void MetadataRequestMessage::handle_message(NodeID sender, const MetadataRequestMessage &args,
const void *data, size_t datalen)
{
// switch on different types of objects that can have metadata
ID id(args.id);
if(id.is_instance()) {
RegionInstanceImpl *impl = get_runtime()->get_instance_impl(args.id);
bool valid = impl->metadata.handle_request(sender);
if(valid) {
Serialization::ByteCountSerializer bcs;
impl->metadata.serialize_msg(bcs);
size_t req_size = bcs.bytes_used();
ActiveMessage<MetadataResponseMessage> amsg(sender, req_size);
impl->metadata.serialize_msg(amsg);
amsg->id = args.id;
log_metadata.info("metadata for " IDFMT " requested by %d",
args.id, sender);
amsg.commit();
}
}
else {
assert(0);
}
}
////////////////////////////////////////////////////////////////////////
//
// class MetadataResponseMessage
//
/*static*/ void MetadataResponseMessage::handle_message(NodeID sender,
const MetadataResponseMessage &args,
const void *data, size_t datalen)
{
log_metadata.info("metadata for " IDFMT " received - %zd bytes",
args.id, datalen);
// switch on different types of objects that can have metadata
ID id(args.id);
if(id.is_instance()) {
RegionInstanceImpl *impl = get_runtime()->get_instance_impl(args.id);
impl->metadata.deserialize(data, datalen);
impl->metadata.handle_response();
} else {
assert(0);
}
}
////////////////////////////////////////////////////////////////////////
//
// class MetadataInvalidateMessage
//
/*static*/ void MetadataInvalidateMessage::handle_message(NodeID sender,const MetadataInvalidateMessage &args,
const void *data, size_t datalen)
{
log_metadata.info("received invalidate request for " IDFMT, args.id);
//
// switch on different types of objects that can have metadata
ID id(args.id);
if(id.is_instance()) {
RegionInstanceImpl *impl = get_runtime()->get_instance_impl(args.id);
impl->metadata.handle_invalidate();
} else {
assert(0);
}
// ack the request
ActiveMessage<MetadataInvalidateAckMessage> amsg(sender);
amsg->id = args.id;
amsg.commit();
}
////////////////////////////////////////////////////////////////////////
//
// class MetadataInvalidateAckMessage
//
/*static*/ void MetadataInvalidateAckMessage::handle_message(NodeID sender,
const MetadataInvalidateAckMessage &args,
const void *data, size_t datalen)
{
log_metadata.info("received invalidate ack for " IDFMT, args.id);
// switch on different types of objects that can have metadata
bool last_ack = false;
ID id(args.id);
if(id.is_instance()) {
RegionInstanceImpl *impl = get_runtime()->get_instance_impl(args.id);
last_ack = impl->metadata.handle_inval_ack(sender);
if(last_ack)
impl->recycle_instance();
} else {
assert(0);
}
if(last_ack) {
log_metadata.info("last inval ack received for " IDFMT, args.id);
}
}
ActiveMessageHandlerReg<MetadataRequestMessage> metadata_request_message_handler;
ActiveMessageHandlerReg<MetadataResponseMessage> metadata_response_message_handler;
ActiveMessageHandlerReg<MetadataInvalidateMessage> metadata_invalidate_message_handler;
ActiveMessageHandlerReg<MetadataInvalidateAckMessage> metadata_invalidate_ack_message_handler;
}; // namespace Realm
<commit_msg>realm: add missing metadata state transition<commit_after>/* Copyright 2021 Stanford University, NVIDIA Corporation
*
* 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.
*/
// Realm object metadata base implementation
#include "realm/metadata.h"
#include "realm/event_impl.h"
#include "realm/inst_impl.h"
#include "realm/runtime_impl.h"
namespace Realm {
Logger log_metadata("metadata");
////////////////////////////////////////////////////////////////////////
//
// class MetadataBase
//
MetadataBase::MetadataBase(void)
: state(STATE_INVALID), valid_event(Event::NO_EVENT)
{}
MetadataBase::~MetadataBase(void)
{}
void MetadataBase::mark_valid(NodeSet& early_reqs)
{
// take lock so we can make sure we get a precise list of early requestors
// if there was an event (i.e. an impatient local reqiest), trigger it too
Event to_trigger = Event::NO_EVENT;
{
AutoLock<> a(mutex);
early_reqs = remote_copies;
state = STATE_VALID;
to_trigger = valid_event;
valid_event = Event::NO_EVENT;
}
if(to_trigger.exists())
GenEventImpl::trigger(to_trigger, false /*!poisoned*/);
}
bool MetadataBase::handle_request(int requestor)
{
// just add the requestor to the list of remote nodes with copies, can send
// response if the data is already valid
AutoLock<> a(mutex);
assert(!remote_copies.contains(requestor));
remote_copies.add(requestor);
return is_valid();
}
void MetadataBase::handle_response(void)
{
// update the state, and
// if there was an event, we'll trigger it
Event to_trigger = Event::NO_EVENT;
{
AutoLock<> a(mutex);
switch(state) {
case STATE_REQUESTED:
{
to_trigger = valid_event;
valid_event = Event::NO_EVENT;
state = STATE_VALID;
break;
}
default:
assert(0);
}
}
if(to_trigger.exists())
GenEventImpl::trigger(to_trigger, false /*!poisoned*/);
}
Event MetadataBase::request_data(int owner, ID::IDType id)
{
// early out - valid data need not be re-requested
if(state == STATE_VALID)
return Event::NO_EVENT;
Event e = Event::NO_EVENT;
bool issue_request = false;
{
AutoLock<> a(mutex);
switch(state) {
case STATE_VALID:
{
// possible if the data came in between our early out check
// above and our taking of the lock - nothing more to do
break;
}
case STATE_INVALID:
{
// if the current state is invalid, we'll need to issue a request
state = STATE_REQUESTED;
valid_event = GenEventImpl::create_genevent()->current_event();
e = valid_event;
// actually, no need to issue a request if we're the owner
issue_request = (owner != Network::my_node_id);
break;
}
case STATE_REQUESTED:
{
// request has already been issued, but return the event again
assert(valid_event.exists());
e = valid_event;
break;
}
case STATE_INVALIDATE:
assert(0 && "requesting metadata we've been told is invalid!");
case STATE_CLEANUP:
assert(0 && "requesting metadata in CLEANUP state!");
}
}
if(issue_request) {
ActiveMessage<MetadataRequestMessage> amsg(owner);
amsg->id = id;
amsg.commit();
}
return e;
}
bool MetadataBase::initiate_cleanup(ID::IDType id)
{
NodeSet invals_to_send;
{
AutoLock<> a(mutex);
assert(state == STATE_VALID);
// eagerly invalidate local contents
do_invalidate();
if(remote_copies.empty()) {
state = STATE_INVALID;
} else {
state = STATE_CLEANUP;
invals_to_send = remote_copies;
}
}
// send invalidations outside the locked section
if(invals_to_send.empty())
return true;
ActiveMessage<MetadataInvalidateMessage> amsg(invals_to_send);
amsg->id = id;
amsg.commit();
// can't free object until we receive all the acks
return false;
}
void MetadataBase::handle_invalidate(void)
{
AutoLock<> a(mutex);
switch(state) {
case STATE_VALID:
{
// was valid, now invalid (up to app to make sure no races exist)
state = STATE_INVALID;
do_invalidate();
break;
}
case STATE_REQUESTED:
{
// hopefully rare case where invalidation passes response to initial request
state = STATE_INVALIDATE;
break;
}
default:
assert(0);
}
}
bool MetadataBase::handle_inval_ack(int sender)
{
bool last_copy;
{
AutoLock<> a(mutex);
assert(remote_copies.contains(sender));
remote_copies.remove(sender);
last_copy = remote_copies.empty();
if(last_copy)
state = STATE_INVALID;
}
return last_copy;
}
////////////////////////////////////////////////////////////////////////
//
// class MetadataRequestMessage
//
/*static*/ void MetadataRequestMessage::handle_message(NodeID sender, const MetadataRequestMessage &args,
const void *data, size_t datalen)
{
// switch on different types of objects that can have metadata
ID id(args.id);
if(id.is_instance()) {
RegionInstanceImpl *impl = get_runtime()->get_instance_impl(args.id);
bool valid = impl->metadata.handle_request(sender);
if(valid) {
Serialization::ByteCountSerializer bcs;
impl->metadata.serialize_msg(bcs);
size_t req_size = bcs.bytes_used();
ActiveMessage<MetadataResponseMessage> amsg(sender, req_size);
impl->metadata.serialize_msg(amsg);
amsg->id = args.id;
log_metadata.info("metadata for " IDFMT " requested by %d",
args.id, sender);
amsg.commit();
}
}
else {
assert(0);
}
}
////////////////////////////////////////////////////////////////////////
//
// class MetadataResponseMessage
//
/*static*/ void MetadataResponseMessage::handle_message(NodeID sender,
const MetadataResponseMessage &args,
const void *data, size_t datalen)
{
log_metadata.info("metadata for " IDFMT " received - %zd bytes",
args.id, datalen);
// switch on different types of objects that can have metadata
ID id(args.id);
if(id.is_instance()) {
RegionInstanceImpl *impl = get_runtime()->get_instance_impl(args.id);
impl->metadata.deserialize(data, datalen);
impl->metadata.handle_response();
} else {
assert(0);
}
}
////////////////////////////////////////////////////////////////////////
//
// class MetadataInvalidateMessage
//
/*static*/ void MetadataInvalidateMessage::handle_message(NodeID sender,const MetadataInvalidateMessage &args,
const void *data, size_t datalen)
{
log_metadata.info("received invalidate request for " IDFMT, args.id);
//
// switch on different types of objects that can have metadata
ID id(args.id);
if(id.is_instance()) {
RegionInstanceImpl *impl = get_runtime()->get_instance_impl(args.id);
impl->metadata.handle_invalidate();
} else {
assert(0);
}
// ack the request
ActiveMessage<MetadataInvalidateAckMessage> amsg(sender);
amsg->id = args.id;
amsg.commit();
}
////////////////////////////////////////////////////////////////////////
//
// class MetadataInvalidateAckMessage
//
/*static*/ void MetadataInvalidateAckMessage::handle_message(NodeID sender,
const MetadataInvalidateAckMessage &args,
const void *data, size_t datalen)
{
log_metadata.info("received invalidate ack for " IDFMT, args.id);
// switch on different types of objects that can have metadata
bool last_ack = false;
ID id(args.id);
if(id.is_instance()) {
RegionInstanceImpl *impl = get_runtime()->get_instance_impl(args.id);
last_ack = impl->metadata.handle_inval_ack(sender);
if(last_ack)
impl->recycle_instance();
} else {
assert(0);
}
if(last_ack) {
log_metadata.info("last inval ack received for " IDFMT, args.id);
}
}
ActiveMessageHandlerReg<MetadataRequestMessage> metadata_request_message_handler;
ActiveMessageHandlerReg<MetadataResponseMessage> metadata_response_message_handler;
ActiveMessageHandlerReg<MetadataInvalidateMessage> metadata_invalidate_message_handler;
ActiveMessageHandlerReg<MetadataInvalidateAckMessage> metadata_invalidate_ack_message_handler;
}; // namespace Realm
<|endoftext|>
|
<commit_before>// kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;
// vim:ai ts=4 et
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <assert.h>
#include <map>
#include <Network/Network.hpp>
#include <Network/PacketReceiver.hpp>
#include <Network/Sender.hpp>
#include <RadioTx.hpp>
#include <RadioRx.hpp>
#include <Utils.hpp>
#include "Radio.hpp"
using namespace std;
Team team = UnknownTeam;
bool useOpp;
Packet::RadioTx txPacket;
Packet::RadioTx oppTxPacket;
void usage(const char* prog)
{
fprintf(stderr, "usage: %s [-n i] [-2010] <-y|-b>\n", prog);
fprintf(stderr, "\t-2010: run 2010 robots (does not apply to opponent team)\n");
fprintf(stderr, "\t-y: run as the yellow team\n");
fprintf(stderr, "\t-b: run as the blue team\n");
fprintf(stderr, "\t-n: use base station i (0 is the first base station detected by libusb)\n");
fprintf(stderr, "\t-o: run an opponent team as well (note: radio only handles up to 5 robots)\n");
fprintf(stderr, "\t--debug_tx: print transmitted packets\n");
fprintf(stderr, "\t--debug_rx: print received packets\n");
exit(1);
}
void packetHandler(const Packet::RadioTx* packet)
{
txPacket = *packet;
}
void oppPacketHandler(const Packet::RadioTx* packet)
{
oppTxPacket = *packet;
}
int main(int argc, char* argv[])
{
bool debug_tx = false;
bool debug_rx = false;
bool model_2010 = false;
int n = 0;
for (int i = 0; i < argc; ++i)
{
const char* var = argv[i];
if (strcmp(var, "-2010") == 0)
{
model_2010 = true;
} else if (strcmp(var, "-y") == 0)
{
team = Yellow;
}
else if (strcmp(var, "-b") == 0)
{
team = Blue;
}
else if (strcmp(var, "--debug_tx") == 0)
{
debug_tx = true;
}
else if (strcmp(var, "--debug_rx") == 0)
{
debug_rx = true;
}
else if (strcmp(var, "-n") == 0)
{
if (i == (argc - 1))
{
fprintf(stderr, "-n must be followed by the base station number\n");
usage(argv[0]);
}
}
else if (strcmp(var, "-o") == 0)
{
useOpp = true;
}
}
if (n)
{
fprintf(stderr, "WARNING: Specifying -n will likely result in the wrong base station being used if it is unplugged and reconnected.\n");
}
Radio *radio = 0;
if (team == UnknownTeam)
{
fprintf(stderr, "Error: No team specified\n");
usage(argv[0]);
}
Network::Sender sender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));
//sender for opponent robots
Network::Sender oppSender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));
uint8_t reverse_packet[Reverse_Size + 2];
Network::PacketReceiver receiverSelf;
Network::PacketReceiver receiverOpp;
receiverSelf.addType(Network::Address, Network::addTeamOffset(team, Network::RadioTx), packetHandler);
if (useOpp)
{
receiverOpp.addType(Network::Address, Network::addTeamOffset(opponentTeam(team), Network::RadioTx), oppPacketHandler);
}
uint8_t forward_packet[Forward_Size];
int sequence = 0;
uint64_t lastTime = Utils::timestamp();
while (true)
{
//clear the incoming packet for the first team only
txPacket = Packet::RadioTx();
//block for self
receiverSelf.receive(true);
//don't block on receiving the opponent
receiverOpp.receive(false);
// Make sure we have a radio
bool first = true;
if (!radio)
{
while (!radio)
{
try
{
radio = new Radio(n);
} catch (exception &ex)
{
if (first)
{
fprintf(stderr, "%s\n", ex.what());
fprintf(stderr, "Waiting for the base station to be connected...\n");
first = false;
}
sleep(1);
}
}
// Drop this forward packet because it's probably really old
continue;
}
//FIXME - Switch between teams for reverse channel
int reverse_board_id = txPacket.reverse_board_id;
// Build a forward packet
forward_packet[0] = (sequence << 4) | reverse_board_id;
forward_packet[1] = 0x0f;
forward_packet[2] = 0x00;
int offset = 3;
int kick_id = -1;
int self_bots = 0;
uint8_t kick_strength = 0;
for (int robot_id = 0; robot_id < 5; ++robot_id)
{
const Packet::RadioTx::Robot &robot = txPacket.robots[robot_id];
int board_id = robot.board_id;
int8_t m0, m1, m2, m3;
uint8_t kick, roller;
if (robot.valid)
{
self_bots++;
m1 = -robot.motors[0];
m2 = -robot.motors[1];
m3 = -robot.motors[2];
m0 = -robot.motors[3];
kick = robot.kick;
if (robot.roller > 0)
{
roller = robot.roller * 2;
} else {
roller = 0;
}
} else {
board_id = 15;
m0 = m1 = m2 = m3 = 0;
kick = 0;
roller = 0;
}
if (kick)
{
kick_id = board_id;
kick_strength = kick;
}
if (model_2010)
{
m0 = -m0;
m1 = -m1;
m2 = -m2;
m3 = -m3;
}
forward_packet[offset++] = m0;
forward_packet[offset++] = m1;
forward_packet[offset++] = m2;
forward_packet[offset++] = m3;
forward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);
}
if (useOpp)
{
offset = 3 + self_bots * 5;
for (int robot_id = 0; robot_id < 5 - self_bots; ++robot_id)
{
const Packet::RadioTx::Robot &robot = oppTxPacket.robots[robot_id];
int board_id = robot.board_id;
int8_t m0, m1, m2, m3;
uint8_t kick, roller;
if (robot.valid)
{
m1 = -robot.motors[0];
m2 = -robot.motors[1];
m3 = -robot.motors[2];
m0 = -robot.motors[3];
kick = robot.kick;
if (robot.roller > 0)
{
roller = robot.roller * 2;
} else {
roller = 0;
}
} else {
board_id = 15;
m0 = m1 = m2 = m3 = 0;
kick = 0;
roller = 0;
}
if (kick)
{
kick_id = board_id;
kick_strength = kick;
}
forward_packet[offset++] = m0;
forward_packet[offset++] = m1;
forward_packet[offset++] = m2;
forward_packet[offset++] = m3;
forward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);
}
}
// ID of kicking robot and kick strength
if (kick_id >= 0)
{
forward_packet[1] = kick_id;
forward_packet[2] = kick_strength;
}
if (debug_rx)
{
uint64_t t1 = Utils::timestamp();
uint64_t dt = t1 - lastTime;
lastTime = t1;
printf("%3ld.%03ldms ", dt / 1000, dt % 1000);
for (unsigned int i = 0; i < Forward_Size; ++i)
{
printf("%02x ", forward_packet[i]);
}
}
bool read_ok = false;
uint64_t rx_time = 0;
try
{
// Send the forward packet
radio->write_packet(forward_packet, Forward_Size);
// Read a forward packet if one is available
read_ok = radio->read_packet(reverse_packet, sizeof(reverse_packet), 1);
rx_time = Utils::timestamp();
} catch (exception &ex)
{
fprintf(stderr, "%s\n", ex.what());
delete radio;
radio = 0;
}
sequence = (sequence + 1) & 15;
// Check for a reverse packet
if (read_ok)
{
if (debug_rx)
{
printf(" rev");
for (unsigned int i = 0; i < Reverse_Size; ++i)
{
printf(" %02x", reverse_packet[i]);
}
}
Packet::RadioRx rxPacket;
int board_id = reverse_packet[0] & 0x0f;
rxPacket.timestamp = rx_time;
rxPacket.board_id = board_id;
rxPacket.rssi = (int8_t)reverse_packet[1] / 2.0;
rxPacket.battery = reverse_packet[3] * 3.3 / 256.0 * 5.0;
rxPacket.ball = reverse_packet[5] & (1 << 5);
rxPacket.charged = reverse_packet[4] & 1;
for (int i = 0; i < 5; ++i)
{
rxPacket.motorFault[i] = reverse_packet[5] & (1 << i);
}
for (int i = 0; i < 5; ++i)
{
rxPacket.encoders[i] = reverse_packet[6 + i];
}
sender.send(rxPacket);
}
if (debug_tx || debug_rx)
{
printf("\n");
}
}
return 0;
}
<commit_msg>removed flag for 2010 robots<commit_after>// kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;
// vim:ai ts=4 et
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <assert.h>
#include <map>
#include <Network/Network.hpp>
#include <Network/PacketReceiver.hpp>
#include <Network/Sender.hpp>
#include <RadioTx.hpp>
#include <RadioRx.hpp>
#include <Utils.hpp>
#include "Radio.hpp"
using namespace std;
Team team = UnknownTeam;
bool useOpp;
Packet::RadioTx txPacket;
Packet::RadioTx oppTxPacket;
void usage(const char* prog)
{
fprintf(stderr, "usage: %s [-n i] [-2010] <-y|-b>\n", prog);
fprintf(stderr, "\t-y: run as the yellow team\n");
fprintf(stderr, "\t-b: run as the blue team\n");
fprintf(stderr, "\t-n: use base station i (0 is the first base station detected by libusb)\n");
fprintf(stderr, "\t-o: run an opponent team as well (note: radio only handles up to 5 robots)\n");
fprintf(stderr, "\t--debug_tx: print transmitted packets\n");
fprintf(stderr, "\t--debug_rx: print received packets\n");
exit(1);
}
void packetHandler(const Packet::RadioTx* packet)
{
txPacket = *packet;
}
void oppPacketHandler(const Packet::RadioTx* packet)
{
oppTxPacket = *packet;
}
int main(int argc, char* argv[])
{
bool debug_tx = false;
bool debug_rx = false;
int n = 0;
for (int i = 0; i < argc; ++i)
{
const char* var = argv[i];
if (strcmp(var, "-y") == 0)
{
team = Yellow;
}
else if (strcmp(var, "-b") == 0)
{
team = Blue;
}
else if (strcmp(var, "--debug_tx") == 0)
{
debug_tx = true;
}
else if (strcmp(var, "--debug_rx") == 0)
{
debug_rx = true;
}
else if (strcmp(var, "-n") == 0)
{
if (i == (argc - 1))
{
fprintf(stderr, "-n must be followed by the base station number\n");
usage(argv[0]);
}
}
else if (strcmp(var, "-o") == 0)
{
useOpp = true;
}
}
if (n)
{
fprintf(stderr, "WARNING: Specifying -n will likely result in the wrong base station being used if it is unplugged and reconnected.\n");
}
Radio *radio = 0;
if (team == UnknownTeam)
{
fprintf(stderr, "Error: No team specified\n");
usage(argv[0]);
}
Network::Sender sender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));
//sender for opponent robots
Network::Sender oppSender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));
uint8_t reverse_packet[Reverse_Size + 2];
Network::PacketReceiver receiverSelf;
Network::PacketReceiver receiverOpp;
receiverSelf.addType(Network::Address, Network::addTeamOffset(team, Network::RadioTx), packetHandler);
if (useOpp)
{
receiverOpp.addType(Network::Address, Network::addTeamOffset(opponentTeam(team), Network::RadioTx), oppPacketHandler);
}
uint8_t forward_packet[Forward_Size];
int sequence = 0;
uint64_t lastTime = Utils::timestamp();
while (true)
{
//clear the incoming packet for the first team only
txPacket = Packet::RadioTx();
//block for self
receiverSelf.receive(true);
//don't block on receiving the opponent
receiverOpp.receive(false);
// Make sure we have a radio
bool first = true;
if (!radio)
{
while (!radio)
{
try
{
radio = new Radio(n);
} catch (exception &ex)
{
if (first)
{
fprintf(stderr, "%s\n", ex.what());
fprintf(stderr, "Waiting for the base station to be connected...\n");
first = false;
}
sleep(1);
}
}
// Drop this forward packet because it's probably really old
continue;
}
//FIXME - Switch between teams for reverse channel
int reverse_board_id = txPacket.reverse_board_id;
// Build a forward packet
forward_packet[0] = (sequence << 4) | reverse_board_id;
forward_packet[1] = 0x0f;
forward_packet[2] = 0x00;
int offset = 3;
int kick_id = -1;
int self_bots = 0;
uint8_t kick_strength = 0;
for (int robot_id = 0; robot_id < 5; ++robot_id)
{
const Packet::RadioTx::Robot &robot = txPacket.robots[robot_id];
int board_id = robot.board_id;
int8_t m0, m1, m2, m3;
uint8_t kick, roller;
if (robot.valid)
{
self_bots++;
m1 = -robot.motors[0];
m2 = -robot.motors[1];
m3 = -robot.motors[2];
m0 = -robot.motors[3];
kick = robot.kick;
if (robot.roller > 0)
{
roller = robot.roller * 2;
} else {
roller = 0;
}
} else {
board_id = 15;
m0 = m1 = m2 = m3 = 0;
kick = 0;
roller = 0;
}
if (kick)
{
kick_id = board_id;
kick_strength = kick;
}
forward_packet[offset++] = m0;
forward_packet[offset++] = m1;
forward_packet[offset++] = m2;
forward_packet[offset++] = m3;
forward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);
}
if (useOpp)
{
offset = 3 + self_bots * 5;
for (int robot_id = 0; robot_id < 5 - self_bots; ++robot_id)
{
const Packet::RadioTx::Robot &robot = oppTxPacket.robots[robot_id];
int board_id = robot.board_id;
int8_t m0, m1, m2, m3;
uint8_t kick, roller;
if (robot.valid)
{
m1 = -robot.motors[0];
m2 = -robot.motors[1];
m3 = -robot.motors[2];
m0 = -robot.motors[3];
kick = robot.kick;
if (robot.roller > 0)
{
roller = robot.roller * 2;
} else {
roller = 0;
}
} else {
board_id = 15;
m0 = m1 = m2 = m3 = 0;
kick = 0;
roller = 0;
}
if (kick)
{
kick_id = board_id;
kick_strength = kick;
}
forward_packet[offset++] = m0;
forward_packet[offset++] = m1;
forward_packet[offset++] = m2;
forward_packet[offset++] = m3;
forward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);
}
}
// ID of kicking robot and kick strength
if (kick_id >= 0)
{
forward_packet[1] = kick_id;
forward_packet[2] = kick_strength;
}
if (debug_rx)
{
uint64_t t1 = Utils::timestamp();
uint64_t dt = t1 - lastTime;
lastTime = t1;
printf("%3ld.%03ldms ", dt / 1000, dt % 1000);
for (unsigned int i = 0; i < Forward_Size; ++i)
{
printf("%02x ", forward_packet[i]);
}
}
bool read_ok = false;
uint64_t rx_time = 0;
try
{
// Send the forward packet
radio->write_packet(forward_packet, Forward_Size);
// Read a forward packet if one is available
read_ok = radio->read_packet(reverse_packet, sizeof(reverse_packet), 1);
rx_time = Utils::timestamp();
} catch (exception &ex)
{
fprintf(stderr, "%s\n", ex.what());
delete radio;
radio = 0;
}
sequence = (sequence + 1) & 15;
// Check for a reverse packet
if (read_ok)
{
if (debug_rx)
{
printf(" rev");
for (unsigned int i = 0; i < Reverse_Size; ++i)
{
printf(" %02x", reverse_packet[i]);
}
}
Packet::RadioRx rxPacket;
int board_id = reverse_packet[0] & 0x0f;
rxPacket.timestamp = rx_time;
rxPacket.board_id = board_id;
rxPacket.rssi = (int8_t)reverse_packet[1] / 2.0;
rxPacket.battery = reverse_packet[3] * 3.3 / 256.0 * 5.0;
rxPacket.ball = reverse_packet[5] & (1 << 5);
rxPacket.charged = reverse_packet[4] & 1;
for (int i = 0; i < 5; ++i)
{
rxPacket.motorFault[i] = reverse_packet[5] & (1 << i);
}
for (int i = 0; i < 5; ++i)
{
rxPacket.encoders[i] = reverse_packet[6 + i];
}
sender.send(rxPacket);
}
if (debug_tx || debug_rx)
{
printf("\n");
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "MarcUtil.h"
#include "Compiler.h"
#include <algorithm>
#include <iterator>
#include <memory>
#include <stdexcept>
#include "Subfields.h"
#include "util.h"
namespace MarcUtil {
bool ReadFields(const std::string &raw_fields, const std::vector<DirectoryEntry> &dir_entries,
std::vector<std::string> * const fields, std::string * const err_msg)
{
fields->clear();
fields->reserve(dir_entries.size());
if (raw_fields[raw_fields.size() - 1] != '\x1D') {
*err_msg = "missing trailing record terminator!";
return false;
}
size_t field_start(0);
for (const auto &dir_entry : dir_entries) {
const size_t next_field_start = field_start + dir_entry.getFieldLength();
if (next_field_start >= raw_fields.length()) {
*err_msg = "misaligned field, extending past the record!";
return false;
}
const std::string field(raw_fields.substr(field_start, dir_entry.getFieldLength()));
if (field[field.length() - 1] != '\x1E') {
*err_msg = "missing field terminator at end of field!";
return false;
}
fields->push_back(field.substr(0, field.length() - 1));
field_start = next_field_start;
}
if (field_start + 1 != raw_fields.length()) {
*err_msg = "field extents do not exhaust record!";
return false;
}
return true;
}
namespace {
class MatchTag {
const std::string tag_to_match_;
public:
explicit MatchTag(const std::string &tag_to_match): tag_to_match_(tag_to_match) { }
bool operator()(const DirectoryEntry &dir_entry) const { return dir_entry.getTag() == tag_to_match_; }
};
} // unnamed namespace
ssize_t GetFieldIndex(const std::vector<DirectoryEntry> &dir_entries, const std::string &field_tag)
{
const auto iter(std::find_if(dir_entries.begin(), dir_entries.end(), MatchTag(field_tag)));
return (iter == dir_entries.end()) ? -1 : std::distance(dir_entries.begin(), iter);
}
// Returns false on error and EOF. To distinguish between the two: on EOF "err_msg" is empty but not when an
// error has been detected. For each entry in "dir_entries" there will be a corresponding entry in "field_data".
bool ReadNextRecord(FILE * const input, Leader ** const leader, std::vector<DirectoryEntry> * const dir_entries,
std::vector<std::string> * const field_data, std::string * const err_msg)
{
dir_entries->clear();
field_data->clear();
err_msg->clear();
//
// Read leader.
//
char leader_buf[Leader::LEADER_LENGTH];
ssize_t read_count;
if ((read_count = std::fread(leader_buf, sizeof leader_buf, 1, input)) != 1)
return false;
if (not Leader::ParseLeader(std::string(leader_buf, Leader::LEADER_LENGTH), leader, err_msg)) {
delete *leader;
return false;
}
//
// Parse directory entries.
//
const ssize_t directory_length((*leader)->getBaseAddressOfData() - Leader::LEADER_LENGTH);
char directory_buf[directory_length];
if ((read_count = std::fread(directory_buf, 1, directory_length, input)) != directory_length) {
*err_msg = "Short read for a directory or premature EOF!";
return false;
}
if (not DirectoryEntry::ParseDirEntries(std::string(directory_buf, directory_length), dir_entries, err_msg))
return false;
//
// Parse variable fields.
//
const size_t field_data_size((*leader)->getRecordLength() - Leader::LEADER_LENGTH - directory_length);
char raw_field_data[field_data_size];
if ((read_count = std::fread(raw_field_data, 1, field_data_size, input))
!= static_cast<ssize_t>(field_data_size))
{
*err_msg = "Short read for field data or premature EOF! (Expected "
+ std::to_string(field_data_size) + " bytes, got "+ std::to_string(read_count) +" bytes.)";
return false;
}
if (not ReadFields(std::string(raw_field_data, field_data_size), *dir_entries, field_data, err_msg))
return false;
return true;
}
void InsertField(const std::string &new_contents, const std::string &new_tag, Leader * const leader,
std::vector<DirectoryEntry> * const dir_entries, std::vector<std::string> * const fields)
{
leader->setRecordLength(leader->getRecordLength() + new_contents.length()
+ DirectoryEntry::DIRECTORY_ENTRY_LENGTH + 1 /* For new field separator. */);
leader->setBaseAddressOfData(leader->getBaseAddressOfData() + DirectoryEntry::DIRECTORY_ENTRY_LENGTH);
// Find the insertion location:
auto dir_entry(dir_entries->begin());
while (dir_entry != dir_entries->end() and new_tag > dir_entry->getTag())
++dir_entry;
// Correct the offsets for old fields and then insert the new fields:
const std::vector<DirectoryEntry>::difference_type new_index(dir_entry - dir_entries->begin());
for (dir_entry = dir_entries->begin() + new_index; dir_entry != dir_entries->end(); ++dir_entry)
dir_entry->setFieldOffset(dir_entry->getFieldOffset() + new_contents.length() + 1);
dir_entries->emplace(dir_entry, new_tag, new_contents.length() + 1, (dir_entry - 1)->getFieldOffset());
const auto field(fields->begin() + new_index);
fields->emplace(field, new_contents);
}
// Creates a binary, a.k.a. "raw" representation of a MARC21 record.
std::string ComposeRecord(const std::vector<DirectoryEntry> &dir_entries, const std::vector<std::string> &fields,
Leader * const leader)
{
size_t record_size(Leader::LEADER_LENGTH);
const size_t directory_size(dir_entries.size() * DirectoryEntry::DIRECTORY_ENTRY_LENGTH);
record_size += directory_size;
++record_size; // field terminator
for (const auto &dir_entry : dir_entries)
record_size += dir_entry.getFieldLength();
++record_size; // record terminator
leader->setRecordLength(record_size);
leader->setBaseAddressOfData(Leader::LEADER_LENGTH + directory_size + 1);
std::string record;
record.reserve(record_size);
record += leader->toString();
for (const auto &dir_entry : dir_entries)
record += dir_entry.toString();
record += '\x1E';
for (const auto &field : fields) {
record += field;
record += '\x1E';
}
record += '\x1D';
return record;
}
// Performs a few sanity checks.
bool RecordSeemsCorrect(const std::string &record, std::string * const err_msg) {
if (record.size() < Leader::LEADER_LENGTH) {
*err_msg = "record too small to contain leader!";
return false;
}
Leader *raw_leader;
if (not Leader::ParseLeader(record.substr(0, Leader::LEADER_LENGTH), &raw_leader, err_msg))
return false;
const std::unique_ptr<Leader> leader(raw_leader);
if (leader->getRecordLength() != record.length()) {
*err_msg = "leader's record length (" + std::to_string(leader->getRecordLength())
+ ") does not equal actual record length (" + std::to_string(record.length()) + ")!";
return false;
}
if (record.length() > 99999) {
*err_msg = "record length (" + std::to_string(record.length())
+ ") exceeds maxium legal record length (99999)!";
return false;
}
if (leader->getBaseAddressOfData() <= Leader::LEADER_LENGTH) {
*err_msg = "impossible base address of data!";
return false;
}
const size_t directory_length(leader->getBaseAddressOfData() - Leader::LEADER_LENGTH - 1);
if ((directory_length % DirectoryEntry::DIRECTORY_ENTRY_LENGTH) != 0) {
*err_msg = "directory length is not a multiple of "
+ std::to_string(DirectoryEntry::DIRECTORY_ENTRY_LENGTH) + "!";
return false;
}
if (record[leader->getBaseAddressOfData() - 1] != '\x1E') {
*err_msg = "directory is not terminated with a field terminator!";
return false;
}
if (record[record.size() - 1] != '\x1D') {
*err_msg = "record is not terminated with a record terminator!";
return false;
}
return true;
}
void ComposeAndWriteRecord(FILE * const output, const std::vector<DirectoryEntry> &dir_entries,
const std::vector<std::string> &field_data, Leader * const leader)
{
std::string err_msg;
const std::string record(MarcUtil::ComposeRecord(dir_entries, field_data, leader));
if (not MarcUtil::RecordSeemsCorrect(record, &err_msg))
Error("Bad record! (" + err_msg + ")");
const size_t write_count = std::fwrite(record.data(), 1, record.size(), output);
if (write_count != record.size())
Error("Failed to write " + std::to_string(record.size()) + " bytes to MARC output!");
}
void UpdateField(const size_t field_index, const std::string &new_field_contents, Leader * const leader,
std::vector<DirectoryEntry> * const dir_entries, std::vector<std::string> * const field_data)
{
if (unlikely(field_index >= dir_entries->size()))
throw std::runtime_error("in MarcUtil::UpdateField: \"field_index\" (" + std::to_string(field_index)
+ ") out of range!");
leader->setRecordLength(leader->getRecordLength() + new_field_contents.length()
- (*field_data)[field_index].length());
(*dir_entries)[field_index].setFieldLength(new_field_contents.length() + 1 /* field terminator */);
(*field_data)[field_index] = new_field_contents;
}
std::string GetLanguage(const std::vector<DirectoryEntry> &dir_entries, const std::vector<std::string> &fields,
const std::string &default_language_code)
{
const ssize_t index(GetFieldIndex(dir_entries, "041"));
if (index == -1)
return default_language_code;
const Subfields subfields(fields[index]);
if (not subfields.hasSubfield('a'))
return default_language_code;
return subfields.getIterators('a').first->second;
}
} // namespace MarcUtil
<commit_msg>Fixed a bug in InsertRecord().<commit_after>#include "MarcUtil.h"
#include "Compiler.h"
#include <algorithm>
#include <iterator>
#include <memory>
#include <stdexcept>
#include "Subfields.h"
#include "util.h"
namespace MarcUtil {
bool ReadFields(const std::string &raw_fields, const std::vector<DirectoryEntry> &dir_entries,
std::vector<std::string> * const fields, std::string * const err_msg)
{
fields->clear();
fields->reserve(dir_entries.size());
if (raw_fields[raw_fields.size() - 1] != '\x1D') {
*err_msg = "missing trailing record terminator!";
return false;
}
size_t field_start(0);
for (const auto &dir_entry : dir_entries) {
const size_t next_field_start = field_start + dir_entry.getFieldLength();
if (next_field_start >= raw_fields.length()) {
*err_msg = "misaligned field, extending past the record!";
return false;
}
const std::string field(raw_fields.substr(field_start, dir_entry.getFieldLength()));
if (field[field.length() - 1] != '\x1E') {
*err_msg = "missing field terminator at end of field!";
return false;
}
fields->push_back(field.substr(0, field.length() - 1));
field_start = next_field_start;
}
if (field_start + 1 != raw_fields.length()) {
*err_msg = "field extents do not exhaust record!";
return false;
}
return true;
}
namespace {
class MatchTag {
const std::string tag_to_match_;
public:
explicit MatchTag(const std::string &tag_to_match): tag_to_match_(tag_to_match) { }
bool operator()(const DirectoryEntry &dir_entry) const { return dir_entry.getTag() == tag_to_match_; }
};
} // unnamed namespace
ssize_t GetFieldIndex(const std::vector<DirectoryEntry> &dir_entries, const std::string &field_tag)
{
const auto iter(std::find_if(dir_entries.begin(), dir_entries.end(), MatchTag(field_tag)));
return (iter == dir_entries.end()) ? -1 : std::distance(dir_entries.begin(), iter);
}
// Returns false on error and EOF. To distinguish between the two: on EOF "err_msg" is empty but not when an
// error has been detected. For each entry in "dir_entries" there will be a corresponding entry in "field_data".
bool ReadNextRecord(FILE * const input, Leader ** const leader, std::vector<DirectoryEntry> * const dir_entries,
std::vector<std::string> * const field_data, std::string * const err_msg)
{
dir_entries->clear();
field_data->clear();
err_msg->clear();
//
// Read leader.
//
char leader_buf[Leader::LEADER_LENGTH];
ssize_t read_count;
if ((read_count = std::fread(leader_buf, sizeof leader_buf, 1, input)) != 1)
return false;
if (not Leader::ParseLeader(std::string(leader_buf, Leader::LEADER_LENGTH), leader, err_msg)) {
delete *leader;
return false;
}
//
// Parse directory entries.
//
const ssize_t directory_length((*leader)->getBaseAddressOfData() - Leader::LEADER_LENGTH);
char directory_buf[directory_length];
if ((read_count = std::fread(directory_buf, 1, directory_length, input)) != directory_length) {
*err_msg = "Short read for a directory or premature EOF!";
return false;
}
if (not DirectoryEntry::ParseDirEntries(std::string(directory_buf, directory_length), dir_entries, err_msg))
return false;
//
// Parse variable fields.
//
const size_t field_data_size((*leader)->getRecordLength() - Leader::LEADER_LENGTH - directory_length);
char raw_field_data[field_data_size];
if ((read_count = std::fread(raw_field_data, 1, field_data_size, input))
!= static_cast<ssize_t>(field_data_size))
{
*err_msg = "Short read for field data or premature EOF! (Expected "
+ std::to_string(field_data_size) + " bytes, got "+ std::to_string(read_count) +" bytes.)";
return false;
}
if (not ReadFields(std::string(raw_field_data, field_data_size), *dir_entries, field_data, err_msg))
return false;
return true;
}
void InsertField(const std::string &new_contents, const std::string &new_tag, Leader * const leader,
std::vector<DirectoryEntry> * const dir_entries, std::vector<std::string> * const fields)
{
leader->setRecordLength(leader->getRecordLength() + new_contents.length()
+ DirectoryEntry::DIRECTORY_ENTRY_LENGTH + 1 /* For new field separator. */);
leader->setBaseAddressOfData(leader->getBaseAddressOfData() + DirectoryEntry::DIRECTORY_ENTRY_LENGTH);
// Find the insertion location:
auto dir_entry(dir_entries->begin());
while (dir_entry != dir_entries->end() and new_tag > dir_entry->getTag())
++dir_entry;
const auto insertion_location(dir_entry);
// Correct the offsets for old fields and then insert the new fields:
const std::vector<DirectoryEntry>::difference_type new_index(dir_entry - dir_entries->begin());
for (dir_entry = dir_entries->begin() + new_index; dir_entry != dir_entries->end(); ++dir_entry)
dir_entry->setFieldOffset(dir_entry->getFieldOffset() + new_contents.length() + 1);
dir_entries->emplace(insertion_location, new_tag, new_contents.length() + 1,
(insertion_location - 1)->getFieldOffset());
const auto field(fields->begin() + new_index);
fields->emplace(field, new_contents);
}
// Creates a binary, a.k.a. "raw" representation of a MARC21 record.
std::string ComposeRecord(const std::vector<DirectoryEntry> &dir_entries, const std::vector<std::string> &fields,
Leader * const leader)
{
size_t record_size(Leader::LEADER_LENGTH);
const size_t directory_size(dir_entries.size() * DirectoryEntry::DIRECTORY_ENTRY_LENGTH);
record_size += directory_size;
++record_size; // field terminator
for (const auto &dir_entry : dir_entries)
record_size += dir_entry.getFieldLength();
++record_size; // record terminator
leader->setRecordLength(record_size);
leader->setBaseAddressOfData(Leader::LEADER_LENGTH + directory_size + 1);
std::string record;
record.reserve(record_size);
record += leader->toString();
for (const auto &dir_entry : dir_entries)
record += dir_entry.toString();
record += '\x1E';
for (const auto &field : fields) {
record += field;
record += '\x1E';
}
record += '\x1D';
return record;
}
// Performs a few sanity checks.
bool RecordSeemsCorrect(const std::string &record, std::string * const err_msg) {
if (record.size() < Leader::LEADER_LENGTH) {
*err_msg = "record too small to contain leader!";
return false;
}
Leader *raw_leader;
if (not Leader::ParseLeader(record.substr(0, Leader::LEADER_LENGTH), &raw_leader, err_msg))
return false;
const std::unique_ptr<Leader> leader(raw_leader);
if (leader->getRecordLength() != record.length()) {
*err_msg = "leader's record length (" + std::to_string(leader->getRecordLength())
+ ") does not equal actual record length (" + std::to_string(record.length()) + ")!";
return false;
}
if (record.length() > 99999) {
*err_msg = "record length (" + std::to_string(record.length())
+ ") exceeds maxium legal record length (99999)!";
return false;
}
if (leader->getBaseAddressOfData() <= Leader::LEADER_LENGTH) {
*err_msg = "impossible base address of data!";
return false;
}
const size_t directory_length(leader->getBaseAddressOfData() - Leader::LEADER_LENGTH - 1);
if ((directory_length % DirectoryEntry::DIRECTORY_ENTRY_LENGTH) != 0) {
*err_msg = "directory length is not a multiple of "
+ std::to_string(DirectoryEntry::DIRECTORY_ENTRY_LENGTH) + "!";
return false;
}
if (record[leader->getBaseAddressOfData() - 1] != '\x1E') {
*err_msg = "directory is not terminated with a field terminator!";
return false;
}
if (record[record.size() - 1] != '\x1D') {
*err_msg = "record is not terminated with a record terminator!";
return false;
}
return true;
}
void ComposeAndWriteRecord(FILE * const output, const std::vector<DirectoryEntry> &dir_entries,
const std::vector<std::string> &field_data, Leader * const leader)
{
std::string err_msg;
const std::string record(MarcUtil::ComposeRecord(dir_entries, field_data, leader));
if (not MarcUtil::RecordSeemsCorrect(record, &err_msg))
Error("Bad record! (" + err_msg + ")");
const size_t write_count = std::fwrite(record.data(), 1, record.size(), output);
if (write_count != record.size())
Error("Failed to write " + std::to_string(record.size()) + " bytes to MARC output!");
}
void UpdateField(const size_t field_index, const std::string &new_field_contents, Leader * const leader,
std::vector<DirectoryEntry> * const dir_entries, std::vector<std::string> * const field_data)
{
if (unlikely(field_index >= dir_entries->size()))
throw std::runtime_error("in MarcUtil::UpdateField: \"field_index\" (" + std::to_string(field_index)
+ ") out of range!");
leader->setRecordLength(leader->getRecordLength() + new_field_contents.length()
- (*field_data)[field_index].length());
(*dir_entries)[field_index].setFieldLength(new_field_contents.length() + 1 /* field terminator */);
(*field_data)[field_index] = new_field_contents;
}
std::string GetLanguage(const std::vector<DirectoryEntry> &dir_entries, const std::vector<std::string> &fields,
const std::string &default_language_code)
{
const ssize_t index(GetFieldIndex(dir_entries, "041"));
if (index == -1)
return default_language_code;
const Subfields subfields(fields[index]);
if (not subfields.hasSubfield('a'))
return default_language_code;
return subfields.getIterators('a').first->second;
}
} // namespace MarcUtil
<|endoftext|>
|
<commit_before>/* Copyright 2014 Aaron Boxer
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "OCLTest.h"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "OCLEncoder.cpp"
using namespace cv;
#include "OCLBasic.h"
#include "OCLDeviceManager.h"
#include "OCLDWT.cpp"
#define OCL_SAMPLE_IMAGE_NAME "baboon.png"
OCLTest::OCLTest(void) : encoder(NULL)
{
}
OCLTest::~OCLTest(void)
{
}
// Read and normalize the input image
Mat ReadInputImage(const std::string &fileName, int flag, int alignCols, int alignRows)
{
Size dsize;
Mat img = imread(fileName, flag);
if (! img.empty())
{
// Make sure that the input image size is fit:
// number of rows is multiple of 8
// number of columns is multiple of 64
dsize.height = ((img.rows % alignRows) == 0) ? img.rows : (((img.rows + alignRows - 1) / alignRows) * alignRows);
dsize.width = ((img.cols % alignCols) == 0) ? img.cols : (((img.cols + alignCols - 1) / alignCols) * alignCols);
resize(img, img, dsize);
}
return img;
}
void OCLTest::test()
{
testInit();
// Read the input image
Mat img_src = ReadInputImage(OCL_SAMPLE_IMAGE_NAME, CV_8UC3, 8, 64);
if (img_src.empty())
{
LogError("Cannot read image file: %s\n", OCL_SAMPLE_IMAGE_NAME);
return;
}
Mat img_dst = Mat::zeros(img_src.size(), CV_8UC1);
int imageSize = img_src.cols * img_src.rows;
// imshow("Before:", img_src);
// waitKey();
int* input = new int[imageSize];
for (int i = 0; i < imageSize; ++i) {
input[i] = img_src.data[i]-128;
}
//simulate RGB image
std::vector<int*> components;
components.push_back(input);
//components.push_back(input);
//components.push_back(input);
double t = my_clock();
int numIterations = 15;
for (int j =0; j < numIterations; ++j) {
testRun(components, img_src.cols, img_src.rows);
}
testFinish();
t = my_clock() - t;
fprintf(stdout, "encode time: %d micro seconds \n", (int)((t * 1000000)/numIterations));
int* results = getTestResults();
if (results) {
for (int i = 0; i < imageSize; ++i)
img_dst.data[i] = results[i]+128;
}
encoder->unmapOutput(results);
delete encoder;
delete[] input;
imshow("After:", img_dst);
waitKey();
}
void OCLTest::testInit() {
OCLDeviceManager* deviceManager = new OCLDeviceManager();
deviceManager->init();
encoder = new OCLEncoder<int>(deviceManager->getInfo(), false);
}
void OCLTest::testRun(std::vector<int*> components,int w,int h) {
encoder->encode(components,w,h);
}
void OCLTest::testFinish() {
encoder->finish();
}
int* OCLTest::getTestResults(){
void* ptr;
encoder->mapOutput(&ptr);
return (int*)ptr;
}
<commit_msg>clamp result at boundaries<commit_after>/* Copyright 2014 Aaron Boxer
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "OCLTest.h"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "OCLEncoder.cpp"
using namespace cv;
#include "OCLBasic.h"
#include "OCLDeviceManager.h"
#include "OCLDWT.cpp"
#define OCL_SAMPLE_IMAGE_NAME "baboon.png"
OCLTest::OCLTest(void) : encoder(NULL)
{
}
OCLTest::~OCLTest(void)
{
}
// Read and normalize the input image
Mat ReadInputImage(const std::string &fileName, int flag, int alignCols, int alignRows)
{
Size dsize;
Mat img = imread(fileName, flag);
if (! img.empty())
{
// Make sure that the input image size is fit:
// number of rows is multiple of 8
// number of columns is multiple of 64
dsize.height = ((img.rows % alignRows) == 0) ? img.rows : (((img.rows + alignRows - 1) / alignRows) * alignRows);
dsize.width = ((img.cols % alignCols) == 0) ? img.cols : (((img.cols + alignCols - 1) / alignCols) * alignCols);
resize(img, img, dsize);
}
return img;
}
void OCLTest::test()
{
testInit();
// Read the input image
Mat img_src = ReadInputImage(OCL_SAMPLE_IMAGE_NAME, CV_8UC3, 8, 64);
if (img_src.empty())
{
LogError("Cannot read image file: %s\n", OCL_SAMPLE_IMAGE_NAME);
return;
}
Mat img_dst = Mat::zeros(img_src.size(), CV_8UC1);
int imageSize = img_src.cols * img_src.rows;
// imshow("Before:", img_src);
// waitKey();
int* input = new int[imageSize];
for (int i = 0; i < imageSize; ++i) {
input[i] = img_src.data[i]-128;
}
//simulate RGB image
std::vector<int*> components;
components.push_back(input);
//components.push_back(input);
//components.push_back(input);
double t = my_clock();
int numIterations = 15;
for (int j =0; j < numIterations; ++j) {
testRun(components, img_src.cols, img_src.rows);
}
testFinish();
t = my_clock() - t;
fprintf(stdout, "encode time: %d micro seconds \n", (int)((t * 1000000)/numIterations));
int* results = getTestResults();
if (results) {
for (int i = 0; i < imageSize; ++i){
int temp = results[i]+128;
if (temp < 0)
temp = 0;
if (temp > 255)
temp = 255;
img_dst.data[i] = temp;
}
}
encoder->unmapOutput(results);
delete encoder;
delete[] input;
imshow("After:", img_dst);
waitKey();
}
void OCLTest::testInit() {
OCLDeviceManager* deviceManager = new OCLDeviceManager();
deviceManager->init();
encoder = new OCLEncoder<int>(deviceManager->getInfo(), false);
}
void OCLTest::testRun(std::vector<int*> components,int w,int h) {
encoder->encode(components,w,h);
}
void OCLTest::testFinish() {
encoder->finish();
}
int* OCLTest::getTestResults(){
void* ptr;
encoder->mapOutput(&ptr);
return (int*)ptr;
}
<|endoftext|>
|
<commit_before>/**
@author Tom Bisson, Pascal Weiß
@date 16.07.2015
*/
#include "SwarmGLFacade.h"
#include <time.h>
#include <iostream>
/**
The initial parameters for the swarm.
Some of them can be changed on runtime in
'Globals.json'
*/
/**
Initial value for the number of particles.
Can't be changed on runtime
*/
int NUMBER_OF_PARTICLES = 2500;
/**
Initial value for the number of quadrants
in one dimension. E.g. for
DIMENSION_LENGTH = 41 you get 41 * 41 * 41
quandrants. This is the space in which the
particles are allowed to move. Can't be
changed on runtime
*/
int DIMENSION_LENGTH = 41;
/**
The length of the particles. Can be changed
on runtime.
*/
float PARTICLE_LENGTH = 0.3f;
/**
Gives some debugging information on runtime.
Can be changed on runtime.
*/
bool DEBUG_FLAG = false;
/**
When too many particles are very close to each
other (in the same quadrant), then they go in
'panic mode', which means, that the direction of
their movement becomes random. The number of
particles, that is required to enable the panic
mode is 'PANIC_THRESHOLD'.
Can be changed on runtime.
*/
int PANIC_THRESHOLD = 10;
/**
The speed of the particle.
Can be changed on runtime.
*/
float VELOCITY = 0.2;
/**
The speed of the particle, when it is in panic
mode. Can be changed on runtime.
*/
float PANIC_VELOCITY = 0.5;
/**
Low value makes the particles attract more to each
other, so they come closer to each other. A big value
makes them spread wider over the space.
Can be changed on runtime.
*/
float OPENNESS = 6;
/**
With a low value, it is very likely, that they panic,
when the THREASHOLD is reached. With a high value,
they might not panic, even though the THREASHOLD is
reached.
Can be changed on runtime.
*/
int PANIC_DAMPING = 200;
int main(void) {
SwarmGLFacade *swarm = new SwarmGLFacade();
delete swarm;
}
<commit_msg>Prettified global default values<commit_after>/**
@author Tom Bisson, Pascal Weiß
@date 16.07.2015
*/
#include "SwarmGLFacade.h"
#include <time.h>
#include <iostream>
/**
The initial parameters for the swarm.
Some of them can be changed on runtime in
'Globals.json'
*/
/**
Initial value for the number of particles.
Can't be changed on runtime
*/
int NUMBER_OF_PARTICLES = 700;
/**
Initial value for the number of quadrants
in one dimension. E.g. for
DIMENSION_LENGTH = 41 you get 41 * 41 * 41
quandrants. This is the space in which the
particles are allowed to move. Can't be
changed on runtime
*/
int DIMENSION_LENGTH = 11;
/**
The length of the particles. Can be changed
on runtime.
*/
float PARTICLE_LENGTH = 0.15f;
/**
Gives some debugging information on runtime.
Can be changed on runtime.
*/
bool DEBUG_FLAG = false;
/**
When too many particles are very close to each
other (in the same quadrant), then they go in
'panic mode', which means, that the direction of
their movement becomes random. The number of
particles, that is required to enable the panic
mode is 'PANIC_THRESHOLD'.
Can be changed on runtime.
*/
int PANIC_THRESHOLD = 14;
/**
The speed of the particle.
Can be changed on runtime.
*/
float VELOCITY = 0.2;
/**
The speed of the particle, when it is in panic
mode. Can be changed on runtime.
*/
float PANIC_VELOCITY = 0.1;
/**
Low value makes the particles attract more to each
other, so they come closer to each other. A big value
makes them spread wider over the space.
Can be changed on runtime.
*/
float OPENNESS = 6;
/**
With a low value, it is very likely, that they panic,
when the THREASHOLD is reached. With a high value,
they might not panic, even though the THREASHOLD is
reached.
Can be changed on runtime.
*/
int PANIC_DAMPING = 200;
int main(void) {
SwarmGLFacade *swarm = new SwarmGLFacade();
delete swarm;
}
<|endoftext|>
|
<commit_before>/*
* main.cpp
* sample codes for algorithm.hpp
*
* written by janus_wel<janus.wel.3@gmail.com>
* This source code is in public domain, and has NO WARRANTY.
* */
#include "../../header/algorithm.hpp"
#include <algorithm>
#include <cstring>
#include <functional>
#include <iostream>
#include <list>
#include <locale>
#include <string>
#include <vector>
// We can't use std::mem_fun_ref() to compose functions for a non-static member
// function in g++ 4.3.3, so it is needed to wrap it.
#ifndef _MSC_VER
inline size_t length(const std::string& str) { return str.size(); }
#endif
template<typename Char>
inline bool is(const std::ctype_base::mask mask, const Char c) {
static const std::ctype<Char>& ctype =
std::use_facet<std::ctype<Char> >(std::locale::classic());
return ctype.is(mask, c);
}
template<typename Char>
class has {
private:
const std::ctype_base::mask mask;
has& operator=(const has&);
public:
has(const std::ctype_base::mask mask) : mask(mask) {}
bool operator()(const std::basic_string<Char>& str) {
return std::find_if(str.begin(), str.end(),
std::bind1st(std::ptr_fun(&(is<Char>)), mask))
!= str.end();
}
};
int main(const int argc, const char* const argv[]) {
typedef std::vector<std::string> string_array_type;
//typedef std::list<std::string> string_array_type;
std::cout << "argv\n";
std::ostream_iterator<const char* const> coitr =
util::algorithm::print<const char* const>(argv, argv + argc, std::cout, "\n");
// Above expression is equivalent to following codes
// std::ostream_iterator<const char* const> coitr(std::cout, "\n");
// util::algorithm::print(argv, argv + argc, coitr);
std::cout << std::endl;
string_array_type params(argc);
std::copy(argv, argv + argc, params.begin());
std::cout << "packed argv as std::string\n";
std::ostream_iterator<std::string> soitr =
util::algorithm::print<std::string>(params.begin(), params.end(), std::cout, "\n");
std::cout << std::endl;
std::cout << "lengths of argv\n";
util::algorithm::print_op<size_t>(argv, argv + argc, std::cout, "\n", std::strlen);
std::cout << std::endl;
std::cout << "lengths of packed argv as std::string\n";
#ifdef _MSC_VER
// In g++ 4.3.3, this expression can't be passed.
util::algorithm::print_op<size_t>(
params.begin(), params.end(),
std::cout, "\n", std::mem_fun_ref(&(std::string::size)));
#else
util::algorithm::print_op<size_t>(
params.begin(), params.end(),
std::cout, "\n", length);
#endif
std::cout << std::endl;
std::cout << "argv that has any digits\n";
util::algorithm::print_if(argv, argv + argc, coitr, has<char>(std::ctype_base::digit));
std::cout << std::endl;
std::cout << "packed argv as std::string that has any punctuations\n";
util::algorithm::print_if(params.begin(), params.end(), soitr, has<char>(std::ctype_base::punct));
std::cout << std::endl;
// emulation of "grep" statement in Perl
// string_array_type greped(std::count_if(params.begin(), params.end(), has_digit<char>()));
// util::algorithm::copy_if(params.begin(), params.end(), greped.begin(), has_digit<char>());
// util::algorithm::print(greped.begin(), greped.end(), soitr);
return 0;
}
<commit_msg>Simplify<commit_after>/*
* main.cpp
* sample codes for algorithm.hpp
*
* written by janus_wel<janus.wel.3@gmail.com>
* This source code is in public domain, and has NO WARRANTY.
* */
#include "../../header/algorithm.hpp"
#include <algorithm>
#include <cstring>
#include <functional>
#include <iostream>
#include <list>
#include <locale>
#include <string>
#include <vector>
template<typename Char>
inline bool is(const std::ctype_base::mask mask, const Char c) {
static const std::ctype<Char>& ctype =
std::use_facet<std::ctype<Char> >(std::locale::classic());
return ctype.is(mask, c);
}
template<typename Char>
class has {
private:
const std::ctype_base::mask mask;
has& operator=(const has&);
public:
has(const std::ctype_base::mask mask) : mask(mask) {}
bool operator()(const std::basic_string<Char>& str) {
return std::find_if(str.begin(), str.end(),
std::bind1st(std::ptr_fun(&(is<Char>)), mask))
!= str.end();
}
};
int main(const int argc, const char* const argv[]) {
typedef std::vector<std::string> string_array_type;
//typedef std::list<std::string> string_array_type;
std::cout << "argv\n";
std::ostream_iterator<const char* const> coitr =
util::algorithm::print<const char* const>(argv, argv + argc, std::cout, "\n");
// Above expression is equivalent to following codes
// std::ostream_iterator<const char* const> coitr(std::cout, "\n");
// util::algorithm::print(argv, argv + argc, coitr);
std::cout << std::endl;
string_array_type params(argc);
std::copy(argv, argv + argc, params.begin());
std::cout << "packed argv as std::string\n";
std::ostream_iterator<std::string> soitr =
util::algorithm::print<std::string>(params.begin(), params.end(), std::cout, "\n");
std::cout << std::endl;
std::cout << "lengths of argv\n";
util::algorithm::print_op<size_t>(argv, argv + argc, std::cout, "\n", std::strlen);
std::cout << std::endl;
std::cout << "lengths of packed argv as std::string\n";
util::algorithm::print_op<std::string::size_type>(
params.begin(), params.end(),
std::cout, "\n", std::mem_fun_ref(&std::string::size));
std::cout << std::endl;
std::cout << "argv that has any digits\n";
util::algorithm::print_if(argv, argv + argc, coitr, has<char>(std::ctype_base::digit));
std::cout << std::endl;
std::cout << "packed argv as std::string that has any punctuations\n";
util::algorithm::print_if(params.begin(), params.end(), soitr, has<char>(std::ctype_base::punct));
std::cout << std::endl;
// emulation of "grep" statement in Perl
// string_array_type greped(std::count_if(params.begin(), params.end(), has_digit<char>()));
// util::algorithm::copy_if(params.begin(), params.end(), greped.begin(), has_digit<char>());
// util::algorithm::print(greped.begin(), greped.end(), soitr);
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2009-2011 qiuu
Copyright (C) 2016 Clownacy
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include <cstring>
#include <fstream>
#include <unistd.h>
#include "Common.h"
#include "PrjHndl.h"
#include "TxtRead.h"
#include "Resource.h"
#ifdef _WIN32
#include "WinAPI.h"
#endif
ProjectData::ProjectData(const char* const prjtxt) {
tileOffset = 0;
letterOffset = numberOffset = 0;
std::ifstream prjfile(prjtxt, std::ios::in);
// Make working directory from project path
char prjdir[strlen(prjtxt)+1];
strcpy(prjdir, prjtxt);
// Find last path separator
char* posix_seperator = strrchr(prjdir, '/'); // First, POSIX
char* windows_seperator = strrchr(prjdir, '\\'); // Then whatever Windows uses
if (posix_seperator != NULL || windows_seperator != NULL)
{
if (posix_seperator != NULL)
(*posix_seperator) = '\0';
else if (windows_seperator != NULL)
(*windows_seperator) = '\0';
chdir(prjdir);
}
while (!prjfile.eof()) {
char line[256];
prjfile.getline(line, 256);
infoType info_type = readInfoType(line);
AssignInfo(info_type, line+strcspn(line, ":")+1);
}
}
void ProjectData::AssignInfo(const infoType type, char* content) {
switch(type) {
case infoType::PALETTE_FILE:
strcpy(pal.name, trimString(content));
break;
case infoType::MAPPING_FILE:
strcpy(map.name, trimString(content));
break;
case infoType::ART_FILE:
strcpy(art.name, trimString(content));
break;
case infoType::PALETTE_OFFSET:
pal.offset = strtol(content, NULL, 0);
break;
case infoType::MAPPING_OFFSET:
map.offset = strtol(content, NULL, 0);
break;
case infoType::ART_OFFSET:
art.offset = strtol(content, NULL, 0);
break;
case infoType::PALETTE_LENGTH:
pal.length = strtol(content, NULL, 0);
break;
case infoType::MAPPING_LENGTH:
map.length = strtol(content, NULL, 0);
break;
case infoType::ART_LENGTH:
art.length = strtol(content, NULL, 0);
break;
case infoType::PALETTE_COMPRESSION:
pal.compression = readComprType(trimString(content));
break;
case infoType::MAPPING_COMPRESSION:
map.compression = readComprType(trimString(content));
break;
case infoType::ART_COMPRESSION:
art.compression = readComprType(trimString(content));
break;
case infoType::PALETTE_DESTINATION_OFFSET:
pal.destination_offset = strtol(content, NULL, 0);
if (pal.destination_offset >= 0x80)
MainScreen->ShowError("Palette Destination Offset cannot be higher than 0x7F (16th entry of 4th palette line; the last palette entry)");
break;
case infoType::X_SIZE:
map.xSize = strtol(content, NULL, 0);
break;
case infoType::Y_SIZE:
map.ySize = strtol(content, NULL, 0);
break;
case infoType::TILE_OFFSET:
tileOffset = strtol(content, NULL, 0);
break;
case infoType::LETTER_OFFSET:
letterOffset = strtol(content, NULL, 0);
break;
case infoType::NUMBER_OFFSET:
numberOffset = strtol(content, NULL, 0);
break;
case infoType::SAVE_FILE:
strcpy(map.saveName, trimString(content));
break;
case infoType::KOSINSKI_MODULE_SIZE:
art.kosinski_module_size = strtol(content, NULL, 0);
break;
}
}
<commit_msg>Remove a VLA<commit_after>/*
Copyright (C) 2009-2011 qiuu
Copyright (C) 2016 Clownacy
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include <cstring>
#include <fstream>
#include <unistd.h>
#include "Common.h"
#include "PrjHndl.h"
#include "TxtRead.h"
#include "Resource.h"
#ifdef _WIN32
#include "WinAPI.h"
#endif
ProjectData::ProjectData(const char* const prjtxt) {
tileOffset = 0;
letterOffset = numberOffset = 0;
std::ifstream prjfile(prjtxt, std::ios::in);
// Make working directory from project path
std::string prjdir = prjtxt;
std::size_t separator = prjdir.find_last_of("/\\");
if (separator != std::string::npos)
{
prjdir[separator] = '\0';
chdir(prjdir.c_str());
}
while (!prjfile.eof()) {
char line[256];
prjfile.getline(line, 256);
infoType info_type = readInfoType(line);
AssignInfo(info_type, line+strcspn(line, ":")+1);
}
}
void ProjectData::AssignInfo(const infoType type, char* content) {
switch(type) {
case infoType::PALETTE_FILE:
strcpy(pal.name, trimString(content));
break;
case infoType::MAPPING_FILE:
strcpy(map.name, trimString(content));
break;
case infoType::ART_FILE:
strcpy(art.name, trimString(content));
break;
case infoType::PALETTE_OFFSET:
pal.offset = strtol(content, NULL, 0);
break;
case infoType::MAPPING_OFFSET:
map.offset = strtol(content, NULL, 0);
break;
case infoType::ART_OFFSET:
art.offset = strtol(content, NULL, 0);
break;
case infoType::PALETTE_LENGTH:
pal.length = strtol(content, NULL, 0);
break;
case infoType::MAPPING_LENGTH:
map.length = strtol(content, NULL, 0);
break;
case infoType::ART_LENGTH:
art.length = strtol(content, NULL, 0);
break;
case infoType::PALETTE_COMPRESSION:
pal.compression = readComprType(trimString(content));
break;
case infoType::MAPPING_COMPRESSION:
map.compression = readComprType(trimString(content));
break;
case infoType::ART_COMPRESSION:
art.compression = readComprType(trimString(content));
break;
case infoType::PALETTE_DESTINATION_OFFSET:
pal.destination_offset = strtol(content, NULL, 0);
if (pal.destination_offset >= 0x80)
MainScreen->ShowError("Palette Destination Offset cannot be higher than 0x7F (16th entry of 4th palette line; the last palette entry)");
break;
case infoType::X_SIZE:
map.xSize = strtol(content, NULL, 0);
break;
case infoType::Y_SIZE:
map.ySize = strtol(content, NULL, 0);
break;
case infoType::TILE_OFFSET:
tileOffset = strtol(content, NULL, 0);
break;
case infoType::LETTER_OFFSET:
letterOffset = strtol(content, NULL, 0);
break;
case infoType::NUMBER_OFFSET:
numberOffset = strtol(content, NULL, 0);
break;
case infoType::SAVE_FILE:
strcpy(map.saveName, trimString(content));
break;
case infoType::KOSINSKI_MODULE_SIZE:
art.kosinski_module_size = strtol(content, NULL, 0);
break;
}
}
<|endoftext|>
|
<commit_before>#include <csignal>
#include <pthread.h>
#include <string>
#include <unistd.h>
#include <utility>
#include <vector>
#include "Program.hpp"
//==============================================================================
// Parses program arguments and stores in arguments
//==============================================================================
Program::Program(int argc, char** argv)
{
// Program name is always the first argument
if (argc > 0)
{
name = argv[0];
}
// Store all arguments
for (int i = 1; i < argc; i++)
{
arguments.push_back(argv[i]);
}
// No signals delivered, we're not even running yet
sigemptyset(&delivered_signals);
// Default attributes should be good enough
pthread_mutex_init(&delivered_signals_mutex, 0);
}
//==============================================================================
// Nothing to do on shutdown here
//==============================================================================
Program::~Program()
{
}
//==============================================================================
// THREAD-SAFE; External sources can use this interface to signal this program;
// signals are not handled immediately, they are placed on a list and handled
// within the processSignals member function
//==============================================================================
void Program::signal(int sig)
{
// Add this signal to our list of delivered signals
pthread_mutex_lock(&delivered_signals_mutex);
sigaddset(&delivered_signals, sig);
pthread_mutex_unlock(&delivered_signals_mutex);
}
//==============================================================================
// Returns a copy of the program name
//==============================================================================
void Program::getName(std::string& name) const
{
name = this->name;
}
//==============================================================================
// Returns a copy of the program arguments
//==============================================================================
void Program::getArguments(std::vector<std::string>& arguments) const
{
arguments = this->arguments;
}
//==============================================================================
// THREAD-SAFE; Returns a copy of the set of delivered signals
//==============================================================================
void Program::getDeliveredSignals(sigset_t& sigset)
{
pthread_mutex_lock(&delivered_signals_mutex);
sigset = this->delivered_signals;
pthread_mutex_unlock(&delivered_signals_mutex);
}
//==============================================================================
// THREAD-SAFE; Returns true if sig has been delivered
//==============================================================================
bool Program::isSignalDelivered(int sig)
{
pthread_mutex_lock(&delivered_signals_mutex);
bool signal_delivered = sigismember(&delivered_signals, sig);
pthread_mutex_unlock(&delivered_signals_mutex);
return signal_delivered;
}
//==============================================================================
// C function "cfun" is assigned to handle signals of type sig
//==============================================================================
bool Program::attachSignal(int sig, void cfun(int))
{
struct sigaction act;
act.sa_handler = cfun;
act.sa_flags = 0;
return sigaction(SIGINT, &act, 0) != -1;
}
//==============================================================================
// Reconfigure self as a background process (daemon)
//==============================================================================
bool Program::daemonize()
{
// Linux-specific and possibly outdated
return daemon(0, 0) == 0;
}
//==============================================================================
// Derived classes should implement this function with their signal handling
// code; get the current set of delivered signals by calling
// getDeliveredSignals() or check if a particular signal is delivered using
// isSignalDelivered(); after signals are processed use unsignal() or
// unsignalAll() to mark signals as processed
//==============================================================================
void Program::processDeliveredSignals()
{
unsignalAll();
}
//==============================================================================
// THREAD-SAFE; Removes a particular signal from the set of delivered signals
//==============================================================================
void Program::unsignal(int sig)
{
pthread_mutex_lock(&delivered_signals_mutex);
sigdelset(&delivered_signals, sig);
pthread_mutex_unlock(&delivered_signals_mutex);
}
//==============================================================================
// THREAD-SAFE; Removes all signals from the set of delivered signals
//==============================================================================
void Program::unsignalAll()
{
pthread_mutex_lock(&delivered_signals_mutex);
sigemptyset(&delivered_signals);
pthread_mutex_unlock(&delivered_signals_mutex);
}
<commit_msg>Initializing uninitialized memory<commit_after>#include <csignal>
#include <pthread.h>
#include <string>
#include <unistd.h>
#include <utility>
#include <vector>
#include "Program.hpp"
//==============================================================================
// Parses program arguments and stores in arguments
//==============================================================================
Program::Program(int argc, char** argv)
{
// Program name is always the first argument
if (argc > 0)
{
name = argv[0];
}
// Store all arguments
for (int i = 1; i < argc; i++)
{
arguments.push_back(argv[i]);
}
// No signals delivered, we're not even running yet
sigemptyset(&delivered_signals);
// Default attributes should be good enough
pthread_mutex_init(&delivered_signals_mutex, 0);
}
//==============================================================================
// Nothing to do on shutdown here
//==============================================================================
Program::~Program()
{
}
//==============================================================================
// THREAD-SAFE; External sources can use this interface to signal this program;
// signals are not handled immediately, they are placed on a list and handled
// within the processSignals member function
//==============================================================================
void Program::signal(int sig)
{
// Add this signal to our list of delivered signals
pthread_mutex_lock(&delivered_signals_mutex);
sigaddset(&delivered_signals, sig);
pthread_mutex_unlock(&delivered_signals_mutex);
}
//==============================================================================
// Returns a copy of the program name
//==============================================================================
void Program::getName(std::string& name) const
{
name = this->name;
}
//==============================================================================
// Returns a copy of the program arguments
//==============================================================================
void Program::getArguments(std::vector<std::string>& arguments) const
{
arguments = this->arguments;
}
//==============================================================================
// THREAD-SAFE; Returns a copy of the set of delivered signals
//==============================================================================
void Program::getDeliveredSignals(sigset_t& sigset)
{
pthread_mutex_lock(&delivered_signals_mutex);
sigset = this->delivered_signals;
pthread_mutex_unlock(&delivered_signals_mutex);
}
//==============================================================================
// THREAD-SAFE; Returns true if sig has been delivered
//==============================================================================
bool Program::isSignalDelivered(int sig)
{
pthread_mutex_lock(&delivered_signals_mutex);
bool signal_delivered = sigismember(&delivered_signals, sig);
pthread_mutex_unlock(&delivered_signals_mutex);
return signal_delivered;
}
//==============================================================================
// C function "cfun" is assigned to handle signals of type sig
//==============================================================================
bool Program::attachSignal(int sig, void cfun(int))
{
struct sigaction act;
act.sa_handler = cfun;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
return sigaction(SIGINT, &act, 0) != -1;
}
//==============================================================================
// Reconfigure self as a background process (daemon)
//==============================================================================
bool Program::daemonize()
{
// Linux-specific and possibly outdated
return daemon(0, 0) == 0;
}
//==============================================================================
// Derived classes should implement this function with their signal handling
// code; get the current set of delivered signals by calling
// getDeliveredSignals() or check if a particular signal is delivered using
// isSignalDelivered(); after signals are processed use unsignal() or
// unsignalAll() to mark signals as processed
//==============================================================================
void Program::processDeliveredSignals()
{
unsignalAll();
}
//==============================================================================
// THREAD-SAFE; Removes a particular signal from the set of delivered signals
//==============================================================================
void Program::unsignal(int sig)
{
pthread_mutex_lock(&delivered_signals_mutex);
sigdelset(&delivered_signals, sig);
pthread_mutex_unlock(&delivered_signals_mutex);
}
//==============================================================================
// THREAD-SAFE; Removes all signals from the set of delivered signals
//==============================================================================
void Program::unsignalAll()
{
pthread_mutex_lock(&delivered_signals_mutex);
sigemptyset(&delivered_signals);
pthread_mutex_unlock(&delivered_signals_mutex);
}
<|endoftext|>
|
<commit_before>#include "FitsObject.h"
#include <stdexcept>
using namespace std;
Fits::Fits(const string &filename)
: m_status(0), m_filename(filename)
{
fits_open_file(&this->m_fptr, this->m_filename.c_str(), READWRITE, &this->m_status);
this->check();
}
Fits::Fits() {}
Fits::~Fits()
{
fits_close_file(this->m_fptr, &this->m_status);
this->check();
}
void Fits::check()
{
if (this->m_status)
{
char buf[FLEN_STATUS];
fits_get_errstatus(this->m_status, buf);
/* Have to set the status back to 0 otherwise
* when the destructor is called and the file is closed
* then another exception will be thrown */
this->m_status = 0;
throw runtime_error(buf);
}
}
void Fits::moveHDU(const string &hduname)
{
fits_movnam_hdu(this->m_fptr, ANY_HDU, const_cast<char*>(hduname.c_str()), 0, &this->m_status);
this->check();
}
void Fits::moveHDU(int hdunum)
{
int hdutype;
fits_movabs_hdu(this->m_fptr, hdunum, &hdutype, &this->m_status);
this->check();
}
void Fits::checkForTable()
{
/* Checks for a table extension */
int hdutype;
fits_get_hdu_type(this->m_fptr, &hdutype, &this->m_status);
this->check();
if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL))
{
throw runtime_error("Non-table hdu found");
}
}
int Fits::columnNumber(const std::string &colname)
{
this->checkForTable();
}
long Fits::nrows()
{
// Ensure the current hdu is a (binary) table
this->checkForTable();
int hdutype;
fits_get_hdu_type(this->m_fptr, &hdutype, &this->m_status);
this->check();
if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL))
{
throw runtime_error("Non-table hdu found");
}
long nrows;
fits_get_num_rows(this->m_fptr, &nrows, &this->m_status);
this->check();
return nrows;
}
fitsfile **Fits::fptr() { return &this->m_fptr; }
int &Fits::status() { return this->m_status; }
void Fits::check(int status)
{
if (status)
{
char buf[FLEN_STATUS];
fits_get_errstatus(status, buf);
throw runtime_error(buf);
}
}
const string Fits::hduname()
{
char buf[FLEN_VALUE];
fits_read_key(this->m_fptr, TSTRING, "EXTNAME", buf, NULL, &this->m_status);
this->check();
return string(buf);
}
NewFits::NewFits(const string &filename)
{
this->m_filename = filename;
this->m_status = 0;
fits_create_file(&this->m_fptr, filename.c_str(), &this->m_status);
this->check();
/* Ensure the basic keywords are there */
long naxes[] = {0, 0};
fits_create_img(this->m_fptr, BYTE_IMG, 0, naxes, &this->m_status);
this->check();
}
<commit_msg>added function functionality<commit_after>#include "FitsObject.h"
#include <stdexcept>
using namespace std;
Fits::Fits(const string &filename)
: m_status(0), m_filename(filename)
{
fits_open_file(&this->m_fptr, this->m_filename.c_str(), READWRITE, &this->m_status);
this->check();
}
Fits::Fits() {}
Fits::~Fits()
{
fits_close_file(this->m_fptr, &this->m_status);
this->check();
}
void Fits::check()
{
if (this->m_status)
{
char buf[FLEN_STATUS];
fits_get_errstatus(this->m_status, buf);
/* Have to set the status back to 0 otherwise
* when the destructor is called and the file is closed
* then another exception will be thrown */
this->m_status = 0;
throw runtime_error(buf);
}
}
void Fits::moveHDU(const string &hduname)
{
fits_movnam_hdu(this->m_fptr, ANY_HDU, const_cast<char*>(hduname.c_str()), 0, &this->m_status);
this->check();
}
void Fits::moveHDU(int hdunum)
{
int hdutype;
fits_movabs_hdu(this->m_fptr, hdunum, &hdutype, &this->m_status);
this->check();
}
void Fits::checkForTable()
{
/* Checks for a table extension */
int hdutype;
fits_get_hdu_type(this->m_fptr, &hdutype, &this->m_status);
this->check();
if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL))
{
throw runtime_error("Non-table hdu found");
}
}
int Fits::columnNumber(const std::string &colname)
{
this->checkForTable();
int colnum;
fits_get_colnum(this->m_fptr, CASEINSEN, const_cast<char*>(colname.c_str()), &colnum, &this->m_status);
this->check();
return colnum;
}
long Fits::nrows()
{
// Ensure the current hdu is a (binary) table
this->checkForTable();
int hdutype;
fits_get_hdu_type(this->m_fptr, &hdutype, &this->m_status);
this->check();
if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL))
{
throw runtime_error("Non-table hdu found");
}
long nrows;
fits_get_num_rows(this->m_fptr, &nrows, &this->m_status);
this->check();
return nrows;
}
fitsfile **Fits::fptr() { return &this->m_fptr; }
int &Fits::status() { return this->m_status; }
void Fits::check(int status)
{
if (status)
{
char buf[FLEN_STATUS];
fits_get_errstatus(status, buf);
throw runtime_error(buf);
}
}
const string Fits::hduname()
{
char buf[FLEN_VALUE];
fits_read_key(this->m_fptr, TSTRING, "EXTNAME", buf, NULL, &this->m_status);
this->check();
return string(buf);
}
NewFits::NewFits(const string &filename)
{
this->m_filename = filename;
this->m_status = 0;
fits_create_file(&this->m_fptr, filename.c_str(), &this->m_status);
this->check();
/* Ensure the basic keywords are there */
long naxes[] = {0, 0};
fits_create_img(this->m_fptr, BYTE_IMG, 0, naxes, &this->m_status);
this->check();
}
<|endoftext|>
|
<commit_before>#ifndef TOMB4FX_H
#define TOMB4FX_H
#include "SPECTYPES.H"
extern char flare_table[121]; // offset 0x92A6C
extern char LaserSightActive; // offset 0xA09FC
extern char LaserSightCol; // offset 0xA09FD
extern long next_fire_spark; // offset 0xA0A0C
extern long next_smoke_spark; // offset 0xA0A10
extern long next_gunshell; // offset 0xA0A18
extern long next_bubble; // offset 0xA0A1C
extern long next_drip; // offset 0xA0A20
extern long next_blood; // offset 0xA0A14
extern long next_spider;
extern struct NODEOFFSET_INFO NodeOffsets[16]; // offset 0xA0A24
extern short FlashFadeR; // offset 0xA0A04
extern short FlashFadeG; // offset 0xA0A06
extern short FlashFadeB; // offset 0xA0A08
extern short FlashFader; // offset 0xA0A0A
extern short ScreenFade; // offset 0xA09F0
extern short dScreenFade; // offset 0xA09F2
extern short ScreenFadeSpeed; // offset 0xA09F4
extern short ScreenFadeBack; // offset 0xA09F6
extern short ScreenFadedOut; // offset 0xA09F8
extern short ScreenFading; // offset 0xA09FA
extern short FadeScreenHeight; // offset 0xA09FE
extern short DestFadeScreenHeight; // offset 0xA0A00
extern short FadeClipSpeed; // offset 0xA0A02
extern long LaserSightX; // offset 0xA3268
extern long LaserSightY; // offset 0xA326C
extern long LaserSightZ; // offset 0xA3270
extern struct GUNFLASH_STRUCT Gunflashes[4]; // offset 0xA31D8
extern struct PHD_VECTOR NodeVectors[16]; // offset 0xA3274
extern struct FIRE_SPARKS fire_spark[20]; // offset 0xA94FC
extern struct SMOKE_SPARKS smoke_spark[32]; // offset 0xA8F7C
extern struct GUNSHELL_STRUCT Gunshells[24]; // offset 0xA7DFC
extern struct BLOOD_STRUCT blood[32]; // offset 0xA88FC
extern struct BUBBLE_STRUCT Bubbles[40]; // offset 0xA80FC
extern struct DRIP_STRUCT Drips[32]; // offset 0xA85FC
extern struct SHOCKWAVE_STRUCT ShockWaves[16]; // offset 0xA7C3C
extern struct FIRE_LIST fires[32]; // offset 0xA8D7C
extern void SetFadeClip(short height, short speed);
extern void UpdateFadeClip();
extern void SetScreenFadeOut(long fadespeed, long fadeback);
extern void SetScreenFadeIn(long fadespeed);
extern int GetFreeDrip();
extern int GetFreeSmokeSpark();
extern int GetFreeSpark();
extern int GetFreeBubble();
extern void CreateBubble(struct PHD_VECTOR* pos, short room_num, int a3, int a4, int a5, int a6, int a7, int a8);
extern void TriggerShatterSmoke(int x, int y, int z);
extern void TriggerBlood(int x, int y, int z, int direction, int speed);
extern void TriggerExplosionBubble(int x, int y, int z, short room_num);
extern void TriggerExplosionSparks(int x, int y, int z, int a4, int a5, int a6, short room_no);
extern void Fade();
extern void SetUpLensFlare(long x, long y, long z, struct GAME_VECTOR* bulb);
extern int ExplodingDeath2(short item_number, long mesh_bits, short Flags);
extern void DrawLensFlares(struct ITEM_INFO *item);
extern void TriggerLightningGlow(long x, long y, long z, long rgb);
extern void trig_actor_gunflash(struct MATRIX3D *matrix, struct PHD_VECTOR *pos);
extern void TriggerFenceSparks(long x, long y, long z, long kill, long crane);
extern void ControlElectricFence(short item_number);
extern void ControlTeleporter(short item_number);
extern void DrawWeaponMissile(struct ITEM_INFO *item);
extern void TriggerLaraDrips();
extern void DoBloodSplat(int x, int y, int z, short speed, short direction, short room_num);
extern void TriggerRicochetSpark(struct GAME_VECTOR* pos, int angle, int num, int a4);
extern void Richochet(struct GAME_VECTOR* pos);
extern void TriggerLightning(struct PHD_VECTOR* a1, struct PHD_VECTOR* a2, char a3, int a4, char a5, char a6, char a7);
extern void TriggerCoinGlow();
extern int GetFreeSpider();
extern void TriggerSmallSplash(int x, int y, int z, int num);
#endif<commit_msg>Fix PSX Compile.<commit_after>#ifndef TOMB4FX_H
#define TOMB4FX_H
#include "SPECTYPES.H"
extern char flare_table[121]; // offset 0x92A6C
extern char LaserSightActive; // offset 0xA09FC
extern char LaserSightCol; // offset 0xA09FD
extern long next_fire_spark; // offset 0xA0A0C
extern long next_smoke_spark; // offset 0xA0A10
extern long next_gunshell; // offset 0xA0A18
extern long next_bubble; // offset 0xA0A1C
extern long next_drip; // offset 0xA0A20
extern long next_blood; // offset 0xA0A14
extern long next_spider;
extern struct NODEOFFSET_INFO NodeOffsets[16]; // offset 0xA0A24
extern short FlashFadeR; // offset 0xA0A04
extern short FlashFadeG; // offset 0xA0A06
extern short FlashFadeB; // offset 0xA0A08
extern short FlashFader; // offset 0xA0A0A
extern short ScreenFade; // offset 0xA09F0
extern short dScreenFade; // offset 0xA09F2
extern short ScreenFadeSpeed; // offset 0xA09F4
extern short ScreenFadeBack; // offset 0xA09F6
extern short ScreenFadedOut; // offset 0xA09F8
extern short ScreenFading; // offset 0xA09FA
extern short FadeScreenHeight; // offset 0xA09FE
extern short DestFadeScreenHeight; // offset 0xA0A00
extern short FadeClipSpeed; // offset 0xA0A02
extern long LaserSightX; // offset 0xA3268
extern long LaserSightY; // offset 0xA326C
extern long LaserSightZ; // offset 0xA3270
extern struct GUNFLASH_STRUCT Gunflashes[4]; // offset 0xA31D8
extern struct PHD_VECTOR NodeVectors[16]; // offset 0xA3274
extern struct FIRE_SPARKS fire_spark[20]; // offset 0xA94FC
extern struct SMOKE_SPARKS smoke_spark[32]; // offset 0xA8F7C
extern struct GUNSHELL_STRUCT Gunshells[24]; // offset 0xA7DFC
extern struct BLOOD_STRUCT blood[32]; // offset 0xA88FC
extern struct BUBBLE_STRUCT Bubbles[40]; // offset 0xA80FC
extern struct DRIP_STRUCT Drips[32]; // offset 0xA85FC
extern struct SHOCKWAVE_STRUCT ShockWaves[16]; // offset 0xA7C3C
extern struct FIRE_LIST fires[32]; // offset 0xA8D7C
extern void SetFadeClip(short height, short speed);
extern void UpdateFadeClip();
extern void SetScreenFadeOut(long fadespeed, long fadeback);
extern void SetScreenFadeIn(long fadespeed);
extern int GetFreeDrip();
extern int GetFreeSmokeSpark();
extern int GetFreeSpark();
extern int GetFreeBubble();
extern void CreateBubble(struct PHD_VECTOR* pos, short room_num, int a3, int a4, int a5, int a6, int a7, int a8);
extern void TriggerShatterSmoke(int x, int y, int z);
extern void TriggerBlood(int x, int y, int z, int direction, int speed);
extern void TriggerExplosionBubble(int x, int y, int z, short room_num);
extern void TriggerExplosionSparks(int x, int y, int z, int a4, int a5, int a6, short room_no);
extern void Fade();
extern void SetUpLensFlare(long x, long y, long z, struct GAME_VECTOR* bulb);
extern int ExplodingDeath2(short item_number, long mesh_bits, short Flags);
extern void DrawLensFlares(struct ITEM_INFO *item);
extern void TriggerLightningGlow(long x, long y, long z, long rgb);
extern void trig_actor_gunflash(struct MATRIX3D *matrix, struct PHD_VECTOR *pos);
extern void TriggerFenceSparks(long x, long y, long z, long kill, long crane);
extern void ControlElectricFence(short item_number);
extern void ControlTeleporter(short item_number);
extern void DrawWeaponMissile(struct ITEM_INFO *item);
extern void TriggerLaraDrips();
#if PC_VERSION
extern void DoBloodSplat(int x, int y, int z, short speed, short direction, short room_num);
extern void TriggerRicochetSpark(struct GAME_VECTOR* pos, int angle, int num, int a4);
#endif
extern void Richochet(struct GAME_VECTOR* pos);
extern void TriggerLightning(struct PHD_VECTOR* a1, struct PHD_VECTOR* a2, char a3, int a4, char a5, char a6, char a7);
extern void TriggerCoinGlow();
extern int GetFreeSpider();
extern void TriggerSmallSplash(int x, int y, int z, int num);
#endif<|endoftext|>
|
<commit_before>#include "HMDWrapper.h"
#include "interface\DeviceMgrInterface.h"
using namespace MathLib;
class CLocalHMDWrapper : public CHMDWrapper
{
public:
CLocalHMDWrapper();
virtual ~CLocalHMDWrapper();
virtual void Init();
virtual void Update();
virtual void Shutdown();
virtual void SetUseHMD(int u);
virtual int GetUseHMD() const;
virtual const MathLib::vec3 &GetLocalDirection() const;
virtual const MathLib::vec3 &GetLocalUp() const;
private:
int m_nUseHMD;
int m_nHaveHMD;
vec3 m_vLocalDirection;
vec3 m_vLocalUp;
};
CLocalHMDWrapper::CLocalHMDWrapper()
{
m_nUseHMD = 1;
m_nHaveHMD = 0;
m_vLocalDirection = forward_vector;
m_vLocalUp = up_vector;
}
CLocalHMDWrapper::~CLocalHMDWrapper()
{
}
void CLocalHMDWrapper::Init()
{
m_nHaveHMD = Interface::CDeviceInterface::GetInstance()->InitEnv();
}
void CLocalHMDWrapper::Update()
{
if (GetUseHMD())
{
Interface::SEulerAngles sData;
Interface::CDeviceInterface::GetInstance()->GetHMDSensorRotation(sData);
Interface::CDeviceInterface::GetInstance()->Run();
vec3 dir = forward_vector;
vec3 up = up_vector;
quat rotate(-sData.fPitch * RAD2DEG, sData.fRoll * RAD2DEG, sData.fYaw * RAD2DEG);
m_vLocalDirection = rotate * dir;
m_vLocalUp = rotate * up;
}
}
void CLocalHMDWrapper::Shutdown()
{
Interface::CDeviceInterface::GetInstance()->Destroy();
}
<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "HMDWrapper.h"
#include "interface\DeviceMgrInterface.h"
using namespace MathLib;
class CLocalHMDWrapper : public CHMDWrapper
{
public:
CLocalHMDWrapper();
virtual ~CLocalHMDWrapper();
virtual void Init();
virtual void Update();
virtual void Shutdown();
virtual void SetUseHMD(int u);
virtual int GetUseHMD() const;
virtual const MathLib::vec3 &GetLocalDirection() const;
virtual const MathLib::vec3 &GetLocalUp() const;
private:
int m_nUseHMD;
int m_nHaveHMD;
vec3 m_vLocalDirection;
vec3 m_vLocalUp;
};
CLocalHMDWrapper::CLocalHMDWrapper()
{
m_nUseHMD = 1;
m_nHaveHMD = 0;
m_vLocalDirection = forward_vector;
m_vLocalUp = up_vector;
}
CLocalHMDWrapper::~CLocalHMDWrapper()
{
}
void CLocalHMDWrapper::Init()
{
m_nHaveHMD = Interface::CDeviceInterface::GetInstance()->InitEnv();
}
void CLocalHMDWrapper::Update()
{
if (GetUseHMD())
{
Interface::SEulerAngles sData;
Interface::CDeviceInterface::GetInstance()->GetHMDSensorRotation(sData);
Interface::CDeviceInterface::GetInstance()->Run();
vec3 dir = forward_vector;
vec3 up = up_vector;
quat rotate(-sData.fPitch * RAD2DEG, sData.fRoll * RAD2DEG, sData.fYaw * RAD2DEG);
m_vLocalDirection = rotate * dir;
m_vLocalUp = rotate * up;
}
}
void CLocalHMDWrapper::Shutdown()
{
Interface::CDeviceInterface::GetInstance()->Destroy();
}
void CLocalHMDWrapper::SetUseHMD(int u)
{
m_nUseHMD = u;
}
<|endoftext|>
|
<commit_before>#include "Isosurface.h"
Vector3D Isosurface::gradientAt(float x, float y, float z) const
{
const float epsilon = 0.0001;
float dx = valueAt(x + epsilon, y, z) - valueAt(x - epsilon, y, z);
float dy = valueAt(x, y + epsilon, z) - valueAt(x, y - epsilon, z);
float dz = valueAt(x, y, z + epsilon) - valueAt(x, y, z - epsilon);
Vector3D result = { dx, dy, dz };
normalize(result);
return result;
}
Isosurface::~Isosurface() {
}
<commit_msg>Fix a brace style inconsistency<commit_after>#include "Isosurface.h"
Vector3D Isosurface::gradientAt(float x, float y, float z) const
{
const float epsilon = 0.0001;
float dx = valueAt(x + epsilon, y, z) - valueAt(x - epsilon, y, z);
float dy = valueAt(x, y + epsilon, z) - valueAt(x, y - epsilon, z);
float dz = valueAt(x, y, z + epsilon) - valueAt(x, y, z - epsilon);
Vector3D result = { dx, dy, dz };
normalize(result);
return result;
}
Isosurface::~Isosurface()
{
}
<|endoftext|>
|
<commit_before>class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,unsigned int> postion;
unsigned int front,rear;
unsigned max_len = 0;
front = rear = 0;
while(rear < s.size())
{
auto index = postion.find(s.at(rear));
if(index == postion.end())
{
postion.insert(make_pair(s.at(rear),rear));
++rear;
}
else
{
auto len = rear - front;
if(len > max_len)
max_len = len;
for(unsigned int i=front; i < index->second; ++i)
{
postion.erase(s.at(i));
}
front = index->second + 1;
index->second = rear;
++rear;
}
}
if(rear - front > max_len)
max_len = rear - front;
return max_len;
}
};
<commit_msg>Update 3.cpp<commit_after>class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,unsigned int> postion;
unsigned int front,rear;
unsigned max_len = 0;
front = rear = 0;
while(rear < s.size())
{
auto index = postion.find(s.at(rear));
if(index == postion.end())
{
postion.insert(make_pair(s.at(rear),rear));
++rear;
}
else
{
auto len = rear - front;
if(len > max_len)
max_len = len;
for(unsigned int i=front; i < index->second; ++i)
{
postion.erase(s.at(i));
}
front = index->second + 1;
index->second = rear;
++rear;
}
}
if(rear - front > max_len)
max_len = rear - front;
return max_len;
}
};
<|endoftext|>
|
<commit_before>#include "Simplex.h"
#include <iostream>
#include <cmath>
/*
Simplex problem constructor
This takes the one dimensional arrays:
A - the LHS variable coefficient matrix of the constraints,
c - the row vector for the coeffients of the variables,
b - the column vector for the RHS
It generates a simplex tableau by mapping the values accordingly
and calling initTableau to create the simplex tableau.
Array x stores the nature of the variables such that a value of:
-1 - corresponds to x>=0
0 - means x is unrestricted
+1 - means x<=0
m is number of constraints
n is number of variables
*/
Simplex::Simplex(long int m, long int n, double A[], double c[], double b[], int x[], bool natureOfProblem)
{
this->natureOfProblem = natureOfProblem;
if (natureOfProblem == maximization) {
int colSize = n; // size of the matrix A column
int rowSize = m; // size of the matrix A row
// to create a modified version of A and c, we calculate the size
// of the new modified A and c. Only the column size will change
// depending on the nature of the variables
for (int i = 0; i<m; i++) {
if (x[i] == 0) n++;
}
this->M = m;
this->N = n;
double* modifiedA = new double[m*n];
double* modifiedC = new double[n];
int col = 0;
for (int i=0; i<colSize; i++) {
for (int j=0; j<rowSize; j++) {
int idx = i*m+j;
int idxMA = col*m+j;
if (x[i] ==-1) {
modifiedA[idxMA] = -(A[idx]);
modifiedC[col] = -(c[i]);
}
if (x[i] == 0) {
modifiedA[idxMA] = +(A[idx]);
modifiedA[idxMA+m] = -(A[idx]);
modifiedC[col] = +(c[i]);
modifiedC[col+1] = -(c[i]);
}
if (x[i] == 1) {
modifiedA[idxMA] = +(A[idx]);
modifiedC[col] = +(c[i]);
}
}
if (x[i] == 0) col+=2;
else col++;
}
this->A = Map<MatrixXd>(modifiedA, m, n);
this->cT = Map<RowVectorXd>(modifiedC, n);
this->b = Map<ColVectorXd>(b, m);
// laundry work!
delete[] modifiedA;
delete[] modifiedC;
}
if (natureOfProblem == minimization) {
// create a temporary matrix
MatrixXd temp(m+1, n+1);
double* modifiedA = new double[m*n];
double* modifiedC = new double[n];
int col = 0;
int colSize = n; // size of the matrix A column
int rowSize = m; // size of the matrix A row
for (int i=0; i<colSize; i++) {
for (int j=0; j<rowSize; j++) {
int idx = i*m+j;
int idxMA = col*m+j;
if (x[i] ==-1) {
modifiedA[idxMA] = -(A[idx]);
modifiedC[col] = -(c[i]);
}
if (x[i] == 0) {
modifiedA[idxMA] = +(A[idx]);
modifiedA[idxMA+m] = -(A[idx]);
modifiedC[col] = +(c[i]);
modifiedC[col+1] = -(c[i]);
}
if (x[i] == 1) {
modifiedA[idxMA] = +(A[idx]);
modifiedC[col] = +(c[i]);
}
}
if (x[i] == 0) col+=2;
else col++;
}
temp.block(0, 0, m, n) = Map<MatrixXd>(modifiedA, m, n);
temp.block(m, 0, 1, n) = Map<RowVectorXd>(modifiedC, n);
temp.block(0, n, m, 1) = Map<ColVectorXd>(b, m);
temp(m, n) = 0;
MatrixXd tempTransposed = temp.transpose();
double* tempA = new double[m*n];
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
tempA[j*n+i] = tempTransposed(i,j);
}
std::cout << '\n';
}
double* tempb = new double[n];
for (int i=0; i<n; i++) {
tempb[i] = tempTransposed(i, m);
}
double* tempc = new double[m];
for (int i=0; i<m; i++) {
tempc[i] = tempTransposed(n, i);
}
this->M = n;
this->N = m;
this->A = Map<MatrixXd>(tempA, n, m);
this->cT = Map<RowVectorXd>(tempc, m);
this->b = Map<ColVectorXd>(tempb, n);
// laundry work!
delete[] modifiedA;
delete[] modifiedC;
delete[] tempA;
delete[] tempb;
delete[] tempc;
}
initTableau();
}
/*
Generate initial tableau for basic feasible solution
*/
void Simplex::initTableau()
{
this->tableau.resize(M+1, M+N+2);
this->tableau(0, 0) = 1;
this->tableau.block(0, 1, 1, N) = (this->cT.array() * -1);
this->tableau.block(0, N+1, 1, M) = RowVectorXd::Zero(M);
this->tableau(0, N+1) = 0;
this->tableau.block(1, 0, M, 1) = ColVectorXd::Zero(M);
this->tableau.block(1, 1, M, N) = this->A;
this->tableau.block(1, N+1, M, M) = MatrixXd::Identity(M, M);
this->tableau.block(1,M+N+1,M, 1) = this->b;
// initialize xB which holds the basic variable column number
xB = new int[M];
cBt.resize(M);
for (int i = 0; i<M; i++) {
xB[i] = i+N+1;
cBt[i] = tableau.row(0)[xB[i]];
}
// creating the B matrix which is the initial basic matrix
B = tableau.block(1, N+1, M, M);
// set pivot
setPivot();
}
/*
Set the pivot location
*/
void Simplex::setPivot()
{
double min = tableau(0, 1);
for (int i=1; i<=N; i++) {
if (tableau(0, i) <= min) {
min = tableau(0, i);
pivotCol = i;
}
}
ColVectorXd solution = tableau.block(1, M+N+1, M, 1);
ColVectorXd pivotColumn = tableau.block(1, pivotCol, M, 1);
ArrayXd ratio = solution.array() / pivotColumn.array();
min = ratio(0);
pivotRow = 0;
for (int i=0; i<M; i++) {
if (ratio(i) <= min) {
min = ratio(i);
pivotRow = i+1;
}
}
}
/*
Calculate the next iteration
It returns true if the there is a next iteration and false if the Simplex
problem is solved
*/
bool Simplex::nextIteration()
{
setPivot();
xB[pivotRow-1] = pivotCol;
cBt[pivotRow-1] = cT[pivotCol-1];
B.col(pivotRow-1) = A.col(pivotCol-1);
MatrixXd Binv = B.inverse();
tableau.block(0, 1, 1, N) = ( (cBt * Binv * A) - cT );
tableau.block(1, 1, M, N) = ( Binv * A );
tableau.block(0, N+1, 1, M) = ( cBt * Binv );
tableau.block(1, N+1, M, M) = ( Binv );
tableau(0, M+N+1) = ( cBt * Binv * b );
tableau.block(1, M+N+1, M, 1) = ( Binv * b );
if (isOptimal())
return false;
return true;
}
/*
Get the Simplex tableau
Returns a matrix object(from eigen implementaion) with the simplex tableau
*/
MatrixXd Simplex::getTableau()
{
return tableau;
}
/*
Get the values of xB
Returns a copy of the basic variables
*/
int* Simplex::getXB()
{
// copy the contents of 'xB' in new 'x' to protect memory from being exposed
// in the outside environment
int* x = new int[M];
for (int i=0; i<M; i++)
x[i] = xB[i];
return x;
}
/*
Get the current cBt matrix
Returns a Matrix instance that contains the values of cBt
*/
MatrixXd Simplex::getCBt()
{
return cBt;
}
/*
Get the current B matrix
Returns a Matrix instance with values B
*/
MatrixXd Simplex::getB()
{
return B;
}
/*
Optimality check
Returns true if the matrix is optimal
*/
bool Simplex::isOptimal()
{
bool result = true;
RowVectorXd temp = tableau.block(0, 1, 1, N);
int *nonBasic = new int[N];
RowVectorXd zRow = this->tableau.block(0, 1, 1, N);
for (int i=0; i<M+N; i++) {
nonBasic[i] = 0;
}
for (int i=0; i<M; i++) {
nonBasic[xB[i]-1] = 1;
}
for (int i=0; i<N; i++) {
if (nonBasic[i] == 0) {
if (zRow(i) > 0) {
result &= true;
} else {
result &= false;
}
}
std::cout << nonBasic[i] << ", " << std::endl;
if (nonBasic[i] == 1) {
if (zRow(i) == 0) {
result &= true;
} else {
result &= false;
}
}
}
/*
for (int i =0; i<N; i++) {
if (!(std::signbit(temp[i]) == 0)) {
return false;
}
}
return true;
*/
return result;
}
/*
Get the pivot column
Returns the value of pivot column corresponding to the simplex tableaux
*/
int Simplex::getPivotCol()
{
return pivotCol;
}
/*
Get the pivot row
Returns the value of pivot row corresponding to the simplex tableaux
*/
int Simplex::getPivotRow()
{
return pivotRow;
}
/*
Check for case of unbounded solutions
The situation occurs when the coefficient for the denominator of
the intercept ratios are either zero or negative.
Returns true or false true indicating the unbounded solution
*/
bool Simplex::hasUnboundedSolutions()
{
ColVectorXd pivotColumn = tableau.block(1, pivotCol-1, M, 1);
bool result = true;
if ((pivotColumn.array() > (-std::numeric_limits<double>::epsilon())).all()) {
result = false;
}
return result;
}
/*
Check for case of Multiple optimal solution / Alternative optimal solutions
When zero appears in the column of a nonbasic variable in the
z-row of the optimal tableau
iReturns true or false true indicating the unbounded solution
*/
bool Simplex::hasMultipleOptimalSolutions() {
int *nonBasic = new int[M+N];
RowVectorXd zRow = this->tableau.block(0, 1, 1, N+M);
for (int i=0; i<M+N; i++) {
nonBasic[i] = 0;
}
for (int i=0; i<M; i++) {
nonBasic[xB[i]-1] = 1;
}
for (int i=0; i<M+N; i++) {
if (nonBasic[i] == 0) {
if (zRow(i) == 0) {
return true;
}
}
}
delete [] nonBasic;
return false;
}
/*
gets N
*/
long int Simplex::getN() {
return this->N;
}
/*
gets M
*/
long int Simplex::getM() {
return this->M;
}
/*
get tableau size
*/
long int Simplex::getTableuCols() {
return tableau.cols();
}
/*
get tableau size
*/
long int Simplex::getTableuRows() {
return tableau.rows();
}
/*
Destructor
*/
Simplex::~Simplex()
{
delete[] xB;
}
<commit_msg>corrected spelling<commit_after>#include "Simplex.h"
#include <iostream>
#include <cmath>
/*
Simplex problem constructor
This takes the one dimensional arrays:
A - the LHS variable coefficient matrix of the constraints,
c - the row vector for the coeffients of the variables,
b - the column vector for the RHS
It generates a simplex tableau by mapping the values accordingly
and calling initTableau to create the simplex tableau.
Array x stores the nature of the variables such that a value of:
-1 - corresponds to x>=0
0 - means x is unrestricted
+1 - means x<=0
m is number of constraints
n is number of variables
*/
Simplex::Simplex(long int m, long int n, double A[], double c[], double b[], int x[], bool natureOfProblem)
{
this->natureOfProblem = natureOfProblem;
if (natureOfProblem == maximization) {
int colSize = n; // size of the matrix A column
int rowSize = m; // size of the matrix A row
// to create a modified version of A and c, we calculate the size
// of the new modified A and c. Only the column size will change
// depending on the nature of the variables
for (int i = 0; i<m; i++) {
if (x[i] == 0) n++;
}
this->M = m;
this->N = n;
double* modifiedA = new double[m*n];
double* modifiedC = new double[n];
int col = 0;
for (int i=0; i<colSize; i++) {
for (int j=0; j<rowSize; j++) {
int idx = i*m+j;
int idxMA = col*m+j;
if (x[i] ==-1) {
modifiedA[idxMA] = -(A[idx]);
modifiedC[col] = -(c[i]);
}
if (x[i] == 0) {
modifiedA[idxMA] = +(A[idx]);
modifiedA[idxMA+m] = -(A[idx]);
modifiedC[col] = +(c[i]);
modifiedC[col+1] = -(c[i]);
}
if (x[i] == 1) {
modifiedA[idxMA] = +(A[idx]);
modifiedC[col] = +(c[i]);
}
}
if (x[i] == 0) col+=2;
else col++;
}
this->A = Map<MatrixXd>(modifiedA, m, n);
this->cT = Map<RowVectorXd>(modifiedC, n);
this->b = Map<ColVectorXd>(b, m);
// laundry work!
delete[] modifiedA;
delete[] modifiedC;
}
if (natureOfProblem == minimization) {
// create a temporary matrix
MatrixXd temp(m+1, n+1);
double* modifiedA = new double[m*n];
double* modifiedC = new double[n];
int col = 0;
int colSize = n; // size of the matrix A column
int rowSize = m; // size of the matrix A row
for (int i=0; i<colSize; i++) {
for (int j=0; j<rowSize; j++) {
int idx = i*m+j;
int idxMA = col*m+j;
if (x[i] ==-1) {
modifiedA[idxMA] = -(A[idx]);
modifiedC[col] = -(c[i]);
}
if (x[i] == 0) {
modifiedA[idxMA] = +(A[idx]);
modifiedA[idxMA+m] = -(A[idx]);
modifiedC[col] = +(c[i]);
modifiedC[col+1] = -(c[i]);
}
if (x[i] == 1) {
modifiedA[idxMA] = +(A[idx]);
modifiedC[col] = +(c[i]);
}
}
if (x[i] == 0) col+=2;
else col++;
}
temp.block(0, 0, m, n) = Map<MatrixXd>(modifiedA, m, n);
temp.block(m, 0, 1, n) = Map<RowVectorXd>(modifiedC, n);
temp.block(0, n, m, 1) = Map<ColVectorXd>(b, m);
temp(m, n) = 0;
MatrixXd tempTransposed = temp.transpose();
double* tempA = new double[m*n];
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
tempA[j*n+i] = tempTransposed(i,j);
}
std::cout << '\n';
}
double* tempb = new double[n];
for (int i=0; i<n; i++) {
tempb[i] = tempTransposed(i, m);
}
double* tempc = new double[m];
for (int i=0; i<m; i++) {
tempc[i] = tempTransposed(n, i);
}
this->M = n;
this->N = m;
this->A = Map<MatrixXd>(tempA, n, m);
this->cT = Map<RowVectorXd>(tempc, m);
this->b = Map<ColVectorXd>(tempb, n);
// laundry work!
delete[] modifiedA;
delete[] modifiedC;
delete[] tempA;
delete[] tempb;
delete[] tempc;
}
initTableau();
}
/*
Generate initial tableau for basic feasible solution
*/
void Simplex::initTableau()
{
this->tableau.resize(M+1, M+N+2);
this->tableau(0, 0) = 1;
this->tableau.block(0, 1, 1, N) = (this->cT.array() * -1);
this->tableau.block(0, N+1, 1, M) = RowVectorXd::Zero(M);
this->tableau(0, N+1) = 0;
this->tableau.block(1, 0, M, 1) = ColVectorXd::Zero(M);
this->tableau.block(1, 1, M, N) = this->A;
this->tableau.block(1, N+1, M, M) = MatrixXd::Identity(M, M);
this->tableau.block(1,M+N+1,M, 1) = this->b;
// initialize xB which holds the basic variable column number
xB = new int[M];
cBt.resize(M);
for (int i = 0; i<M; i++) {
xB[i] = i+N+1;
cBt[i] = tableau.row(0)[xB[i]];
}
// creating the B matrix which is the initial basic matrix
B = tableau.block(1, N+1, M, M);
// set pivot
setPivot();
}
/*
Set the pivot location
*/
void Simplex::setPivot()
{
double min = tableau(0, 1);
for (int i=1; i<=N; i++) {
if (tableau(0, i) <= min) {
min = tableau(0, i);
pivotCol = i;
}
}
ColVectorXd solution = tableau.block(1, M+N+1, M, 1);
ColVectorXd pivotColumn = tableau.block(1, pivotCol, M, 1);
ArrayXd ratio = solution.array() / pivotColumn.array();
min = ratio(0);
pivotRow = 0;
for (int i=0; i<M; i++) {
if (ratio(i) <= min) {
min = ratio(i);
pivotRow = i+1;
}
}
}
/*
Calculate the next iteration
It returns true if the there is a next iteration and false if the Simplex
problem is solved
*/
bool Simplex::nextIteration()
{
setPivot();
xB[pivotRow-1] = pivotCol;
cBt[pivotRow-1] = cT[pivotCol-1];
B.col(pivotRow-1) = A.col(pivotCol-1);
MatrixXd Binv = B.inverse();
tableau.block(0, 1, 1, N) = ( (cBt * Binv * A) - cT );
tableau.block(1, 1, M, N) = ( Binv * A );
tableau.block(0, N+1, 1, M) = ( cBt * Binv );
tableau.block(1, N+1, M, M) = ( Binv );
tableau(0, M+N+1) = ( cBt * Binv * b );
tableau.block(1, M+N+1, M, 1) = ( Binv * b );
if (isOptimal())
return false;
return true;
}
/*
Get the Simplex tableau
Returns a matrix object(from eigen implementaion) with the simplex tableau
*/
MatrixXd Simplex::getTableau()
{
return tableau;
}
/*
Get the values of xB
Returns a copy of the basic variables
*/
int* Simplex::getXB()
{
// copy the contents of 'xB' in new 'x' to protect memory from being exposed
// in the outside environment
int* x = new int[M];
for (int i=0; i<M; i++)
x[i] = xB[i];
return x;
}
/*
Get the current cBt matrix
Returns a Matrix instance that contains the values of cBt
*/
MatrixXd Simplex::getCBt()
{
return cBt;
}
/*
Get the current B matrix
Returns a Matrix instance with values B
*/
MatrixXd Simplex::getB()
{
return B;
}
/*
Optimality check
Returns true if the matrix is optimal
*/
bool Simplex::isOptimal()
{
bool result = true;
RowVectorXd temp = tableau.block(0, 1, 1, N);
int *nonBasic = new int[N];
RowVectorXd zRow = this->tableau.block(0, 1, 1, N);
for (int i=0; i<M+N; i++) {
nonBasic[i] = 0;
}
for (int i=0; i<M; i++) {
nonBasic[xB[i]-1] = 1;
}
for (int i=0; i<N; i++) {
if (nonBasic[i] == 0) {
if (zRow(i) > 0) {
result &= true;
} else {
result &= false;
}
}
std::cout << nonBasic[i] << ", " << std::endl;
if (nonBasic[i] == 1) {
if (zRow(i) == 0) {
result &= true;
} else {
result &= false;
}
}
}
/*
for (int i =0; i<N; i++) {
if (!(std::signbit(temp[i]) == 0)) {
return false;
}
}
return true;
*/
return result;
}
/*
Get the pivot column
Returns the value of pivot column corresponding to the simplex tableaux
*/
int Simplex::getPivotCol()
{
return pivotCol;
}
/*
Get the pivot row
Returns the value of pivot row corresponding to the simplex tableaux
*/
int Simplex::getPivotRow()
{
return pivotRow;
}
/*
Check for case of unbounded solutions
The situation occurs when the coefficient for the denominator of
the intercept ratios are either zero or negative.
Returns true or false true indicating the unbounded solution
*/
bool Simplex::hasUnboundedSolutions()
{
ColVectorXd pivotColumn = tableau.block(1, pivotCol-1, M, 1);
bool result = true;
if ((pivotColumn.array() > (-std::numeric_limits<double>::epsilon())).all()) {
result = false;
}
return result;
}
/*
Check for case of Multiple optimal solution / Alternative optimal solutions
When zero appears in the column of a nonbasic variable in the
z-row of the optimal tableau
iReturns true or false true indicating the unbounded solution
*/
bool Simplex::hasMultipleOptimalSolutions() {
int *nonBasic = new int[M+N];
RowVectorXd zRow = this->tableau.block(0, 1, 1, N+M);
for (int i=0; i<M+N; i++) {
nonBasic[i] = 0;
}
for (int i=0; i<M; i++) {
nonBasic[xB[i]-1] = 1;
}
for (int i=0; i<M+N; i++) {
if (nonBasic[i] == 0) {
if (zRow(i) == 0) {
return true;
}
}
}
delete [] nonBasic;
return false;
}
/*
gets N
*/
long int Simplex::getN() {
return this->N;
}
/*
gets M
*/
long int Simplex::getM() {
return this->M;
}
/*
get tableau size
*/
long int Simplex::getTableauCols() {
return tableau.cols();
}
/*
get tableau size
*/
long int Simplex::getTableauRows() {
return tableau.rows();
}
/*
Destructor
*/
Simplex::~Simplex()
{
delete[] xB;
}
<|endoftext|>
|
<commit_before>/* SbHalfPong, sort of like Pong but for one
author: Ulrike Hager
*/
#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>
#include <climits>
#include <cmath>
#include <random>
#include <algorithm>
#include <functional>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_image.h>
#include "SbTexture.h"
#include "SbTimer.h"
#include "SbWindow.h"
#include "SbObject.h"
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
class Ball;
class Spark;
class Paddle;
class Paddle : public SbObject
{
public:
Paddle();
void handle_event(const SDL_Event& event);
int move();
};
class Ball : public SbObject
{
public:
Ball();
// void handle_event(const SDL_Event& event);
/*! \retval 1 if ball in goal
\retval 0 else
*/
int move(const SDL_Rect& paddleBox);
void render();
/*! Reset after goal.
*/
void reset();
static Uint32 resetball(Uint32 interval, void *param );
Uint32 remove_spark(Uint32 interval, void *param, int index );
private:
int goal_ = 0;
std::vector<Spark> sparks_;
std::default_random_engine generator_;
std::uniform_int_distribution<int> distr_number { 15, 30 };
std::normal_distribution<double> distr_position { 0.0, 0.01 };
std::normal_distribution<double> distr_size { 0.003, 0.002 };
std::uniform_int_distribution<int> distr_lifetime { 100, 400 };
void create_sparks();
void center_in_front(const SDL_Rect& paddleBox);
void delete_spark(int index);
};
class Spark : public SbObject
{
friend class Ball;
public:
Spark(double x, double y, double width, double height);
~Spark();
static Uint32 expire(Uint32 interval, void* param);
void set_texture(SbTexture* tex) {texture_ = tex;}
int index() { return index_;}
bool is_dead() {return is_dead_;}
Uint32 lifetime() { return lifetime_;}
private:
// SDL_TimerID spark_timer_;
int index_ = 0;
bool is_dead_ = false;
Uint32 lifetime_ = 100;
};
class Message : public SbObject
{
public:
Message(double x, double y, double width, double height);
~Message();
void set_font(TTF_Font* font){ font_ = font;}
void set_text(std::string text);
private:
TTF_Font* font_ = nullptr;
SDL_Color color_{210, 160, 10, 0};
};
/*! Paddle implementation
*/
Paddle::Paddle()
: SbObject(SCREEN_WIDTH - 70, 200, 20, 80)
{
// bounding_rect_ = {};
velocity_y_ = 0;
velocity_ = 1200;
SDL_Color color = {210, 160, 10, 0};
texture_ = new SbTexture();
texture_->from_rectangle( window->renderer(), bounding_rect_.w, bounding_rect_.h, color );
}
void
Paddle::handle_event(const SDL_Event& event)
{
SbObject::handle_event( event );
if( event.type == SDL_KEYDOWN && event.key.repeat == 0 ) {
switch( event.key.keysym.sym ) {
case SDLK_UP: velocity_y_ -= velocity_; break;
case SDLK_DOWN: velocity_y_ += velocity_; break;
}
}
else if( event.type == SDL_KEYUP && event.key.repeat == 0 ) {
switch( event.key.keysym.sym ) {
case SDLK_UP: velocity_y_ += velocity_; break;
case SDLK_DOWN: velocity_y_ -= velocity_; break;
}
}
}
int
Paddle::move()
{
Uint32 deltaT = timer_.get_time();
int velocity = ( window->height() / velocity_y_ )* deltaT;
bounding_rect_.y += velocity;
if( ( bounding_rect_.y < 0 ) || ( bounding_rect_.y + bounding_rect_.h > window->height() ) ) {
bounding_rect_.y -= velocity;
}
move_bounding_box();
timer_.start();
return 0;
}
Spark::Spark(double x, double y, double width, double height)
: SbObject(x,y,width,height)
{
}
Spark::~Spark()
{
#ifdef DEBUG
std::cout << "[Spark::~Spark] index " << index_ << " - lifetime " << lifetime_ << std::endl;
#endif // DEBUG
texture_ = nullptr;
// SDL_RemoveTimer(spark_timer_);
}
Uint32
Spark::expire(Uint32 interval, void* param)
{
#ifdef DEBUG
std::cout << "[Spark::expire] interval " << interval << std::flush;
#endif // DEBUG
Spark* spark = ((Spark*)param);
#ifdef DEBUG
std::cout << "[Spark::expire] index " << spark->index_ << std::endl;
#endif // DEBUG
if (spark) spark->is_dead_ = true;
return(0);
}
/*! Ball implementation
*/
Ball::Ball()
: SbObject(50, 300, 25, 25)
{
// bounding_box_ = {};
velocity_y_ = 1500;
velocity_x_ = 1500;
velocity_ = 1500;
texture_ = new SbTexture();
texture_->from_file(window->renderer(), "resources/ball.png", bounding_rect_.w, bounding_rect_.h );
}
void
Ball::center_in_front(const SDL_Rect& paddleBox)
{
bounding_rect_.x = paddleBox.x - bounding_rect_.w - 2;
bounding_rect_.y = paddleBox.y + paddleBox.h / 2 - bounding_rect_.h/2 ;
move_bounding_box();
}
void
Ball::create_sparks()
{
#ifdef DEBUG
std::cout << "[Ball::create_sparks]" << std::endl;
#endif // DEBUG
if (! sparks_.empty() ) {
sparks_.clear();
}
int n_sparks = distr_number(generator_);
for ( int i = 0 ; i < n_sparks ; ++i ) {
double x = distr_position(generator_);
double y = distr_position(generator_);
double d = distr_size(generator_);
x += ( bounding_box_[0] + bounding_box_[2]/2);
y += ( bounding_box_[1] + bounding_box_[3]/2);
Spark toAdd(x, y, d, d);
toAdd.index_ = i;
toAdd.set_texture( texture_ );
toAdd.lifetime_ = Uint32(distr_lifetime(generator_));
toAdd.timer_.start();
sparks_.push_back(toAdd);
#ifdef DEBUG
std::cout << "[Ball::create_sparks] index " << i << " - lifetime " << (sparks_.back()).lifetime() << std::endl;
#endif // DEBUG
// std::function<Uint32(Uint32,void*)> funct = std::bind(&Ball::remove_spark, this, std::placeholders::_1, std::placeholders::_2, toAdd.index_ );
// sparks_.back().spark_timer_ = SDL_AddTimer(lifetime, Spark::expire, &sparks_.back());
}
}
void
Ball::delete_spark(int index)
{
std::remove_if( sparks_.begin(), sparks_.end(),
[index](Spark& spark) -> bool { return spark.index() == index;} );
// ((Spark*)param)->set_texture( nullptr );
}
int
Ball::move(const SDL_Rect& paddleBox)
{
if ( goal_ ) {
center_in_front(paddleBox);
return 0;
}
Uint32 deltaT = timer_.get_time();
int x_velocity = ( window->width() / velocity_x_ ) * deltaT;
int y_velocity = ( window->height() / velocity_y_ ) * deltaT;
bounding_rect_.y += y_velocity;
bounding_rect_.x += x_velocity;
if ( bounding_rect_.x + bounding_rect_.w >= window->width() ) {
goal_ = 1;
center_in_front(paddleBox);
return goal_;
}
bool in_xrange = false, in_yrange = false, x_hit = false, y_hit = false ;
if ( bounding_rect_.x + bounding_rect_.w/2 >= paddleBox.x &&
bounding_rect_.x + bounding_rect_.w/2 <= paddleBox.x + paddleBox.w )
in_xrange = true;
if ( bounding_rect_.y + bounding_rect_.h/2 >= paddleBox.y &&
bounding_rect_.y + bounding_rect_.h/2 <= paddleBox.y + paddleBox.h)
in_yrange = true;
if ( bounding_rect_.x + bounding_rect_.w >= paddleBox.x &&
bounding_rect_.x <= paddleBox.x + paddleBox.w )
x_hit = true;
if ( bounding_rect_.y + bounding_rect_.h >= paddleBox.y &&
bounding_rect_.y <= paddleBox.y + paddleBox.h )
y_hit = true;
if ( ( x_hit && in_yrange ) || bounding_rect_.x <= 0 ) {
velocity_x_ *= -1;
if ( x_hit && in_yrange )
create_sparks();
}
if ( ( y_hit && in_xrange ) || bounding_rect_.y <= 0 || ( bounding_rect_.y + bounding_rect_.h >= window->height() ) )
velocity_y_ *= -1;
move_bounding_box();
timer_.start();
return goal_;
}
Uint32
Ball::remove_spark(Uint32 interval, void *param, int index )
{
((Ball*)param)->delete_spark(index);
return(0);
}
void
Ball::render()
{
SbObject::render();
if ( sparks_.empty() )
return;
// std::for_each( sparks_.begin(), sparks_.end(),
// [](Spark& spark) -> void { if ( !spark.is_dead() ) spark.render(); } );
auto iter = sparks_.begin();
while ( iter != sparks_.end() ) {
if ( iter->time() > iter->lifetime() ){
iter = sparks_.erase(iter);
}
else {
iter->render();
++iter;
}
}
}
void
Ball::reset()
{
goal_ = 0;
if ( velocity_x_ > 0 ) velocity_x_ *= -1;
timer_.start();
}
Uint32
Ball::resetball(Uint32 interval, void *param )
{
((Ball*)param)->reset();
return(0);
}
Message::Message(double x, double y, double width, double height)
: SbObject(x,y,width,height)
{
}
void
Message::set_text(std::string message)
{
if ( !font_)
throw std::runtime_error( "[Message::set_text] no font. Call set_font before setting the text." );
texture_->from_text( window->renderer(), message, font_, color_);
}
Message::~Message()
{
font_ = nullptr;
}
SbWindow* SbObject::window;
TTF_Font *fps_font = nullptr;
int main()
{
try {
SbWindow window;
window.initialize("Half-Pong", SCREEN_WIDTH, SCREEN_HEIGHT);
SbObject::window = &window ;
Paddle paddle;
Ball ball;
fps_font = TTF_OpenFont( "resources/FreeSans.ttf", 120 );
if ( !fps_font )
throw std::runtime_error( "TTF_OpenFont: " + std::string( TTF_GetError() ) );
Message fps_counter(0,0,0.07,0.035);
Message goals(0.2,0.003,0.07,0.09);
Message game_over(0.4,0.6,0.3,0.2);
fps_counter.set_font(fps_font);
goals.set_font(fps_font);
game_over.set_font(fps_font);
game_over.set_text("Game Over");
// SbTexture *fps_texture = new SbTexture();
// SDL_Color fps_color = {210, 160, 10, 0};
SbTimer fps_timer;
int goal_counter = 3;
goals.set_text( std::to_string(goal_counter) );
SDL_TimerID reset_timer = 0;
SDL_Event event;
bool quit = false;
int frame_counter = 0;
fps_timer.start();
while (!quit) {
while( SDL_PollEvent( &event ) ) {
if (event.type == SDL_QUIT) quit = true;
else if (event.type == SDL_KEYDOWN ) {
switch ( event.key.keysym.sym ) {
case SDLK_ESCAPE:
quit = true;
break;
case SDLK_n:
goal_counter = 3;
ball.reset();
goals.set_text( std::to_string(goal_counter) );
break;
}
}
window.handle_event(event);
paddle.handle_event(event);
ball.handle_event( event );
fps_counter.handle_event( event );
goals.handle_event( event );
}
// move objects
if ( goal_counter > 0 ) {
paddle.move();
#ifdef DEBUG
std::cout << "Paddle moved: " << std::flush;
paddle.print_dimensions(std::cout);
std::cout << std::endl;
#endif // DEBUG
int goal = ball.move( paddle.bounding_rect() );
#ifdef DEBUG
std::cout << "Ball moved: " << std::flush;
ball.print_dimensions(std::cout);
std::cout << std::endl;
#endif // DEBUG
if ( goal ) {
reset_timer = SDL_AddTimer(1000, Ball::resetball, &ball);
--goal_counter;
goals.set_text( std::to_string(goal_counter) );
}
}
// fps counter
if ( frame_counter > 0 && frame_counter < 1000 /*INT_MAX*/ ) {
double average = double(frame_counter)/ ( fps_timer.get_time()/1000.0 ) ;
std::string fps_text = std::to_string(int(average)) + " fps";
fps_counter.set_text( fps_text );
}
else {
frame_counter = 0;
fps_timer.start();
}
// render
SDL_RenderClear( window.renderer() );
if ( goal_counter == 0 ) {
game_over.render();
}
paddle.render();
ball.render();
fps_counter.render();
goals.render();
SDL_RenderPresent( window.renderer() );
++frame_counter;
}
}
catch (const std::exception& expt) {
std::cerr << expt.what() << std::endl;
}
return 0;
}
<commit_msg>Game over message now scales. Also return and space for new game.<commit_after>/* SbHalfPong, sort of like Pong but for one
author: Ulrike Hager
*/
#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>
#include <climits>
#include <cmath>
#include <random>
#include <algorithm>
#include <functional>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_image.h>
#include "SbTexture.h"
#include "SbTimer.h"
#include "SbWindow.h"
#include "SbObject.h"
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
class Ball;
class Spark;
class Paddle;
class Paddle : public SbObject
{
public:
Paddle();
void handle_event(const SDL_Event& event);
int move();
};
class Ball : public SbObject
{
public:
Ball();
// void handle_event(const SDL_Event& event);
/*! \retval 1 if ball in goal
\retval 0 else
*/
int move(const SDL_Rect& paddleBox);
void render();
/*! Reset after goal.
*/
void reset();
static Uint32 resetball(Uint32 interval, void *param );
Uint32 remove_spark(Uint32 interval, void *param, int index );
private:
int goal_ = 0;
std::vector<Spark> sparks_;
std::default_random_engine generator_;
std::uniform_int_distribution<int> distr_number { 15, 30 };
std::normal_distribution<double> distr_position { 0.0, 0.01 };
std::normal_distribution<double> distr_size { 0.003, 0.002 };
std::uniform_int_distribution<int> distr_lifetime { 100, 400 };
void create_sparks();
void center_in_front(const SDL_Rect& paddleBox);
void delete_spark(int index);
};
class Spark : public SbObject
{
friend class Ball;
public:
Spark(double x, double y, double width, double height);
~Spark();
static Uint32 expire(Uint32 interval, void* param);
void set_texture(SbTexture* tex) {texture_ = tex;}
int index() { return index_;}
bool is_dead() {return is_dead_;}
Uint32 lifetime() { return lifetime_;}
private:
// SDL_TimerID spark_timer_;
int index_ = 0;
bool is_dead_ = false;
Uint32 lifetime_ = 100;
};
class Message : public SbObject
{
public:
Message(double x, double y, double width, double height);
~Message();
void set_font(TTF_Font* font){ font_ = font;}
void set_text(std::string text);
private:
TTF_Font* font_ = nullptr;
SDL_Color color_{210, 160, 10, 0};
};
/*! Paddle implementation
*/
Paddle::Paddle()
: SbObject(SCREEN_WIDTH - 70, 200, 20, 80)
{
// bounding_rect_ = {};
velocity_y_ = 0;
velocity_ = 1200;
SDL_Color color = {210, 160, 10, 0};
texture_ = new SbTexture();
texture_->from_rectangle( window->renderer(), bounding_rect_.w, bounding_rect_.h, color );
}
void
Paddle::handle_event(const SDL_Event& event)
{
SbObject::handle_event( event );
if( event.type == SDL_KEYDOWN && event.key.repeat == 0 ) {
switch( event.key.keysym.sym ) {
case SDLK_UP: velocity_y_ -= velocity_; break;
case SDLK_DOWN: velocity_y_ += velocity_; break;
}
}
else if( event.type == SDL_KEYUP && event.key.repeat == 0 ) {
switch( event.key.keysym.sym ) {
case SDLK_UP: velocity_y_ += velocity_; break;
case SDLK_DOWN: velocity_y_ -= velocity_; break;
}
}
}
int
Paddle::move()
{
Uint32 deltaT = timer_.get_time();
int velocity = ( window->height() / velocity_y_ )* deltaT;
bounding_rect_.y += velocity;
if( ( bounding_rect_.y < 0 ) || ( bounding_rect_.y + bounding_rect_.h > window->height() ) ) {
bounding_rect_.y -= velocity;
}
move_bounding_box();
timer_.start();
return 0;
}
Spark::Spark(double x, double y, double width, double height)
: SbObject(x,y,width,height)
{
}
Spark::~Spark()
{
#ifdef DEBUG
std::cout << "[Spark::~Spark] index " << index_ << " - lifetime " << lifetime_ << std::endl;
#endif // DEBUG
texture_ = nullptr;
// SDL_RemoveTimer(spark_timer_);
}
Uint32
Spark::expire(Uint32 interval, void* param)
{
#ifdef DEBUG
std::cout << "[Spark::expire] interval " << interval << std::flush;
#endif // DEBUG
Spark* spark = ((Spark*)param);
#ifdef DEBUG
std::cout << "[Spark::expire] index " << spark->index_ << std::endl;
#endif // DEBUG
if (spark) spark->is_dead_ = true;
return(0);
}
/*! Ball implementation
*/
Ball::Ball()
: SbObject(50, 300, 25, 25)
{
// bounding_box_ = {};
velocity_y_ = 1500;
velocity_x_ = 1500;
velocity_ = 1500;
texture_ = new SbTexture();
texture_->from_file(window->renderer(), "resources/ball.png", bounding_rect_.w, bounding_rect_.h );
}
void
Ball::center_in_front(const SDL_Rect& paddleBox)
{
bounding_rect_.x = paddleBox.x - bounding_rect_.w - 2;
bounding_rect_.y = paddleBox.y + paddleBox.h / 2 - bounding_rect_.h/2 ;
move_bounding_box();
}
void
Ball::create_sparks()
{
#ifdef DEBUG
std::cout << "[Ball::create_sparks]" << std::endl;
#endif // DEBUG
if (! sparks_.empty() ) {
sparks_.clear();
}
int n_sparks = distr_number(generator_);
for ( int i = 0 ; i < n_sparks ; ++i ) {
double x = distr_position(generator_);
double y = distr_position(generator_);
double d = distr_size(generator_);
x += ( bounding_box_[0] + bounding_box_[2]/2);
y += ( bounding_box_[1] + bounding_box_[3]/2);
Spark toAdd(x, y, d, d);
toAdd.index_ = i;
toAdd.set_texture( texture_ );
toAdd.lifetime_ = Uint32(distr_lifetime(generator_));
toAdd.timer_.start();
sparks_.push_back(toAdd);
#ifdef DEBUG
std::cout << "[Ball::create_sparks] index " << i << " - lifetime " << (sparks_.back()).lifetime() << std::endl;
#endif // DEBUG
// std::function<Uint32(Uint32,void*)> funct = std::bind(&Ball::remove_spark, this, std::placeholders::_1, std::placeholders::_2, toAdd.index_ );
// sparks_.back().spark_timer_ = SDL_AddTimer(lifetime, Spark::expire, &sparks_.back());
}
}
void
Ball::delete_spark(int index)
{
std::remove_if( sparks_.begin(), sparks_.end(),
[index](Spark& spark) -> bool { return spark.index() == index;} );
// ((Spark*)param)->set_texture( nullptr );
}
int
Ball::move(const SDL_Rect& paddleBox)
{
if ( goal_ ) {
center_in_front(paddleBox);
return 0;
}
Uint32 deltaT = timer_.get_time();
int x_velocity = ( window->width() / velocity_x_ ) * deltaT;
int y_velocity = ( window->height() / velocity_y_ ) * deltaT;
bounding_rect_.y += y_velocity;
bounding_rect_.x += x_velocity;
if ( bounding_rect_.x + bounding_rect_.w >= window->width() ) {
goal_ = 1;
center_in_front(paddleBox);
return goal_;
}
bool in_xrange = false, in_yrange = false, x_hit = false, y_hit = false ;
if ( bounding_rect_.x + bounding_rect_.w/2 >= paddleBox.x &&
bounding_rect_.x + bounding_rect_.w/2 <= paddleBox.x + paddleBox.w )
in_xrange = true;
if ( bounding_rect_.y + bounding_rect_.h/2 >= paddleBox.y &&
bounding_rect_.y + bounding_rect_.h/2 <= paddleBox.y + paddleBox.h)
in_yrange = true;
if ( bounding_rect_.x + bounding_rect_.w >= paddleBox.x &&
bounding_rect_.x <= paddleBox.x + paddleBox.w )
x_hit = true;
if ( bounding_rect_.y + bounding_rect_.h >= paddleBox.y &&
bounding_rect_.y <= paddleBox.y + paddleBox.h )
y_hit = true;
if ( ( x_hit && in_yrange ) || bounding_rect_.x <= 0 ) {
velocity_x_ *= -1;
if ( x_hit && in_yrange )
create_sparks();
}
if ( ( y_hit && in_xrange ) || bounding_rect_.y <= 0 || ( bounding_rect_.y + bounding_rect_.h >= window->height() ) )
velocity_y_ *= -1;
move_bounding_box();
timer_.start();
return goal_;
}
Uint32
Ball::remove_spark(Uint32 interval, void *param, int index )
{
((Ball*)param)->delete_spark(index);
return(0);
}
void
Ball::render()
{
SbObject::render();
if ( sparks_.empty() )
return;
// std::for_each( sparks_.begin(), sparks_.end(),
// [](Spark& spark) -> void { if ( !spark.is_dead() ) spark.render(); } );
auto iter = sparks_.begin();
while ( iter != sparks_.end() ) {
if ( iter->time() > iter->lifetime() ){
iter = sparks_.erase(iter);
}
else {
iter->render();
++iter;
}
}
}
void
Ball::reset()
{
goal_ = 0;
if ( velocity_x_ > 0 ) velocity_x_ *= -1;
timer_.start();
}
Uint32
Ball::resetball(Uint32 interval, void *param )
{
((Ball*)param)->reset();
return(0);
}
Message::Message(double x, double y, double width, double height)
: SbObject(x,y,width,height)
{
}
void
Message::set_text(std::string message)
{
if ( !font_)
throw std::runtime_error( "[Message::set_text] no font. Call set_font before setting the text." );
texture_->from_text( window->renderer(), message, font_, color_);
}
Message::~Message()
{
font_ = nullptr;
}
SbWindow* SbObject::window;
TTF_Font *fps_font = nullptr;
int main()
{
try {
SbWindow window;
window.initialize("Half-Pong", SCREEN_WIDTH, SCREEN_HEIGHT);
SbObject::window = &window ;
Paddle paddle;
Ball ball;
fps_font = TTF_OpenFont( "resources/FreeSans.ttf", 120 );
if ( !fps_font )
throw std::runtime_error( "TTF_OpenFont: " + std::string( TTF_GetError() ) );
Message fps_counter(0,0,0.07,0.035);
Message goals(0.2,0.003,0.07,0.09);
Message game_over(0.4,0.6,0.3,0.2);
fps_counter.set_font(fps_font);
goals.set_font(fps_font);
game_over.set_font(fps_font);
game_over.set_text("Game Over");
// SbTexture *fps_texture = new SbTexture();
// SDL_Color fps_color = {210, 160, 10, 0};
SbTimer fps_timer;
int goal_counter = 3;
goals.set_text( std::to_string(goal_counter) );
SDL_TimerID reset_timer = 0;
SDL_Event event;
bool quit = false;
int frame_counter = 0;
fps_timer.start();
while (!quit) {
while( SDL_PollEvent( &event ) ) {
if (event.type == SDL_QUIT) quit = true;
else if (event.type == SDL_KEYDOWN ) {
switch ( event.key.keysym.sym ) {
case SDLK_ESCAPE:
quit = true;
break;
case SDLK_n: case SDLK_SPACE: case SDLK_RETURN:
goal_counter = 3;
ball.reset();
goals.set_text( std::to_string(goal_counter) );
break;
}
}
window.handle_event(event);
paddle.handle_event(event);
ball.handle_event( event );
fps_counter.handle_event( event );
goals.handle_event( event );
game_over.handle_event( event );
}
// move objects
if ( goal_counter > 0 ) {
paddle.move();
int goal = ball.move( paddle.bounding_rect() );
if ( goal ) {
reset_timer = SDL_AddTimer(1000, Ball::resetball, &ball);
--goal_counter;
goals.set_text( std::to_string(goal_counter) );
}
}
// fps counter
if ( frame_counter > 0 && frame_counter < 1000 /*INT_MAX*/ ) {
double average = double(frame_counter)/ ( fps_timer.get_time()/1000.0 ) ;
std::string fps_text = std::to_string(int(average)) + " fps";
fps_counter.set_text( fps_text );
}
else {
frame_counter = 0;
fps_timer.start();
}
// render
SDL_RenderClear( window.renderer() );
if ( goal_counter == 0 ) {
game_over.render();
}
paddle.render();
ball.render();
fps_counter.render();
goals.render();
SDL_RenderPresent( window.renderer() );
++frame_counter;
}
}
catch (const std::exception& expt) {
std::cerr << expt.what() << std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <unordered_map>
#include <string>
namespace slea {
class INI {
public:
/**
* \brief The internal map used to store categories and entries.
*/
std::unordered_map<std::string, std::unordered_map<std::string, std::string>> map;
INI();
/**
* \param path The path to the ini file to read from.
*/
INI(const std::string& path);
/**
* \brief Check if there are any entries.
*/
bool IsEmpty() const;
/**
* \brief Clears the internal map and reads an ini file into it.
*
* \param path The path to the ini file to read from.
*
* \return Nothing
*/
void Read(const std::string& path);
/**
* \brief Get key from an entry in the ini file.
*
* \param category The category in which the entry is located.
* \param name The name of the entry to get the key of.
*
* \return Value associated with the entry.
*/
const std::string& Get(const std::string& category, const std::string& name) const;
/**
* \brief Get key from an entry in the ini file.
*
* \param name The name of the entry to get the key of.
*
* \return Value associated with the entry.
*
* \note Looks for entries without a category.
*/
const std::string& Get(const std::string& name) const;
operator bool() const;
};
}
<commit_msg>Added doxyfile<commit_after>#pragma once
#include <unordered_map>
#include <string>
namespace slea {
class INI {
public:
/**
* \brief The internal map used to store categories and entries.
*/
std::unordered_map<std::string, std::unordered_map<std::string, std::string>> map;
/**
* \brief Construct new INI object.
*/
INI();
/**
* \brief Construct new INI object.
*
* \param path The path to the ini file to read from.
*/
INI(const std::string& path);
/**
* \brief Check if there are any entries.
*/
bool IsEmpty() const;
/**
* \brief Clears the internal map and reads an ini file into it.
*
* \param path The path to the ini file to read from.
*/
void Read(const std::string& path);
/**
* \brief Get key from an entry in the ini file.
*
* \param category The category in which the entry is located.
* \param name The name of the entry to get the key of.
*
* \return Value associated with the entry.
*/
const std::string& Get(const std::string& category, const std::string& name) const;
/**
* \brief Get key from an entry in the ini file.
*
* \param name The name of the entry to get the key of.
*
* \return Value associated with the entry.
*
* \note Looks for entries without a category, same as Get("", name).
*/
const std::string& Get(const std::string& name) const;
/**
* \brief Check if this INI object is valid.
*/
operator bool() const;
};
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2012 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2PixelFormat.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreBitwise.h"
namespace Ogre {
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLOriginFormat(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
return GL_ALPHA;
case PF_L8:
case PF_L16:
return GL_LUMINANCE;
#if GL_OES_texture_half_float
case PF_FLOAT16_RGB:
return GL_RGB;
case PF_FLOAT16_RGBA:
return GL_RGBA;
#endif
#if GL_EXT_texture_rg
case PF_FLOAT16_R:
case PF_R8:
return GL_RED_EXT;
case PF_FLOAT16_GR:
case PF_RG8:
return GL_RG_EXT;
#endif
case PF_BYTE_LA:
case PF_SHORT_GR:
return GL_LUMINANCE_ALPHA;
// PVRTC compressed formats
#if GL_IMG_texture_compression_pvrtc
case PF_PVRTC_RGB2:
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGB4:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case PF_PVRTC_RGBA2:
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGBA4:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif
case PF_R5G6B5:
case PF_B5G6R5:
case PF_R8G8B8:
case PF_B8G8R8:
return GL_RGB;
case PF_A1R5G5B5:
return GL_BGRA;
case PF_A4R4G4B4:
case PF_X8R8G8B8:
case PF_A8R8G8B8:
case PF_B8G8R8A8:
case PF_X8B8G8R8:
case PF_A8B8G8R8:
return GL_RGBA;
case PF_DXT1:
#if GL_EXT_texture_compression_dxt1
return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
#endif
case PF_DXT3:
#if GL_EXT_texture_compression_s3tc
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
case PF_DXT5:
#if GL_EXT_texture_compression_s3tc
return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
#endif
case PF_FLOAT32_GR:
case PF_FLOAT32_R:
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLOriginDataType(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
case PF_L8:
case PF_L16:
case PF_R8G8B8:
case PF_B8G8R8:
case PF_BYTE_LA:
return GL_UNSIGNED_BYTE;
case PF_R5G6B5:
case PF_B5G6R5:
return GL_UNSIGNED_SHORT_5_6_5;
case PF_A4R4G4B4:
return GL_UNSIGNED_SHORT_4_4_4_4;
case PF_A1R5G5B5:
return GL_UNSIGNED_SHORT_5_5_5_1;
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
case PF_X8B8G8R8:
case PF_A8B8G8R8:
return GL_UNSIGNED_INT_8_8_8_8_REV;
case PF_X8R8G8B8:
case PF_A8B8G8R8:
case PF_A8R8G8B8:
return GL_UNSIGNED_INT_8_8_8_8_REV;
case PF_B8G8R8A8:
return GL_UNSIGNED_BYTE;
case PF_R8G8B8A8:
return GL_UNSIGNED_BYTE;
#else
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_X8R8G8B8:
case PF_A8R8G8B8:
case PF_B8G8R8A8:
case PF_R8G8B8A8:
return GL_UNSIGNED_BYTE;
#endif
case PF_FLOAT16_R:
case PF_FLOAT16_GR:
case PF_FLOAT16_RGB:
case PF_FLOAT16_RGBA:
#if GL_OES_texture_half_float
return GL_HALF_FLOAT_OES;
#else
return 0;
#endif
#if GL_EXT_texture_rg
case PF_R8:
case PF_RG8:
return GL_UNSIGNED_BYTE;
#endif
case PF_FLOAT32_R:
case PF_FLOAT32_GR:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
return GL_FLOAT;
case PF_DXT1:
case PF_DXT3:
case PF_DXT5:
case PF_R3G3B2:
case PF_A2R10G10B10:
case PF_A2B10G10R10:
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
// TODO not supported
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)
{
switch (fmt)
{
case PF_L8:
case PF_L16:
return GL_LUMINANCE;
case PF_A8:
return GL_ALPHA;
case PF_BYTE_LA:
return GL_LUMINANCE_ALPHA;
#if GL_IMG_texture_compression_pvrtc
case PF_PVRTC_RGB2:
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGB4:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case PF_PVRTC_RGBA2:
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGBA4:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif
case PF_X8B8G8R8:
case PF_X8R8G8B8:
case PF_A8B8G8R8:
case PF_A8R8G8B8:
case PF_B8G8R8A8:
case PF_A1R5G5B5:
case PF_A4R4G4B4:
return GL_RGBA;
case PF_R5G6B5:
case PF_B5G6R5:
case PF_R8G8B8:
case PF_B8G8R8:
return GL_RGB;
case PF_A4L4:
case PF_R3G3B2:
case PF_A2R10G10B10:
case PF_A2B10G10R10:
case PF_FLOAT16_RGBA:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
case PF_DXT1:
#if GL_EXT_texture_compression_dxt1
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
#endif
case PF_DXT3:
#if GL_EXT_texture_compression_s3tc
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
case PF_DXT5:
#if GL_EXT_texture_compression_s3tc
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
#if GL_EXT_texture_rg
case PF_FLOAT16_R:
case PF_FLOAT32_R:
case PF_R8:
return GL_RED_EXT;
case PF_FLOAT16_GR:
case PF_FLOAT32_GR:
case PF_RG8:
return GL_RG_EXT;
#endif
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,
bool hwGamma)
{
GLenum format = getGLInternalFormat(mFormat, hwGamma);
if (format == GL_NONE)
{
if (hwGamma)
{
// TODO not supported
return 0;
}
else
{
return GL_RGBA;
}
}
else
{
return format;
}
}
//-----------------------------------------------------------------------------
PixelFormat GLES2PixelUtil::getClosestOGREFormat(GLenum fmt, GLenum dataType)
{
switch (fmt)
{
#if GL_IMG_texture_compression_pvrtc
case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
return PF_PVRTC_RGB2;
case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
return PF_PVRTC_RGBA2;
case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
return PF_PVRTC_RGB4;
case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
return PF_PVRTC_RGBA4;
#endif
case GL_LUMINANCE:
return PF_L8;
case GL_ALPHA:
return PF_A8;
case GL_LUMINANCE_ALPHA:
return PF_BYTE_LA;
case GL_RGB:
switch(dataType)
{
case GL_UNSIGNED_SHORT_5_6_5:
return PF_B5G6R5;
default:
return PF_R8G8B8;
};
case GL_RGBA:
switch(dataType)
{
case GL_UNSIGNED_SHORT_5_5_5_1:
return PF_A1R5G5B5;
case GL_UNSIGNED_SHORT_4_4_4_4:
return PF_A4R4G4B4;
default:
#if (OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS)
return PF_A8R8G8B8;
#else
return PF_A8B8G8R8;
#endif
}
#ifdef GL_BGRA
case GL_BGRA:
return PF_A8B8G8R8;
#endif
#if GL_EXT_texture_compression_dxt1
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return PF_DXT1;
#endif
#if GL_EXT_texture_compression_s3tc
case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
return PF_DXT3;
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
return PF_DXT5;
#endif
#if GL_EXT_texture_rg
case GL_R8_EXT:
return PF_R8;
case GL_RG8_EXT:
return PF_RG8;
#endif
default:
//TODO: not supported
return PF_A8R8G8B8;
};
}
//-----------------------------------------------------------------------------
size_t GLES2PixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,
PixelFormat format)
{
size_t count = 0;
if((width > 0) && (height > 0))
{
do {
if(width>1) width = width/2;
if(height>1) height = height/2;
if(depth>1) depth = depth/2;
/*
NOT needed, compressed formats will have mipmaps up to 1x1
if(PixelUtil::isValidExtent(width, height, depth, format))
count ++;
else
break;
*/
count ++;
} while(!(width == 1 && height == 1 && depth == 1));
}
return count;
}
//-----------------------------------------------------------------------------
size_t GLES2PixelUtil::optionalPO2(size_t value)
{
const RenderSystemCapabilities *caps =
Root::getSingleton().getRenderSystem()->getCapabilities();
if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))
{
return value;
}
else
{
return Bitwise::firstPO2From((uint32)value);
}
}
void GLES2PixelUtil::convertToGLformat(const PixelBox &src, const PixelBox &dst)
{
// Always need to convert PF_A4R4G4B4, GL expects the colors to be in the
// reverse order
if (dst.format == PF_A4R4G4B4)
{
// Convert PF_A4R4G4B4 -> PF_B4G4R4A4
// Reverse pixel order
uint16 *srcptr = static_cast<uint16*>(src.data)
+ (src.left + src.top * src.rowPitch + src.front * src.slicePitch);
uint16 *dstptr = static_cast<uint16*>(dst.data)
+ (dst.left + dst.top * dst.rowPitch + dst.front * dst.slicePitch);
const size_t srcSliceSkip = src.getSliceSkip();
const size_t dstSliceSkip = dst.getSliceSkip();
const size_t k = src.right - src.left;
for(size_t z=src.front; z<src.back; z++)
{
for(size_t y=src.top; y<src.bottom; y++)
{
for(size_t x=0; x<k; x++)
{
dstptr[x] = ((srcptr[x]&0x000F)<<12) | // B
((srcptr[x]&0x00F0)<<4) | // G
((srcptr[x]&0x0F00)>>4) | // R
((srcptr[x]&0xF000)>>12); // A
}
srcptr += src.rowPitch;
dstptr += dst.rowPitch;
}
srcptr += srcSliceSkip;
dstptr += dstSliceSkip;
}
}
}
}
<commit_msg>GLES2: Reorder a little code so red and red-green textures work properly. Also fixes Apple dev tools crashes.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2012 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2PixelFormat.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreBitwise.h"
namespace Ogre {
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLOriginFormat(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
return GL_ALPHA;
case PF_L8:
case PF_L16:
return GL_LUMINANCE;
#if GL_OES_texture_half_float
case PF_FLOAT16_RGB:
return GL_RGB;
case PF_FLOAT16_RGBA:
return GL_RGBA;
#endif
#if GL_EXT_texture_rg
case PF_FLOAT16_R:
case PF_R8:
return GL_RED_EXT;
case PF_FLOAT16_GR:
case PF_RG8:
return GL_RG_EXT;
#endif
case PF_BYTE_LA:
case PF_SHORT_GR:
return GL_LUMINANCE_ALPHA;
// PVRTC compressed formats
#if GL_IMG_texture_compression_pvrtc
case PF_PVRTC_RGB2:
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGB4:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case PF_PVRTC_RGBA2:
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGBA4:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif
case PF_R5G6B5:
case PF_B5G6R5:
case PF_R8G8B8:
case PF_B8G8R8:
return GL_RGB;
case PF_A1R5G5B5:
return GL_BGRA;
case PF_A4R4G4B4:
case PF_X8R8G8B8:
case PF_A8R8G8B8:
case PF_B8G8R8A8:
case PF_X8B8G8R8:
case PF_A8B8G8R8:
return GL_RGBA;
case PF_DXT1:
#if GL_EXT_texture_compression_dxt1
return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
#endif
case PF_DXT3:
#if GL_EXT_texture_compression_s3tc
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
case PF_DXT5:
#if GL_EXT_texture_compression_s3tc
return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
#endif
case PF_FLOAT32_GR:
case PF_FLOAT32_R:
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLOriginDataType(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
case PF_L8:
case PF_L16:
case PF_R8G8B8:
case PF_B8G8R8:
case PF_BYTE_LA:
return GL_UNSIGNED_BYTE;
case PF_R5G6B5:
case PF_B5G6R5:
return GL_UNSIGNED_SHORT_5_6_5;
case PF_A4R4G4B4:
return GL_UNSIGNED_SHORT_4_4_4_4;
case PF_A1R5G5B5:
return GL_UNSIGNED_SHORT_5_5_5_1;
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
case PF_X8B8G8R8:
case PF_A8B8G8R8:
return GL_UNSIGNED_INT_8_8_8_8_REV;
case PF_X8R8G8B8:
case PF_A8B8G8R8:
case PF_A8R8G8B8:
return GL_UNSIGNED_INT_8_8_8_8_REV;
case PF_B8G8R8A8:
return GL_UNSIGNED_BYTE;
case PF_R8G8B8A8:
return GL_UNSIGNED_BYTE;
#else
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_X8R8G8B8:
case PF_A8R8G8B8:
case PF_B8G8R8A8:
case PF_R8G8B8A8:
return GL_UNSIGNED_BYTE;
#endif
case PF_FLOAT16_R:
case PF_FLOAT16_GR:
case PF_FLOAT16_RGB:
case PF_FLOAT16_RGBA:
#if GL_OES_texture_half_float
return GL_HALF_FLOAT_OES;
#else
return 0;
#endif
#if GL_EXT_texture_rg
case PF_R8:
case PF_RG8:
return GL_UNSIGNED_BYTE;
#endif
case PF_FLOAT32_R:
case PF_FLOAT32_GR:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
return GL_FLOAT;
case PF_DXT1:
case PF_DXT3:
case PF_DXT5:
case PF_R3G3B2:
case PF_A2R10G10B10:
case PF_A2B10G10R10:
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
// TODO not supported
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)
{
switch (fmt)
{
case PF_L8:
case PF_L16:
return GL_LUMINANCE;
case PF_A8:
return GL_ALPHA;
case PF_BYTE_LA:
return GL_LUMINANCE_ALPHA;
#if GL_IMG_texture_compression_pvrtc
case PF_PVRTC_RGB2:
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGB4:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case PF_PVRTC_RGBA2:
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGBA4:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif
case PF_X8B8G8R8:
case PF_X8R8G8B8:
case PF_A8B8G8R8:
case PF_A8R8G8B8:
case PF_B8G8R8A8:
case PF_A1R5G5B5:
case PF_A4R4G4B4:
return GL_RGBA;
case PF_R5G6B5:
case PF_B5G6R5:
case PF_R8G8B8:
case PF_B8G8R8:
return GL_RGB;
#if GL_EXT_texture_rg
case PF_FLOAT16_R:
case PF_FLOAT32_R:
case PF_R8:
return GL_RED_EXT;
case PF_FLOAT16_GR:
case PF_FLOAT32_GR:
case PF_RG8:
return GL_RG_EXT;
#endif
case PF_A4L4:
case PF_R3G3B2:
case PF_A2R10G10B10:
case PF_A2B10G10R10:
case PF_FLOAT16_RGBA:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
case PF_DXT1:
#if GL_EXT_texture_compression_dxt1
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
#endif
case PF_DXT3:
#if GL_EXT_texture_compression_s3tc
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
case PF_DXT5:
#if GL_EXT_texture_compression_s3tc
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,
bool hwGamma)
{
GLenum format = getGLInternalFormat(mFormat, hwGamma);
if (format == GL_NONE)
{
if (hwGamma)
{
// TODO not supported
return 0;
}
else
{
return GL_RGBA;
}
}
else
{
return format;
}
}
//-----------------------------------------------------------------------------
PixelFormat GLES2PixelUtil::getClosestOGREFormat(GLenum fmt, GLenum dataType)
{
switch (fmt)
{
#if GL_IMG_texture_compression_pvrtc
case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
return PF_PVRTC_RGB2;
case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
return PF_PVRTC_RGBA2;
case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
return PF_PVRTC_RGB4;
case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
return PF_PVRTC_RGBA4;
#endif
case GL_LUMINANCE:
return PF_L8;
case GL_ALPHA:
return PF_A8;
case GL_LUMINANCE_ALPHA:
return PF_BYTE_LA;
case GL_RGB:
switch(dataType)
{
case GL_UNSIGNED_SHORT_5_6_5:
return PF_B5G6R5;
default:
return PF_R8G8B8;
};
case GL_RGBA:
switch(dataType)
{
case GL_UNSIGNED_SHORT_5_5_5_1:
return PF_A1R5G5B5;
case GL_UNSIGNED_SHORT_4_4_4_4:
return PF_A4R4G4B4;
default:
#if (OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS)
return PF_A8R8G8B8;
#else
return PF_A8B8G8R8;
#endif
}
#ifdef GL_BGRA
case GL_BGRA:
return PF_A8B8G8R8;
#endif
#if GL_EXT_texture_compression_dxt1
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return PF_DXT1;
#endif
#if GL_EXT_texture_compression_s3tc
case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
return PF_DXT3;
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
return PF_DXT5;
#endif
#if GL_EXT_texture_rg
case GL_R8_EXT:
return PF_R8;
case GL_RG8_EXT:
return PF_RG8;
#endif
default:
//TODO: not supported
return PF_A8R8G8B8;
};
}
//-----------------------------------------------------------------------------
size_t GLES2PixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,
PixelFormat format)
{
size_t count = 0;
if((width > 0) && (height > 0))
{
do {
if(width>1) width = width/2;
if(height>1) height = height/2;
if(depth>1) depth = depth/2;
/*
NOT needed, compressed formats will have mipmaps up to 1x1
if(PixelUtil::isValidExtent(width, height, depth, format))
count ++;
else
break;
*/
count ++;
} while(!(width == 1 && height == 1 && depth == 1));
}
return count;
}
//-----------------------------------------------------------------------------
size_t GLES2PixelUtil::optionalPO2(size_t value)
{
const RenderSystemCapabilities *caps =
Root::getSingleton().getRenderSystem()->getCapabilities();
if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))
{
return value;
}
else
{
return Bitwise::firstPO2From((uint32)value);
}
}
void GLES2PixelUtil::convertToGLformat(const PixelBox &src, const PixelBox &dst)
{
// Always need to convert PF_A4R4G4B4, GL expects the colors to be in the
// reverse order
if (dst.format == PF_A4R4G4B4)
{
// Convert PF_A4R4G4B4 -> PF_B4G4R4A4
// Reverse pixel order
uint16 *srcptr = static_cast<uint16*>(src.data)
+ (src.left + src.top * src.rowPitch + src.front * src.slicePitch);
uint16 *dstptr = static_cast<uint16*>(dst.data)
+ (dst.left + dst.top * dst.rowPitch + dst.front * dst.slicePitch);
const size_t srcSliceSkip = src.getSliceSkip();
const size_t dstSliceSkip = dst.getSliceSkip();
const size_t k = src.right - src.left;
for(size_t z=src.front; z<src.back; z++)
{
for(size_t y=src.top; y<src.bottom; y++)
{
for(size_t x=0; x<k; x++)
{
dstptr[x] = ((srcptr[x]&0x000F)<<12) | // B
((srcptr[x]&0x00F0)<<4) | // G
((srcptr[x]&0x0F00)>>4) | // R
((srcptr[x]&0xF000)>>12); // A
}
srcptr += src.rowPitch;
dstptr += dst.rowPitch;
}
srcptr += srcSliceSkip;
dstptr += dstSliceSkip;
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2013 Puck Meerburg, puck@puckipedia.nl
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "BlogPositivePostEditorView.h"
#include <Catalog.h>
#include <GroupLayout.h>
#include <Menu.h>
#include <MenuBar.h>
#include <MenuItem.h>
#include <Message.h>
#include <TextView.h>
#include "../API/BlogPositiveBlog.h"
#include "../API/BlogPositivePlugin.h"
#include "../API/BlogPositivePost.h"
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Post Editor View"
const uint32 kPostEditorSavePost = 'PESP';
BlogPositivePostEditorView::BlogPositivePostEditorView(const char* name,
BlogPositivePost* post)
:
BView(name, 0),
fPost(post)
{
fTextView = new BTextView("TextView");
fTextView->SetText(post->Page());
BMenuBar* menuBar = new BMenuBar("MenuBar");
fMenuItem = new BMenuItem(B_TRANSLATE("Save"),
new BMessage(kPostEditorSavePost));
menuBar->AddItem(fMenuItem);
SetLayout(new BGroupLayout(B_VERTICAL, 0));
AddChild(menuBar);
AddChild(fTextView);
}
void
BlogPositivePostEditorView::AttachedToWindow()
{
fMenuItem->SetTarget(this);
}
void
BlogPositivePostEditorView::Save()
{
fPost->SetPage(fTextView->Text());
fPost->Blog()->Plugin()->SavePost(fPost);
}
void
BlogPositivePostEditorView::MessageReceived(BMessage* message)
{
switch (message->what) {
case kPostEditorSavePost:
Save();
break;
default:
BView::MessageReceived(message);
}
}
<commit_msg>Add scrollbar to Editor view<commit_after>/*
* Copyright 2013 Puck Meerburg, puck@puckipedia.nl
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "BlogPositivePostEditorView.h"
#include <Catalog.h>
#include <GroupLayout.h>
#include <Menu.h>
#include <MenuBar.h>
#include <MenuItem.h>
#include <Message.h>
#include <TextView.h>
#include "../API/BlogPositiveBlog.h"
#include "../API/BlogPositivePlugin.h"
#include "../API/BlogPositivePost.h"
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Post Editor View"
const uint32 kPostEditorSavePost = 'PESP';
BlogPositivePostEditorView::BlogPositivePostEditorView(const char* name,
BlogPositivePost* post)
:
BView(name, 0),
fPost(post)
{
fTextView = new BTextView("TextView");
fTextView->SetText(post->Page());
BMenuBar* menuBar = new BMenuBar("MenuBar");
fMenuItem = new BMenuItem(B_TRANSLATE("Save"),
new BMessage(kPostEditorSavePost));
menuBar->AddItem(fMenuItem);
SetLayout(new BGroupLayout(B_VERTICAL, 0));
AddChild(menuBar);
AddChild(new BScrollView("scroll_view", fTextView, 0, false, true));
}
void
BlogPositivePostEditorView::AttachedToWindow()
{
fMenuItem->SetTarget(this);
}
void
BlogPositivePostEditorView::Save()
{
fPost->SetPage(fTextView->Text());
fPost->Blog()->Plugin()->SavePost(fPost);
}
void
BlogPositivePostEditorView::MessageReceived(BMessage* message)
{
switch (message->what) {
case kPostEditorSavePost:
Save();
break;
default:
BView::MessageReceived(message);
}
}
<|endoftext|>
|
<commit_before>// Copyright 2008, Google Inc.
// 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 Google Inc. 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.
//
// NPAPI interactive UI tests.
//
#include "base/file_path.h"
#include "base/keyboard_codes.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "chrome/test/ui_test_utils.h"
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("npapi");
// Tests if a plugin executing a self deleting script in the context of
// a synchronous mousemove works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousMouseMove) {
if (!UITest::in_process_renderer()) {
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
HWND tab_window = NULL;
tab_proxy->GetHWND(&tab_window);
EXPECT_TRUE(IsWindow(tab_window));
show_window_ = true;
const FilePath kTestDir(FILE_PATH_LITERAL("npapi"));
const FilePath test_case(
FILE_PATH_LITERAL("execute_script_delete_in_mouse_move.html"));
GURL url = ui_test_utils::GetTestUrl(kTestDir, test_case);
NavigateToURL(url);
POINT cursor_position = {130, 130};
ClientToScreen(tab_window, &cursor_position);
double screen_width = ::GetSystemMetrics(SM_CXSCREEN) - 1;
double screen_height = ::GetSystemMetrics(SM_CYSCREEN) - 1;
double location_x = cursor_position.x * (65535.0f / screen_width);
double location_y = cursor_position.y * (65535.0f / screen_height);
INPUT input_info = {0};
input_info.type = INPUT_MOUSE;
input_info.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
input_info.mi.dx = static_cast<long>(location_x);
input_info.mi.dy = static_cast<long>(location_y);
::SendInput(1, &input_info, sizeof(INPUT));
WaitForFinish("execute_script_delete_in_mouse_move", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
}
TEST_F(NPAPIVisiblePluginTester, GetURLRequest404Response) {
if (UITest::in_process_renderer())
return;
GURL url(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL(
"npapi/plugin_url_request_404.html"))));
NavigateToURL(url);
// Wait for the alert dialog and then close it.
automation()->WaitForAppModalDialog();
scoped_refptr<WindowProxy> window(automation()->GetActiveWindow());
ASSERT_TRUE(window.get());
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_ESCAPE, 0));
WaitForFinish("geturl_404_response", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, action_max_timeout_ms());
}
// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeAlert) {
const FilePath test_case(
FILE_PATH_LITERAL("self_delete_plugin_invoke_alert.html"));
GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
// Wait for the alert dialog and then close it.
ASSERT_TRUE(automation()->WaitForAppModalDialog());
scoped_refptr<WindowProxy> window(automation()->GetActiveWindow());
ASSERT_TRUE(window.get());
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_ESCAPE, 0));
WaitForFinish("self_delete_plugin_invoke_alert", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
<commit_msg>[GTTF] Disable NPAPIVisiblePluginTester.SelfDeletePluginInvokeAlert which flakily exceeds test timeout.<commit_after>// Copyright 2008, Google Inc.
// 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 Google Inc. 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.
//
// NPAPI interactive UI tests.
//
#include "base/file_path.h"
#include "base/keyboard_codes.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "chrome/test/ui_test_utils.h"
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("npapi");
// Tests if a plugin executing a self deleting script in the context of
// a synchronous mousemove works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousMouseMove) {
if (!UITest::in_process_renderer()) {
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
HWND tab_window = NULL;
tab_proxy->GetHWND(&tab_window);
EXPECT_TRUE(IsWindow(tab_window));
show_window_ = true;
const FilePath kTestDir(FILE_PATH_LITERAL("npapi"));
const FilePath test_case(
FILE_PATH_LITERAL("execute_script_delete_in_mouse_move.html"));
GURL url = ui_test_utils::GetTestUrl(kTestDir, test_case);
NavigateToURL(url);
POINT cursor_position = {130, 130};
ClientToScreen(tab_window, &cursor_position);
double screen_width = ::GetSystemMetrics(SM_CXSCREEN) - 1;
double screen_height = ::GetSystemMetrics(SM_CYSCREEN) - 1;
double location_x = cursor_position.x * (65535.0f / screen_width);
double location_y = cursor_position.y * (65535.0f / screen_height);
INPUT input_info = {0};
input_info.type = INPUT_MOUSE;
input_info.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
input_info.mi.dx = static_cast<long>(location_x);
input_info.mi.dy = static_cast<long>(location_y);
::SendInput(1, &input_info, sizeof(INPUT));
WaitForFinish("execute_script_delete_in_mouse_move", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
}
TEST_F(NPAPIVisiblePluginTester, GetURLRequest404Response) {
if (UITest::in_process_renderer())
return;
GURL url(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL(
"npapi/plugin_url_request_404.html"))));
NavigateToURL(url);
// Wait for the alert dialog and then close it.
automation()->WaitForAppModalDialog();
scoped_refptr<WindowProxy> window(automation()->GetActiveWindow());
ASSERT_TRUE(window.get());
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_ESCAPE, 0));
WaitForFinish("geturl_404_response", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, action_max_timeout_ms());
}
// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
// Disabled, flakily exceeds timeout, http://crbug.com/46257.
TEST_F(NPAPIVisiblePluginTester, DISABLED_SelfDeletePluginInvokeAlert) {
const FilePath test_case(
FILE_PATH_LITERAL("self_delete_plugin_invoke_alert.html"));
GURL url = ui_test_utils::GetTestUrl(FilePath(kTestDir), test_case);
ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
// Wait for the alert dialog and then close it.
ASSERT_TRUE(automation()->WaitForAppModalDialog());
scoped_refptr<WindowProxy> window(automation()->GetActiveWindow());
ASSERT_TRUE(window.get());
ASSERT_TRUE(window->SimulateOSKeyPress(base::VKEY_ESCAPE, 0));
WaitForFinish("self_delete_plugin_invoke_alert", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
<|endoftext|>
|
<commit_before>//
// ImplicitSectors.cpp
// Clock Signal
//
// Created by Thomas Harte on 29/09/2017.
// Copyright 2017 Thomas Harte. All rights reserved.
//
#include "ImplicitSectors.hpp"
#include <cstring>
#include "../../../Encodings/MFM/Sector.hpp"
#include "../../../Encodings/MFM/Encoder.hpp"
#include "../../../Encodings/MFM/Constants.hpp"
#include "../../../Track/TrackSerialiser.hpp"
#include "../../../Encodings/MFM/SegmentParser.hpp"
using namespace Storage::Disk;
std::shared_ptr<Track> Storage::Disk::track_for_sectors(uint8_t *const source, int number_of_sectors, uint8_t track, uint8_t side, uint8_t first_sector, uint8_t size, bool is_double_density) {
std::vector<Storage::Encodings::MFM::Sector> sectors;
off_t byte_size = static_cast<off_t>(128 << size);
off_t source_pointer = 0;
for(int sector = 0; sector < number_of_sectors; sector++) {
sectors.emplace_back();
Storage::Encodings::MFM::Sector &new_sector = sectors.back();
new_sector.address.track = track;
new_sector.address.side = side;
new_sector.address.sector = first_sector;
first_sector++;
new_sector.size = size;
new_sector.samples.emplace_back();
new_sector.samples[0].insert(new_sector.samples[0].begin(), source + source_pointer, source + source_pointer + byte_size);
source_pointer += byte_size;
}
if(sectors.size()) {
return is_double_density ? Storage::Encodings::MFM::GetMFMTrackWithSectors(sectors) : Storage::Encodings::MFM::GetFMTrackWithSectors(sectors);
}
return nullptr;
}
void Storage::Disk::decode_sectors(Track &track, uint8_t *const destination, uint8_t first_sector, uint8_t last_sector, uint8_t sector_size, bool is_double_density) {
std::map<std::size_t, Storage::Encodings::MFM::Sector> sectors =
Storage::Encodings::MFM::sectors_from_segment(
Storage::Disk::track_serialisation(track, is_double_density ? Storage::Encodings::MFM::MFMBitLength : Storage::Encodings::MFM::FMBitLength),
is_double_density);
std::size_t byte_size = static_cast<std::size_t>(128 << sector_size);
for(const auto &pair : sectors) {
if(pair.second.address.sector > last_sector) continue;
if(pair.second.address.sector < first_sector) continue;
if(pair.second.size != sector_size) continue;
if(pair.second.samples.empty()) continue;
std::memcpy(&destination[pair.second.address.sector * byte_size], pair.second.samples[0].data(), std::min(pair.second.samples[0].size(), byte_size));
}
}
<commit_msg>Minor style fix.<commit_after>//
// ImplicitSectors.cpp
// Clock Signal
//
// Created by Thomas Harte on 29/09/2017.
// Copyright 2017 Thomas Harte. All rights reserved.
//
#include "ImplicitSectors.hpp"
#include <cstring>
#include "../../../Encodings/MFM/Sector.hpp"
#include "../../../Encodings/MFM/Encoder.hpp"
#include "../../../Encodings/MFM/Constants.hpp"
#include "../../../Track/TrackSerialiser.hpp"
#include "../../../Encodings/MFM/SegmentParser.hpp"
using namespace Storage::Disk;
std::shared_ptr<Track> Storage::Disk::track_for_sectors(uint8_t *const source, int number_of_sectors, uint8_t track, uint8_t side, uint8_t first_sector, uint8_t size, bool is_double_density) {
std::vector<Storage::Encodings::MFM::Sector> sectors;
off_t byte_size = static_cast<off_t>(128 << size);
off_t source_pointer = 0;
for(int sector = 0; sector < number_of_sectors; sector++) {
sectors.emplace_back();
Storage::Encodings::MFM::Sector &new_sector = sectors.back();
new_sector.address.track = track;
new_sector.address.side = side;
new_sector.address.sector = first_sector;
first_sector++;
new_sector.size = size;
new_sector.samples.emplace_back();
new_sector.samples[0].insert(new_sector.samples[0].begin(), source + source_pointer, source + source_pointer + byte_size);
source_pointer += byte_size;
}
if(!sectors.empty()) {
return is_double_density ? Storage::Encodings::MFM::GetMFMTrackWithSectors(sectors) : Storage::Encodings::MFM::GetFMTrackWithSectors(sectors);
}
return nullptr;
}
void Storage::Disk::decode_sectors(Track &track, uint8_t *const destination, uint8_t first_sector, uint8_t last_sector, uint8_t sector_size, bool is_double_density) {
std::map<std::size_t, Storage::Encodings::MFM::Sector> sectors =
Storage::Encodings::MFM::sectors_from_segment(
Storage::Disk::track_serialisation(track, is_double_density ? Storage::Encodings::MFM::MFMBitLength : Storage::Encodings::MFM::FMBitLength),
is_double_density);
std::size_t byte_size = static_cast<std::size_t>(128 << sector_size);
for(const auto &pair : sectors) {
if(pair.second.address.sector > last_sector) continue;
if(pair.second.address.sector < first_sector) continue;
if(pair.second.size != sector_size) continue;
if(pair.second.samples.empty()) continue;
std::memcpy(&destination[pair.second.address.sector * byte_size], pair.second.samples[0].data(), std::min(pair.second.samples[0].size(), byte_size));
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkGeometry2DDataToSurfaceFilter.h"
#include "mitkSurface.h"
#include "mitkGeometry3D.h"
#include "mitkGeometry2DData.h"
#include "mitkPlaneGeometry.h"
#include "mitkAbstractTransformGeometry.h"
#include "mitkDataTree.h"
#include <vtkPolyData.h>
#include <vtkPlaneSource.h>
#include <vtkTransformPolyDataFilter.h>
#include <vtkCubeSource.h>
#include <vtkTransformPolyDataFilter.h>
#include <vtkTransform.h>
#include <vtkPlane.h>
#include <vtkCutter.h>
#include <vtkStripper.h>
#include <vtkTriangleFilter.h>
#include <vtkBox.h>
#include <vtkClipPolyData.h>
#include <vtkTextureMapToPlane.h>
mitk::Geometry2DDataToSurfaceFilter::Geometry2DDataToSurfaceFilter()
: m_UseGeometryParametricBounds( true ), m_XResolution( 10 ),
m_YResolution( 10 ), m_PlaceByGeometry( false ), m_UseBoundingBox( false )
{
m_PlaneSource = vtkPlaneSource::New();
m_Transform = vtkTransform::New();
m_CubeSource = vtkCubeSource::New();
m_PolyDataTransformer = vtkTransformPolyDataFilter::New();
m_Plane = vtkPlane::New();
m_PlaneCutter = vtkCutter::New();
m_PlaneStripper = vtkStripper::New();
m_PlanePolyData = vtkPolyData::New();
m_PlaneTriangler = vtkTriangleFilter::New();
m_TextureMapToPlane = vtkTextureMapToPlane::New();
m_Box = vtkBox::New();
m_PlaneClipper = vtkClipPolyData::New();
m_VtkTransformPlaneFilter = vtkTransformPolyDataFilter::New();
m_VtkTransformPlaneFilter->SetInput( m_PlaneSource->GetOutput() );
}
mitk::Geometry2DDataToSurfaceFilter::~Geometry2DDataToSurfaceFilter()
{
m_PlaneSource->Delete();
m_Transform->Delete();
m_CubeSource->Delete();
m_PolyDataTransformer->Delete();
m_Plane->Delete();
m_PlaneCutter->Delete();
m_PlaneStripper->Delete();
m_PlanePolyData->Delete();
m_PlaneTriangler->Delete();
m_TextureMapToPlane->Delete();
m_Box = vtkBox::New();
m_PlaneClipper = vtkClipPolyData::New();
m_VtkTransformPlaneFilter->Delete();
}
void mitk::Geometry2DDataToSurfaceFilter::GenerateOutputInformation()
{
mitk::Geometry2DData::ConstPointer input = this->GetInput();
mitk::Surface::Pointer output = this->GetOutput();
if ( input.IsNull() || (input->GetGeometry2D() == NULL)
|| (input->GetGeometry2D()->IsValid() == false)
|| (m_UseBoundingBox && (m_BoundingBox.IsNull() || (m_BoundingBox->GetDiagonalLength2() < mitk::eps))) )
{
return;
}
Point3D origin;
Point3D right, bottom;
vtkPolyData *planeSurface = NULL;
// Does the Geometry2DData contain a PlaneGeometry?
if ( dynamic_cast< PlaneGeometry * >( input->GetGeometry2D() ) != NULL )
{
mitk::PlaneGeometry *planeGeometry =
dynamic_cast< PlaneGeometry * >( input->GetGeometry2D() );
if ( m_PlaceByGeometry )
{
// Let the output use the input geometry to appropriately transform the
// coordinate system.
mitk::AffineGeometryFrame3D::TransformType *affineTransform =
planeGeometry->GetIndexToWorldTransform();
mitk::TimeSlicedGeometry *timeGeometry = output->GetTimeSlicedGeometry();
timeGeometry->SetIndexToWorldTransform( affineTransform );
mitk::Geometry3D *g3d = timeGeometry->GetGeometry3D( 0 );
g3d->SetIndexToWorldTransform( affineTransform );
}
if ( !m_UseBoundingBox)
{
// We do not have a bounding box, so no clipping is required.
if ( m_PlaceByGeometry )
{
// Derive coordinate axes and origin from input geometry extent
origin.Fill( 0.0 );
FillVector3D( right, planeGeometry->GetExtent(0), 0.0, 0.0 );
FillVector3D( bottom, 0.0, planeGeometry->GetExtent(1), 0.0 );
}
else
{
// Take the coordinate axes and origin directly from the input geometry.
origin = planeGeometry->GetOrigin();
right = planeGeometry->GetCornerPoint( false, true );
bottom = planeGeometry->GetCornerPoint( true, false );
}
// Since the plane is planar, there is no need to subdivide the grid
// (cf. AbstractTransformGeometry case)
m_PlaneSource->SetXResolution( 1 );
m_PlaneSource->SetYResolution( 1 );
m_PlaneSource->SetOrigin( origin[0], origin[1], origin[2] );
m_PlaneSource->SetPoint1( right[0], right[1], right[2] );
m_PlaneSource->SetPoint2( bottom[0], bottom[1], bottom[2] );
planeSurface = m_PlaneSource->GetOutput();
planeSurface->Update();
}
else
{
// Set up a cube with the extent and origin of the bounding box. This
// cube will be clipped by a plane later on. The intersection of the
// cube and the plane will be the surface we are interested in. Note
// that the bounding box needs to be explicitly specified by the user
// of this class, since it is not necessarily clear from the data
// available herein which bounding box to use. In most cases, this
// would be the bounding box of the input geometry's reference
// geometry, but this is not an inevitable requirement.
mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum();
mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum();
mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter();
m_CubeSource->SetXLength( boundingBoxMax[0] - boundingBoxMin[0] );
m_CubeSource->SetYLength( boundingBoxMax[1] - boundingBoxMin[1] );
m_CubeSource->SetZLength( boundingBoxMax[2] - boundingBoxMin[2] );
m_CubeSource->SetCenter(
boundingBoxCenter[0],
boundingBoxCenter[1],
boundingBoxCenter[2] );
// Now we have to transform the cube, so that it will cut our plane
// appropriately. (As can be seen below, the plane corresponds to the
// z-plane in the coordinate system and is *not* transformed.) Therefore,
// we get the inverse of the plane geometry's transform and concatenate
// it with the transform of the reference geometry, if available.
m_Transform->Identity();
m_Transform->Concatenate(
planeGeometry->GetVtkTransform()->GetLinearInverse()
);
Geometry3D *referenceGeometry = planeGeometry->GetReferenceGeometry();
if ( referenceGeometry )
{
m_Transform->Concatenate(
referenceGeometry->GetVtkTransform()
);
}
// Transform the cube accordingly (s.a.)
m_PolyDataTransformer->SetInput( m_CubeSource->GetOutput() );
m_PolyDataTransformer->SetTransform( m_Transform );
// Initialize the plane to clip the cube with, as lying on the z-plane
m_Plane->SetOrigin( 0.0, 0.0, 0.0 );
m_Plane->SetNormal( 0.0, 0.0, 1.0 );
// Cut the plane with the cube.
m_PlaneCutter->SetInput( m_PolyDataTransformer->GetOutput() );
m_PlaneCutter->SetCutFunction( m_Plane );
// The output of the cutter must be converted into appropriate poly data.
m_PlaneStripper->SetInput( m_PlaneCutter->GetOutput() );
m_PlaneStripper->Update();
m_PlanePolyData->SetPoints( m_PlaneStripper->GetOutput()->GetPoints() );
m_PlanePolyData->SetPolys( m_PlaneStripper->GetOutput()->GetLines() );
m_PlaneTriangler->SetInput( m_PlanePolyData );
// Get bounds of the resulting surface and use it to generate the texture
// mapping information
m_PlaneTriangler->Update();
m_PlaneTriangler->GetOutput()->ComputeBounds();
vtkFloatingPointType *surfaceBounds =
m_PlaneTriangler->GetOutput()->GetBounds();
origin[0] = surfaceBounds[0];
origin[1] = surfaceBounds[2];
origin[2] = surfaceBounds[4];
right[0] = surfaceBounds[1];
right[1] = surfaceBounds[2];
right[2] = surfaceBounds[4];
bottom[0] = surfaceBounds[0];
bottom[1] = surfaceBounds[3];
bottom[2] = surfaceBounds[4];
// Now we tell the data how it shall be textured afterwards;
// description see above.
m_TextureMapToPlane->SetInput( m_PlaneTriangler->GetOutput() );
m_TextureMapToPlane->AutomaticPlaneGenerationOn();
m_TextureMapToPlane->SetOrigin( origin[0], origin[1], origin[2] );
m_TextureMapToPlane->SetPoint1( right[0], right[1], right[2] );
m_TextureMapToPlane->SetPoint2( bottom[0], bottom[1], bottom[2] );
// Need to call update so that output data and bounds are immediately
// available
m_TextureMapToPlane->Update();
// Return the output of this generation process
planeSurface = dynamic_cast< vtkPolyData * >(
m_TextureMapToPlane->GetOutput()
);
}
}
// Does the Geometry2DData contain an AbstractTransformGeometry?
else if ( mitk::AbstractTransformGeometry *abstractGeometry =
dynamic_cast< AbstractTransformGeometry * >( input->GetGeometry2D() ) )
{
// In the case of an AbstractTransformGeometry (which holds a possibly
// non-rigid transform), we proceed slightly differently: since the
// plane can be arbitrarily deformed, we need to transform it by the
// abstract transform before clipping it. The setup for this is partially
// done in the constructor.
origin = abstractGeometry->GetPlane()->GetOrigin();
right = origin + abstractGeometry->GetPlane()->GetAxisVector( 0 );
bottom = origin + abstractGeometry->GetPlane()->GetAxisVector( 1 );
// Define the plane
m_PlaneSource->SetOrigin( origin[0], origin[1], origin[2] );
m_PlaneSource->SetPoint1( right[0], right[1], right[2] );
m_PlaneSource->SetPoint2( bottom[0], bottom[1], bottom[2] );
// Set the plane's resolution (unlike for non-deformable planes, the plane
// grid needs to have a certain resolution so that the deformation has the
// desired effect).
if ( m_UseGeometryParametricBounds )
{
m_PlaneSource->SetXResolution(
(int)abstractGeometry->GetParametricExtent(0)
);
m_PlaneSource->SetYResolution(
(int)abstractGeometry->GetParametricExtent(1)
);
}
else
{
m_PlaneSource->SetXResolution( m_XResolution );
m_PlaneSource->SetYResolution( m_YResolution );
}
// Use the non-rigid transform for transforming the plane.
m_VtkTransformPlaneFilter->SetTransform(
abstractGeometry->GetVtkAbstractTransform()
);
if ( m_UseBoundingBox )
{
mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum();
mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum();
mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter();
m_Box->SetXMin( boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2] );
m_Box->SetXMax( boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2] );
}
else
{
// Plane will not be clipped
m_Box->SetXMin( -10000.0, -10000.0, -10000.0 );
m_Box->SetXMax( 10000.0, 10000.0, 10000.0 );
}
m_Transform->Identity();
m_Transform->Concatenate( input->GetGeometry2D()->GetVtkTransform() );
m_Transform->PreMultiply();
m_Box->SetTransform( m_Transform );
m_PlaneClipper->SetInput( m_VtkTransformPlaneFilter->GetOutput() );
m_PlaneClipper->SetClipFunction( m_Box );
m_PlaneClipper->GenerateClippedOutputOn();
m_PlaneClipper->InsideOutOn();
m_PlaneClipper->SetValue( 0.0 );
planeSurface = m_PlaneClipper->GetOutput();
}
output->SetVtkPolyData( planeSurface );
output->CalculateBoundingBox();
}
void mitk::Geometry2DDataToSurfaceFilter::GenerateData()
{
mitk::Surface::Pointer output = this->GetOutput();
if (output.IsNull()) return;
if (output->GetVtkPolyData()==NULL) return;
output->GetVtkPolyData()->Update();
}
const mitk::Geometry2DData *mitk::Geometry2DDataToSurfaceFilter::GetInput()
{
if (this->GetNumberOfInputs() < 1)
{
return 0;
}
return static_cast<const mitk::Geometry2DData * >
( this->ProcessObject::GetInput(0) );
}
const mitk::Geometry2DData *
mitk::Geometry2DDataToSurfaceFilter
::GetInput(unsigned int idx)
{
return static_cast< const mitk::Geometry2DData * >
( this->ProcessObject::GetInput(idx) );
}
void
mitk::Geometry2DDataToSurfaceFilter
::SetInput(const mitk::Geometry2DData *input)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput( 0,
const_cast< mitk::Geometry2DData * >( input )
);
}
void
mitk::Geometry2DDataToSurfaceFilter
::SetInput(unsigned int index, const mitk::Geometry2DData *input)
{
if( index+1 > this->GetNumberOfInputs() )
{
this->SetNumberOfRequiredInputs( index + 1 );
}
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(index,
const_cast< mitk::Geometry2DData *>( input )
);
}
void
mitk::Geometry2DDataToSurfaceFilter
::SetBoundingBox( const mitk::BoundingBox *boundingBox )
{
m_BoundingBox = boundingBox;
this->UseBoundingBoxOn();
}
const mitk::BoundingBox *
mitk::Geometry2DDataToSurfaceFilter
::GetBoundingBox() const
{
return m_BoundingBox.GetPointer();
}
<commit_msg>BUG: Removed VTK warning in case of empty clipped plane (cf. bug #433)<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkGeometry2DDataToSurfaceFilter.h"
#include "mitkSurface.h"
#include "mitkGeometry3D.h"
#include "mitkGeometry2DData.h"
#include "mitkPlaneGeometry.h"
#include "mitkAbstractTransformGeometry.h"
#include "mitkDataTree.h"
#include <vtkPolyData.h>
#include <vtkPlaneSource.h>
#include <vtkTransformPolyDataFilter.h>
#include <vtkCubeSource.h>
#include <vtkTransformPolyDataFilter.h>
#include <vtkTransform.h>
#include <vtkPlane.h>
#include <vtkCutter.h>
#include <vtkStripper.h>
#include <vtkTriangleFilter.h>
#include <vtkBox.h>
#include <vtkClipPolyData.h>
#include <vtkTextureMapToPlane.h>
mitk::Geometry2DDataToSurfaceFilter::Geometry2DDataToSurfaceFilter()
: m_UseGeometryParametricBounds( true ), m_XResolution( 10 ),
m_YResolution( 10 ), m_PlaceByGeometry( false ), m_UseBoundingBox( false )
{
m_PlaneSource = vtkPlaneSource::New();
m_Transform = vtkTransform::New();
m_CubeSource = vtkCubeSource::New();
m_PolyDataTransformer = vtkTransformPolyDataFilter::New();
m_Plane = vtkPlane::New();
m_PlaneCutter = vtkCutter::New();
m_PlaneStripper = vtkStripper::New();
m_PlanePolyData = vtkPolyData::New();
m_PlaneTriangler = vtkTriangleFilter::New();
m_TextureMapToPlane = vtkTextureMapToPlane::New();
m_Box = vtkBox::New();
m_PlaneClipper = vtkClipPolyData::New();
m_VtkTransformPlaneFilter = vtkTransformPolyDataFilter::New();
m_VtkTransformPlaneFilter->SetInput( m_PlaneSource->GetOutput() );
}
mitk::Geometry2DDataToSurfaceFilter::~Geometry2DDataToSurfaceFilter()
{
m_PlaneSource->Delete();
m_Transform->Delete();
m_CubeSource->Delete();
m_PolyDataTransformer->Delete();
m_Plane->Delete();
m_PlaneCutter->Delete();
m_PlaneStripper->Delete();
m_PlanePolyData->Delete();
m_PlaneTriangler->Delete();
m_TextureMapToPlane->Delete();
m_Box = vtkBox::New();
m_PlaneClipper = vtkClipPolyData::New();
m_VtkTransformPlaneFilter->Delete();
}
void mitk::Geometry2DDataToSurfaceFilter::GenerateOutputInformation()
{
mitk::Geometry2DData::ConstPointer input = this->GetInput();
mitk::Surface::Pointer output = this->GetOutput();
if ( input.IsNull() || (input->GetGeometry2D() == NULL)
|| (input->GetGeometry2D()->IsValid() == false)
|| (m_UseBoundingBox && (m_BoundingBox.IsNull() || (m_BoundingBox->GetDiagonalLength2() < mitk::eps))) )
{
return;
}
Point3D origin;
Point3D right, bottom;
vtkPolyData *planeSurface = NULL;
// Does the Geometry2DData contain a PlaneGeometry?
if ( dynamic_cast< PlaneGeometry * >( input->GetGeometry2D() ) != NULL )
{
mitk::PlaneGeometry *planeGeometry =
dynamic_cast< PlaneGeometry * >( input->GetGeometry2D() );
if ( m_PlaceByGeometry )
{
// Let the output use the input geometry to appropriately transform the
// coordinate system.
mitk::AffineGeometryFrame3D::TransformType *affineTransform =
planeGeometry->GetIndexToWorldTransform();
mitk::TimeSlicedGeometry *timeGeometry = output->GetTimeSlicedGeometry();
timeGeometry->SetIndexToWorldTransform( affineTransform );
mitk::Geometry3D *g3d = timeGeometry->GetGeometry3D( 0 );
g3d->SetIndexToWorldTransform( affineTransform );
}
if ( !m_UseBoundingBox)
{
// We do not have a bounding box, so no clipping is required.
if ( m_PlaceByGeometry )
{
// Derive coordinate axes and origin from input geometry extent
origin.Fill( 0.0 );
FillVector3D( right, planeGeometry->GetExtent(0), 0.0, 0.0 );
FillVector3D( bottom, 0.0, planeGeometry->GetExtent(1), 0.0 );
}
else
{
// Take the coordinate axes and origin directly from the input geometry.
origin = planeGeometry->GetOrigin();
right = planeGeometry->GetCornerPoint( false, true );
bottom = planeGeometry->GetCornerPoint( true, false );
}
// Since the plane is planar, there is no need to subdivide the grid
// (cf. AbstractTransformGeometry case)
m_PlaneSource->SetXResolution( 1 );
m_PlaneSource->SetYResolution( 1 );
m_PlaneSource->SetOrigin( origin[0], origin[1], origin[2] );
m_PlaneSource->SetPoint1( right[0], right[1], right[2] );
m_PlaneSource->SetPoint2( bottom[0], bottom[1], bottom[2] );
planeSurface = m_PlaneSource->GetOutput();
planeSurface->Update();
}
else
{
// Set up a cube with the extent and origin of the bounding box. This
// cube will be clipped by a plane later on. The intersection of the
// cube and the plane will be the surface we are interested in. Note
// that the bounding box needs to be explicitly specified by the user
// of this class, since it is not necessarily clear from the data
// available herein which bounding box to use. In most cases, this
// would be the bounding box of the input geometry's reference
// geometry, but this is not an inevitable requirement.
mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum();
mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum();
mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter();
m_CubeSource->SetXLength( boundingBoxMax[0] - boundingBoxMin[0] );
m_CubeSource->SetYLength( boundingBoxMax[1] - boundingBoxMin[1] );
m_CubeSource->SetZLength( boundingBoxMax[2] - boundingBoxMin[2] );
m_CubeSource->SetCenter(
boundingBoxCenter[0],
boundingBoxCenter[1],
boundingBoxCenter[2] );
// Now we have to transform the cube, so that it will cut our plane
// appropriately. (As can be seen below, the plane corresponds to the
// z-plane in the coordinate system and is *not* transformed.) Therefore,
// we get the inverse of the plane geometry's transform and concatenate
// it with the transform of the reference geometry, if available.
m_Transform->Identity();
m_Transform->Concatenate(
planeGeometry->GetVtkTransform()->GetLinearInverse()
);
Geometry3D *referenceGeometry = planeGeometry->GetReferenceGeometry();
if ( referenceGeometry )
{
m_Transform->Concatenate(
referenceGeometry->GetVtkTransform()
);
}
// Transform the cube accordingly (s.a.)
m_PolyDataTransformer->SetInput( m_CubeSource->GetOutput() );
m_PolyDataTransformer->SetTransform( m_Transform );
// Initialize the plane to clip the cube with, as lying on the z-plane
m_Plane->SetOrigin( 0.0, 0.0, 0.0 );
m_Plane->SetNormal( 0.0, 0.0, 1.0 );
// Cut the plane with the cube.
m_PlaneCutter->SetInput( m_PolyDataTransformer->GetOutput() );
m_PlaneCutter->SetCutFunction( m_Plane );
// The output of the cutter must be converted into appropriate poly data.
m_PlaneStripper->SetInput( m_PlaneCutter->GetOutput() );
m_PlaneStripper->Update();
if ( m_PlaneStripper->GetOutput()->GetNumberOfPoints() < 3 )
{
return;
}
m_PlanePolyData->SetPoints( m_PlaneStripper->GetOutput()->GetPoints() );
m_PlanePolyData->SetPolys( m_PlaneStripper->GetOutput()->GetLines() );
m_PlaneTriangler->SetInput( m_PlanePolyData );
// Get bounds of the resulting surface and use it to generate the texture
// mapping information
m_PlaneTriangler->Update();
m_PlaneTriangler->GetOutput()->ComputeBounds();
vtkFloatingPointType *surfaceBounds =
m_PlaneTriangler->GetOutput()->GetBounds();
origin[0] = surfaceBounds[0];
origin[1] = surfaceBounds[2];
origin[2] = surfaceBounds[4];
right[0] = surfaceBounds[1];
right[1] = surfaceBounds[2];
right[2] = surfaceBounds[4];
bottom[0] = surfaceBounds[0];
bottom[1] = surfaceBounds[3];
bottom[2] = surfaceBounds[4];
// Now we tell the data how it shall be textured afterwards;
// description see above.
m_TextureMapToPlane->SetInput( m_PlaneTriangler->GetOutput() );
m_TextureMapToPlane->AutomaticPlaneGenerationOn();
m_TextureMapToPlane->SetOrigin( origin[0], origin[1], origin[2] );
m_TextureMapToPlane->SetPoint1( right[0], right[1], right[2] );
m_TextureMapToPlane->SetPoint2( bottom[0], bottom[1], bottom[2] );
// Need to call update so that output data and bounds are immediately
// available
m_TextureMapToPlane->Update();
// Return the output of this generation process
planeSurface = dynamic_cast< vtkPolyData * >(
m_TextureMapToPlane->GetOutput()
);
}
}
// Does the Geometry2DData contain an AbstractTransformGeometry?
else if ( mitk::AbstractTransformGeometry *abstractGeometry =
dynamic_cast< AbstractTransformGeometry * >( input->GetGeometry2D() ) )
{
// In the case of an AbstractTransformGeometry (which holds a possibly
// non-rigid transform), we proceed slightly differently: since the
// plane can be arbitrarily deformed, we need to transform it by the
// abstract transform before clipping it. The setup for this is partially
// done in the constructor.
origin = abstractGeometry->GetPlane()->GetOrigin();
right = origin + abstractGeometry->GetPlane()->GetAxisVector( 0 );
bottom = origin + abstractGeometry->GetPlane()->GetAxisVector( 1 );
// Define the plane
m_PlaneSource->SetOrigin( origin[0], origin[1], origin[2] );
m_PlaneSource->SetPoint1( right[0], right[1], right[2] );
m_PlaneSource->SetPoint2( bottom[0], bottom[1], bottom[2] );
// Set the plane's resolution (unlike for non-deformable planes, the plane
// grid needs to have a certain resolution so that the deformation has the
// desired effect).
if ( m_UseGeometryParametricBounds )
{
m_PlaneSource->SetXResolution(
(int)abstractGeometry->GetParametricExtent(0)
);
m_PlaneSource->SetYResolution(
(int)abstractGeometry->GetParametricExtent(1)
);
}
else
{
m_PlaneSource->SetXResolution( m_XResolution );
m_PlaneSource->SetYResolution( m_YResolution );
}
// Use the non-rigid transform for transforming the plane.
m_VtkTransformPlaneFilter->SetTransform(
abstractGeometry->GetVtkAbstractTransform()
);
if ( m_UseBoundingBox )
{
mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum();
mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum();
mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter();
m_Box->SetXMin( boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2] );
m_Box->SetXMax( boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2] );
}
else
{
// Plane will not be clipped
m_Box->SetXMin( -10000.0, -10000.0, -10000.0 );
m_Box->SetXMax( 10000.0, 10000.0, 10000.0 );
}
m_Transform->Identity();
m_Transform->Concatenate( input->GetGeometry2D()->GetVtkTransform() );
m_Transform->PreMultiply();
m_Box->SetTransform( m_Transform );
m_PlaneClipper->SetInput( m_VtkTransformPlaneFilter->GetOutput() );
m_PlaneClipper->SetClipFunction( m_Box );
m_PlaneClipper->GenerateClippedOutputOn();
m_PlaneClipper->InsideOutOn();
m_PlaneClipper->SetValue( 0.0 );
planeSurface = m_PlaneClipper->GetOutput();
}
output->SetVtkPolyData( planeSurface );
output->CalculateBoundingBox();
}
void mitk::Geometry2DDataToSurfaceFilter::GenerateData()
{
mitk::Surface::Pointer output = this->GetOutput();
if (output.IsNull()) return;
if (output->GetVtkPolyData()==NULL) return;
output->GetVtkPolyData()->Update();
}
const mitk::Geometry2DData *mitk::Geometry2DDataToSurfaceFilter::GetInput()
{
if (this->GetNumberOfInputs() < 1)
{
return 0;
}
return static_cast<const mitk::Geometry2DData * >
( this->ProcessObject::GetInput(0) );
}
const mitk::Geometry2DData *
mitk::Geometry2DDataToSurfaceFilter
::GetInput(unsigned int idx)
{
return static_cast< const mitk::Geometry2DData * >
( this->ProcessObject::GetInput(idx) );
}
void
mitk::Geometry2DDataToSurfaceFilter
::SetInput(const mitk::Geometry2DData *input)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput( 0,
const_cast< mitk::Geometry2DData * >( input )
);
}
void
mitk::Geometry2DDataToSurfaceFilter
::SetInput(unsigned int index, const mitk::Geometry2DData *input)
{
if( index+1 > this->GetNumberOfInputs() )
{
this->SetNumberOfRequiredInputs( index + 1 );
}
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(index,
const_cast< mitk::Geometry2DData *>( input )
);
}
void
mitk::Geometry2DDataToSurfaceFilter
::SetBoundingBox( const mitk::BoundingBox *boundingBox )
{
m_BoundingBox = boundingBox;
this->UseBoundingBoxOn();
}
const mitk::BoundingBox *
mitk::Geometry2DDataToSurfaceFilter
::GetBoundingBox() const
{
return m_BoundingBox.GetPointer();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* 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 Google Inc. 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.
*/
#include "config.h"
#include "core/dom/custom/CustomElementRegistry.h"
#include "bindings/core/v8/CustomElementConstructorBuilder.h"
#include "core/HTMLNames.h"
#include "core/SVGNames.h"
#include "core/dom/DocumentLifecycleObserver.h"
#include "core/dom/custom/CustomElementException.h"
#include "core/dom/custom/CustomElementRegistrationContext.h"
namespace blink {
class RegistrationContextObserver : public DocumentLifecycleObserver {
public:
explicit RegistrationContextObserver(Document* document)
: DocumentLifecycleObserver(document)
, m_wentAway(!document)
{
}
bool registrationContextWentAway() { return m_wentAway; }
private:
#if ENABLE(OILPAN)
// In oilpan we don't have the disposed phase for context lifecycle observer.
virtual void documentWasDetached() OVERRIDE { m_wentAway = true; }
#else
virtual void documentWasDisposed() OVERRIDE { m_wentAway = true; }
#endif
bool m_wentAway;
};
CustomElementDefinition* CustomElementRegistry::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& userSuppliedName, CustomElement::NameSet validNames, ExceptionState& exceptionState)
{
// FIXME: In every instance except one it is the
// CustomElementConstructorBuilder that observes document
// destruction during registration. This responsibility should be
// consolidated in one place.
RegistrationContextObserver observer(document);
AtomicString type = userSuppliedName.lower();
if (!constructorBuilder->isFeatureAllowed()) {
CustomElementException::throwException(CustomElementException::CannotRegisterFromExtension, type, exceptionState);
return 0;
}
if (!CustomElement::isValidName(type, validNames)) {
CustomElementException::throwException(CustomElementException::InvalidName, type, exceptionState);
return 0;
}
QualifiedName tagName = QualifiedName::null();
if (!constructorBuilder->validateOptions(type, tagName, exceptionState))
return 0;
ASSERT(tagName.namespaceURI() == HTMLNames::xhtmlNamespaceURI || tagName.namespaceURI() == SVGNames::svgNamespaceURI);
// FIXME: This should be done earlier in validateOptions.
if (m_registeredTypeNames.contains(type)) {
CustomElementException::throwException(CustomElementException::TypeAlreadyRegistered, type, exceptionState);
return 0;
}
ASSERT(!observer.registrationContextWentAway());
RefPtr<CustomElementLifecycleCallbacks> lifecycleCallbacks = constructorBuilder->createCallbacks();
// Consulting the constructor builder could execute script and
// kill the document.
if (observer.registrationContextWentAway()) {
CustomElementException::throwException(CustomElementException::ContextDestroyedCreatingCallbacks, type, exceptionState);
return 0;
}
const CustomElementDescriptor descriptor(type, tagName.namespaceURI(), tagName.localName());
RefPtr<CustomElementDefinition> definition = CustomElementDefinition::create(descriptor, lifecycleCallbacks);
if (!constructorBuilder->createConstructor(document, definition.get(), exceptionState))
return 0;
m_definitions.add(descriptor, definition);
m_registeredTypeNames.add(descriptor.type());
if (!constructorBuilder->didRegisterDefinition(definition.get())) {
CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, type, exceptionState);
return 0;
}
return definition.get();
}
CustomElementDefinition* CustomElementRegistry::find(const CustomElementDescriptor& descriptor) const
{
return m_definitions.get(descriptor);
}
} // namespace blink
<commit_msg>Check for type registeration of Custom element before validating options<commit_after>/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* 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 Google Inc. 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.
*/
#include "config.h"
#include "core/dom/custom/CustomElementRegistry.h"
#include "bindings/core/v8/CustomElementConstructorBuilder.h"
#include "core/HTMLNames.h"
#include "core/SVGNames.h"
#include "core/dom/DocumentLifecycleObserver.h"
#include "core/dom/custom/CustomElementException.h"
#include "core/dom/custom/CustomElementRegistrationContext.h"
namespace blink {
class RegistrationContextObserver : public DocumentLifecycleObserver {
public:
explicit RegistrationContextObserver(Document* document)
: DocumentLifecycleObserver(document)
, m_wentAway(!document)
{
}
bool registrationContextWentAway() { return m_wentAway; }
private:
#if ENABLE(OILPAN)
// In oilpan we don't have the disposed phase for context lifecycle observer.
virtual void documentWasDetached() OVERRIDE { m_wentAway = true; }
#else
virtual void documentWasDisposed() OVERRIDE { m_wentAway = true; }
#endif
bool m_wentAway;
};
CustomElementDefinition* CustomElementRegistry::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& userSuppliedName, CustomElement::NameSet validNames, ExceptionState& exceptionState)
{
// FIXME: In every instance except one it is the
// CustomElementConstructorBuilder that observes document
// destruction during registration. This responsibility should be
// consolidated in one place.
RegistrationContextObserver observer(document);
AtomicString type = userSuppliedName.lower();
if (!constructorBuilder->isFeatureAllowed()) {
CustomElementException::throwException(CustomElementException::CannotRegisterFromExtension, type, exceptionState);
return 0;
}
if (!CustomElement::isValidName(type, validNames)) {
CustomElementException::throwException(CustomElementException::InvalidName, type, exceptionState);
return 0;
}
if (m_registeredTypeNames.contains(type)) {
CustomElementException::throwException(CustomElementException::TypeAlreadyRegistered, type, exceptionState);
return 0;
}
QualifiedName tagName = QualifiedName::null();
if (!constructorBuilder->validateOptions(type, tagName, exceptionState))
return 0;
ASSERT(tagName.namespaceURI() == HTMLNames::xhtmlNamespaceURI || tagName.namespaceURI() == SVGNames::svgNamespaceURI);
ASSERT(!observer.registrationContextWentAway());
RefPtr<CustomElementLifecycleCallbacks> lifecycleCallbacks = constructorBuilder->createCallbacks();
// Consulting the constructor builder could execute script and
// kill the document.
if (observer.registrationContextWentAway()) {
CustomElementException::throwException(CustomElementException::ContextDestroyedCreatingCallbacks, type, exceptionState);
return 0;
}
const CustomElementDescriptor descriptor(type, tagName.namespaceURI(), tagName.localName());
RefPtr<CustomElementDefinition> definition = CustomElementDefinition::create(descriptor, lifecycleCallbacks);
if (!constructorBuilder->createConstructor(document, definition.get(), exceptionState))
return 0;
m_definitions.add(descriptor, definition);
m_registeredTypeNames.add(descriptor.type());
if (!constructorBuilder->didRegisterDefinition(definition.get())) {
CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, type, exceptionState);
return 0;
}
return definition.get();
}
CustomElementDefinition* CustomElementRegistry::find(const CustomElementDescriptor& descriptor) const
{
return m_definitions.get(descriptor);
}
} // namespace blink
<|endoftext|>
|
<commit_before>// Source : https://leetcode.com/problems/restore-ip-addresses/
// Author : Yijing Bai
// Date : 2016-01-09
/**********************************************************************************
*
* Given a string containing only digits, restore it by returning all possible valid IP
* address combinations.
*
* For example:
* Given "25525511135",
*
* return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
*
*
*
*
*
**********************************************************************************/
<commit_msg>Finished Restore IP address<commit_after>// Source : https://leetcode.com/problems/restore-ip-addresses/
// Author : Yijing Bai
// Date : 2016-01-09
/**********************************************************************************
*
* Given a string containing only digits, restore it by returning all possible valid IP
* address combinations.
*
* For example:
* Given "25525511135",
*
* return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
*
**********************************************************************************/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
void restore_helper(vector<string>& result, string s, string restored, int index, int count) {
if (count > 4) return;
if (count == 4 && index == s.length()) {
result.push_back(restored);
return;
}
for (int i = 1; i < 4; i++) {
if (index + i > s.size()) break;
string subip = s.substr(index, i);
if ((subip[0] == '0' && subip.length() > 1) || (i == 3 && stoi(subip) >= 256)) continue;
restore_helper(result, s, restored + subip + (count == 3 ? "" : "."), index + i, count + 1);
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> result;
if (s == "") return result;
string restored;
restore_helper(result, s, restored, 0, 0);
return result;
}
};
int main() {
Solution s;
s.restoreIpAddresses("1111");
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkExceptionObject.h"
#include "otbImageFileReader.h"
#include "otbImage.h"
#include "otbStandardWriterWatcher.h"
#include "itkGradientMagnitudeImageFilter.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImageFileWriter.h"
int otbStandardWriterWatcher(int argc, char * argv[])
{
const char * infname = argv[1];
const char * outfname = argv[2];
const unsigned int nbsd = atoi(argv[3]);
const unsigned int Dimension = 2;
typedef unsigned char PixelType;
typedef otb::Image<PixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef itk::GradientMagnitudeImageFilter<ImageType, ImageType> FilterType;
typedef otb::StreamingImageFileWriter<ImageType> StreamingWriterType;
typedef otb::ImageFileWriter<ImageType> WriterType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
FilterType::Pointer gradient = FilterType::New();
gradient->SetInput(reader->GetOutput());
StreamingWriterType::Pointer writer1 = StreamingWriterType::New();
writer1->SetNumberOfStreamDivisions(nbsd);
writer1->SetInput(gradient->GetOutput());
writer1->SetFileName(outfname);
otb::StandardWriterWatcher watcher1(writer1, "Gradient (streaming)");
writer1->Update();
WriterType::Pointer writer2 = WriterType::New();
writer2->SetInput(gradient->GetOutput());
writer2->SetFileName(outfname);
otb::StandardWriterWatcher watcher2(writer2, "Gradient (non streaming)");
writer2->Update();
return EXIT_SUCCESS;
}
<commit_msg>TEST: coverage of StandardWriterWatcher<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkExceptionObject.h"
#include "otbImageFileReader.h"
#include "otbImage.h"
#include "otbStandardWriterWatcher.h"
#include "itkGradientMagnitudeImageFilter.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImageFileWriter.h"
int otbStandardWriterWatcher(int argc, char * argv[])
{
const char * infname = argv[1];
const char * outfname = argv[2];
const unsigned int nbsd = atoi(argv[3]);
const unsigned int Dimension = 2;
typedef unsigned char PixelType;
typedef otb::Image<PixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef itk::GradientMagnitudeImageFilter<ImageType, ImageType> FilterType;
typedef otb::StreamingImageFileWriter<ImageType> StreamingWriterType;
typedef otb::ImageFileWriter<ImageType> WriterType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
FilterType::Pointer gradient = FilterType::New();
gradient->SetInput(reader->GetOutput());
StreamingWriterType::Pointer writer1 = StreamingWriterType::New();
writer1->SetNumberOfStreamDivisions(nbsd);
writer1->SetInput(gradient->GetOutput());
writer1->SetFileName(outfname);
otb::StandardWriterWatcher watcher1(writer1, "Gradient (streaming)");
otb::StandardWriterWatcher watcher3(writer1, gradient, "Gradient");
otb::StandardWriterWatcher watcher4(watcher1);
otb::StandardWriterWatcher watcher5 = watcher1;
writer1->Update();
WriterType::Pointer writer2 = WriterType::New();
writer2->SetInput(gradient->GetOutput());
writer2->SetFileName(outfname);
otb::StandardWriterWatcher watcher2(writer2, "Gradient (non streaming)");
writer2->Update();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <SpecificLogFile.hpp>
#include <Utility/Utilities/Include/Logging/LogTag.hpp>
#include <Utility/Utilities/Include/Logging/LogLevel.hpp>
#include <Utility/Utilities/Include/Logging/LogTagConverter.hpp>
#include <Utility/Utilities/Include/Logging/LogTextData.hpp>
#include <Utility/Utilities/Include/String/StringHelper.hpp>
#include <Utility/Utilities/Include/Chrono/Timer.hpp>
#include <iostream>
#include <exception>
#include <Windows.h>
using namespace Doremi::Utilities;
SpecificLogFile::SpecificLogFile() : m_fileStream(nullptr), m_timer(nullptr), m_flushTimerLimit(0), m_elapsedTime(0)
{
m_timer = new Chrono::Timer();
// TODORT
// TODOXX Might decrease / increase the performance
// TODOCONF ??
m_flushTimerLimit = 1.0;
}
SpecificLogFile::~SpecificLogFile()
{
if(m_fileStream != nullptr)
{
m_fileStream->close();
delete m_fileStream;
}
}
void SpecificLogFile::Initialize(const Logging::LogTag& p_logTag)
{
Logging::LogTagInfo fileNameInfo = Logging::LogTagConverter::convert(p_logTag);
fileNameInfo.name.append(".txt");
BuildLogFile(fileNameInfo.name);
OpenFileStream(fileNameInfo.name);
}
void SpecificLogFile::BuildLogFile(const std::string& p_fileName)
{
void* fileHandle = CreateFile(String::StringToWideString(p_fileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);
if(fileHandle == nullptr)
{
const std::string message = std::string("Failed to build logfile with given name: ") + p_fileName;
throw std::runtime_error(message);
}
CloseHandle(fileHandle);
}
void SpecificLogFile::OpenFileStream(const std::string& p_fileName)
{
m_fileStream = new std::ofstream(p_fileName, std::ofstream::out | std::ofstream::app);
if(m_fileStream->is_open() == false)
{
const std::string message = std::string("Failed to open filestream to given filename: ") + p_fileName;
throw std::runtime_error(message);
}
}
void SpecificLogFile::Write(const Doremi::Utilities::Logging::LogTextData& p_data)
{
*m_fileStream << p_data.message << "\n";
m_elapsedTime += m_timer->Tick().GetElapsedTimeInSeconds();
// If called often, flush
if(m_elapsedTime > m_flushTimerLimit)
{
Flush();
}
}
void SpecificLogFile::Flush()
{
m_elapsedTime = 0;
m_fileStream->flush();
}
<commit_msg>Removed memory leak by deleting variables<commit_after>#include <SpecificLogFile.hpp>
#include <Utility/Utilities/Include/Logging/LogTag.hpp>
#include <Utility/Utilities/Include/Logging/LogLevel.hpp>
#include <Utility/Utilities/Include/Logging/LogTagConverter.hpp>
#include <Utility/Utilities/Include/Logging/LogTextData.hpp>
#include <Utility/Utilities/Include/String/StringHelper.hpp>
#include <Utility/Utilities/Include/Chrono/Timer.hpp>
#include <iostream>
#include <exception>
#include <Windows.h>
using namespace Doremi::Utilities;
SpecificLogFile::SpecificLogFile() : m_fileStream(nullptr), m_timer(nullptr), m_flushTimerLimit(0), m_elapsedTime(0)
{
m_timer = new Chrono::Timer();
// TODORT
// TODOXX Might decrease / increase the performance
// TODOCONF ??
m_flushTimerLimit = 1.0;
}
SpecificLogFile::~SpecificLogFile()
{
if(m_fileStream != nullptr)
{
m_fileStream->close();
delete m_fileStream;
}
if(m_timer != nullptr)
{
delete m_timer;
}
}
void SpecificLogFile::Initialize(const Logging::LogTag& p_logTag)
{
Logging::LogTagInfo fileNameInfo = Logging::LogTagConverter::convert(p_logTag);
fileNameInfo.name.append(".txt");
BuildLogFile(fileNameInfo.name);
OpenFileStream(fileNameInfo.name);
}
void SpecificLogFile::BuildLogFile(const std::string& p_fileName)
{
void* fileHandle = CreateFile(String::StringToWideString(p_fileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);
if(fileHandle == nullptr)
{
const std::string message = std::string("Failed to build logfile with given name: ") + p_fileName;
throw std::runtime_error(message);
}
CloseHandle(fileHandle);
}
void SpecificLogFile::OpenFileStream(const std::string& p_fileName)
{
m_fileStream = new std::ofstream(p_fileName, std::ofstream::out | std::ofstream::app);
if(m_fileStream->is_open() == false)
{
const std::string message = std::string("Failed to open filestream to given filename: ") + p_fileName;
throw std::runtime_error(message);
}
}
void SpecificLogFile::Write(const Doremi::Utilities::Logging::LogTextData& p_data)
{
*m_fileStream << p_data.message << "\n";
m_elapsedTime += m_timer->Tick().GetElapsedTimeInSeconds();
// If called often, flush
if(m_elapsedTime > m_flushTimerLimit)
{
Flush();
}
}
void SpecificLogFile::Flush()
{
m_elapsedTime = 0;
m_fileStream->flush();
}
<|endoftext|>
|
<commit_before>#include "Keyboard.h"
#include "Login.h"
#include "ServicesHandler.h"
#include "MainCharacter.h"
#include "EnemyCharacter.h"
#include "Door.h"
#include "Graphics.h"
extern Status *status;
extern Model *model;
extern MainCharacter *character;
extern EnemyCharacter *enemy;
extern Door *door1;
void Keyboard::loginKeyboard(unsigned char key, int x, int y) {
if (status->nextInput) { // enter in passwod
if (key == 13) {
Login *login = new Login();
int id = login->LoginUser(status->username, status->password);
int x = 1;
if (id >= 1) { // valid user // for testing purpose replace by 'true' and press ENTER twice
status->loggedIn = true;
status->password = "";
status->passwd = "";
Keyboard::help();
/* SET UP THE MUSIC */
status->background_music = new Music("background.wav");
//status->background_music->play();
} else {
status->username = "";
status->password = "";
status->passwd = "";
status->nextInput = false;
status->loginErrorMessage = "Invalid user, try again !!";
}
}
else if (key == 8) { // backspace
if (status->password.compare("") != 0) {
status->password.pop_back();
status->passwd.pop_back();
}
} else {
if (key > 33 && key < 126) {
status->password.push_back(key);
status->passwd.push_back('*');
}
}
}
else {
if (key == 13) { // enter in username
status->nextInput = true; // go to password
}
else if (key == 8) { // backspace
if (status->username.compare("") != 0) {
status->username.pop_back();
}
} else {
if (key > 33 && key < 126) {
status->username.push_back(key);
}
}
}
glutPostRedisplay();
}
void Keyboard::keyboardUp(unsigned char key, int x, int y){
switch (key) {
case ' ':
status->attacking = GL_FALSE;
break;
}
}
void Keyboard::keyboard(unsigned char key, int x, int y){
if (status->loggedIn) {
switch (key) {
case 27:
if (status->finished == false && status->gameRoute.compare("") != 0) {
ServicesHandler *handler = new ServicesHandler();
handler->uploadScore(status->score);
handler->uploadRoute(status->gameRoute);
}
exit(0);
break;
}
// in case wordls menu is visible
if (status->showMapMenu) {
switch (key) {
case'1':
status->mapfile = "mundo1.grafo";
leGrafo(status->mapfile);
status->showMapMenu = false;
status->mainMenu = false;
break;
case '2':
status->mapfile = "quarto1.grafo";
leGrafo(status->mapfile);
status->showMapMenu = false;
status->mainMenu = false;
break;
case '0':
status->showMapMenu = false;
status->mainMenu = true;
break;
}
}
else if (status->showSoundsMenu) {
switch (key) {
case '0':
status->showSoundsMenu = false;
status->mainMenu = true;
break;
}
int option = key - 48; // convert key
if (option > 0 && option <= status->soundsList.size()) {
ServicesHandler *handler = new ServicesHandler();
handler->saveSound(status->soundsList.at(option-1));
status->showSoundsMenu = false;
Graphics::createTextures(model->texID);
}
}
else if (status->showTexturesMenu) {
switch (key) {
case '0':
status->showTexturesMenu = false;
status->mainMenu = true;
break;
}
int option = key - 48; // convert key
if (option > 0 && option <= status->texturesList.size()) {
ServicesHandler *handler = new ServicesHandler();
handler->saveTexture(status->texturesList.at(option-1));
status->showTexturesMenu = false;
Graphics::createTextures(model->texID);
}
}
else if (status->showEnemiesModelsMenu){
switch (key){
case '0':
status->showEnemiesModelsMenu = false;
status->mainMenu = true;
break;
}
int option = key - 48;
if (option > 0 && option <= status->enemiesModelsList.size()){
ServicesHandler *sh = new ServicesHandler();
sh->saveModels(status->enemiesModelsList.at(option - 1));
status->showEnemiesModelsMenu = false;
}
}
else {
switch (key){
case 27:
if (status->finished == false && status->gameRoute.compare("") != 0) {
ServicesHandler *handler = new ServicesHandler();
handler->uploadScore(status->score);
handler->uploadRoute(status->gameRoute);
}
exit(0);
break;
case 'h':
case 'H':
Keyboard::help();
break;
case 'l':
case 'L':
if (status->lightViewer)
status->lightViewer = 0;
else
status->lightViewer = 1;
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, status->lightViewer);
glutPostRedisplay();
break;
case 'k':
case 'K':
status->light = !status->light;
glutPostRedisplay();
break;
case 'w':
case 'W':
glDisable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glutPostRedisplay();
break;
case 'p':
case 'P':
glDisable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
glutPostRedisplay();
break;
case 's':
case 'S':
glEnable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glutPostRedisplay();
break;
case 'c':
case 'C':
if (status->mainMenu && status->finished == false) {
status->mainMenu = false;
}
else {
if (glIsEnabled(GL_CULL_FACE))
glDisable(GL_CULL_FACE);
else
glEnable(GL_CULL_FACE);
glutPostRedisplay();
break;
}
case 'n':
case 'N':
if (status->mainMenu) {
//INICIAR NOVO JOGO
status->setDefaults();
model->setDefaults();
character->setDefaults();
character->homer.SetSequence(0);
enemy->setDefaults();
door1->setDefaults(15, 290);
status->mainMenu = false;
}
else {
status->apresentaNormais = !status->apresentaNormais;
glutPostRedisplay();
}
break;
case 'i':
case 'I':
//INICIAR NOVO JOGO
status->setDefaults();
model->setDefaults();
character->setDefaults();
character->homer.SetSequence(0);
enemy->setDefaults();
door1->setDefaults(15, 290);
status->mainMenu = false;
break;
case 'o':
case 'O':
status->tecla_o = !status->tecla_o;
break;
case 'm':
case 'M':
//status->showMapMenu = !status->showMapMenu;
status->snow = GL_FALSE;
status->mainMenu = !status->mainMenu;
break;
case 'd':
case 'D':
status->daynight = GL_FALSE;
if (status->main_light == white_light) {
status->main_light = (GLfloat*)night_light;
}
else {
status->main_light = (GLfloat*)white_light;
}
break;
case '1':
status->showMapMenu = true;
status->showSoundsMenu = false;
status->showTexturesMenu = false;
break;
case '2':
status->showSoundsMenu = true;
status->showMapMenu = false;
status->showTexturesMenu = false;
break;
case '3':
status->showTexturesMenu = !status->showTexturesMenu;
status->showSoundsMenu = false;
status->showMapMenu = false;
break;
case '4':
status->showEnemiesModelsMenu = true;
break;
case '5':
if (!status->mainMenu) {
status->rain = !status->rain;
}
break;
case '6':
if (!status->mainMenu) {
status->snow = !status->snow;
}
break;
case 'F':
case 'f':
status->spotlight = !status->spotlight;
break;
case ' ':
status->attacking = GL_TRUE;
break;
}
}
}
else {
loginKeyboard(key, x, y);
}
}
void Keyboard::specialKeyUp(int key, int x, int y)
{
if (status->loggedIn) {
switch (key)
{
// case 'o':
// case 'O':
// status->tecla_o = AL_FALSE;
// break;
case GLUT_KEY_UP: {
status->up = GL_FALSE;
string novo = "(" + to_string((int)character->position->x) + "," + to_string((int)character->position->y) + "," + to_string((int)character->position->y) + "),";
status->gameRoute += novo;
break;
}
case GLUT_KEY_DOWN:
status->down = GL_FALSE;
break;
case GLUT_KEY_LEFT:
status->left = GL_FALSE;
break;
case GLUT_KEY_RIGHT:
status->right = GL_FALSE;
break;
}
}
}
void Keyboard::Special(int key, int x, int y){
if (status->loggedIn) {
switch (key){
case GLUT_KEY_F1:
gravaGrafo(status->mapfile);
break;
case GLUT_KEY_F2:
leGrafo(status->mapfile);
glutPostRedisplay();
break;
case GLUT_KEY_F3:
status->top = GL_TRUE;
status->first = GL_FALSE;
glutPostRedisplay();
break;
case GLUT_KEY_F4:
status->top = GL_FALSE;
status->first = GL_TRUE;
glutPostRedisplay();
break;
case GLUT_KEY_F5:
status->top = GL_FALSE;
status->first = GL_FALSE;
glutPostRedisplay();
break;
case GLUT_KEY_F6:
numNos = numArcos = 0;
addNo(criaNo(0, 10, 0)); // 0
addNo(criaNo(0, 5, 0)); // 1
addNo(criaNo(-5, 5, 0)); // 2
addNo(criaNo(5, 5, 0)); // 3
addNo(criaNo(-5, 0, 0)); // 4
addNo(criaNo(5, 0, 0)); // 5
addNo(criaNo(-5, -5, 0)); // 6
addArco(criaArco(0, 1, 1, 1)); // 0 - 1
addArco(criaArco(1, 2, 1, 1)); // 1 - 2
addArco(criaArco(1, 3, 1, 1)); // 1 - 3
addArco(criaArco(2, 4, 1, 1)); // 2 - 4
addArco(criaArco(3, 5, 1, 1)); // 3 - 5
addArco(criaArco(4, 5, 1, 1)); // 4 - 5
addArco(criaArco(4, 6, 1, 1)); // 4 - 6
glutPostRedisplay();
break;
/*case GLUT_KEY_UP:
status->camera->dist -= 1;
glutPostRedisplay();
break;
case GLUT_KEY_DOWN:
status->camera->dist += 1;
glutPostRedisplay();
break;*/
case GLUT_KEY_UP:
status->up = GL_TRUE;
break;
case GLUT_KEY_DOWN:
status->down = GL_TRUE;
break;
case GLUT_KEY_LEFT:
status->left = GL_TRUE;
break;
case GLUT_KEY_RIGHT:
status->right = GL_TRUE;
break;
}
}
}
void Keyboard::help(void){
printf("\n\nDesenho de um labirinto a partir de um grafo\n");
printf("h,H - Ajuda \n");
printf("i,I - Reset dos Valores \n");
printf("******* Diversos ******* \n");
printf("l,L - Alterna o calculo luz entre Z e eye (GL_LIGHT_MODEL_LOCAL_VIEWER)\n");
printf("k,K - Alerna luz de camera com luz global \n");
printf("s,S - PolygonMode Fill \n");
printf("w,W - PolygonMode Wireframe \n");
printf("p,P - PolygonMode Point \n");
printf("c,C - Liga/Desliga Cull Face \n");
printf("n,N - Liga/Desliga apresentaÁ„o das normais \n");
printf("d,D - Alternar entre dia / noite\n");
printf("******* Mundos ******* \n");
printf("m,M - Seleccionar mundo \n");
printf("******* grafos ******* \n");
printf("F1 - Grava grafo do ficheiro \n");
printf("F2 - LÍ grafo para ficheiro \n");
printf("F6 - Cria novo grafo\n");
printf("******* Camera ******* \n");
printf("Bot„o esquerdo - Arrastar os eixos (centro da camera)\n");
printf("Bot„o direito - Rodar camera\n");
printf("Bot„o direito com CTRL - Zoom-in/out\n");
printf("PAGE_UP, PAGE_DOWN - Altera dist‚ncia da camara \n");
printf("ESC - Sair\n");
}
<commit_msg>Decommented background music<commit_after>#include "Keyboard.h"
#include "Login.h"
#include "ServicesHandler.h"
#include "MainCharacter.h"
#include "EnemyCharacter.h"
#include "Door.h"
#include "Graphics.h"
extern Status *status;
extern Model *model;
extern MainCharacter *character;
extern EnemyCharacter *enemy;
extern Door *door1;
void Keyboard::loginKeyboard(unsigned char key, int x, int y) {
if (status->nextInput) { // enter in passwod
if (key == 13) {
Login *login = new Login();
int id = login->LoginUser(status->username, status->password);
int x = 1;
if (id >= 1) { // valid user // for testing purpose replace by 'true' and press ENTER twice
status->loggedIn = true;
status->password = "";
status->passwd = "";
Keyboard::help();
/* SET UP THE MUSIC */
status->background_music = new Music("background.wav");
status->background_music->play();
} else {
status->username = "";
status->password = "";
status->passwd = "";
status->nextInput = false;
status->loginErrorMessage = "Invalid user, try again !!";
}
}
else if (key == 8) { // backspace
if (status->password.compare("") != 0) {
status->password.pop_back();
status->passwd.pop_back();
}
} else {
if (key > 33 && key < 126) {
status->password.push_back(key);
status->passwd.push_back('*');
}
}
}
else {
if (key == 13) { // enter in username
status->nextInput = true; // go to password
}
else if (key == 8) { // backspace
if (status->username.compare("") != 0) {
status->username.pop_back();
}
} else {
if (key > 33 && key < 126) {
status->username.push_back(key);
}
}
}
glutPostRedisplay();
}
void Keyboard::keyboardUp(unsigned char key, int x, int y){
switch (key) {
case ' ':
status->attacking = GL_FALSE;
break;
}
}
void Keyboard::keyboard(unsigned char key, int x, int y){
if (status->loggedIn) {
switch (key) {
case 27:
if (status->finished == false && status->gameRoute.compare("") != 0) {
ServicesHandler *handler = new ServicesHandler();
handler->uploadScore(status->score);
handler->uploadRoute(status->gameRoute);
}
exit(0);
break;
}
// in case wordls menu is visible
if (status->showMapMenu) {
switch (key) {
case'1':
status->mapfile = "mundo1.grafo";
leGrafo(status->mapfile);
status->showMapMenu = false;
status->mainMenu = false;
break;
case '2':
status->mapfile = "quarto1.grafo";
leGrafo(status->mapfile);
status->showMapMenu = false;
status->mainMenu = false;
break;
case '0':
status->showMapMenu = false;
status->mainMenu = true;
break;
}
}
else if (status->showSoundsMenu) {
switch (key) {
case '0':
status->showSoundsMenu = false;
status->mainMenu = true;
break;
}
int option = key - 48; // convert key
if (option > 0 && option <= status->soundsList.size()) {
ServicesHandler *handler = new ServicesHandler();
handler->saveSound(status->soundsList.at(option-1));
status->showSoundsMenu = false;
Graphics::createTextures(model->texID);
}
}
else if (status->showTexturesMenu) {
switch (key) {
case '0':
status->showTexturesMenu = false;
status->mainMenu = true;
break;
}
int option = key - 48; // convert key
if (option > 0 && option <= status->texturesList.size()) {
ServicesHandler *handler = new ServicesHandler();
handler->saveTexture(status->texturesList.at(option-1));
status->showTexturesMenu = false;
Graphics::createTextures(model->texID);
}
}
else if (status->showEnemiesModelsMenu){
switch (key){
case '0':
status->showEnemiesModelsMenu = false;
status->mainMenu = true;
break;
}
int option = key - 48;
if (option > 0 && option <= status->enemiesModelsList.size()){
ServicesHandler *sh = new ServicesHandler();
sh->saveModels(status->enemiesModelsList.at(option - 1));
status->showEnemiesModelsMenu = false;
}
}
else {
switch (key){
case 27:
if (status->finished == false && status->gameRoute.compare("") != 0) {
ServicesHandler *handler = new ServicesHandler();
handler->uploadScore(status->score);
handler->uploadRoute(status->gameRoute);
}
exit(0);
break;
case 'h':
case 'H':
Keyboard::help();
break;
case 'l':
case 'L':
if (status->lightViewer)
status->lightViewer = 0;
else
status->lightViewer = 1;
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, status->lightViewer);
glutPostRedisplay();
break;
case 'k':
case 'K':
status->light = !status->light;
glutPostRedisplay();
break;
case 'w':
case 'W':
glDisable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glutPostRedisplay();
break;
case 'p':
case 'P':
glDisable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
glutPostRedisplay();
break;
case 's':
case 'S':
glEnable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glutPostRedisplay();
break;
case 'c':
case 'C':
if (status->mainMenu && status->finished == false) {
status->mainMenu = false;
}
else {
if (glIsEnabled(GL_CULL_FACE))
glDisable(GL_CULL_FACE);
else
glEnable(GL_CULL_FACE);
glutPostRedisplay();
break;
}
case 'n':
case 'N':
if (status->mainMenu) {
//INICIAR NOVO JOGO
status->setDefaults();
model->setDefaults();
character->setDefaults();
character->homer.SetSequence(0);
enemy->setDefaults();
door1->setDefaults(15, 290);
status->mainMenu = false;
}
else {
status->apresentaNormais = !status->apresentaNormais;
glutPostRedisplay();
}
break;
case 'i':
case 'I':
//INICIAR NOVO JOGO
status->setDefaults();
model->setDefaults();
character->setDefaults();
character->homer.SetSequence(0);
enemy->setDefaults();
door1->setDefaults(15, 290);
status->mainMenu = false;
break;
case 'o':
case 'O':
status->tecla_o = !status->tecla_o;
break;
case 'm':
case 'M':
//status->showMapMenu = !status->showMapMenu;
status->snow = GL_FALSE;
status->mainMenu = !status->mainMenu;
break;
case 'd':
case 'D':
status->daynight = GL_FALSE;
if (status->main_light == white_light) {
status->main_light = (GLfloat*)night_light;
}
else {
status->main_light = (GLfloat*)white_light;
}
break;
case '1':
status->showMapMenu = true;
status->showSoundsMenu = false;
status->showTexturesMenu = false;
break;
case '2':
status->showSoundsMenu = true;
status->showMapMenu = false;
status->showTexturesMenu = false;
break;
case '3':
status->showTexturesMenu = !status->showTexturesMenu;
status->showSoundsMenu = false;
status->showMapMenu = false;
break;
case '4':
status->showEnemiesModelsMenu = true;
break;
case '5':
if (!status->mainMenu) {
status->rain = !status->rain;
}
break;
case '6':
if (!status->mainMenu) {
status->snow = !status->snow;
}
break;
case 'F':
case 'f':
status->spotlight = !status->spotlight;
break;
case ' ':
status->attacking = GL_TRUE;
break;
}
}
}
else {
loginKeyboard(key, x, y);
}
}
void Keyboard::specialKeyUp(int key, int x, int y)
{
if (status->loggedIn) {
switch (key)
{
// case 'o':
// case 'O':
// status->tecla_o = AL_FALSE;
// break;
case GLUT_KEY_UP: {
status->up = GL_FALSE;
string novo = "(" + to_string((int)character->position->x) + "," + to_string((int)character->position->y) + "," + to_string((int)character->position->y) + "),";
status->gameRoute += novo;
break;
}
case GLUT_KEY_DOWN:
status->down = GL_FALSE;
break;
case GLUT_KEY_LEFT:
status->left = GL_FALSE;
break;
case GLUT_KEY_RIGHT:
status->right = GL_FALSE;
break;
}
}
}
void Keyboard::Special(int key, int x, int y){
if (status->loggedIn) {
switch (key){
case GLUT_KEY_F1:
gravaGrafo(status->mapfile);
break;
case GLUT_KEY_F2:
leGrafo(status->mapfile);
glutPostRedisplay();
break;
case GLUT_KEY_F3:
status->top = GL_TRUE;
status->first = GL_FALSE;
glutPostRedisplay();
break;
case GLUT_KEY_F4:
status->top = GL_FALSE;
status->first = GL_TRUE;
glutPostRedisplay();
break;
case GLUT_KEY_F5:
status->top = GL_FALSE;
status->first = GL_FALSE;
glutPostRedisplay();
break;
case GLUT_KEY_F6:
numNos = numArcos = 0;
addNo(criaNo(0, 10, 0)); // 0
addNo(criaNo(0, 5, 0)); // 1
addNo(criaNo(-5, 5, 0)); // 2
addNo(criaNo(5, 5, 0)); // 3
addNo(criaNo(-5, 0, 0)); // 4
addNo(criaNo(5, 0, 0)); // 5
addNo(criaNo(-5, -5, 0)); // 6
addArco(criaArco(0, 1, 1, 1)); // 0 - 1
addArco(criaArco(1, 2, 1, 1)); // 1 - 2
addArco(criaArco(1, 3, 1, 1)); // 1 - 3
addArco(criaArco(2, 4, 1, 1)); // 2 - 4
addArco(criaArco(3, 5, 1, 1)); // 3 - 5
addArco(criaArco(4, 5, 1, 1)); // 4 - 5
addArco(criaArco(4, 6, 1, 1)); // 4 - 6
glutPostRedisplay();
break;
/*case GLUT_KEY_UP:
status->camera->dist -= 1;
glutPostRedisplay();
break;
case GLUT_KEY_DOWN:
status->camera->dist += 1;
glutPostRedisplay();
break;*/
case GLUT_KEY_UP:
status->up = GL_TRUE;
break;
case GLUT_KEY_DOWN:
status->down = GL_TRUE;
break;
case GLUT_KEY_LEFT:
status->left = GL_TRUE;
break;
case GLUT_KEY_RIGHT:
status->right = GL_TRUE;
break;
}
}
}
void Keyboard::help(void){
printf("\n\nDesenho de um labirinto a partir de um grafo\n");
printf("h,H - Ajuda \n");
printf("i,I - Reset dos Valores \n");
printf("******* Diversos ******* \n");
printf("l,L - Alterna o calculo luz entre Z e eye (GL_LIGHT_MODEL_LOCAL_VIEWER)\n");
printf("k,K - Alerna luz de camera com luz global \n");
printf("s,S - PolygonMode Fill \n");
printf("w,W - PolygonMode Wireframe \n");
printf("p,P - PolygonMode Point \n");
printf("c,C - Liga/Desliga Cull Face \n");
printf("n,N - Liga/Desliga apresentaÁ„o das normais \n");
printf("d,D - Alternar entre dia / noite\n");
printf("******* Mundos ******* \n");
printf("m,M - Seleccionar mundo \n");
printf("******* grafos ******* \n");
printf("F1 - Grava grafo do ficheiro \n");
printf("F2 - LÍ grafo para ficheiro \n");
printf("F6 - Cria novo grafo\n");
printf("******* Camera ******* \n");
printf("Bot„o esquerdo - Arrastar os eixos (centro da camera)\n");
printf("Bot„o direito - Rodar camera\n");
printf("Bot„o direito com CTRL - Zoom-in/out\n");
printf("PAGE_UP, PAGE_DOWN - Altera dist‚ncia da camara \n");
printf("ESC - Sair\n");
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: diagram.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2008-01-17 08:05:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <functional>
#include <boost/bind.hpp>
#include "oox/drawingml/diagram/diagram.hxx"
#include "oox/core/namespaces.hxx"
#include "tokens.hxx"
namespace oox { namespace drawingml {
namespace dgm {
void Connection::dump()
{
OSL_TRACE("dgm: cnx modelId %s, srcId %s, dstId %s",
OUSTRING_TO_CSTR( msModelId ),
OUSTRING_TO_CSTR( msSourceId ),
OUSTRING_TO_CSTR( msDestId ) );
}
Point::Point()
: mpShape( new Shape( "com.sun.star.drawing.GroupShape" ) )
, mnType( 0 )
{
}
void Point::dump()
{
OSL_TRACE( "dgm: pt cnxId %s, modelId %s",
OUSTRING_TO_CSTR( msCnxId ),
OUSTRING_TO_CSTR( msModelId ) );
}
}
DiagramData::DiagramData()
: mpFillProperties( new FillProperties( ) )
{
}
void DiagramData::dump()
{
OSL_TRACE("Dgm: DiagramData # of cnx: %d", maConnections.size() );
std::for_each( maConnections.begin(), maConnections.end(),
boost::bind( &dgm::Connection::dump, _1 ) );
OSL_TRACE("Dgm: DiagramData # of pt: %d", maPoints.size() );
std::for_each( maPoints.begin(), maPoints.end(),
boost::bind( &dgm::Point::dump, _1 ) );
}
void Diagram::setData( const DiagramDataPtr & pData)
{
mpData = pData;
}
void Diagram::setLayout( const DiagramLayoutPtr & pLayout)
{
mpLayout = pLayout;
}
void Diagram::setQStyles( const DiagramQStylesPtr & pStyles)
{
mpQStyles = pStyles;
}
void Diagram::setColors( const DiagramColorsPtr & pColors)
{
mpColors = pColors;
}
void Diagram::addTo( const ShapePtr & pShape )
{
dgm::Points & aPoints( mpData->getPoints( ) );
std::for_each( aPoints.begin(), aPoints.end(),
boost::bind( &Shape::addChild, boost::ref( pShape ),
boost::bind( &dgm::Point::getShape, _1 ) ) );
OSL_TRACE( "Dgm: addTo() # of childs %d", pShape->getChilds().size() );
for( std::vector< ShapePtr >::iterator iter = pShape->getChilds().begin();
iter != pShape->getChilds().end(); ++iter)
{
OSL_TRACE( "Dgm: shape name %s", OUSTRING_TO_CSTR( (*iter)->getName() ) );
}
}
} }
<commit_msg>INTEGRATION: CWS xmlfilter03_DEV300 (1.2.4); FILE MERGED 2008/01/24 22:01:50 hub 1.2.4.1: More work on SmartArt. Non-functionnal layout.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: diagram.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2008-03-05 18:37:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <functional>
#include <boost/bind.hpp>
#include <com/sun/star/awt/Point.hpp>
#include <com/sun/star/awt/Size.hpp>
#include "oox/drawingml/diagram/diagram.hxx"
#include "oox/core/namespaces.hxx"
#include "tokens.hxx"
using rtl::OUString;
using namespace ::com::sun::star;
namespace oox { namespace drawingml {
namespace dgm {
void Connection::dump()
{
OSL_TRACE("dgm: cnx modelId %s, srcId %s, dstId %s",
OUSTRING_TO_CSTR( msModelId ),
OUSTRING_TO_CSTR( msSourceId ),
OUSTRING_TO_CSTR( msDestId ) );
}
Point::Point()
: mpShape( new Shape( "com.sun.star.drawing.GraphicObjectShape" ) )
, mnType( 0 )
{
}
void Point::dump()
{
OSL_TRACE( "dgm: pt cnxId %s, modelId %s",
OUSTRING_TO_CSTR( msCnxId ),
OUSTRING_TO_CSTR( msModelId ) );
}
void Point::setModelId( const ::rtl::OUString & sModelId )
{
msModelId = sModelId;
mpShape->setName( msModelId );
}
bool PointsTree::addChild( const PointsTreePtr & pChild )
{
bool added = false;
OSL_ENSURE( pChild->mpParent.expired(), "can't add, has already a parent" );
OSL_ENSURE( mpNode, "has no node" );
if( mpNode && pChild->mpParent.expired() )
{
pChild->mpParent = shared_from_this();
maChildrens.push_back( pChild );
added = true;
}
return added;
}
PointsTreePtr PointsTree::getParent() const
{
if( !mpParent.expired() )
{
return mpParent.lock() ;
}
return PointsTreePtr();
}
} // dgm namespace
DiagramData::DiagramData()
: mpFillProperties( new FillProperties( ) )
{
}
void DiagramData::dump()
{
OSL_TRACE("Dgm: DiagramData # of cnx: %d", maConnections.size() );
std::for_each( maConnections.begin(), maConnections.end(),
boost::bind( &dgm::Connection::dump, _1 ) );
OSL_TRACE("Dgm: DiagramData # of pt: %d", maPoints.size() );
std::for_each( maPoints.begin(), maPoints.end(),
boost::bind( &dgm::Point::dump, _1 ) );
}
static void setPosition( const dgm::PointPtr & pPoint, const awt::Point & pt )
{
ShapePtr pShape = pPoint->getShape();
awt::Size sz;
sz.Width = 50;
sz.Height = 50;
pShape->setPosition( pt );
pShape->setSize( sz );
}
void DiagramLayout::layout( const dgm::PointsTreePtr & pTree, const awt::Point & pt )
{
setPosition( pTree->getPoint(), pt );
awt::Point nextPt = pt;
nextPt.Y += 50;
dgm::PointsTree::Childrens::const_iterator iter;
for( iter = pTree->beginChild(); iter != pTree->endChild(); iter++ )
{
layout( *iter, nextPt );
nextPt.X += 50;
}
}
void Diagram::setData( const DiagramDataPtr & pData)
{
mpData = pData;
}
void Diagram::setLayout( const DiagramLayoutPtr & pLayout)
{
mpLayout = pLayout;
}
void Diagram::setQStyles( const DiagramQStylesPtr & pStyles)
{
mpQStyles = pStyles;
}
void Diagram::setColors( const DiagramColorsPtr & pColors)
{
mpColors = pColors;
}
void Diagram::build( )
{
OSL_TRACE( "building diagram" );
typedef std::map< OUString, dgm::PointPtr > PointsMap;
PointsMap aPointsMap;
dgm::Points::iterator aPointsIter( mpData->getPoints( ).begin() );
for( ; aPointsIter != mpData->getPoints( ).end() ; aPointsIter++ )
{
const OUString & sName((*aPointsIter)->getModelId());
if( sName.getLength() > 0 )
{
aPointsMap[ sName ] = *aPointsIter;
}
}
typedef std::map< OUString, dgm::PointsTreePtr > PointsTreeMap;
PointsTreeMap aTreeMap;
PointsTreeMap aRoots;
dgm::Connections & aConnections(mpData->getConnections( ) );
dgm::Connections::iterator aCnxIter;
for( aCnxIter = aConnections.begin(); aCnxIter != aConnections.end(); ++aCnxIter )
{
OSL_ENSURE( *aCnxIter, "NULL connection found" );
if( (*aCnxIter)->mnType != XML_parOf )
{
// OSL_TRACE( "ignoring relation %s", OUSTRING_TO_CSTR( (*aCnxIter)->msModelId ) );
continue;
}
dgm::PointPtr pDest;
dgm::PointsTreePtr pSource;
PointsMap::iterator iterP;
OUString & srcId( (*aCnxIter)->msSourceId );
OUString & dstId( (*aCnxIter)->msDestId );
OSL_TRACE( "connexion %s -> %s", OUSTRING_TO_CSTR( srcId ),
OUSTRING_TO_CSTR( dstId ) );
PointsTreeMap::iterator iterT = aTreeMap.find( srcId );
if( iterT != aTreeMap.end() )
{
pSource = iterT->second;
}
else
{
// this tree node is not found. create it with the source
// and make it the root node.
iterP = aPointsMap.find( srcId );
if( iterP != aPointsMap.end() )
{
pSource.reset( new dgm::PointsTree( iterP->second ) );
aRoots[ srcId ] = pSource;
aTreeMap[ srcId ] = pSource;
}
else
{
OSL_TRACE("parent node not found !");
}
}
iterP = aPointsMap.find( dstId );
if( iterP != aPointsMap.end() )
{
pDest = iterP->second;
}
OSL_ENSURE( pDest, "destination not found" );
OSL_ENSURE( pSource, "source not found" );
if(pDest && pSource)
{
dgm::PointsTreePtr pNode( new dgm::PointsTree( pDest ) );
bool added = pSource->addChild( pNode );
(void)added;
aRoots.erase( dstId );
OSL_ENSURE( added, "add child failed" );
aTreeMap[ dstId ] = pNode;
}
}
// check bounds
OSL_ENSURE( aRoots.size() == 1, "more than one root" );
mpRoot = aRoots.begin()->second;
OSL_TRACE( "root is %s", OUSTRING_TO_CSTR( mpRoot->getPoint()->getModelId() ) );
for( PointsTreeMap::iterator iter = aTreeMap.begin();
iter != aTreeMap.end(); iter++ )
{
if(! iter->second->getParent() )
{
OSL_TRACE("node without parent %s", OUSTRING_TO_CSTR( iter->first ) );
}
}
}
void Diagram::addTo( const ShapePtr & pParentShape )
{
dgm::Points & aPoints( mpData->getPoints( ) );
dgm::Points::iterator aPointsIter;
build( );
mpLayout->layout( mpRoot, awt::Point( 0, 0 ) );
for( aPointsIter = aPoints.begin(); aPointsIter != aPoints.end(); ++aPointsIter )
{
if( ( *aPointsIter )->getType() != XML_node )
{
continue;
}
ShapePtr pShape = ( *aPointsIter )->getShape( );
if( pShape->getName( ).getLength() > 0 )
{
maShapeMap[ pShape->getName( ) ] = pShape;
OSL_TRACE( "Dgm: added shape %s to map", OUSTRING_TO_CSTR( pShape->getName() ) );
}
pParentShape->addChild( pShape );
}
OSL_TRACE( "Dgm: addTo() # of childs %d", pParentShape->getChilds().size() );
for( std::vector< ShapePtr >::iterator iter = pParentShape->getChilds().begin();
iter != pParentShape->getChilds().end(); ++iter)
{
OSL_TRACE( "Dgm: shape name %s", OUSTRING_TO_CSTR( (*iter)->getName() ) );
}
}
OUString Diagram::getLayoutId() const
{
OUString sLayoutId;
if( mpLayout )
{
sLayoutId = mpLayout->getUniqueId();
}
return sLayoutId;
}
} }
<|endoftext|>
|
<commit_before>/*
sma - simple moving average
Written in 2015 by <Ahmet Inan> <xdsopl@googlemail.com>
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
#include <chrono>
#include <iostream>
#include <random>
#include <array>
#include <numeric>
#include "kahan.hh"
#include "pairwise.hh"
std::random_device rd;
std::default_random_engine generator(rd());
std::normal_distribution<float> distribution(0.0f, 1.0f);
auto myrand = std::bind(distribution, generator);
template <typename T, int N>
class SMA1
{
std::vector<T> history;
int position;
public:
SMA1() : history(N), position(0) {}
T operator ()(T v)
{
history[position] = v;
position = (position + 1) % N;
#if 0
return std::accumulate(history.begin(), history.end(), T(0)) / T(N);
#else
return kahan_sum(history.begin(), history.end(), T(0)) / T(N);
#endif
}
};
template <typename T, int N>
class SMA2
{
std::vector<T> history;
int position;
T sum;
public:
SMA2() : history(N), position(0), sum(0) {}
T operator ()(T v)
{
sum += v - history[position];
history[position] = v;
position = (position + 1) % N;
return sum / T(N);
}
};
template <typename T, int N>
class SMA3
{
std::vector<T> history;
int position;
Kahan<T> sum;
public:
SMA3() : history(N), position(0), sum(0) {}
T operator ()(T v)
{
sum(-history[position]);
history[position] = v;
position = (position + 1) % N;
return sum(v) / T(N);
}
};
template <typename T, int N>
class SMA4
{
struct add {
T operator () (T l, T r) { return l + r; }
};
Pairwise<T, N, add> history;
int position;
public:
SMA4() : position(0) {}
T operator ()(T v)
{
history[position] = v;
position = (position + 1) % N;
return history.reduce() / T(N);
}
};
template <typename SMA, typename T>
int benchmark(T &output, T &input)
{
SMA sma;
auto start = std::chrono::system_clock::now();
for (size_t i = 0; i < input.size(); ++i)
output[i] = sma(input[i]);
auto end = std::chrono::system_clock::now();
auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
return msec.count();
}
template <typename T>
typename T::value_type compare(T &a, T &b)
{
typename T::value_type max_error(0);
for (size_t i = 0; i < a.size(); ++i)
max_error = std::max(max_error, std::abs(a[i] - b[i]));
return max_error;
}
int main()
{
const int num_samples = 10000000;
std::vector<float> input(num_samples), output1(num_samples), output2(num_samples), output3(num_samples), output4(num_samples);
const int window_length = 500;
for (size_t i = 0; i < input.size(); ++i)
input[i] = sin(i * 4.0f * 2.0f * M_PI / num_samples) + myrand();
{
int msec = benchmark<SMA1<float, window_length>>(output1, input);
std::cerr << "sma1: " << msec << " milliseconds." << std::endl;
}{
int msec = benchmark<SMA2<float, window_length>>(output2, input);
float max_error = compare(output1, output2);
std::cerr << "sma2: " << msec << " milliseconds. max absolute error: " << max_error << std::endl;
}{
int msec = benchmark<SMA3<float, window_length>>(output3, input);
float max_error = compare(output1, output3);
std::cerr << "sma3: " << msec << " milliseconds. max absolute error: " << max_error << std::endl;
}{
int msec = benchmark<SMA4<float, window_length>>(output4, input);
float max_error = compare(output1, output4);
std::cerr << "sma4: " << msec << " milliseconds. max absolute error: " << max_error << std::endl;
}
#if 1
for (size_t i = 0; i < input.size(); ++i)
std::cout << input[i] << " " << output1[i] << " " << output2[i] << " " << output3[i] << " " << output4[i] << std::endl;
#endif
}
<commit_msg>bind comes from functional<commit_after>/*
sma - simple moving average
Written in 2015 by <Ahmet Inan> <xdsopl@googlemail.com>
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
#include <chrono>
#include <iostream>
#include <random>
#include <array>
#include <numeric>
#include <functional>
#include "kahan.hh"
#include "pairwise.hh"
std::random_device rd;
std::default_random_engine generator(rd());
std::normal_distribution<float> distribution(0.0f, 1.0f);
auto myrand = std::bind(distribution, generator);
template <typename T, int N>
class SMA1
{
std::vector<T> history;
int position;
public:
SMA1() : history(N), position(0) {}
T operator ()(T v)
{
history[position] = v;
position = (position + 1) % N;
#if 0
return std::accumulate(history.begin(), history.end(), T(0)) / T(N);
#else
return kahan_sum(history.begin(), history.end(), T(0)) / T(N);
#endif
}
};
template <typename T, int N>
class SMA2
{
std::vector<T> history;
int position;
T sum;
public:
SMA2() : history(N), position(0), sum(0) {}
T operator ()(T v)
{
sum += v - history[position];
history[position] = v;
position = (position + 1) % N;
return sum / T(N);
}
};
template <typename T, int N>
class SMA3
{
std::vector<T> history;
int position;
Kahan<T> sum;
public:
SMA3() : history(N), position(0), sum(0) {}
T operator ()(T v)
{
sum(-history[position]);
history[position] = v;
position = (position + 1) % N;
return sum(v) / T(N);
}
};
template <typename T, int N>
class SMA4
{
struct add {
T operator () (T l, T r) { return l + r; }
};
Pairwise<T, N, add> history;
int position;
public:
SMA4() : position(0) {}
T operator ()(T v)
{
history[position] = v;
position = (position + 1) % N;
return history.reduce() / T(N);
}
};
template <typename SMA, typename T>
int benchmark(T &output, T &input)
{
SMA sma;
auto start = std::chrono::system_clock::now();
for (size_t i = 0; i < input.size(); ++i)
output[i] = sma(input[i]);
auto end = std::chrono::system_clock::now();
auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
return msec.count();
}
template <typename T>
typename T::value_type compare(T &a, T &b)
{
typename T::value_type max_error(0);
for (size_t i = 0; i < a.size(); ++i)
max_error = std::max(max_error, std::abs(a[i] - b[i]));
return max_error;
}
int main()
{
const int num_samples = 10000000;
std::vector<float> input(num_samples), output1(num_samples), output2(num_samples), output3(num_samples), output4(num_samples);
const int window_length = 500;
for (size_t i = 0; i < input.size(); ++i)
input[i] = sin(i * 4.0f * 2.0f * M_PI / num_samples) + myrand();
{
int msec = benchmark<SMA1<float, window_length>>(output1, input);
std::cerr << "sma1: " << msec << " milliseconds." << std::endl;
}{
int msec = benchmark<SMA2<float, window_length>>(output2, input);
float max_error = compare(output1, output2);
std::cerr << "sma2: " << msec << " milliseconds. max absolute error: " << max_error << std::endl;
}{
int msec = benchmark<SMA3<float, window_length>>(output3, input);
float max_error = compare(output1, output3);
std::cerr << "sma3: " << msec << " milliseconds. max absolute error: " << max_error << std::endl;
}{
int msec = benchmark<SMA4<float, window_length>>(output4, input);
float max_error = compare(output1, output4);
std::cerr << "sma4: " << msec << " milliseconds. max absolute error: " << max_error << std::endl;
}
#if 1
for (size_t i = 0; i < input.size(); ++i)
std::cout << input[i] << " " << output1[i] << " " << output2[i] << " " << output3[i] << " " << output4[i] << std::endl;
#endif
}
<|endoftext|>
|
<commit_before>class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int maxr=0,ins=0;
for(int i=0;i<nums.size();i++){
if(nums[i]){
ins++;
}else{
if(ins>maxr) maxr=ins;
ins=0;
}
}
if(ins>maxr) maxr=ins;
return maxr;
}
};
<commit_msg>Max Consecutive Ones<commit_after>class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int maxr = 0, ins = 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i]){
ins++;
}else{
if(ins > maxr) maxr = ins;
ins = 0;
}
}
if(ins > maxr) maxr = ins;
return maxr;
}
};
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdlib.h>
#include <stack>
using namespace std;
struct node{
int data;
node *left, *right, *root;
};
node *createNode(int n){
node *newnode = new node;
newnode->right = NULL;
newnode->left = NULL;
newnode->data = n;
return newnode;
}
void check(node *root, int n){
node *temp = root;
while(temp != NULL){
if(n >= temp->data){
if(temp->right!=NULL){
temp = temp->right;
}else{
node *nn = createNode(n);
temp->right = nn;
break;
}
}else{
if(temp->left != NULL){
temp = temp->left;
}else{
node *nn = createNode(n);
temp->left = nn;
break;
}
}
}
}
void insert(node *T, int n){
if(T->root == NULL){
T->root = createNode(n);
}else{
check(T->root, n);
}
}
void inorder(node *T){
if(T != NULL){
inorder(T->left);
cout<<T->data<<endl;
inorder(T->right);
}
}
void postorder(node *T){
if(T != NULL){
postorder(T->left);
postorder(T->right);
cout<<T->data<<endl;
}
}
void preorder(node *T){
if(T != NULL){
cout<<T->data<<endl;
postorder(T->left);
postorder(T->right);
}
}
bool search(node *T, int n){
if(T!=NULL){
if(T->data == n){
return true;
}
else{
if( n < T->data && T->left != NULL){
if(search(T->left, n) == 1)return true;
else return false;
}else{
if(n > T->data && T->right != NULL){
if(search(T->right, n) == 1)return true;
else return false;
}
}
return false;
}
}
}
node *lca(node *root, int n1, int n2){
if (root == NULL) return NULL;
if (root->data > n1 && root->data > n2)
return lca(root->left, n1, n2);
if (root->data < n1 && root->data < n2)
return lca(root->right, n1, n2);
return root;
}
void nonrecinorder(node *ptr){
int top =0;
node* stack[50];
stack[0] = NULL;
while(1)
{
if(ptr != NULL )
{
stack[++top] = ptr;
ptr = ptr->left;
}else{
ptr = stack[top--];
if( ptr == NULL)
return;
cout<<" "<<ptr->data;
if(ptr->right != NULL)
ptr = ptr->right;
else
ptr = NULL;
}
}
//return stack;
}
void nonrecpreorder(node *ptr){
int top=0;
node *stack[50];
stack[0] = NULL;
while(1){
if(ptr!=NULL){
cout<<ptr->data<<endl;
stack[++top] = ptr;
ptr = ptr->left;
}else{
ptr = stack[top--];
if( ptr == NULL)
return;
if(ptr->right != NULL)
ptr = ptr->right;
else
ptr = NULL;
}
}
}
void nonrecpostorder(node *ptr){
int top=0;
node *stack[50];
stack[0] = NULL;
node *prev = NULL;
while(1){
if(ptr!=NULL){
stack[++top] = ptr;
ptr = ptr->left;
}else{
ptr = stack[top];
if( ptr == NULL)
return;
if(ptr->right != NULL && ptr->right != prev){
ptr = ptr->right;
}else{
top--;
cout<<ptr->data<<endl;
prev = ptr;
ptr = NULL;
}
}
}
}
void printStack(node* s){
}
int main(){
node *T = new node;
T->root = NULL;
insert(T,30);
insert(T,20);
insert(T,50);
insert(T,10);
insert(T,15);
insert(T,25);
insert(T,35);
insert(T,5);
insert(T,60);
insert(T,32);
nonrecpostorder(T->root);
system("pause");
return 0;
}
<commit_msg>changes<commit_after>#include <iostream>
#include <stdlib.h>
#include <stack>
#include<queue>
using namespace std;
struct node{
int data;
node *left, *right, *root;
};
queue<node*> q;
queue<node*> val;
queue<node*> inq;
queue<node*> emp;
node *createNode(int n){
node *newnode = new node;
newnode->right = NULL;
newnode->left = NULL;
newnode->data = n;
return newnode;
}
void check(node *root, int n){
node *temp = root;
while(temp != NULL){
if(n >= temp->data){
if(temp->right!=NULL){
temp = temp->right;
}else{
node *nn = createNode(n);
temp->right = nn;
break;
}
}else{
if(temp->left != NULL){
temp = temp->left;
}else{
node *nn = createNode(n);
temp->left = nn;
break;
}
}
}
}
void insert(node *T, int n){
if(T->root == NULL){
T->root = createNode(n);
}else{
check(T->root, n);
}
}
void inorder(node *T){
if(T != NULL){
inorder(T->left);
cout<<T->data<<endl;
inorder(T->right);
}
}
void postorder(node *T){
if(T != NULL){
postorder(T->left);
postorder(T->right);
cout<<T->data<<endl;
}
}
void preorder(node *T){
if(T != NULL){
cout<<T->data<<endl;
//inq.push(T);
preorder(T->left);
preorder(T->right);
}
}
bool search(node *T, int n){
if(T!=NULL){
if(T->data == n){
return true;
}
else{
if( n < T->data && T->left != NULL){
if(search(T->left, n) == 1)return true;
else return false;
}else{
if(n > T->data && T->right != NULL){
if(search(T->right, n) == 1)return true;
else return false;
}
}
return false;
}
}
}
node *lca(node *root, int n1, int n2){
if (root == NULL) return NULL;
if (root->data > n1 && root->data > n2)
return lca(root->left, n1, n2);
if (root->data < n1 && root->data < n2)
return lca(root->right, n1, n2);
return root;
}
void nonrecinorder(node *ptr){
int top =0;
node* stack[50];
stack[0] = NULL;
while(1)
{
if(ptr != NULL )
{
stack[++top] = ptr;
ptr = ptr->left;
}else{
ptr = stack[top--];
if( ptr == NULL)
return;
cout<<" "<<ptr->data;
if(ptr->right != NULL)
ptr = ptr->right;
else
ptr = NULL;
}
}
//return stack;
}
void nonrecpreorder(node *ptr){
int top=0;
node *stack[50];
stack[0] = NULL;
while(1){
if(ptr!=NULL){
cout<<ptr->data<<endl;
stack[++top] = ptr;
ptr = ptr->left;
}else{
ptr = stack[top--];
if( ptr == NULL)
return;
if(ptr->right != NULL)
ptr = ptr->right;
else
ptr = NULL;
}
}
}
void nonrecpostorder(node *ptr){
int top=0;
node *stack[50];
stack[0] = NULL;
node *prev = NULL;
while(1){
if(ptr!=NULL){
stack[++top] = ptr;
ptr = ptr->left;
}else{
ptr = stack[top];
if( ptr == NULL)
return;
if(ptr->right != NULL && ptr->right != prev){
ptr = ptr->right;
}else{
top--;
cout<<ptr->data<<endl;
prev = ptr;
ptr = NULL;
}
}
}
}
void printqueue(queue<node*> qp){
while(!qp.empty()){
cout<<(qp.front())->data<<endl;
qp.pop();
}
}
void bfs(node *ptr){
q.push(ptr);
while(!q.empty()){
node *nd = q.front();
val.push(nd);
q.pop();
if(nd->left != NULL || nd ->right!=NULL){
if(nd->left != NULL){
q.push(nd->left);
}
if(nd->right != NULL){
q.push(nd->right);
}
}
}
}
void checkMirror(node *root, int n){
node *temp = root;
while(temp != NULL){
if(n >= temp->data){
if(temp->left!=NULL){
temp = temp->left;
}else{
node *nn = createNode(n);
temp->left = nn;
break;
}
}else{
if(temp->right != NULL){
temp = temp->right;
}else{
node *nn = createNode(n);
temp->right = nn;
break;
}
}
}
}
void insertMirror(node *T, int n){
if(T->root == NULL){
T->root = createNode(n);
}else{
checkMirror(T->root, n);
}
}
void createMirror(node* ptr){
while(!val.empty()){
insertMirror(ptr,(val.front())->data);
val.pop();
}
}
int main(){
node *T = new node;
T->root = NULL;
insert(T,30);
insert(T,20);
insert(T,50);
insert(T,10);
insert(T,15);
insert(T,25);
insert(T,35);
insert(T,5);
insert(T,60);
insert(T,32);
preorder(T->root);
bfs(T->root);
node* mir = new node;
mir->root=NULL;
createMirror(mir);
preorder(mir->root);
//swap(inq, emp);
//preorder(T->root);
printqueue(val);
system("pause");
return 0;
}
<|endoftext|>
|
<commit_before>#include <gtksourceview/gtksourceview.h>
namespace Jazz
{
namespace Gtk
{
// Widget assumes ownership of the pointer you give it
// use release to get its ownership
class Widget
{
public:
// Interface
void Show() const
{
gtk_widget_show(widget);
}
void ShowAll() const
{
gtk_widget_show_all(widget);
}
Widget Parent() const
{
return Widget(gtk_widget_get_parent(widget));
}
void Destroy() const
{
gtk_widget_destroy(widget);
}
GtkWidget* Release()
{
auto result = widget;
widget = nullptr;
return result;
}
Widget() = delete;
Widget(GtkWidget* input)
{
widget = input;
}
Widget(Widget&& other)
{
widget = other.widget;
other.widget = nullptr;
}
~Widget()
{
if(widget != nullptr)
{
g_obj_unref(widget);
this->widget = nullptr;
}
}
operator GtkWidget*() { return widget; }
bool Valid() { return widget != nullptr; }
protected:
GtkWidget* widget = nullptr;
};
class Container : public Widget
{
public:
Container(GtkWidget* cont):Widget(cont){}
//
void Add(GtkWidget& other)
{
gtk_container_add(other);
}
void Remove(GtkWidget& other)
{
gtk_container_remove(other);
}
}
class Bin : public Container
{
public:
Bin(GtkWidget* bin): Container(bin) {}
//
Widget Child() const
{
return gtk_bin_get_child(bin);
}
};
class ScrolledWindow: public Bin
{
public:
ScrolledWindow(): Bin(gtk_scrolled_window_new(nullptr,nullptr)) {}
}
}
}<commit_msg>fixed up gtk.hpp<commit_after>#pragma once
#include <gtksourceview/gtksourceview.h>
#include <gtk/gtk.h>
namespace Jazz
{
namespace Gtk
{
// Widget assumes ownership of the pointer you give it
// use release to get its ownership
class Widget
{
public:
// Interface
GtkWidget* Object() const
{
return widget;
}
void Show() const
{
gtk_widget_show(widget);
}
void ShowAll() const
{
gtk_widget_show_all(widget);
}
Widget Parent() const
{
return Widget(gtk_widget_get_parent(widget));
}
void Destroy() const
{
gtk_widget_destroy(widget);
}
GtkWidget* Release()
{
auto result = widget;
widget = nullptr;
return result;
}
Widget() = delete;
Widget(GtkWidget* input)
{
widget = input;
}
Widget(const Widget& other)
{
widget = other.widget;
g_object_ref(widget);
}
Widget(Widget&& other)
{
widget = other.widget;
other.widget = nullptr;
}
~Widget()
{
if(widget != nullptr)
{
g_object_unref(widget);
this->widget = nullptr;
}
}
operator GtkWidget*() const { return widget; }
bool Valid() { return widget != nullptr; }
protected:
GtkWidget* widget = nullptr;
};
class Container : public Widget
{
public:
Container(GtkWidget* cont):Widget(cont){}
//
void Add(const Widget& other)
{
gtk_container_add(GTK_CONTAINER(widget),other.Object());
}
void Remove(const Widget& other)
{
gtk_container_remove(GTK_CONTAINER(widget),other.Object());
}
};
class Bin : public Container
{
public:
Bin(GtkWidget* bin): Container(bin) {}
//
Widget Child() const
{
return gtk_bin_get_child(GTK_BIN(widget));
}
};
class ScrolledWindow: public Bin
{
public:
ScrolledWindow(): Bin(gtk_scrolled_window_new(nullptr,nullptr)) {}
};
}
}<|endoftext|>
|
<commit_before>/*
* Map.cpp
*
* Created on: Apr 22, 2014
* Author: user
*/
#include "Map.h"
Map::Map(int rows, int columns, double resolution)
{
// TODO: input checks
_resolution = resolution;
float fixed_resolution = 1 / resolution;
_rows = ceil(rows * fixed_resolution);
_columns = ceil(columns * fixed_resolution);
_matrix.init(_rows, _columns, MAP_STATE_UNKNOWN);
}
/*
* X, Y may be nagative
*
* in our map, 0 is the middle
* any negative value is relative to the left
* and any positive value is relative to the right
*
* - - - - 0 + + + +
*-4 -3 -2 -1 1 2 3 4
*------------------------------
* 0 1 2 3 4 5 6 7 8
*
*/
int Map::convertYToRow(double y) const
{
int value = (_rows / 2) - (y / _resolution);
return value;
}
int Map::convertXToColumn(double x) const
{
int value = (_columns / 2) + (x / _resolution);
return value;
}
int Map::get(double x, double y) const
{
// TODO: input checks
// Convert x and y to row and column
int row = convertYToRow(y);
int column = convertXToColumn(x);
return get(row, column);
}
void Map::set(double x, double y, int value)
{
// TODO: input checks
// Convert x and y to row and column
int row = convertYToRow(y);
int column = convertXToColumn(x);
set(row, column, value);
}
int Map::get(int row, int column) const
{
// TODO: input checks
return _matrix(row, column);
}
void Map::set(int row, int column, int value)
{
int previews_value = get(row, column);
switch (previews_value)
{
case (MAP_STATE_OBSTACLE):
// Ignore this cell update
break;
default:
_matrix(row, column) = value;
break;
}
}
void Map::set(const Point& point, int value)
{
int pointRow = convertYToRow(point.getY());
int pointColumn = convertXToColumn(point.getX());
set(pointRow, pointColumn, value);
}
bool Map::isMismatch(int row, int column, int value)
{
int previews_value = get(row, column);
// For unknown values we do not care what is the new value
if (previews_value == MAP_STATE_UNKNOWN)
{
return false;
}
// If they are not equals then this is a mismatch
bool mismatch = !(previews_value == value);
return mismatch;
}
bool Map::isMismatch(const Point& point, int value)
{
// Convert x and y to row and column
int pointRow = convertYToRow(point.getY());
int pointColumn = convertXToColumn(point.getX());
return isMismatch(pointRow, pointColumn, value);
}
// Print operator
std::ostream& operator<<(ostream &os, const Map& map)
{
for (int i = 0; i < map._rows; i++)
{
for (int j = 0; j < map._columns; j++)
{
int value = map.get(i, j);
switch (value)
{
case (MAP_STATE_CLEAR):
os << " ";
break;
case (MAP_STATE_OBSTACLE):
os << "█";
break;
case (MAP_STATE_UNKNOWN):
os << "░";
break;
}
}
os << endl;
}
return os;
}
int Map::handleObstacles(const Point& initalPoint, const vector<Point>& obstacles)
{
int mismatchCount = 0;
vector<Point> freePointsToFlush;
set(initalPoint, MAP_STATE_CLEAR);
for (std::vector<Point>::const_iterator it = obstacles.begin(); it != obstacles.end(); ++it)
{
const Point& obstaclePoint = *it;
if (isMismatch(obstaclePoint, MAP_STATE_OBSTACLE))
{
mismatchCount++;
}
// Get intermediate points (the points between the robot and the obstacle)
vector<Point> intermediatePoints;
MathHelper::GetIntermediatePoints(initalPoint, obstaclePoint, MAP_INTERMEDIATE_POINT_DISTANCE, intermediatePoints);
// Enumerate Intermediate Points,
// Set each intermediate Point to 'CLEAR' map state
for (std::vector<Point>::const_iterator it2 = intermediatePoints.begin(); it2 != intermediatePoints.end(); ++it2)
{
const Point& intermediatePoint = *it2;
if (isMismatch(intermediatePoint, MAP_STATE_CLEAR))
{
mismatchCount++;
}
freePointsToFlush.push_back(intermediatePoint);
}
}
for (std::vector<Point>::const_iterator it = obstacles.begin(); it != obstacles.end(); ++it)
{
set(*it, MAP_STATE_OBSTACLE);
}
for (std::vector<Point>::const_iterator it = freePointsToFlush.begin(); it != freePointsToFlush.end(); ++it)
{
set(*it, MAP_STATE_CLEAR);
}
return mismatchCount;
}
int Map::handleObstacles(Robot& robot, const vector<Point>& obstacles)
{
double robotX = robot.getX();
double robotY = robot.getX();
Point initalPoint(robotX, robotY);
int mismatchCount = handleObstacles(initalPoint, obstacles);
return mismatchCount;
}
int Map::update(double x, double y, double yaw, const Laser& laser)
{
// Handle new Obstacles
vector<Point> obstacles;
laser.getObstacles(x, y, yaw, obstacles);
Point initalPoint(x, y);
int mismatchCount = handleObstacles(initalPoint, obstacles);
return mismatchCount;
}
<commit_msg>fix a bug that calling for getX() method of robot to get the Y coordinate<commit_after>/*
* Map.cpp
*
* Created on: Apr 22, 2014
* Author: user
*/
#include "Map.h"
Map::Map(int rows, int columns, double resolution)
{
// TODO: input checks
_resolution = resolution;
float fixed_resolution = 1 / resolution;
_rows = ceil(rows * fixed_resolution);
_columns = ceil(columns * fixed_resolution);
_matrix.init(_rows, _columns, MAP_STATE_UNKNOWN);
}
/*
* X, Y may be nagative
*
* in our map, 0 is the middle
* any negative value is relative to the left
* and any positive value is relative to the right
*
* - - - - 0 + + + +
*-4 -3 -2 -1 1 2 3 4
*------------------------------
* 0 1 2 3 4 5 6 7 8
*
*/
int Map::convertYToRow(double y) const
{
int value = (_rows / 2) - (y / _resolution);
return value;
}
int Map::convertXToColumn(double x) const
{
int value = (_columns / 2) + (x / _resolution);
return value;
}
int Map::get(double x, double y) const
{
// TODO: input checks
// Convert x and y to row and column
int row = convertYToRow(y);
int column = convertXToColumn(x);
return get(row, column);
}
void Map::set(double x, double y, int value)
{
// TODO: input checks
// Convert x and y to row and column
int row = convertYToRow(y);
int column = convertXToColumn(x);
set(row, column, value);
}
int Map::get(int row, int column) const
{
// TODO: input checks
return _matrix(row, column);
}
void Map::set(int row, int column, int value)
{
int previews_value = get(row, column);
switch (previews_value)
{
case (MAP_STATE_OBSTACLE):
// Ignore this cell update
break;
default:
_matrix(row, column) = value;
break;
}
}
void Map::set(const Point& point, int value)
{
int pointRow = convertYToRow(point.getY());
int pointColumn = convertXToColumn(point.getX());
set(pointRow, pointColumn, value);
}
bool Map::isMismatch(int row, int column, int value)
{
int previews_value = get(row, column);
// For unknown values we do not care what is the new value
if (previews_value == MAP_STATE_UNKNOWN)
{
return false;
}
// If they are not equals then this is a mismatch
bool mismatch = !(previews_value == value);
return mismatch;
}
bool Map::isMismatch(const Point& point, int value)
{
// Convert x and y to row and column
int pointRow = convertYToRow(point.getY());
int pointColumn = convertXToColumn(point.getX());
return isMismatch(pointRow, pointColumn, value);
}
// Print operator
std::ostream& operator<<(ostream &os, const Map& map)
{
for (int i = 0; i < map._rows; i++)
{
for (int j = 0; j < map._columns; j++)
{
int value = map.get(i, j);
switch (value)
{
case (MAP_STATE_CLEAR):
os << " ";
break;
case (MAP_STATE_OBSTACLE):
os << "█";
break;
case (MAP_STATE_UNKNOWN):
os << "░";
break;
}
}
os << endl;
}
return os;
}
int Map::handleObstacles(const Point& initalPoint, const vector<Point>& obstacles)
{
//////////////////////////////////////////////////
// TODO: DELETE THIS LINE - ONLY FOR TESTING
int num_of_obstacles = obstacles.size();
//////////////////////////////////////////////////
int mismatchCount = 0;
vector<Point> freePointsToFlush;
set(initalPoint, MAP_STATE_CLEAR);
for (std::vector<Point>::const_iterator it = obstacles.begin(); it != obstacles.end(); ++it)
{
const Point& obstaclePoint = *it;
if (isMismatch(obstaclePoint, MAP_STATE_OBSTACLE))
{
mismatchCount++;
}
// Get intermediate points (the points between the robot and the obstacle)
vector<Point> intermediatePoints;
MathHelper::GetIntermediatePoints(initalPoint, obstaclePoint, MAP_INTERMEDIATE_POINT_DISTANCE, intermediatePoints);
////////////////////////////////////////////////
// TODO: DELETE THIS LINE - ONLY FOR TESTING
int num_of_intermediatePoints = intermediatePoints.size();
///////////////////////////////////////////////
// Enumerate Intermediate Points,
// Set each intermediate Point to 'CLEAR' map state
for (std::vector<Point>::const_iterator it2 = intermediatePoints.begin(); it2 != intermediatePoints.end(); ++it2)
{
const Point& intermediatePoint = *it2;
if (isMismatch(intermediatePoint, MAP_STATE_CLEAR))
{
mismatchCount++;
}
freePointsToFlush.push_back(intermediatePoint);
}
}
for (std::vector<Point>::const_iterator it = obstacles.begin(); it != obstacles.end(); ++it)
{
set(*it, MAP_STATE_OBSTACLE);
}
for (std::vector<Point>::const_iterator it = freePointsToFlush.begin(); it != freePointsToFlush.end(); ++it)
{
set(*it, MAP_STATE_CLEAR);
}
return mismatchCount;
}
int Map::handleObstacles(Robot& robot, const vector<Point>& obstacles)
{
double robotX = robot.getX();
double robotY = robot.getY();
Point initalPoint(robotX, robotY);
int mismatchCount = handleObstacles(initalPoint, obstacles);
return mismatchCount;
}
int Map::update(double x, double y, double yaw, const Laser& laser)
{
// Handle new Obstacles
vector<Point> obstacles;
laser.getObstacles(x, y, yaw, obstacles);
Point initalPoint(x, y);
int mismatchCount = handleObstacles(initalPoint, obstacles);
return mismatchCount;
}
<|endoftext|>
|
<commit_before>//NIM dabs oktber 1997
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
//etta fall a birta stu allra eldsptnahrgna (hrgur fleirtlu eignarfalli)
void birta( int* hruga );
//etta fall a reikna t hversu margar eldsptur eru eftir hrgunum:
int samtals( int* hruga );
//etta fall ltur tlvuna gera:
void tolva( int* hruga );
//etta fall ltur notandann gera:
void notandi( int* hruga );
//etta fall birtir reglurnar spilinu:
void hjalp( );
//etta fall spilar spili:
void spila( );
//g leyfi mr a nota eina vvra breytu af v a forriti notar alltaf
//mismargar hrgur hvert og eitt skipti:
int hrugufjoldi;
//Hr byrjar aalforriti:
void main( )
{
int val;
do
{
cout << endl << endl << endl;
cout << " ADALVALMYND " << endl << endl;
cout << " 1. Spila NIM" << endl;
cout << " 2. Birta reglurnar i NIM" << endl;
cout << " 3. Haetta " << endl << endl;
cout << " Veldu 1, 2 eda 3:" << endl << endl;
cin >> val;
switch ( val )
{
case 1:
spila( );
break;
case 2:
hjalp( );
break;
case 3:
break;
}
}
while ( val != 3 );
}
void spila( )
{
int hruga[ 10 ];
cout << "*-------------------------------------------------------*" << endl;
cout << " NU SPILUM VID NIM!!" << endl;
cout << "*-------------------------------------------------------*" << endl;
cout << endl << endl;
cout << "Veljum med hve margar hrugur vid spilum. " << endl;
cout << "Yttu a einhvern lykil: " << endl;
while( !kbhit( ) )
{
rand( );
}
hrugufjoldi = ( (rand( ) % 8 ) + 2 );
cout << "Vid spilum med " << hrugufjoldi << " hrugur. " << endl;
for ( int i = 0; i < hrugufjoldi; i++ )
{
hruga[ i ]=( ( rand( ) % 14 ) + 1 );
}
cout << endl;
birta ( hruga );
do
{
notandi( hruga );
birta( hruga );
tolva( hruga );
birta( hruga );
}
while ( samtals( hruga ) );
}
void hjalp( )
{
cout << " UM NIM - LEIKINN " << endl << endl;
cout << "Leikurinn NIM er upprunninn fra Asiu thar sem hann var" << endl;
cout << "leikinn med steinvolum. Reglurnar eru thessar: " << endl;
cout << "Keppendur setja einhvern fjolda af eldspytum i hrugur " << endl;
cout << "(their akveda sjalfir hve margar hrugur og hve margar " << endl;
cout << "eldspytur i hverri hrugu) og skiptast svo a um ad " << endl;
cout << "draga eldspytur ur einhverri hrugunni. Their mega " << endl;
cout << "taka eina eldspytu, nokkrar eda allar ur einni " << endl;
cout << "hrugunni en their mega aldrei taka ur fleiri en " << endl;
cout << "einni hrugu i einu. Sa sem tekur sidustu eldspytuna " << endl;
cout << "ur sidustu hrugunni vinnur. Gangi ykkur vel! " << endl << endl;
cout << "Sladu a einhvern lykil... " << endl;
getch( );
}
void birta( int* hruga )
{
if( !samtals( hruga ) )
{
return;
}
cout << " Hruga nr.: ";
for (int i = 0; i < hrugufjoldi; i++ )
{
cout << " " << (i + 1) << " ";
}
cout << endl << endl;
cout << "Fjoldi eldspytna i hverri hrugu er: ";
for ( int c = 0; c < hrugufjoldi; c++ )
{
if( hruga[c] < 10 )
{
cout << " " << hruga[ c ] << " ";
}
else
{
cout << hruga[ c ] << " ";
}
}
cout << endl << endl;
}
void notandi( int* hruga )
{
if ( samtals( hruga ) == 0 )
{
return;
}
int eldspytur;
int hrugunumer;
do
{
cout << "Sladu inn hve margar eldspytur thu vilt taka: ";
cin >> eldspytur;
cout << endl;
if( eldspytur < 1 )
{
cout << "Thu verdur ad taka a.m.k. eina eldspytu. Veldu aftur. " << endl << endl;
continue;
}
cout << "Sladu inn ur hvada hrugu: ";
cin >> hrugunumer;
if( hrugunumer > hrugufjoldi )
{
cout << "Thad er engin hruga med thessu numeri. Veldu aftur." <<endl<<endl;
continue;
}
if( eldspytur > hruga[ (hrugunumer) - 1 ] )
{
cout <<"Thad eru ekki nogu margar eldspytur eftir i hrugunni. Veldu aftur."<<endl<<endl;
continue;
}
}
while ( eldspytur > hruga[ (hrugunumer) - 1 ] || eldspytur < 1 );
hruga[ hrugunumer - 1 ] -= eldspytur;
if( !samtals( hruga ) )
{
cout << endl << "Thu vannst. Til hamingju!" << endl << endl;
cout << "Sladu a einhvern lykil... " << endl;
getch( );
}
cout << endl;
}
void tolva( int* hruga )
{
if( samtals( hruga ) == 0 )
{
return;
}
int eldspytur;
int hrugunumer;
do
{
eldspytur = ( ( rand( ) % 14 ) + 1 );
hrugunumer = ( ( rand( ) % hrugufjoldi ) + 1 );
if( eldspytur > hruga[(hrugunumer)-1] )
{
continue;
}
}
while ( eldspytur > hruga[ (hrugunumer) - 1 ] );
if ( eldspytur > 1 )
{
cout << " Eg tek " << eldspytur << " eldspytur ur hrugu nr. ";
}
else
{
cout << " Eg tek " << eldspytur << " eldspytu ur hrugu nr. ";
}
cout << hrugunumer << "." << endl;
hruga[ (hrugunumer) - 1 ] -= eldspytur;
if( !samtals( hruga ) )
{
cout << endl << "Eg vann. Thad gengur bara betur naest!" << endl << endl;
cout << "Sladu a einhvern lykil... " << endl;
getch( );
}
cout << endl;
}
int samtals( int* hruga )
{
int samtala = 0;
for( int i = 0; i < hrugufjoldi; i++ )
{
samtala += hruga[ i ];
}
return samtala;
}<commit_msg>Third commit<commit_after>//NIM dabs oktber 1997
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
//etta fall a birta stu allra eldsptnahrgna (hrgur fleirtlu eignarfalli)
void birta( int* hruga );
//etta fall a reikna t hversu margar eldsptur eru eftir hrgunum:
int samtals( int* hruga );
//etta fall ltur tlvuna gera:
void tolva( int* hruga );
//etta fall ltur notandann gera:
void notandi( int* hruga );
//etta fall birtir reglurnar spilinu:
void hjalp( );
//etta fall spilar spili:
void spila( );
//g leyfi mr a nota eina vvra breytu af v a forriti notar alltaf
//mismargar hrgur hvert og eitt skipti:
int hrugufjoldi;
//Hr byrjar aalforriti:
void main( )
{
int val;
do
{
cout << endl << endl << endl;
cout << " ADALVALMYND " << endl << endl;
cout << " 1. Spila NIM" << endl;
cout << " 2. Birta reglurnar i NIM" << endl;
cout << " 3. Haetta " << endl << endl;
cout << " Veldu 1, 2 eda 3:" << endl << endl;
cin >> val;
switch ( val )
{
case 1:
spila( );
break;
case 2:
hjalp( );
break;
case 3:
break;
}
}
while ( val != 3 );
}
void spila( )
{
int hruga[ 10 ];
cout << "*-------------------------------------------------------*" << endl;
cout << " NU SPILUM VID NIM!!" << endl;
cout << "*-------------------------------------------------------*" << endl;
cout << endl << endl;
cout << "Veljum med hve margar hrugur vid spilum. " << endl;
cout << "Yttu a einhvern lykil: " << endl;
while( !kbhit( ) )
{
rand( );
}
hrugufjoldi = ( (rand( ) % 8 ) + 2 );
cout << "Vid spilum med " << hrugufjoldi << " hrugur. " << endl;
for ( int i = 0; i < hrugufjoldi; i++ )
{
hruga[ i ]=( ( rand( ) % 14 ) + 1 );
}
cout << endl;
birta ( hruga );
do
{
notandi( hruga );
birta( hruga );
tolva( hruga );
birta( hruga );
}
while ( samtals( hruga ) );
}
void hjalp( )
{
cout << " UM NIM - LEIKINN " << endl << endl;
cout << "Leikurinn NIM er upprunninn fra Asiu thar sem hann var" << endl;
cout << "leikinn med steinvolum. Reglurnar eru thessar: " << endl;
cout << "Keppendur setja einhvern fjolda af eldspytum i hrugur " << endl;
cout << "(their akveda sjalfir hve margar hrugur og hve margar " << endl;
cout << "eldspytur i hverri hrugu) og skiptast svo a um ad " << endl;
cout << "draga eldspytur ur einhverri hrugunni. Their mega " << endl;
cout << "taka eina eldspytu, nokkrar eda allar ur einni " << endl;
cout << "hrugunni en their mega aldrei taka ur fleiri en " << endl;
cout << "einni hrugu i einu. Sa sem tekur sidustu eldspytuna " << endl;
cout << "ur sidustu hrugunni vinnur. Gangi ykkur vel! " << endl << endl;
cout << "Sladu a einhvern lykil... " << endl;
getch( );
}
void birta( int* hruga )
{
if( !samtals( hruga ) )
{
return;
}
cout << " Hruga nr.: ";
for (int i = 0; i < hrugufjoldi; i++ )
{
cout << " " << (i + 1) << " ";
}
cout << endl << endl;
cout << "Fjoldi eldspytna i hverri hrugu er: ";
for ( int c = 0; c < hrugufjoldi; c++ )
{
if( hruga[c] < 10 )
{
cout << " " << hruga[ c ] << " ";
}
else
{
cout << hruga[ c ] << " ";
}
}
cout << endl << endl;
}
void notandi( int* hruga )
{
if ( samtals( hruga ) == 0 )
{
return;
}
int eldspytur;
int hrugunumer;
do
{
cout << "Sladu inn hve margar eldspytur thu vilt taka: ";
cin >> eldspytur;
cout << endl;
if( eldspytur < 1 )
{
cout << "Thu verdur ad taka a.m.k. eina eldspytu. Veldu aftur. " << endl << endl;
continue;
}
cout << "Sladu inn ur hvada hrugu: ";
cin >> hrugunumer;
if( hrugunumer > hrugufjoldi )
{
cout << "Thad er engin hruga med thessu numeri. Veldu aftur." <<endl<<endl;
continue;
}
if( eldspytur > hruga[ (hrugunumer) - 1 ] )
{
cout <<"Thad eru ekki nogu margar eldspytur eftir i hrugunni. Veldu aftur."<<endl<<endl;
continue;
}
}
while ( eldspytur > hruga[ (hrugunumer) - 1 ] || eldspytur < 1 );
hruga[ hrugunumer - 1 ] -= eldspytur;
if( !samtals( hruga ) )
{
cout << endl << "Thu vannst. Til hamingju!" << endl << endl;
cout << "Sladu a einhvern lykil... " << endl;
getch( );
}
cout << endl;
}
void tolva( int* hruga )
{
if( samtals( hruga ) == 0 )
{
return;
}
int eldspytur;
int hrugunumer;
do
{
eldspytur = ( ( rand( ) % 14 ) + 1 );
hrugunumer = ( ( rand( ) % hrugufjoldi ) + 1 );
if( eldspytur > hruga[(hrugunumer)-1] )
{
continue;
}
}
while ( eldspytur > hruga[ (hrugunumer) - 1 ] );
if ( eldspytur > 1 )
{
cout << " Eg tek " << eldspytur << " eldspytur ur hrugu nr. ";
}
else
{
cout << " Eg tek " << eldspytur << " eldspytu ur hrugu nr. ";
}
cout << hrugunumer << "." << endl;
hruga[ (hrugunumer) - 1 ] -= eldspytur;
if( !samtals( hruga ) )
{
cout << endl << "Eg vann. Thad gengur bara betur naest!" << endl << endl;
cout << "Sladu a einhvern lykil... " << endl;
getch( );
}
cout << endl;
}
int samtals( int* hruga )
{
int samtala = 0;
for( int i = 0; i < hrugufjoldi; i++ )
{
samtala += hruga[ i ];
}
return samtala;
}<|endoftext|>
|
<commit_before>#pragma once
#include <array>
#include <memory>
#include <cstring>
#include <type_traits>
namespace detail
{
template <typename _DeleterT,
typename _AnyT>
struct deleter
{
~deleter() { _DeleterT()(reinterpret_cast<_AnyT&>(*this)); }
};
template <typename _AnyT>
struct deleter<void, _AnyT> {};
}
template <std::size_t _N, typename _DeleterT = void>
struct any : public detail::deleter<_DeleterT, any<_N>>
{
typedef std::size_t size_type;
template <typename _T,
typename _D = _DeleterT>
typename std::enable_if<std::is_same<_D, void>::value, any&>::type
operator=(_T&& t)
{
static_assert(std::is_trivially_destructible<_T>::value, "_T is not trivially destructible and does not use any deleter");
copy_object(std::move(t));
return *this;
}
template <typename _T,
typename _D = _DeleterT>
typename std::enable_if<!std::is_same<_D, void>::value, any&>::type
operator=(_T&& t)
{
copy_object(std::move(t));
return *this;
}
template <typename _T>
void copy_object(_T&& t)
{
static_assert(std::is_trivially_copyable<_T>::value, "_T is not trivially copyable");
static_assert(size() >= sizeof(_T), "_T is too big to be copied to any");
std::memcpy(buff_.data(), (char*)&t, sizeof(_T));
}
template <typename _T>
_T& get() { return reinterpret_cast<_T&>(*buff_.data()); }
template <typename _T>
const _T& get() const { return reinterpret_cast<_T&>(*buff_.data()); }
static constexpr size_type size() { return _N; }
private:
std::array<char, _N> buff_;
};
<commit_msg>any: fix bug around pointer type<commit_after>#pragma once
#include <array>
#include <memory>
#include <cstring>
#include <type_traits>
namespace detail
{
template <typename _DeleterT,
typename _AnyT>
struct deleter
{
~deleter() { _DeleterT()(reinterpret_cast<_AnyT&>(*this)); }
};
template <typename _AnyT>
struct deleter<void, _AnyT> {};
}
template <std::size_t _N, typename _DeleterT = void>
struct any : public detail::deleter<_DeleterT, any<_N>>
{
typedef std::size_t size_type;
template <typename _T,
typename _D = _DeleterT>
typename std::enable_if<std::is_same<_D, void>::value, any&>::type
operator=(_T&& t)
{
static_assert(std::is_trivially_destructible<_T>::value, "_T is not trivially destructible and does not use any deleter");
copy_object(std::move(t));
return *this;
}
template <typename _T,
typename _D = _DeleterT>
typename std::enable_if<!std::is_same<_D, void>::value, any&>::type
operator=(_T&& t)
{
copy_object(std::move(t));
return *this;
}
template <typename _T>
void copy_object(_T&& t)
{
static_assert(std::is_trivially_copyable<_T>::value, "_T is not trivially copyable");
static_assert(size() >= sizeof(_T), "_T is too big to be copied to any");
std::memcpy(buff_.data(), (char*)&t, sizeof(_T));
}
template <typename _T>
typename std::enable_if<!std::is_pointer<_T>::value, _T&>::type
get() { return reinterpret_cast<_T&>(*buff_.data()); }
template <typename _T>
typename std::enable_if<!std::is_pointer<_T>::value, const _T&>::type
get() const { return reinterpret_cast<const _T>(*buff_.data()); }
template <typename _T>
typename std::enable_if<std::is_pointer<_T>::value, _T>::type
get() { return reinterpret_cast<_T>(buff_.data()); }
template <typename _T>
typename std::enable_if<std::is_pointer<_T>::value, const _T>::type
get() const { return reinterpret_cast<const _T>(buff_.data()); }
static constexpr size_type size() { return _N; }
private:
std::array<char, _N> buff_;
};
<|endoftext|>
|
<commit_before>#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include <map>
#include <algorithm>
#include <cstdio>
#include <sys/types.h>
#include <cctype>
enum asmmode_t {
ERROR = 0,
DATA,
CODE
} mode = ERROR;
FILE* fin = NULL,* fout = NULL;
size_t data_pos, code_pos;
size_t* current_size;
static void error()
{
size_t pos = ftell(fin);
fprintf(stderr, "Error @%ld\n", pos);
throw 1;
}
//=============================================================
// internal
//=============================================================
#define cassert(X) (!(X) ? fprintf(stderr, "Assertion failed: %s @%ld\n", #X, ftell(fin)), throw 0, 0 : 1)
#define END(X, N) if(X[N] != '\0') error();
static void clearOutputFile(FILE* f, size_t size)
{
unsigned char buffer[0x1000];
memset(buffer, 0, sizeof(unsigned char) * 0x1000);
fseek(f, 0, SEEK_SET);
for(size_t i = 0; i < size/0x1000; ++i) {
fwrite(buffer, sizeof(unsigned char), 0x1000, f);
}
fseek(f, 0, SEEK_SET);
}
static void tillEol()
{
int c;
do {
c = fgetc(fin);
if(isspace(c)) {
ungetc(c, fin);
return;
}
if(c == EOF || feof(fin)) {
return;
}
} while(1);
}
static std::string getToken()
{
char tok[128];
char* p = &tok[0];
int c;
while(isspace(c = fgetc(fin)))
;
*p++ = c;
do {
if(feof(fin)) break;
c = fgetc(fin);
if(c == EOF || feof(fin)) break;
if(isspace(c)) break;
if(c == ',' && tok[0] != '\'') break;
if(c == ';') {
tillEol();
continue;
}
*p++ = c;
} while(1);
*p++ = '\0';
return tok;
}
std::map<std::string, size_t> label_definitions;
std::map<size_t, std::string> label_usages;
static void add_label_to_definitions(std::string const& token)
{
label_definitions.insert(std::make_pair(std::string(token), *current_size));
}
static void add_label_used_at(size_t size, std::string const& token)
{
label_usages.insert(std::make_pair(size, std::string(token)));
}
static void resolve_labels()
{
std::for_each(label_usages.begin(), label_usages.end(), [&](decltype(label_usages)::value_type const& lbl){
fseek(fout, lbl.first, SEEK_SET);
auto found = label_definitions.find(lbl.second);
if(found == label_definitions.end()) error();
fwrite(&found->second, sizeof(size_t), 1, fout);
});
}
//=============================================================
// output
//=============================================================
static void produce(unsigned char c)
{
fwrite(&c, 1, 1, fout);
*current_size = ftell(fout);
}
static void produce_reg(unsigned char code, char const* token)
{
int nbr = -1;
switch(token[3]) {
case '1':
switch(token[4]) {
case '\0':
nbr = 1;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
nbr = 10 + (token[4] - '0');
break;
default: error();
}
case '2':
switch(token[4]) {
case '\0':
nbr = 2;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
nbr = 20 + (token[4] - '0');
break;
default: error();
}
case '3':
switch(token[4]) {
case '\0':
nbr = 3;
break;
case '0':
case '1':
nbr = 30 + (token[4] - '0');
break;
default: error();
}
case '0':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
nbr = token[3] - '0';
break;
default: error();
}
unsigned char reg = 0x1F & nbr;
unsigned char opcode = code << 5;
unsigned char i = opcode | reg;
produce(i);
}
//=============================================================
// decoders
//=============================================================
#define switch_mode(X) do{ \
if(X.compare(".code") == 0) { \
mode = CODE; \
} else if(X.compare(".data") == 0) { \
mode = DATA; \
} else { \
mode = ERROR; \
} \
}while(0)
static void for_data()
{
while(!feof(fin)) {
std::string name = getToken();
if(name[0] == '.') {
switch_mode(name);
return;
}
add_label_to_definitions(name);
std::string ssize = getToken();
long size = atol(ssize.c_str());
while(size > 0 && !feof(fin)) {
std::string name = getToken();
if(name[0] == '\'') {
size_t i = 1;
auto pEnd = name.substr(1).rfind('\'') - 1;
cassert(pEnd != std::string::npos);
while(i <= pEnd && name[i] != '\'') {
char c1 = '\0';
char c2 = '\0';
if(i < pEnd) {
c1 = name[i];
}
if(i < pEnd - 1) {
c2 = name[i + 1];
}
short data = ((unsigned char)c1 << 8) | (unsigned char)c2;
fwrite(&data, sizeof(short), 1, fout);
size--;
}
} else {
long num = atol(name.c_str());
short data = num;
fwrite(&data, sizeof(short), 1, fout);
size--;
}
}
}
}
static void push_imed()
{
std::string token = getToken();
produce(0x5);
if(token[0] == ':') {
add_label_used_at(*current_size, token);
produce(0);
produce(0);
}
char* endptr;
long num = strtol(token.c_str(), &endptr, 0);
if(endptr && *endptr) error();
produce((num >> 8) & 0xFF);
produce(num & 0xFF);
}
static void for_code()
{
while(!feof(fin)) {
std::string token = getToken();
switch(token[0]) {
case '.':
switch_mode(token);
break;
case ':':
add_label_to_definitions(token);
continue;
case 'A':
switch(token[1]) {
case 'D':
produce(0xA);
continue;
case 'N':
produce(0x10);
continue;
default: error();
}
case 'C':
switch(token[1]) {
case 'S':
produce(0x18);
continue;
case 'U':
produce(0x19);
continue;
default: error();
}
case 'D':
switch(token[1]) {
case 'I':
produce(0x3);
continue;
case 'V':
produce(0xE);
continue;
default: error();
}
case 'E':
switch(token[1]) {
case 'I':
produce(0x2);
continue;
default: error();
}
case 'I':
switch(token[1]) {
case 'N':
produce(0x1);
continue;
default: error();
}
case 'J':
switch(token[1]) {
case 'P':
produce(0x1E);
continue;
case 'Z':
produce(0x1F);
continue;
default: error();
}
case 'L':
switch(token[1]) {
case 'D':
produce(0x8);
continue;
default: error();
}
case 'M':
switch(token[1]) {
case 'O':
produce(0xD);
continue;
case 'U':
produce(0xC);
continue;
default: error();
}
case 'N':
switch(token[1]) {
case 'E':
produce(0x17);
continue;
case 'O':
produce(0);
continue;
case 'T':
produce(0x13);
continue;
default: error();
}
case 'O':
switch(token[1]) {
case 'R':
produce(0x11);
continue;
default: error();
}
case 'P':
switch(token[1]) {
case 'I':
push_imed();
continue;
case 'R':
if(token[2] != '.') error();
produce_reg(0x5, token.c_str());
continue;
default: error();
}
case 'R':
switch(token[1]) {
case 'D':
case 'I':
case 'L':
case 'M':
case 'P':
case 'R':
case 'T':
default: error();
}
case 'S':
switch(token[1]) {
case 'T':
case 'U':
case 'V':
default: error();
}
case 'X':
switch(token[1]) {
case 'R':
END(token, 2);
produce(0x12);
continue;
default: error();
}
}
}
}
static void assemble()
{
mode = DATA;
current_size = &data_pos;
while(!feof(fin)) {
asmmode_t prevMode = mode;
switch(mode) {
case DATA:
for_data();
break;
case CODE:
for_code();
break;
default: error();
}
if(mode != prevMode) {
switch(prevMode) {
case DATA:
data_pos = ftell(fout);
fseek(fout, code_pos, SEEK_SET);
current_size = &code_pos;
break;
case CODE:
code_pos = ftell(fout);
fseek(fout, data_pos, SEEK_SET);
current_size = &data_pos;
break;
}
}
}
}
//=============================================================
// main
//=============================================================
int main(int argc, char* argv[])
{
if(argc != 2) throw 1;
fin = fopen(argv[1], "r");
std::string name = argv[1];
auto p = name.rfind(".");
if(p != std::string::npos) {
name = name.substr(0, p) + ".hss";
if(name.compare(argv[1]) == 0) name += ".out";
} else {
name += ".hss";
}
fout = fopen(name.c_str(), "w");
ftruncate(fileno(fout), /*code*/0x10000 + /*data*/0x20000);
clearOutputFile(fout, 0x10000 + 0x20000);
code_pos = 0;
data_pos = 0x10000;
fseek(fout, data_pos, SEEK_SET);
assemble();
fclose(fin);
fclose(fout);
return 0;
}
<commit_msg>small fixes<commit_after>#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include <map>
#include <algorithm>
#include <cstdio>
#include <sys/types.h>
#include <cctype>
enum asmmode_t {
ERROR = 0,
DATA,
CODE
} mode = ERROR;
FILE* fin = NULL,* fout = NULL;
size_t data_pos, code_pos;
size_t* current_size;
static void error()
{
size_t pos = ftell(fin);
fprintf(stderr, "Error @%ld\n", pos);
throw 1;
}
//=============================================================
// internal
//=============================================================
#define cassert(X) (!(X) ? fprintf(stderr, "Assertion failed: %s @%ld\n", #X, ftell(fin)), throw 0, 0 : 1)
#define END(X, N) if(X[N] != '\0') error();
static void clearOutputFile(FILE* f, size_t size)
{
unsigned char buffer[0x1000];
memset(buffer, 0, sizeof(unsigned char) * 0x1000);
fseek(f, 0, SEEK_SET);
for(size_t i = 0; i < size/0x1000; ++i) {
fwrite(buffer, sizeof(unsigned char), 0x1000, f);
}
fseek(f, 0, SEEK_SET);
}
static void tillEol()
{
int c;
do {
c = fgetc(fin);
if(isspace(c)) {
ungetc(c, fin);
return;
}
if(c == EOF || feof(fin)) {
return;
}
} while(1);
}
static std::string getToken()
{
char tok[128];
char* p = &tok[0];
int c;
while(isspace(c = fgetc(fin)))
;
*p++ = c;
do {
if(feof(fin)) break;
c = fgetc(fin);
if(c == EOF || feof(fin)) break;
if(isspace(c)) break;
if(c == ',' && tok[0] != '\'') break;
if(c == ';') {
tillEol();
continue;
}
*p++ = c;
} while(1);
*p++ = '\0';
return tok;
}
std::map<std::string, size_t> label_definitions;
std::map<size_t, std::string> label_usages;
static void add_label_to_definitions(std::string const& token)
{
label_definitions.insert(std::make_pair(std::string(token), *current_size));
}
static void add_label_used_at(size_t size, std::string const& token)
{
label_usages.insert(std::make_pair(size, std::string(token)));
}
static void resolve_labels()
{
std::for_each(label_usages.begin(), label_usages.end(), [&](decltype(label_usages)::value_type const& lbl){
fseek(fout, lbl.first, SEEK_SET);
auto found = label_definitions.find(lbl.second);
if(found == label_definitions.end()) error();
fwrite(&found->second, sizeof(size_t), 1, fout);
});
}
//=============================================================
// output
//=============================================================
static void produce(unsigned char c)
{
fwrite(&c, 1, 1, fout);
*current_size = ftell(fout);
}
static void produce_reg(unsigned char code, char const* token)
{
int nbr = -1;
switch(token[3]) {
case '1':
switch(token[4]) {
case '\0':
nbr = 1;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
nbr = 10 + (token[4] - '0');
break;
default: error();
}
case '2':
switch(token[4]) {
case '\0':
nbr = 2;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
nbr = 20 + (token[4] - '0');
break;
default: error();
}
case '3':
switch(token[4]) {
case '\0':
nbr = 3;
break;
case '0':
case '1':
nbr = 30 + (token[4] - '0');
break;
default: error();
}
case '0':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
nbr = token[3] - '0';
break;
default: error();
}
unsigned char reg = 0x1F & nbr;
unsigned char opcode = code << 5;
unsigned char i = opcode | reg;
produce(i);
}
//=============================================================
// decoders
//=============================================================
#define switch_mode(X) do{ \
if(X.compare(".code") == 0) { \
mode = CODE; \
} else if(X.compare(".data") == 0) { \
mode = DATA; \
} else { \
mode = ERROR; \
} \
}while(0)
static void for_data()
{
while(!feof(fin)) {
std::string name = getToken();
if(name[0] == '.') {
switch_mode(name);
return;
}
add_label_to_definitions(name);
std::string ssize = getToken();
long size = atol(ssize.c_str());
while(size > 0 && !feof(fin)) {
std::string name = getToken();
if(name[0] == '\'') {
size_t i = 1;
auto pEnd = name.substr(1).rfind('\'') - 1;
cassert(pEnd != std::string::npos);
while(i <= pEnd && name[i] != '\'') {
char c1 = '\0';
char c2 = '\0';
if(i < pEnd) {
c1 = name[i];
}
if(i < pEnd - 1) {
c2 = name[i + 1];
}
short data = ((unsigned char)c1 << 8) | (unsigned char)c2;
fwrite(&data, sizeof(short), 1, fout);
size--;
}
} else {
long num = atol(name.c_str());
short data = num;
fwrite(&data, sizeof(short), 1, fout);
size--;
}
}
}
}
static void push_imed()
{
std::string token = getToken();
produce(0x5);
if(token[0] == ':') {
add_label_used_at(*current_size, token);
produce(0);
produce(0);
return;
}
char* endptr;
long num = strtol(token.c_str(), &endptr, 0);
if(endptr && *endptr) error();
produce((num >> 8) & 0xFF);
produce(num & 0xFF);
}
static void for_code()
{
while(!feof(fin)) {
std::string token = getToken();
switch(token[0]) {
case '.':
switch_mode(token);
break;
case ':':
add_label_to_definitions(token);
continue;
case 'A':
switch(token[1]) {
case 'D':
produce(0xA);
continue;
case 'N':
produce(0x10);
continue;
default: error();
}
case 'C':
switch(token[1]) {
case 'S':
produce(0x18);
continue;
case 'U':
produce(0x19);
continue;
default: error();
}
case 'D':
switch(token[1]) {
case 'I':
produce(0x3);
continue;
case 'V':
produce(0xE);
continue;
default: error();
}
case 'E':
switch(token[1]) {
case 'I':
produce(0x2);
continue;
default: error();
}
case 'I':
switch(token[1]) {
case 'N':
produce(0x1);
continue;
default: error();
}
case 'J':
switch(token[1]) {
case 'P':
produce(0x1E);
continue;
case 'Z':
produce(0x1F);
continue;
default: error();
}
case 'L':
switch(token[1]) {
case 'D':
produce(0x8);
continue;
default: error();
}
case 'M':
switch(token[1]) {
case 'O':
produce(0xD);
continue;
case 'U':
produce(0xC);
continue;
default: error();
}
case 'N':
switch(token[1]) {
case 'E':
produce(0x17);
continue;
case 'O':
produce(0);
continue;
case 'T':
produce(0x13);
continue;
default: error();
}
case 'O':
switch(token[1]) {
case 'R':
produce(0x11);
continue;
default: error();
}
case 'P':
switch(token[1]) {
case 'I':
push_imed();
continue;
case 'R':
if(token[2] != '.') error();
produce_reg(0x5, token.c_str());
continue;
default: error();
}
case 'R':
switch(token[1]) {
case 'D':
case 'I':
case 'L':
case 'M':
case 'P':
case 'R':
case 'T':
default: error();
}
case 'S':
switch(token[1]) {
case 'T':
case 'U':
case 'V':
default: error();
}
case 'X':
switch(token[1]) {
case 'R':
END(token, 2);
produce(0x12);
continue;
default: error();
}
}
}
}
static void assemble()
{
mode = DATA;
current_size = &data_pos;
while(!feof(fin)) {
asmmode_t prevMode = mode;
switch(mode) {
case DATA:
for_data();
break;
case CODE:
for_code();
break;
default: error();
}
if(mode != prevMode) {
switch(prevMode) {
case DATA:
data_pos = ftell(fout);
fseek(fout, code_pos, SEEK_SET);
current_size = &code_pos;
break;
case CODE:
code_pos = ftell(fout);
fseek(fout, data_pos, SEEK_SET);
current_size = &data_pos;
break;
}
}
}
}
//=============================================================
// main
//=============================================================
int main(int argc, char* argv[])
{
if(argc != 2) throw 1;
fin = fopen(argv[1], "r");
std::string name = argv[1];
auto p = name.rfind(".");
if(p != std::string::npos) {
name = name.substr(0, p) + ".hss";
if(name.compare(argv[1]) == 0) name += ".out";
} else {
name += ".hss";
}
fout = fopen(name.c_str(), "w");
ftruncate(fileno(fout), /*code*/0x10000 + /*data*/0x20000);
clearOutputFile(fout, 0x10000 + 0x20000);
code_pos = 0;
data_pos = 0x10000;
fseek(fout, data_pos, SEEK_SET);
assemble();
fclose(fin);
fclose(fout);
return 0;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\ProjectEuler\Problem2.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace ProjectEulerTests
{
TEST_CLASS(Problem2Tests)
{
public:
TEST_METHOD(FibonacciSumEven_Input1_Returns0)
{
auto result = Problem2::FibonacciSumEven(1);
Assert::AreEqual(0, result);
}
};
}<commit_msg>red-commit - FibonacciSumEven_Input2_Returns2<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\ProjectEuler\Problem2.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace ProjectEulerTests
{
TEST_CLASS(Problem2Tests)
{
public:
TEST_METHOD(FibonacciSumEven_Input1_Returns0)
{
auto result = Problem2::FibonacciSumEven(1);
Assert::AreEqual(0, result);
}
TEST_METHOD(FibonacciSumEven_Input2_Returns2)
{
auto result = Problem2::FibonacciSumEven(2);
Assert::AreEqual(2, result);
}
};
}<|endoftext|>
|
<commit_before>#include "Runtime/AutoMapper/CMapUniverse.hpp"
#include "Runtime/CSimplePool.hpp"
#include "Runtime/CGameState.hpp"
#include "Runtime/GameGlobalObjects.hpp"
namespace urde {
CMapUniverse::CMapUniverse(CInputStream& in, u32 version) : x0_hexagonId(in.readUint32Big()) {
x4_hexagonToken = g_SimplePool->GetObj({FOURCC('MAPA'), x0_hexagonId});
u32 count = in.readUint32Big();
x10_worldDatas.reserve(count);
for (u32 i = 0; i < count; ++i)
x10_worldDatas.emplace_back(in, version);
}
CMapUniverse::CMapWorldData::CMapWorldData(CInputStream& in, u32 version)
: x0_label(in.readString()), x10_worldAssetId(in.readUint32Big()) {
x14_transform.read34RowMajor(in);
u32 worldCount = in.readUint32Big();
x44_hexagonXfs.reserve(worldCount);
for (u32 i = 0; i < worldCount; ++i) {
x44_hexagonXfs.emplace_back();
x44_hexagonXfs.back().read34RowMajor(in);
}
if (version != 0)
x54_surfColorSelected.readRGBABig(in);
else
x54_surfColorSelected.fromRGBA32(255 | (u32(x10_worldAssetId.Value()) & 0xFFFFFF00));
x58_outlineColorSelected = zeus::CColor::lerp(zeus::skWhite, x54_surfColorSelected, 0.5f);
x5c_surfColorUnselected = zeus::CColor::lerp(zeus::skBlack, x54_surfColorSelected, 0.5f);
x60_outlineColorUnselected = zeus::CColor::lerp(zeus::skWhite, x5c_surfColorUnselected, 0.5f);
for (const zeus::CTransform& xf : x44_hexagonXfs)
x64_centerPoint += xf.origin;
x64_centerPoint *= zeus::CVector3f(1.0f / float(x44_hexagonXfs.size()));
}
void CMapUniverse::Draw(const CMapUniverseDrawParms& parms, const zeus::CVector3f&, float, float) const {
if (!x4_hexagonToken.IsLoaded())
return;
SCOPED_GRAPHICS_DEBUG_GROUP("CMapUniverse::Draw", zeus::skBlue);
u32 totalSurfaceCount = 0;
for (const CMapWorldData& data : x10_worldDatas)
totalSurfaceCount += data.GetNumMapAreaDatas() * x4_hexagonToken->GetNumSurfaces();
std::vector<CMapObjectSortInfo> sortInfos;
sortInfos.reserve(totalSurfaceCount);
for (size_t w = 0; w < x10_worldDatas.size(); ++w) {
const CMapWorldData& data = x10_worldDatas[w];
const CMapWorldInfo& mwInfo = *g_GameState->StateForWorld(data.GetWorldAssetId()).MapWorldInfo();
if (!mwInfo.IsAnythingSet())
continue;
zeus::CColor surfColor, outlineColor;
if (w == parms.GetFocusWorldIndex()) {
surfColor = data.GetSurfaceColorSelected();
surfColor.a() *= parms.GetAlpha();
outlineColor = data.GetOutlineColorSelected();
outlineColor.a() *= parms.GetAlpha();
} else {
surfColor = data.GetSurfaceColorUnselected();
surfColor.a() *= parms.GetAlpha();
outlineColor = data.GetSurfaceColorUnselected();
outlineColor.a() *= parms.GetAlpha();
}
for (u32 h = 0; h < data.GetNumMapAreaDatas(); ++h) {
zeus::CTransform hexXf = parms.GetCameraTransform().inverse() * data.GetMapAreaData(h);
for (u32 s = 0; s < x4_hexagonToken->GetNumSurfaces(); ++s) {
const CMapArea::CMapAreaSurface& surf = x4_hexagonToken->GetSurface(s);
zeus::CVector3f centerPos = hexXf * surf.GetCenterPosition();
sortInfos.emplace_back(centerPos.y(), w, h, s, surfColor, outlineColor);
}
}
}
std::sort(sortInfos.begin(), sortInfos.end(), [](const CMapObjectSortInfo& a, const CMapObjectSortInfo& b) {
return a.GetZDistance() > b.GetZDistance();
});
int lastWldIdx = -1;
int lastHexIdx = -1;
size_t instIdx = 0;
for (const CMapObjectSortInfo& info : sortInfos) {
const CMapWorldData& mwData = x10_worldDatas[info.GetWorldIndex()];
zeus::CColor surfColor = info.GetSurfaceColor();
zeus::CColor outlineColor = info.GetOutlineColor();
if (parms.GetWorldAssetId() == mwData.GetWorldAssetId() && parms.GetClosestArea() == info.GetAreaIndex()) {
surfColor = zeus::CColor::lerp(g_tweakAutoMapper->GetSurfaceSelectVisitedColor(),
g_tweakAutoMapper->GetAreaFlashPulseColor(), parms.GetFlashPulse());
surfColor.a() = info.GetSurfaceColor().a();
outlineColor = zeus::CColor::lerp(g_tweakAutoMapper->GetOutlineSelectVisitedColor(),
g_tweakAutoMapper->GetAreaFlashPulseColor(), parms.GetFlashPulse());
outlineColor.a() = info.GetOutlineColor().a();
}
zeus::CTransform hexXf = mwData.GetMapAreaData(info.GetAreaIndex());
hexXf.orthonormalize();
const CMapArea::CMapAreaSurface& surf = x4_hexagonToken->GetSurface(info.GetObjectIndex());
zeus::CColor color(std::max(0.f, (-parms.GetCameraTransform().basis[1]).dot(hexXf.rotate(surf.GetNormal()))) *
g_tweakAutoMapper->GetMapSurfaceNormColorLinear() +
g_tweakAutoMapper->GetMapSurfaceNormColorConstant());
surfColor *= color;
if (info.GetAreaIndex() != lastHexIdx || info.GetWorldIndex() != lastWldIdx)
CGraphics::SetModelMatrix(parms.GetPaneProjectionTransform() * mwData.GetMapAreaData(info.GetAreaIndex()));
surf.Draw(x4_hexagonToken->GetVertices(), surfColor, outlineColor, 2.f, instIdx++);
}
}
CFactoryFnReturn FMapUniverseFactory(const SObjectTag&, CInputStream& in, const CVParamTransfer&, CObjectReference*) {
in.readUint32Big();
u32 version = in.readUint32Big();
return TToken<CMapUniverse>::GetIObjObjectFor(std::make_unique<CMapUniverse>(in, version));
}
} // namespace urde
<commit_msg>CMapUniverse: Resolve sign conversion warning in Draw()<commit_after>#include "Runtime/AutoMapper/CMapUniverse.hpp"
#include "Runtime/CSimplePool.hpp"
#include "Runtime/CGameState.hpp"
#include "Runtime/GameGlobalObjects.hpp"
namespace urde {
CMapUniverse::CMapUniverse(CInputStream& in, u32 version) : x0_hexagonId(in.readUint32Big()) {
x4_hexagonToken = g_SimplePool->GetObj({FOURCC('MAPA'), x0_hexagonId});
u32 count = in.readUint32Big();
x10_worldDatas.reserve(count);
for (u32 i = 0; i < count; ++i)
x10_worldDatas.emplace_back(in, version);
}
CMapUniverse::CMapWorldData::CMapWorldData(CInputStream& in, u32 version)
: x0_label(in.readString()), x10_worldAssetId(in.readUint32Big()) {
x14_transform.read34RowMajor(in);
u32 worldCount = in.readUint32Big();
x44_hexagonXfs.reserve(worldCount);
for (u32 i = 0; i < worldCount; ++i) {
x44_hexagonXfs.emplace_back();
x44_hexagonXfs.back().read34RowMajor(in);
}
if (version != 0)
x54_surfColorSelected.readRGBABig(in);
else
x54_surfColorSelected.fromRGBA32(255 | (u32(x10_worldAssetId.Value()) & 0xFFFFFF00));
x58_outlineColorSelected = zeus::CColor::lerp(zeus::skWhite, x54_surfColorSelected, 0.5f);
x5c_surfColorUnselected = zeus::CColor::lerp(zeus::skBlack, x54_surfColorSelected, 0.5f);
x60_outlineColorUnselected = zeus::CColor::lerp(zeus::skWhite, x5c_surfColorUnselected, 0.5f);
for (const zeus::CTransform& xf : x44_hexagonXfs)
x64_centerPoint += xf.origin;
x64_centerPoint *= zeus::CVector3f(1.0f / float(x44_hexagonXfs.size()));
}
void CMapUniverse::Draw(const CMapUniverseDrawParms& parms, const zeus::CVector3f&, float, float) const {
if (!x4_hexagonToken.IsLoaded())
return;
SCOPED_GRAPHICS_DEBUG_GROUP("CMapUniverse::Draw", zeus::skBlue);
u32 totalSurfaceCount = 0;
for (const CMapWorldData& data : x10_worldDatas)
totalSurfaceCount += data.GetNumMapAreaDatas() * x4_hexagonToken->GetNumSurfaces();
std::vector<CMapObjectSortInfo> sortInfos;
sortInfos.reserve(totalSurfaceCount);
for (size_t w = 0; w < x10_worldDatas.size(); ++w) {
const CMapWorldData& data = x10_worldDatas[w];
const CMapWorldInfo& mwInfo = *g_GameState->StateForWorld(data.GetWorldAssetId()).MapWorldInfo();
if (!mwInfo.IsAnythingSet())
continue;
zeus::CColor surfColor, outlineColor;
if (s32(w) == parms.GetFocusWorldIndex()) {
surfColor = data.GetSurfaceColorSelected();
surfColor.a() *= parms.GetAlpha();
outlineColor = data.GetOutlineColorSelected();
outlineColor.a() *= parms.GetAlpha();
} else {
surfColor = data.GetSurfaceColorUnselected();
surfColor.a() *= parms.GetAlpha();
outlineColor = data.GetSurfaceColorUnselected();
outlineColor.a() *= parms.GetAlpha();
}
for (u32 h = 0; h < data.GetNumMapAreaDatas(); ++h) {
zeus::CTransform hexXf = parms.GetCameraTransform().inverse() * data.GetMapAreaData(h);
for (u32 s = 0; s < x4_hexagonToken->GetNumSurfaces(); ++s) {
const CMapArea::CMapAreaSurface& surf = x4_hexagonToken->GetSurface(s);
zeus::CVector3f centerPos = hexXf * surf.GetCenterPosition();
sortInfos.emplace_back(centerPos.y(), w, h, s, surfColor, outlineColor);
}
}
}
std::sort(sortInfos.begin(), sortInfos.end(), [](const CMapObjectSortInfo& a, const CMapObjectSortInfo& b) {
return a.GetZDistance() > b.GetZDistance();
});
int lastWldIdx = -1;
int lastHexIdx = -1;
size_t instIdx = 0;
for (const CMapObjectSortInfo& info : sortInfos) {
const CMapWorldData& mwData = x10_worldDatas[info.GetWorldIndex()];
zeus::CColor surfColor = info.GetSurfaceColor();
zeus::CColor outlineColor = info.GetOutlineColor();
if (parms.GetWorldAssetId() == mwData.GetWorldAssetId() && parms.GetClosestArea() == info.GetAreaIndex()) {
surfColor = zeus::CColor::lerp(g_tweakAutoMapper->GetSurfaceSelectVisitedColor(),
g_tweakAutoMapper->GetAreaFlashPulseColor(), parms.GetFlashPulse());
surfColor.a() = info.GetSurfaceColor().a();
outlineColor = zeus::CColor::lerp(g_tweakAutoMapper->GetOutlineSelectVisitedColor(),
g_tweakAutoMapper->GetAreaFlashPulseColor(), parms.GetFlashPulse());
outlineColor.a() = info.GetOutlineColor().a();
}
zeus::CTransform hexXf = mwData.GetMapAreaData(info.GetAreaIndex());
hexXf.orthonormalize();
const CMapArea::CMapAreaSurface& surf = x4_hexagonToken->GetSurface(info.GetObjectIndex());
zeus::CColor color(std::max(0.f, (-parms.GetCameraTransform().basis[1]).dot(hexXf.rotate(surf.GetNormal()))) *
g_tweakAutoMapper->GetMapSurfaceNormColorLinear() +
g_tweakAutoMapper->GetMapSurfaceNormColorConstant());
surfColor *= color;
if (info.GetAreaIndex() != lastHexIdx || info.GetWorldIndex() != lastWldIdx)
CGraphics::SetModelMatrix(parms.GetPaneProjectionTransform() * mwData.GetMapAreaData(info.GetAreaIndex()));
surf.Draw(x4_hexagonToken->GetVertices(), surfColor, outlineColor, 2.f, instIdx++);
}
}
CFactoryFnReturn FMapUniverseFactory(const SObjectTag&, CInputStream& in, const CVParamTransfer&, CObjectReference*) {
in.readUint32Big();
u32 version = in.readUint32Big();
return TToken<CMapUniverse>::GetIObjObjectFor(std::make_unique<CMapUniverse>(in, version));
}
} // namespace urde
<|endoftext|>
|
<commit_before>#include "souistd.h"
#include "core/SwndLayoutBuilder.h"
namespace SOUI
{
//////////////////////////////////////////////////////////////////////////
SWindowRepos::SWindowRepos(SWindow *pWnd):m_pWnd(pWnd)
{
SASSERT(m_pWnd);
m_rcWnd = m_pWnd->m_rcWindow;
SwndLayoutBuilder::InitLayoutState(m_pWnd->m_rcWindow);
}
SWindowRepos::~SWindowRepos()
{
if(m_pWnd->m_rcWindow != m_rcWnd)
{
m_pWnd->OnRelayout(m_rcWnd,m_pWnd->m_rcWindow);
}
}
//////////////////////////////////////////////////////////////////////////
// SwndLayout
void SwndLayoutBuilder::InitLayoutState(CRect &rcWindow)
{
rcWindow.SetRect(POS_INIT,POS_INIT,POS_INIT,POS_INIT);
}
BOOL SwndLayoutBuilder::IsWaitingPos( int nPos )
{
return nPos == POS_INIT || nPos == POS_WAIT;
}
CRect SwndLayoutBuilder::GetWindowLayoutRect(SWindow *pWindow)
{
CRect rc = pWindow->m_rcWindow;
if(!pWindow->m_bDisplay && !pWindow->m_bVisible)
{
rc.right=rc.left;
rc.bottom=rc.top;
}
return rc;
}
int SwndLayoutBuilder::PositionItem2Value(SWindow *pWindow,const POSITION_ITEM &pos ,int nMin, int nMax,BOOL bX)
{
int nRet=0;
int nSize=nMax-nMin;
switch(pos.pit)
{
case PIT_CENTER:
nRet=(int)pos.nPos * pos.cMinus + nSize/2 + nMin;
break;
case PIT_NORMAL:
if(pos.cMinus == -1)
nRet=nMax-(int)pos.nPos;
else
nRet=nMin+(int)pos.nPos;
break;
case PIT_PERCENT:
if(pos.cMinus == -1)
nRet=nMin+(int)((100.0f-pos.nPos)*nSize/100);
else
nRet=nMin+(int)(pos.nPos*nSize/100);
if(nRet>nMax) nRet=nMax;
break;
case PIT_PREV_NEAR:
case PIT_PREV_FAR:
{
SWindow *pRefWnd=pWindow->GetWindow(GSW_PREVSIBLING);
if(!pRefWnd) pRefWnd=pWindow->GetWindow(GSW_PARENT);
if(pRefWnd)
{//ҪȷοǷɲ
CRect rcRef = GetWindowLayoutRect(pRefWnd);
if(bX)
{
LONG refPos = (pos.pit == PIT_PREV_NEAR)?rcRef.right:rcRef.left;
if(IsWaitingPos(refPos))
nRet=POS_WAIT;
else
nRet=refPos+(int)pos.nPos*pos.cMinus;
}else
{
LONG refPos = (pos.pit == PIT_PREV_NEAR)?rcRef.bottom:rcRef.top;
if(IsWaitingPos(refPos))
nRet=POS_WAIT;
else
nRet=refPos+(int)pos.nPos*pos.cMinus;
}
}
}
break;
case PIT_NEXT_NEAR:
case PIT_NEXT_FAR:
{
SWindow *pRefWnd=pWindow->GetWindow(GSW_NEXTSIBLING);
if(!pRefWnd) pRefWnd=pWindow->GetWindow(GSW_PARENT);
if(pRefWnd)
{//ҪȷοǷɲ
CRect rcRef = GetWindowLayoutRect(pRefWnd);
if(bX)
{
LONG refPos = (pos.pit == PIT_NEXT_NEAR)?rcRef.left:rcRef.right;
if(IsWaitingPos(refPos))
nRet=POS_WAIT;
else
nRet=refPos+(int)pos.nPos*pos.cMinus;
}else
{
LONG refPos = (pos.pit == PIT_NEXT_NEAR)?rcRef.top:rcRef.bottom;
if(IsWaitingPos(refPos))
nRet=POS_WAIT;
else
nRet=refPos+(int)pos.nPos*pos.cMinus;
}
}
}
break;
}
return nRet;
}
int SwndLayoutBuilder::CalcPosition(SWindow *pWnd,const CRect & rcContainer,CRect & rcWindow, const SwndLayout * pSwndLayout/*=NULL*/)
{
int nRet=0;
if(pSwndLayout == NULL) pSwndLayout = pWnd->GetLayout();
if(pSwndLayout->nCount==4)
{//ָ4
if(IsWaitingPos(rcWindow.left))
rcWindow.left=PositionItem2Value(pWnd,pSwndLayout->pos[PI_LEFT],rcContainer.left,rcContainer.right,TRUE);
if(rcWindow.left==POS_WAIT) nRet++;
if(IsWaitingPos(rcWindow.top))
rcWindow.top=PositionItem2Value(pWnd,pSwndLayout->pos[PI_TOP],rcContainer.top,rcContainer.bottom,FALSE);
if(rcWindow.top==POS_WAIT) nRet++;
if(IsWaitingPos(rcWindow.right))
{
if(pSwndLayout->pos[PI_RIGHT].pit == PIT_SIZE)
{
if(!IsWaitingPos(rcWindow.left))
{
if(pSwndLayout->pos[PI_RIGHT].cMinus == -1)
{
CSize szWnd=pWnd->GetDesiredSize(rcContainer);
rcWindow.right = rcWindow.left + szWnd.cx;
}else
{
rcWindow.right = rcWindow.left + (int)pSwndLayout->pos[PI_RIGHT].nPos;
}
}
}else
{
rcWindow.right=PositionItem2Value(pWnd,pSwndLayout->pos[PI_RIGHT],rcContainer.left,rcContainer.right,TRUE);
}
}
if(rcWindow.right==POS_WAIT) nRet++;
if(IsWaitingPos(rcWindow.bottom ))
{
if(pSwndLayout->pos[PI_BOTTOM].pit == PIT_SIZE)
{
if(!IsWaitingPos(rcWindow.top))
{
if(pSwndLayout->pos[PI_RIGHT].cMinus == -1)
{
CSize szWnd=pWnd->GetDesiredSize(rcContainer);
rcWindow.bottom = rcWindow.top + szWnd.cy;
}else
{
rcWindow.bottom = rcWindow.top + (int)pSwndLayout->pos[PI_BOTTOM].nPos;
}
}
}else
{
rcWindow.bottom=PositionItem2Value(pWnd,pSwndLayout->pos[PI_BOTTOM],rcContainer.top,rcContainer.bottom,FALSE);
}
}
if(rcWindow.bottom==POS_WAIT) nRet++;
}else
{
CPoint pt = pWnd->m_rcWindow.TopLeft();
if(pSwndLayout->nCount==2)
{//ָ
if(IsWaitingPos(pt.x)) pt.x=PositionItem2Value(pWnd,pSwndLayout->pos[PI_LEFT],rcContainer.left,rcContainer.right,TRUE);
if(pt.x==POS_WAIT) nRet++;
if(IsWaitingPos(pt.y)) pt.y=PositionItem2Value(pWnd,pSwndLayout->pos[PI_TOP],rcContainer.top,rcContainer.bottom,FALSE);
if(pt.y==POS_WAIT) nRet++;
}else //if(nCount==0)
{
if(IsWaitingPos(pt.x) && pSwndLayout->IsFitParent(PD_X))
{
pt.x=rcContainer.left;
}
if(IsWaitingPos(pt.y) && pSwndLayout->IsFitParent(PD_Y))
{
pt.y=rcContainer.top;
}
//ԶŰ
SWindow *pSibling=pWnd->GetWindow(GSW_PREVSIBLING);
if(!pSibling)
{//ûֵܴڣӸϽǿʼ
if(IsWaitingPos(pt.x)) pt.x=rcContainer.left;
if(IsWaitingPos(pt.y)) pt.y=rcContainer.top;
}else
{
CRect rcSib = pSibling->m_rcWindow;
if(IsWaitingPos(pt.x))
{
if(!IsWaitingPos(rcSib.right))
{
SWindow *pParent = pWnd->GetParent();
SASSERT(pParent);
pt.x=rcSib.right+pParent->m_style.m_bySepSpace;
}else
{
pt.x=POS_WAIT,nRet++;
}
}
if(IsWaitingPos(pt.y))
{
if(!IsWaitingPos(rcSib.top))
{
pt.y=rcSib.top;
}else
{
pt.y=POS_WAIT,nRet++;
}
}
}
}
if(nRet==0)
rcWindow=CRect(pt,CalcSize(pWnd,rcContainer,pSwndLayout));
else
rcWindow.left=pt.x,rcWindow.top=pt.y;
}
if(nRet==0)
{//ûȴ
rcWindow.NormalizeRect();
//ڵƫ(offset)
CSize sz = rcWindow.Size();
CPoint ptOffset;
ptOffset.x = (LONG)(sz.cx * pSwndLayout->fOffsetX);
ptOffset.y = (LONG)(sz.cy * pSwndLayout->fOffsetY);
rcWindow.OffsetRect(ptOffset);
}
return nRet;
}
BOOL SwndLayoutBuilder::CalcChildrenPosition(SList<SWindowRepos*> *pListChildren,const CRect & rcContainer)
{
SPOSITION pos=pListChildren->GetHeadPosition();
int nChildrenCount=pListChildren->GetCount();
while(pos)
{
SPOSITION posOld=pos;
SWindow *pChild=pListChildren->GetNext(pos)->GetWindow();
if(0 == SwndLayoutBuilder::CalcPosition(pChild,rcContainer,pChild->m_rcWindow))
{
delete pListChildren->GetAt(posOld);
pListChildren->RemoveAt(posOld);
}
}
if(0==pListChildren->GetCount())
return TRUE;
if(nChildrenCount == pListChildren->GetCount())
{//ڲ
SASSERT(FALSE);
return FALSE;
}else
{
return CalcChildrenPosition(pListChildren,rcContainer);
}
}
CSize SwndLayoutBuilder::CalcSize(SWindow *pWnd,const CRect & rcContainer,const SwndLayout * pSwndLayout)
{
CSize sz;
if(!pSwndLayout) pSwndLayout = pWnd->GetLayout();
if(pSwndLayout->IsSpecifySize(PD_X))
sz.cx=pSwndLayout->uSpecifyWidth;
else if(pSwndLayout->IsFitParent(PD_X))
sz.cx=rcContainer.right-rcContainer.left;
if(pSwndLayout->IsSpecifySize(PD_Y))
sz.cy=pSwndLayout->uSpecifyHeight;
else if(pSwndLayout->IsFitParent(PD_Y))
sz.cy=rcContainer.bottom-rcContainer.top;
if((pSwndLayout->IsFitContent(PD_ALL) ) && pSwndLayout->nCount!=4)
{
CSize szDesire=pWnd->GetDesiredSize(rcContainer);
if(pSwndLayout->IsFitContent(PD_X))
sz.cx=szDesire.cx;
if(pSwndLayout->IsFitContent(PD_Y))
sz.cy=szDesire.cy;
}
return sz;
}
}
<commit_msg><commit_after>#include "souistd.h"
#include "core/SwndLayoutBuilder.h"
namespace SOUI
{
//////////////////////////////////////////////////////////////////////////
SWindowRepos::SWindowRepos(SWindow *pWnd):m_pWnd(pWnd)
{
SASSERT(m_pWnd);
m_rcWnd = m_pWnd->m_rcWindow;
SwndLayoutBuilder::InitLayoutState(m_pWnd->m_rcWindow);
}
SWindowRepos::~SWindowRepos()
{
if(m_pWnd->m_rcWindow != m_rcWnd)
{
m_pWnd->OnRelayout(m_rcWnd,m_pWnd->m_rcWindow);
}
}
//////////////////////////////////////////////////////////////////////////
// SwndLayout
void SwndLayoutBuilder::InitLayoutState(CRect &rcWindow)
{
rcWindow.SetRect(POS_INIT,POS_INIT,POS_INIT,POS_INIT);
}
BOOL SwndLayoutBuilder::IsWaitingPos( int nPos )
{
return nPos == POS_INIT || nPos == POS_WAIT;
}
CRect SwndLayoutBuilder::GetWindowLayoutRect(SWindow *pWindow)
{
CRect rc = pWindow->m_rcWindow;
if(!pWindow->m_bDisplay && !pWindow->m_bVisible)
{
rc.right=rc.left;
rc.bottom=rc.top;
}
return rc;
}
int SwndLayoutBuilder::PositionItem2Value(SWindow *pWindow,const POSITION_ITEM &pos ,int nMin, int nMax,BOOL bX)
{
int nRet=0;
int nSize=nMax-nMin;
switch(pos.pit)
{
case PIT_CENTER:
nRet=(int)pos.nPos * pos.cMinus + nSize/2 + nMin;
break;
case PIT_NORMAL:
if(pos.cMinus == -1)
nRet=nMax-(int)pos.nPos;
else
nRet=nMin+(int)pos.nPos;
break;
case PIT_PERCENT:
if(pos.cMinus == -1)
nRet=nMin+(int)((100.0f-pos.nPos)*nSize/100);
else
nRet=nMin+(int)(pos.nPos*nSize/100);
if(nRet>nMax) nRet=nMax;
break;
case PIT_PREV_NEAR:
case PIT_PREV_FAR:
{
SWindow *pRefWnd=pWindow->GetWindow(GSW_PREVSIBLING);
if(!pRefWnd) pRefWnd=pWindow->GetWindow(GSW_PARENT);
if(pRefWnd)
{//ҪȷοǷɲ
CRect rcRef = GetWindowLayoutRect(pRefWnd);
if(bX)
{
LONG refPos = (pos.pit == PIT_PREV_NEAR)?rcRef.right:rcRef.left;
if(IsWaitingPos(refPos))
nRet=POS_WAIT;
else
nRet=refPos+(int)pos.nPos*pos.cMinus;
}else
{
LONG refPos = (pos.pit == PIT_PREV_NEAR)?rcRef.bottom:rcRef.top;
if(IsWaitingPos(refPos))
nRet=POS_WAIT;
else
nRet=refPos+(int)pos.nPos*pos.cMinus;
}
}
}
break;
case PIT_NEXT_NEAR:
case PIT_NEXT_FAR:
{
SWindow *pRefWnd=pWindow->GetWindow(GSW_NEXTSIBLING);
if(!pRefWnd) pRefWnd=pWindow->GetWindow(GSW_PARENT);
if(pRefWnd)
{//ҪȷοǷɲ
CRect rcRef = GetWindowLayoutRect(pRefWnd);
if(bX)
{
LONG refPos = (pos.pit == PIT_NEXT_NEAR)?rcRef.left:rcRef.right;
if(IsWaitingPos(refPos))
nRet=POS_WAIT;
else
nRet=refPos+(int)pos.nPos*pos.cMinus;
}else
{
LONG refPos = (pos.pit == PIT_NEXT_NEAR)?rcRef.top:rcRef.bottom;
if(IsWaitingPos(refPos))
nRet=POS_WAIT;
else
nRet=refPos+(int)pos.nPos*pos.cMinus;
}
}
}
break;
}
return nRet;
}
int SwndLayoutBuilder::CalcPosition(SWindow *pWnd,const CRect & rcContainer,CRect & rcWindow, const SwndLayout * pSwndLayout/*=NULL*/)
{
int nRet=0;
if(pSwndLayout == NULL) pSwndLayout = pWnd->GetLayout();
if(pSwndLayout->nCount==4)
{//ָ4
if(IsWaitingPos(rcWindow.left))
rcWindow.left=PositionItem2Value(pWnd,pSwndLayout->pos[PI_LEFT],rcContainer.left,rcContainer.right,TRUE);
if(rcWindow.left==POS_WAIT) nRet++;
if(IsWaitingPos(rcWindow.top))
rcWindow.top=PositionItem2Value(pWnd,pSwndLayout->pos[PI_TOP],rcContainer.top,rcContainer.bottom,FALSE);
if(rcWindow.top==POS_WAIT) nRet++;
if(IsWaitingPos(rcWindow.right))
{
if(pSwndLayout->pos[PI_RIGHT].pit == PIT_SIZE)
{
if(!IsWaitingPos(rcWindow.left))
{
if(pSwndLayout->pos[PI_RIGHT].cMinus == -1)
{
CSize szWnd=pWnd->GetDesiredSize(rcContainer);
rcWindow.right = rcWindow.left + szWnd.cx;
}else
{
rcWindow.right = rcWindow.left + (int)pSwndLayout->pos[PI_RIGHT].nPos;
}
}
}else
{
rcWindow.right=PositionItem2Value(pWnd,pSwndLayout->pos[PI_RIGHT],rcContainer.left,rcContainer.right,TRUE);
}
}
if(rcWindow.right==POS_WAIT) nRet++;
if(IsWaitingPos(rcWindow.bottom ))
{
if(pSwndLayout->pos[PI_BOTTOM].pit == PIT_SIZE)
{
if(!IsWaitingPos(rcWindow.top))
{
if(pSwndLayout->pos[PI_BOTTOM].cMinus == -1)
{
CSize szWnd=pWnd->GetDesiredSize(rcContainer);
rcWindow.bottom = rcWindow.top + szWnd.cy;
}else
{
rcWindow.bottom = rcWindow.top + (int)pSwndLayout->pos[PI_BOTTOM].nPos;
}
}
}else
{
rcWindow.bottom=PositionItem2Value(pWnd,pSwndLayout->pos[PI_BOTTOM],rcContainer.top,rcContainer.bottom,FALSE);
}
}
if(rcWindow.bottom==POS_WAIT) nRet++;
}else
{
CPoint pt = pWnd->m_rcWindow.TopLeft();
if(pSwndLayout->nCount==2)
{//ָ
if(IsWaitingPos(pt.x)) pt.x=PositionItem2Value(pWnd,pSwndLayout->pos[PI_LEFT],rcContainer.left,rcContainer.right,TRUE);
if(pt.x==POS_WAIT) nRet++;
if(IsWaitingPos(pt.y)) pt.y=PositionItem2Value(pWnd,pSwndLayout->pos[PI_TOP],rcContainer.top,rcContainer.bottom,FALSE);
if(pt.y==POS_WAIT) nRet++;
}else //if(nCount==0)
{
if(IsWaitingPos(pt.x) && pSwndLayout->IsFitParent(PD_X))
{
pt.x=rcContainer.left;
}
if(IsWaitingPos(pt.y) && pSwndLayout->IsFitParent(PD_Y))
{
pt.y=rcContainer.top;
}
//ԶŰ
SWindow *pSibling=pWnd->GetWindow(GSW_PREVSIBLING);
if(!pSibling)
{//ûֵܴڣӸϽǿʼ
if(IsWaitingPos(pt.x)) pt.x=rcContainer.left;
if(IsWaitingPos(pt.y)) pt.y=rcContainer.top;
}else
{
CRect rcSib = pSibling->m_rcWindow;
if(IsWaitingPos(pt.x))
{
if(!IsWaitingPos(rcSib.right))
{
SWindow *pParent = pWnd->GetParent();
SASSERT(pParent);
pt.x=rcSib.right+pParent->m_style.m_bySepSpace;
}else
{
pt.x=POS_WAIT,nRet++;
}
}
if(IsWaitingPos(pt.y))
{
if(!IsWaitingPos(rcSib.top))
{
pt.y=rcSib.top;
}else
{
pt.y=POS_WAIT,nRet++;
}
}
}
}
if(nRet==0)
rcWindow=CRect(pt,CalcSize(pWnd,rcContainer,pSwndLayout));
else
rcWindow.left=pt.x,rcWindow.top=pt.y;
}
if(nRet==0)
{//ûȴ
rcWindow.NormalizeRect();
//ڵƫ(offset)
CSize sz = rcWindow.Size();
CPoint ptOffset;
ptOffset.x = (LONG)(sz.cx * pSwndLayout->fOffsetX);
ptOffset.y = (LONG)(sz.cy * pSwndLayout->fOffsetY);
rcWindow.OffsetRect(ptOffset);
}
return nRet;
}
BOOL SwndLayoutBuilder::CalcChildrenPosition(SList<SWindowRepos*> *pListChildren,const CRect & rcContainer)
{
SPOSITION pos=pListChildren->GetHeadPosition();
int nChildrenCount=pListChildren->GetCount();
while(pos)
{
SPOSITION posOld=pos;
SWindow *pChild=pListChildren->GetNext(pos)->GetWindow();
if(0 == SwndLayoutBuilder::CalcPosition(pChild,rcContainer,pChild->m_rcWindow))
{
delete pListChildren->GetAt(posOld);
pListChildren->RemoveAt(posOld);
}
}
if(0==pListChildren->GetCount())
return TRUE;
if(nChildrenCount == pListChildren->GetCount())
{//ڲ
SASSERT(FALSE);
return FALSE;
}else
{
return CalcChildrenPosition(pListChildren,rcContainer);
}
}
CSize SwndLayoutBuilder::CalcSize(SWindow *pWnd,const CRect & rcContainer,const SwndLayout * pSwndLayout)
{
CSize sz;
if(!pSwndLayout) pSwndLayout = pWnd->GetLayout();
if(pSwndLayout->IsSpecifySize(PD_X))
sz.cx=pSwndLayout->uSpecifyWidth;
else if(pSwndLayout->IsFitParent(PD_X))
sz.cx=rcContainer.right-rcContainer.left;
if(pSwndLayout->IsSpecifySize(PD_Y))
sz.cy=pSwndLayout->uSpecifyHeight;
else if(pSwndLayout->IsFitParent(PD_Y))
sz.cy=rcContainer.bottom-rcContainer.top;
if((pSwndLayout->IsFitContent(PD_ALL) ) && pSwndLayout->nCount!=4)
{
CSize szDesire=pWnd->GetDesiredSize(rcContainer);
if(pSwndLayout->IsFitContent(PD_X))
sz.cx=szDesire.cx;
if(pSwndLayout->IsFitContent(PD_Y))
sz.cy=szDesire.cy;
}
return sz;
}
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "esp_event.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "tcpip_adapter.h"
#include <string.h>
#include <sys/param.h>
#include <algorithm>
#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include <lwip/netdb.h>
#include <inet/IPAddress.h>
#include <inet/InetError.h>
#include <inet/InetLayer.h>
#include <platform/CHIPDeviceLayer.h>
#include <support/CodeUtils.h>
#include <support/ErrorStr.h>
#include <system/SystemPacketBuffer.h>
#include <transport/SecureSessionMgr.h>
#include <transport/UDP.h>
#include "DataModelHandler.h"
#include "LEDWidget.h"
static const char * TAG = "echo_server";
using namespace ::chip;
using namespace ::chip::Inet;
using namespace ::chip::Transport;
constexpr NodeId kLocalNodeId = 12344321;
extern LEDWidget statusLED; // In wifi-echo.cpp
namespace {
const unsigned char local_private_key[] = { 0xc6, 0x1a, 0x2f, 0x89, 0x36, 0x67, 0x2b, 0x26, 0x12, 0x47, 0x4f,
0x11, 0x0e, 0x34, 0x15, 0x81, 0x81, 0x12, 0xfc, 0x36, 0xeb, 0x65,
0x61, 0x07, 0xaa, 0x63, 0xe8, 0xc5, 0x22, 0xac, 0x52, 0xa1 };
const unsigned char remote_public_key[] = { 0x04, 0x30, 0x77, 0x2c, 0xe7, 0xd4, 0x0a, 0xf2, 0xf3, 0x19, 0xbd, 0xfb, 0x1f,
0xcc, 0x88, 0xd9, 0x83, 0x25, 0x89, 0xf2, 0x09, 0xf3, 0xab, 0xe4, 0x33, 0xb6,
0x7a, 0xff, 0x73, 0x3b, 0x01, 0x35, 0x34, 0x92, 0x73, 0x14, 0x59, 0x0b, 0xbd,
0x44, 0x72, 0x1b, 0xcd, 0xb9, 0x02, 0x53, 0xd9, 0xaf, 0xcc, 0x1a, 0xcd, 0xae,
0xe8, 0x87, 0x2e, 0x52, 0x3b, 0x98, 0xf0, 0xa1, 0x88, 0x4a, 0xe3, 0x03, 0x75 };
/**
* A data model message has nonzero length and always has a first byte whose
* value is one of: 0x00, 0x01, 0x02, 0x03. See chipZclEncodeZclHeader for the
* construction of the message and in particular the first byte.
*
* Echo messages should generally not have a first byte with those values, so we
* can use that to try to distinguish between the two.
*/
static bool ContentMayBeADataModelMessage(System::PacketBuffer * buffer)
{
const size_t data_len = buffer->DataLength();
const uint8_t * data = buffer->Start();
bool maybeDataModelMessage = true;
// Has to have nonzero length.
VerifyOrExit(data_len > 0, maybeDataModelMessage = false);
// Has to have a valid first byte value.
VerifyOrExit(data[0] < 0x04, maybeDataModelMessage = false);
exit:
return maybeDataModelMessage;
}
void newConnectionHandler(PeerConnectionState * state, SecureSessionMgr * transport)
{
CHIP_ERROR err;
ESP_LOGI(TAG, "Received a new connection.");
err = state->GetSecureSession().TemporaryManualKeyExchange(remote_public_key, sizeof(remote_public_key), local_private_key,
sizeof(local_private_key));
VerifyOrExit(err == CHIP_NO_ERROR, ESP_LOGE(TAG, "Failed to setup encryption"));
exit:
return;
}
// Transport Callbacks
void echo(const MessageHeader & header, Transport::PeerConnectionState * state, System::PacketBuffer * buffer,
SecureSessionMgr * transport)
{
CHIP_ERROR err;
const size_t data_len = buffer->DataLength();
// as soon as a client connects, assume it is connected
VerifyOrExit(transport != NULL && buffer != NULL, ESP_LOGE(TAG, "Received data but couldn't process it..."));
VerifyOrExit(state->GetPeerNodeId() != kUndefinedNodeId, ESP_LOGE(TAG, "Unknown source for received message"));
{
char src_addr[Transport::PeerAddress::kMaxToStringSize];
state->GetPeerAddress().ToString(src_addr, sizeof(src_addr));
ESP_LOGI(TAG, "Packet received from %s: %zu bytes", src_addr, static_cast<size_t>(data_len));
}
// FIXME: Long-term we shouldn't be guessing what sort of message this is
// based on the message bytes. We're doing this for now to support both
// data model messages and text echo messages, but in the long term we
// should either do echo via a data model command or do echo on a separate
// port from data model processing.
if (ContentMayBeADataModelMessage(buffer))
{
HandleDataModelMessage(buffer);
buffer = NULL;
}
else
{
ESP_LOGI(TAG, "Client sent: \"%.*s\"", data_len, buffer->Start());
// Attempt to echo back
err = transport->SendMessage(header.GetSourceNodeId().Value(), buffer);
buffer = NULL;
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "Unable to echo back to client: %s", ErrorStr(err));
}
else
{
ESP_LOGI(TAG, "Echo sent");
}
}
exit:
// SendTo calls Free on the buffer without an AddRef, if SendTo was not called, free the buffer.
if (buffer != NULL)
{
System::PacketBuffer::Free(buffer);
}
}
void error(CHIP_ERROR error, const IPPacketInfo & pi)
{
ESP_LOGE(TAG, "ERROR: %s\n Got UDP error", ErrorStr(error));
statusLED.BlinkOnError();
}
} // namespace
// The echo server assumes the platform's networking has been setup already
void setupTransport(IPAddressType type, SecureSessionMgr * transport)
{
CHIP_ERROR err = CHIP_NO_ERROR;
struct netif * netif = NULL;
if (type == kIPAddressType_IPv6)
{
tcpip_adapter_get_netif(TCPIP_ADAPTER_IF_AP, (void **) &netif);
}
err = transport->Init(kLocalNodeId, &DeviceLayer::InetLayer, UdpListenParameters().SetAddressType(type).SetInterfaceId(netif));
SuccessOrExit(err);
transport->SetMessageReceiveHandler(echo, transport);
transport->SetReceiveErrorHandler(error);
transport->SetNewConnectionHandler(newConnectionHandler, transport);
exit:
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "ERROR setting up transport: %s", ErrorStr(err));
}
else
{
ESP_LOGI(TAG, "Echo Server Listening...");
}
}
// The echo server assumes the platform's networking has been setup already
void startServer(SecureSessionMgr * transport_ipv4, SecureSessionMgr * transport_ipv6)
{
setupTransport(kIPAddressType_IPv6, transport_ipv6);
setupTransport(kIPAddressType_IPv4, transport_ipv4);
}
<commit_msg>support logging of arbitrary binary payload (#1249)<commit_after>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "esp_event.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "tcpip_adapter.h"
#include <algorithm>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include <lwip/netdb.h>
#include <inet/IPAddress.h>
#include <inet/InetError.h>
#include <inet/InetLayer.h>
#include <platform/CHIPDeviceLayer.h>
#include <support/CodeUtils.h>
#include <support/ErrorStr.h>
#include <system/SystemPacketBuffer.h>
#include <transport/SecureSessionMgr.h>
#include <transport/UDP.h>
#include "DataModelHandler.h"
#include "LEDWidget.h"
static const char * TAG = "echo_server";
using namespace ::chip;
using namespace ::chip::Inet;
using namespace ::chip::Transport;
constexpr NodeId kLocalNodeId = 12344321;
extern LEDWidget statusLED; // In wifi-echo.cpp
namespace {
const unsigned char local_private_key[] = { 0xc6, 0x1a, 0x2f, 0x89, 0x36, 0x67, 0x2b, 0x26, 0x12, 0x47, 0x4f,
0x11, 0x0e, 0x34, 0x15, 0x81, 0x81, 0x12, 0xfc, 0x36, 0xeb, 0x65,
0x61, 0x07, 0xaa, 0x63, 0xe8, 0xc5, 0x22, 0xac, 0x52, 0xa1 };
const unsigned char remote_public_key[] = { 0x04, 0x30, 0x77, 0x2c, 0xe7, 0xd4, 0x0a, 0xf2, 0xf3, 0x19, 0xbd, 0xfb, 0x1f,
0xcc, 0x88, 0xd9, 0x83, 0x25, 0x89, 0xf2, 0x09, 0xf3, 0xab, 0xe4, 0x33, 0xb6,
0x7a, 0xff, 0x73, 0x3b, 0x01, 0x35, 0x34, 0x92, 0x73, 0x14, 0x59, 0x0b, 0xbd,
0x44, 0x72, 0x1b, 0xcd, 0xb9, 0x02, 0x53, 0xd9, 0xaf, 0xcc, 0x1a, 0xcd, 0xae,
0xe8, 0x87, 0x2e, 0x52, 0x3b, 0x98, 0xf0, 0xa1, 0x88, 0x4a, 0xe3, 0x03, 0x75 };
/**
* A data model message has nonzero length and always has a first byte whose
* value is one of: 0x00, 0x01, 0x02, 0x03. See chipZclEncodeZclHeader for the
* construction of the message and in particular the first byte.
*
* Echo messages should generally not have a first byte with those values, so we
* can use that to try to distinguish between the two.
*/
static bool ContentMayBeADataModelMessage(System::PacketBuffer * buffer)
{
const size_t data_len = buffer->DataLength();
const uint8_t * data = buffer->Start();
bool maybeDataModelMessage = true;
// Has to have nonzero length.
VerifyOrExit(data_len > 0, maybeDataModelMessage = false);
// Has to have a valid first byte value.
VerifyOrExit(data[0] < 0x04, maybeDataModelMessage = false);
exit:
return maybeDataModelMessage;
}
void newConnectionHandler(PeerConnectionState * state, SecureSessionMgr * transport)
{
CHIP_ERROR err;
ESP_LOGI(TAG, "Received a new connection.");
err = state->GetSecureSession().TemporaryManualKeyExchange(remote_public_key, sizeof(remote_public_key), local_private_key,
sizeof(local_private_key));
VerifyOrExit(err == CHIP_NO_ERROR, ESP_LOGE(TAG, "Failed to setup encryption"));
exit:
return;
}
/**
* @brief implements something like "od -c", changes an arbitrary byte string
* into a single-line of ascii. Destroys any byte-wise encoding that
* might be present, e.g. utf-8.
*
* @param bytes potentially unprintable buffer
* @param bytes_len length of bytes
* @param out where to put the printable string
* @param out_len length of out
* @return size_t required size of output buffer, including null-termination
*/
static size_t odc(const uint8_t * bytes, size_t bytes_len, char * out, size_t out_len)
{
size_t required = 1; // always need null termination
memset(out, 0, out_len);
// count and print
for (; bytes_len > 0; bytes_len--, bytes++)
{
uint8_t byte = *bytes;
if ((byte >= '\t' && byte <= '\r') || byte == '\\')
{
static const char * kCodes = "tnvfr";
char code = (byte == '\\') ? '\\' : kCodes[byte - '\t'];
required += 2;
if (out_len > 2)
{
*out++ = '\\';
*out++ = code;
out_len -= 2;
}
}
else if (byte >= ' ' && byte <= '~')
{
required += 1;
if (out_len > 1)
{
*out++ = byte;
out_len--;
}
}
else
{
static const size_t kBinCodeLen = sizeof("\\xFF") - 1;
static const char * kCodes = "0123456789ABCDEF";
required += kBinCodeLen;
if (out_len > kBinCodeLen)
{
*out++ = '\\';
*out++ = 'x';
*out++ = kCodes[(byte & 0xf0) >> 4];
*out++ = kCodes[byte & 0xf];
out_len -= kBinCodeLen;
}
}
}
return required;
}
// Transport Callbacks
void receiveHandler(const MessageHeader & header, Transport::PeerConnectionState * state, System::PacketBuffer * buffer,
SecureSessionMgr * transport)
{
CHIP_ERROR err;
const size_t data_len = buffer->DataLength();
// as soon as a client connects, assume it is connected
VerifyOrExit(transport != NULL && buffer != NULL, ESP_LOGE(TAG, "Received data but couldn't process it..."));
VerifyOrExit(state->GetPeerNodeId() != kUndefinedNodeId, ESP_LOGE(TAG, "Unknown source for received message"));
{
char src_addr[Transport::PeerAddress::kMaxToStringSize];
state->GetPeerAddress().ToString(src_addr, sizeof(src_addr));
ESP_LOGI(TAG, "Packet received from %s: %zu bytes", src_addr, static_cast<size_t>(data_len));
}
// FIXME: Long-term we shouldn't be guessing what sort of message this is
// based on the message bytes. We're doing this for now to support both
// data model messages and text echo messages, but in the long term we
// should either do echo via a data model command or do echo on a separate
// port from data model processing.
if (ContentMayBeADataModelMessage(buffer))
{
HandleDataModelMessage(buffer);
buffer = NULL;
}
else
{
char logmsg[512];
odc(buffer->Start(), data_len, logmsg, sizeof(logmsg));
ESP_LOGI(TAG, "Client sent: %s", logmsg);
// Attempt to echo back
err = transport->SendMessage(header.GetSourceNodeId().Value(), buffer);
buffer = NULL;
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "Unable to echo back to client: %s", ErrorStr(err));
}
else
{
ESP_LOGI(TAG, "Echo sent");
}
}
exit:
// SendTo calls Free on the buffer without an AddRef, if SendTo was not called, free the buffer.
if (buffer != NULL)
{
System::PacketBuffer::Free(buffer);
}
}
void error(CHIP_ERROR error, const IPPacketInfo & pi)
{
ESP_LOGE(TAG, "ERROR: %s\n Got UDP error", ErrorStr(error));
statusLED.BlinkOnError();
}
} // namespace
// The echo server assumes the platform's networking has been setup already
void setupTransport(IPAddressType type, SecureSessionMgr * transport)
{
CHIP_ERROR err = CHIP_NO_ERROR;
struct netif * netif = NULL;
if (type == kIPAddressType_IPv6)
{
tcpip_adapter_get_netif(TCPIP_ADAPTER_IF_AP, (void **) &netif);
}
err = transport->Init(kLocalNodeId, &DeviceLayer::InetLayer, UdpListenParameters().SetAddressType(type).SetInterfaceId(netif));
SuccessOrExit(err);
transport->SetMessageReceiveHandler(receiveHandler, transport);
transport->SetReceiveErrorHandler(error);
transport->SetNewConnectionHandler(newConnectionHandler, transport);
exit:
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "ERROR setting up transport: %s", ErrorStr(err));
}
else
{
ESP_LOGI(TAG, "Echo Server Listening...");
}
}
// The echo server assumes the platform's networking has been setup already
void startServer(SecureSessionMgr * transport_ipv4, SecureSessionMgr * transport_ipv6)
{
setupTransport(kIPAddressType_IPv6, transport_ipv6);
setupTransport(kIPAddressType_IPv4, transport_ipv4);
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "esp_event.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "tcpip_adapter.h"
#include <string.h>
#include <sys/param.h>
#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include <lwip/netdb.h>
#include <inet/IPAddress.h>
#include <inet/InetError.h>
#include <inet/InetLayer.h>
#include <platform/CHIPDeviceLayer.h>
#include <support/ErrorStr.h>
#include <system/SystemPacketBuffer.h>
#include <transport/SecureTransport.h>
#include "DataModelHandler.h"
static const char * TAG = "echo_server";
using namespace ::chip;
using namespace ::chip::Inet;
// Transport Callbacks
static void echo(SecureTransport * transport, System::PacketBuffer * buffer, const IPPacketInfo * packet_info)
{
bool status = transport != NULL && buffer != NULL && packet_info != NULL;
if (status)
{
char src_addr[INET_ADDRSTRLEN];
char dest_addr[INET_ADDRSTRLEN];
const size_t data_len = buffer->DataLength();
packet_info->SrcAddress.ToString(src_addr, sizeof(src_addr));
packet_info->DestAddress.ToString(dest_addr, sizeof(dest_addr));
ESP_LOGI(TAG, "UDP packet received from %s:%u to %s:%u (%zu bytes)", src_addr, packet_info->SrcPort, dest_addr,
packet_info->DestPort, static_cast<size_t>(data_len));
if (data_len > 0 && buffer->Start()[0] < 0x20)
{
// Non-ACII; assume it's a data model message.
HandleDataModelMessage(buffer);
return;
}
ESP_LOGI(TAG, "Client sent: \"%.*s\"", data_len, buffer->Start());
// Attempt to echo back
CHIP_ERROR err = transport->SendMessage(buffer, packet_info->SrcAddress);
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "Unable to echo back to client: %s", ErrorStr(err));
}
else
{
ESP_LOGI(TAG, "Echo sent");
}
}
if (!status)
{
ESP_LOGE(TAG, "Received data but couldn't process it...");
// SendTo calls Free on the buffer without an AddRef, if SendTo was not called, free the buffer.
if (buffer != NULL)
{
System::PacketBuffer::Free(buffer);
}
}
}
static void error(SecureTransport * st, CHIP_ERROR error, const IPPacketInfo * pi)
{
ESP_LOGE(TAG, "ERROR: %s\n Got UDP error", ErrorStr(error));
}
static const unsigned char local_private_key[] = { 0xc6, 0x1a, 0x2f, 0x89, 0x36, 0x67, 0x2b, 0x26, 0x12, 0x47, 0x4f,
0x11, 0x0e, 0x34, 0x15, 0x81, 0x81, 0x12, 0xfc, 0x36, 0xeb, 0x65,
0x61, 0x07, 0xaa, 0x63, 0xe8, 0xc5, 0x22, 0xac, 0x52, 0xa1 };
static const unsigned char remote_public_key[] = { 0x04, 0x30, 0x77, 0x2c, 0xe7, 0xd4, 0x0a, 0xf2, 0xf3, 0x19, 0xbd, 0xfb, 0x1f,
0xcc, 0x88, 0xd9, 0x83, 0x25, 0x89, 0xf2, 0x09, 0xf3, 0xab, 0xe4, 0x33, 0xb6,
0x7a, 0xff, 0x73, 0x3b, 0x01, 0x35, 0x34, 0x92, 0x73, 0x14, 0x59, 0x0b, 0xbd,
0x44, 0x72, 0x1b, 0xcd, 0xb9, 0x02, 0x53, 0xd9, 0xaf, 0xcc, 0x1a, 0xcd, 0xae,
0xe8, 0x87, 0x2e, 0x52, 0x3b, 0x98, 0xf0, 0xa1, 0x88, 0x4a, 0xe3, 0x03, 0x75 };
// The echo server assumes the platform's networking has been setup already
void setupTransport(IPAddressType type, SecureTransport * transport)
{
CHIP_ERROR err = CHIP_NO_ERROR;
transport->Init(&DeviceLayer::InetLayer);
if (type == kIPAddressType_IPv6)
{
struct netif * netif;
tcpip_adapter_get_netif(TCPIP_ADAPTER_IF_AP, (void **) &netif);
err = transport->Connect(type, netif);
}
else
{
err = transport->Connect(type);
}
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "ERROR: %s\n Couldn't create transport, server will not start.", ErrorStr(err));
return;
}
transport->OnMessageReceived = echo;
transport->OnReceiveError = error;
err = transport->ManualKeyExchange(remote_public_key, sizeof(remote_public_key), local_private_key, sizeof(local_private_key));
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "ERROR: %s\n Couldn't establish security keys.", ErrorStr(err));
return;
}
ESP_LOGI(TAG, "Echo Server Listening...");
}
// The echo server assumes the platform's networking has been setup already
void startServer(SecureTransport * transport_ipv4, SecureTransport * transport_ipv6)
{
setupTransport(kIPAddressType_IPv4, transport_ipv4);
setupTransport(kIPAddressType_IPv6, transport_ipv6);
}
<commit_msg>Swap the IPv6 and IPv4 Server init order<commit_after>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "esp_event.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "tcpip_adapter.h"
#include <string.h>
#include <sys/param.h>
#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include <lwip/netdb.h>
#include <inet/IPAddress.h>
#include <inet/InetError.h>
#include <inet/InetLayer.h>
#include <platform/CHIPDeviceLayer.h>
#include <support/ErrorStr.h>
#include <system/SystemPacketBuffer.h>
#include <transport/SecureTransport.h>
#include "DataModelHandler.h"
static const char * TAG = "echo_server";
using namespace ::chip;
using namespace ::chip::Inet;
// Transport Callbacks
static void echo(SecureTransport * transport, System::PacketBuffer * buffer, const IPPacketInfo * packet_info)
{
bool status = transport != NULL && buffer != NULL && packet_info != NULL;
if (status)
{
char src_addr[INET_ADDRSTRLEN];
char dest_addr[INET_ADDRSTRLEN];
const size_t data_len = buffer->DataLength();
packet_info->SrcAddress.ToString(src_addr, sizeof(src_addr));
packet_info->DestAddress.ToString(dest_addr, sizeof(dest_addr));
ESP_LOGI(TAG, "UDP packet received from %s:%u to %s:%u (%zu bytes)", src_addr, packet_info->SrcPort, dest_addr,
packet_info->DestPort, static_cast<size_t>(data_len));
if (data_len > 0 && buffer->Start()[0] < 0x20)
{
// Non-ACII; assume it's a data model message.
HandleDataModelMessage(buffer);
return;
}
ESP_LOGI(TAG, "Client sent: \"%.*s\"", data_len, buffer->Start());
// Attempt to echo back
CHIP_ERROR err = transport->SendMessage(buffer, packet_info->SrcAddress);
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "Unable to echo back to client: %s", ErrorStr(err));
}
else
{
ESP_LOGI(TAG, "Echo sent");
}
}
if (!status)
{
ESP_LOGE(TAG, "Received data but couldn't process it...");
// SendTo calls Free on the buffer without an AddRef, if SendTo was not called, free the buffer.
if (buffer != NULL)
{
System::PacketBuffer::Free(buffer);
}
}
}
static void error(SecureTransport * st, CHIP_ERROR error, const IPPacketInfo * pi)
{
ESP_LOGE(TAG, "ERROR: %s\n Got UDP error", ErrorStr(error));
}
static const unsigned char local_private_key[] = { 0xc6, 0x1a, 0x2f, 0x89, 0x36, 0x67, 0x2b, 0x26, 0x12, 0x47, 0x4f,
0x11, 0x0e, 0x34, 0x15, 0x81, 0x81, 0x12, 0xfc, 0x36, 0xeb, 0x65,
0x61, 0x07, 0xaa, 0x63, 0xe8, 0xc5, 0x22, 0xac, 0x52, 0xa1 };
static const unsigned char remote_public_key[] = { 0x04, 0x30, 0x77, 0x2c, 0xe7, 0xd4, 0x0a, 0xf2, 0xf3, 0x19, 0xbd, 0xfb, 0x1f,
0xcc, 0x88, 0xd9, 0x83, 0x25, 0x89, 0xf2, 0x09, 0xf3, 0xab, 0xe4, 0x33, 0xb6,
0x7a, 0xff, 0x73, 0x3b, 0x01, 0x35, 0x34, 0x92, 0x73, 0x14, 0x59, 0x0b, 0xbd,
0x44, 0x72, 0x1b, 0xcd, 0xb9, 0x02, 0x53, 0xd9, 0xaf, 0xcc, 0x1a, 0xcd, 0xae,
0xe8, 0x87, 0x2e, 0x52, 0x3b, 0x98, 0xf0, 0xa1, 0x88, 0x4a, 0xe3, 0x03, 0x75 };
// The echo server assumes the platform's networking has been setup already
void setupTransport(IPAddressType type, SecureTransport * transport)
{
CHIP_ERROR err = CHIP_NO_ERROR;
transport->Init(&DeviceLayer::InetLayer);
if (type == kIPAddressType_IPv6)
{
struct netif * netif;
tcpip_adapter_get_netif(TCPIP_ADAPTER_IF_AP, (void **) &netif);
err = transport->Connect(type, netif);
}
else
{
err = transport->Connect(type);
}
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "ERROR: %s\n Couldn't create transport, server will not start.", ErrorStr(err));
return;
}
transport->OnMessageReceived = echo;
transport->OnReceiveError = error;
err = transport->ManualKeyExchange(remote_public_key, sizeof(remote_public_key), local_private_key, sizeof(local_private_key));
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "ERROR: %s\n Couldn't establish security keys.", ErrorStr(err));
return;
}
ESP_LOGI(TAG, "Echo Server Listening...");
}
// The echo server assumes the platform's networking has been setup already
void startServer(SecureTransport * transport_ipv4, SecureTransport * transport_ipv6)
{
setupTransport(kIPAddressType_IPv6, transport_ipv6);
setupTransport(kIPAddressType_IPv4, transport_ipv4);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007-2008 Intel Corporation. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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.
*/
/*
* it is a real program to show how VAAPI encoding work,
* It does H264 element stream level encoding on auto-generated YUV data
*
* gcc -o h264encode h264encode -lva -lva-x11
* ./h264encode -w <width> -h <height> -n <frame_num>
*
*/
#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <utils/Log.h>
#include <surfaceflinger/ISurfaceComposer.h>
#include <surfaceflinger/Surface.h>
#include <surfaceflinger/ISurface.h>
#include <surfaceflinger/SurfaceComposerClient.h>
#include <binder/MemoryHeapBase.h>
#define Display unsigned int
using namespace android;
#include "../android_winsys.cpp"
#include "h264encode_common.c"
sp<SurfaceComposerClient> client;
sp<Surface> android_surface;
sp<ISurface> android_isurface;
sp<SurfaceControl> surface_ctrl;
#if 0
static int display_surface(int frame_id, int *exit_encode)
{
VAStatus va_status;
sp<ProcessState> proc(ProcessState::self());
ProcessState::self()->startThreadPool();
printf("Create window0 for thread0\n");
SURFACE_CREATE(client,surface_ctrl,android_surface, android_isurface, 0, 0, win_width, win_height);
va_status = vaPutSurface(va_dpy, surface_id[frame_id], android_isurface,
0,0, frame_width, frame_height,
0,0, win_width, win_height,
NULL,0,0);
*exit_encode = 0;
return 0;
}
#endif
<commit_msg>h264encode: remove the leftover file h264encode_android.cpp<commit_after><|endoftext|>
|
<commit_before>#include <dune/stuff/test/test_common.hh>
#include <utility>
#include <memory>
#include <dune/grid/sgrid.hh>
#include <dune/grid/part/leaf.hh>
#include <dune/stuff/grid/provider.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/detailed-solvers/linearelliptic/model.hh>
#include <dune/detailed-solvers/linearelliptic/solver/interface.hh>
#include <dune/detailed-solvers/linearelliptic/solver/cg/detailed-discretizations.hh>
#include <dune/detailed-solvers/linearelliptic/solver/fv/pdelab.hh>
namespace Stuff = Dune::Stuff;
namespace Elliptic = Dune::DetailedSolvers::LinearElliptic;
static const int dimDomain = 2;
typedef Dune::SGrid< 2, 2 > GridType;
typedef typename GridType::ctype DomainFieldType;
typedef double RangeFieldType;
static const int dimRange = 1;
typedef Dune::grid::Part::Leaf::Const< GridType > GridPartType;
typedef testing::Types< std::pair< Elliptic::SolverContinuousGalerkinDD< GridPartType, RangeFieldType, dimRange, 1 >,
Elliptic::SolverContinuousGalerkinDDTraits< GridPartType, RangeFieldType, dimRange, 1 >
>
, std::pair< Elliptic::SolverFiniteVolumePdelab< GridPartType, RangeFieldType, dimRange >,
Elliptic::SolverFiniteVolumePdelabTraits< GridPartType, RangeFieldType, dimRange >
>
> SolverTypes;
template< class T >
struct SolverCRTPtest
: public ::testing::Test
{
typedef typename T::first_type SolverType;
typedef typename T::second_type Traits;
typedef Elliptic::SolverInterface< Traits > SolverInterfaceType;
typedef Stuff::GridProviderInterface< GridType > GridProviderType;
typedef typename GridPartType::GridViewType GridViewType;
typedef Stuff::GridboundaryInterface< GridViewType > GridBoundaryinfoType;
typedef Elliptic::ModelInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
void check() const
{
typedef Stuff::GridProviders< GridType > GridProviders;
const std::shared_ptr< const GridProviderType >
gridProvider(GridProviders::create(GridProviders::available()[0],
GridProviders::createSampleDescription(GridProviders::available()[0])));
const std::shared_ptr< const GridPartType > gridPart(new GridPartType(*gridProvider->grid()));
typedef Stuff::Gridboundaries< GridViewType > Gridboundaries;
const std::shared_ptr< const GridBoundaryinfoType >
boundaryInfo(Gridboundaries::create(Gridboundaries::available()[0],
Gridboundaries::createSampleDescription(Gridboundaries::available()[0])));
typedef Elliptic::Models< DomainFieldType, dimDomain, RangeFieldType, dimRange > EllipticModels;
const std::shared_ptr< const ModelType >
model(EllipticModels::create(EllipticModels::available()[0],
EllipticModels::createSampleDescription(EllipticModels::available()[0])));
SolverType solver(gridPart, boundaryInfo, model);
SolverInterfaceType& solverAsInterface = static_cast< SolverInterfaceType& >(solver);
// check for static information
typedef typename SolverType::GridPartType TestGridPartType;
const int DUNE_UNUSED(testPolOrder) = SolverType::polOrder;
typedef typename SolverType::DomainFieldType TestDomainFieldType;
const int DUNE_UNUSED(testDimDomain) = SolverType::dimDomain;
typedef typename SolverType::RangeFieldType TestRangeFieldType;
const int DUNE_UNUSED(testDimRange) = SolverType::dimRange;
typedef typename SolverType::BoundaryInfoType TestBoundaryInfoType;
typedef typename SolverType::ModelType TestModelType;
typedef typename SolverType::VectorType VectorType;
const std::string DUNE_UNUSED(id) = SolverType::id();
// check for functionality
const std::shared_ptr< const TestGridPartType > DUNE_UNUSED(testGridPart) = solverAsInterface.gridPart();
const std::shared_ptr< const TestBoundaryInfoType > DUNE_UNUSED(testBoundaryInfo) = solverAsInterface.boundaryInfo();
const std::shared_ptr< const TestModelType > DUNE_UNUSED(testModel) = solverAsInterface.model();
solverAsInterface.init(Dune::Stuff::Common::Logger().devnull(), "");
if (!solverAsInterface.initialized())
DUNE_THROW(Dune::InvalidStateException, "This should not happen!");
std::shared_ptr< VectorType > vector = solverAsInterface.createVector();
solverAsInterface.visualize(vector, "test_empty_vector", "empty vector", Dune::Stuff::Common::Logger().devnull(), "");
solverAsInterface.solve(vector, "bicgstab.ilut", 1e-6, 1000, Dune::Stuff::Common::Logger().devnull(), "");
solverAsInterface.visualize(vector, "test_solution", "solution", Dune::Stuff::Common::Logger().devnull(), "");
}
}; // struct SolverCRTPtest
TYPED_TEST_CASE(SolverCRTPtest, SolverTypes);
TYPED_TEST(SolverCRTPtest, SolverCRTP)
{
this->check();
}
typedef testing::Types< std::pair< Elliptic::SolverContinuousGalerkinDD< GridPartType, RangeFieldType, dimRange, 1 >,
Elliptic::SolverContinuousGalerkinDDTraits< GridPartType, RangeFieldType, dimRange, 1 >
>
, std::pair< Elliptic::SolverFiniteVolumePdelab< GridPartType, RangeFieldType, dimRange >,
Elliptic::SolverFiniteVolumePdelabTraits< GridPartType, RangeFieldType, dimRange >
>
> ParametricSolverTypes;
template< class T >
struct ParametricSolverCRTPtest
: public ::testing::Test
{
typedef typename T::first_type SolverType;
typedef typename T::second_type Traits;
typedef Elliptic::SolverParametricInterface< Traits > SolverInterfaceType;
typedef Stuff::GridProviderInterface< GridType > GridProviderType;
typedef typename GridPartType::GridViewType GridViewType;
typedef Stuff::GridboundaryInterface< GridViewType > GridBoundaryinfoType;
typedef Elliptic::ModelInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
void check() const
{
typedef Stuff::GridProviders< GridType > GridProviders;
const std::shared_ptr< const GridProviderType >
gridProvider(GridProviders::create(GridProviders::available()[0],
GridProviders::createSampleDescription(GridProviders::available()[0])));
const std::shared_ptr< const GridPartType > gridPart(new GridPartType(*gridProvider->grid()));
typedef Stuff::Gridboundaries< GridViewType > Gridboundaries;
const std::shared_ptr< const GridBoundaryinfoType >
boundaryInfo(Gridboundaries::create(Gridboundaries::available()[0],
Gridboundaries::createSampleDescription(Gridboundaries::available()[0])));
typedef Elliptic::Models< DomainFieldType, dimDomain, RangeFieldType, dimRange > EllipticModels;
const std::string modelType = "model.linearelliptic.affineparametric.thermalblock";
const std::shared_ptr< const ModelType >
model(EllipticModels::create(modelType,
EllipticModels::createSampleDescription(modelType)));
SolverType solver(gridPart, boundaryInfo, model);
SolverInterfaceType& solverAsInterface = static_cast< SolverInterfaceType& >(solver);
// check for static information
typedef typename SolverType::GridPartType TestGridPartType;
const int DUNE_UNUSED(testPolOrder) = SolverType::polOrder;
typedef typename SolverType::DomainFieldType TestDomainFieldType;
const int DUNE_UNUSED(testDimDomain) = SolverType::dimDomain;
typedef typename SolverType::RangeFieldType TestRangeFieldType;
const int DUNE_UNUSED(testDimRange) = SolverType::dimRange;
typedef typename SolverType::BoundaryInfoType TestBoundaryInfoType;
typedef typename SolverType::ModelType TestModelType;
typedef typename SolverType::ParamType ParamType;
typedef typename SolverType::VectorType VectorType;
const std::string DUNE_UNUSED(id) = SolverType::id();
// check for functionality
const std::shared_ptr< const TestGridPartType > DUNE_UNUSED(testGridPart) = solverAsInterface.gridPart();
const std::shared_ptr< const TestBoundaryInfoType > DUNE_UNUSED(testBoundaryInfo) = solverAsInterface.boundaryInfo();
const std::shared_ptr< const TestModelType > DUNE_UNUSED(testModel) = solverAsInterface.model();
solverAsInterface.init(Dune::Stuff::Common::Logger().devnull(), "");
if (!solverAsInterface.initialized())
DUNE_THROW(Dune::InvalidStateException, "This should not happen!");
std::shared_ptr< VectorType > vector = solverAsInterface.createVector();
solverAsInterface.visualize(vector, "test_empty_vector", "empty vector", Dune::Stuff::Common::Logger().devnull(), "");
const ParamType mu = model->paramRange()[0];
solverAsInterface.solve(vector, mu, "bicgstab.ilut", 1e-6, 1000, Dune::Stuff::Common::Logger().devnull(), "");
solverAsInterface.visualize(vector, "test_solution", "solution", Dune::Stuff::Common::Logger().devnull(), "");
}
}; // struct ParametricSolverCRTPtest
TYPED_TEST_CASE(ParametricSolverCRTPtest, ParametricSolverTypes);
TYPED_TEST(ParametricSolverCRTPtest, SolverCRTP)
{
this->check();
}
int main(int argc, char** argv)
{
test_init(argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>[test.linearelliptic_solvers_crtp] updated parametric yet to be reenabled<commit_after>#include <dune/stuff/test/test_common.hh>
#include <utility>
#include <memory>
#include <dune/grid/sgrid.hh>
#include <dune/grid/part/leaf.hh>
#include <dune/stuff/grid/provider.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/detailed-solvers/linearelliptic/model.hh>
#include <dune/detailed-solvers/linearelliptic/solver/interface.hh>
#include <dune/detailed-solvers/linearelliptic/solver/cg/detailed-discretizations.hh>
//#include <dune/detailed-solvers/linearelliptic/solver/fv/pdelab.hh>
namespace Stuff = Dune::Stuff;
namespace Elliptic = Dune::DetailedSolvers::LinearElliptic;
static const int dimDomain = 2;
typedef Dune::SGrid< 2, 2 > GridType;
typedef typename GridType::ctype DomainFieldType;
typedef double RangeFieldType;
static const int dimRange = 1;
typedef Dune::grid::Part::Leaf::Const< GridType > GridPartType;
typedef testing::Types< std::pair< Elliptic::SolverContinuousGalerkinDD< GridPartType, RangeFieldType, dimRange, 1 >,
Elliptic::SolverContinuousGalerkinDDTraits< GridPartType, RangeFieldType, dimRange, 1 >
>
// , std::pair< Elliptic::SolverFiniteVolumePdelab< GridPartType, RangeFieldType, dimRange >,
// Elliptic::SolverFiniteVolumePdelabTraits< GridPartType, RangeFieldType, dimRange >
// >
> SolverTypes;
template< class T >
struct SolverCRTPtest
: public ::testing::Test
{
typedef typename T::first_type SolverType;
typedef typename T::second_type Traits;
typedef Elliptic::SolverInterface< Traits > SolverInterfaceType;
typedef Stuff::GridProviderInterface< GridType > GridProviderType;
typedef typename GridPartType::GridViewType GridViewType;
typedef Stuff::GridboundaryInterface< GridViewType > GridBoundaryinfoType;
typedef Elliptic::ModelInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
void check() const
{
typedef Stuff::GridProviders< GridType > GridProviders;
const std::shared_ptr< const GridProviderType >
gridProvider(GridProviders::create(GridProviders::available()[0],
GridProviders::defaultSettings(GridProviders::available()[0])));
const std::shared_ptr< const GridPartType > gridPart(new GridPartType(*gridProvider->grid()));
typedef Stuff::Gridboundaries< GridViewType > Gridboundaries;
const std::shared_ptr< const GridBoundaryinfoType >
boundaryInfo(Gridboundaries::create(Gridboundaries::available()[0],
Gridboundaries::defaultSettings(Gridboundaries::available()[0])));
typedef Elliptic::Models< DomainFieldType, dimDomain, RangeFieldType, dimRange > EllipticModels;
const std::shared_ptr< const ModelType >
model(EllipticModels::create(EllipticModels::available()[0],
EllipticModels::defaultSettings(EllipticModels::available()[0])));
SolverType solver(gridPart, boundaryInfo, model);
SolverInterfaceType& solverAsInterface = static_cast< SolverInterfaceType& >(solver);
// check for static information
typedef typename SolverType::GridPartType TestGridPartType;
const int DUNE_UNUSED(testPolOrder) = SolverType::polOrder;
typedef typename SolverType::DomainFieldType TestDomainFieldType;
const int DUNE_UNUSED(testDimDomain) = SolverType::dimDomain;
typedef typename SolverType::RangeFieldType TestRangeFieldType;
const int DUNE_UNUSED(testDimRange) = SolverType::dimRange;
typedef typename SolverType::BoundaryInfoType TestBoundaryInfoType;
typedef typename SolverType::ModelType TestModelType;
typedef typename SolverType::MatrixType MatrixType;
typedef typename SolverType::VectorType VectorType;
typedef typename SolverType::SettingsType SettingsType;
const std::string DUNE_UNUSED(id) = SolverType::id();
// check for functionality
const std::shared_ptr< const TestGridPartType > DUNE_UNUSED(testGridPart) = solverAsInterface.gridPart();
const std::shared_ptr< const TestBoundaryInfoType > DUNE_UNUSED(testBoundaryInfo) = solverAsInterface.boundaryInfo();
const std::shared_ptr< const TestModelType > DUNE_UNUSED(testModel) = solverAsInterface.model();
solverAsInterface.init(Dune::Stuff::Common::Logger().devnull(), "");
if (!solverAsInterface.initialized())
DUNE_THROW(Dune::InvalidStateException, "This should not happen!");
std::shared_ptr< VectorType > vector = solverAsInterface.createVector();
solverAsInterface.visualize(vector, "test_empty_vector", "empty vector", Dune::Stuff::Common::Logger().devnull(), "");
const std::string linearSolverType = Dune::Stuff::LA::solverTypes()[0];
auto linearSolverSettings = Dune::Stuff::LA::solverDefaultSettings< MatrixType, VectorType >(linearSolverType);
linearSolverSettings["type"] = linearSolverType;
solverAsInterface.solve(vector, linearSolverSettings , Dune::Stuff::Common::Logger().devnull(), "");
solverAsInterface.visualize(vector, "test_solution", "solution", Dune::Stuff::Common::Logger().devnull(), "");
}
}; // struct SolverCRTPtest
TYPED_TEST_CASE(SolverCRTPtest, SolverTypes);
TYPED_TEST(SolverCRTPtest, SolverCRTP)
{
this->check();
}
//typedef testing::Types< std::pair< Elliptic::SolverContinuousGalerkinDD< GridPartType, RangeFieldType, dimRange, 1 >,
// Elliptic::SolverContinuousGalerkinDDTraits< GridPartType, RangeFieldType, dimRange, 1 >
// >
// , std::pair< Elliptic::SolverFiniteVolumePdelab< GridPartType, RangeFieldType, dimRange >,
// Elliptic::SolverFiniteVolumePdelabTraits< GridPartType, RangeFieldType, dimRange >
// >
// > ParametricSolverTypes;
//template< class T >
//struct ParametricSolverCRTPtest
// : public ::testing::Test
//{
// typedef typename T::first_type SolverType;
// typedef typename T::second_type Traits;
// typedef Elliptic::SolverParametricInterface< Traits > SolverInterfaceType;
// typedef Stuff::GridProviderInterface< GridType > GridProviderType;
// typedef typename GridPartType::GridViewType GridViewType;
// typedef Stuff::GridboundaryInterface< GridViewType > GridBoundaryinfoType;
// typedef Elliptic::ModelInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
// void check() const
// {
// typedef Stuff::GridProviders< GridType > GridProviders;
// const std::shared_ptr< const GridProviderType >
// gridProvider(GridProviders::create(GridProviders::available()[0],
// GridProviders::createSampleDescription(GridProviders::available()[0])));
// const std::shared_ptr< const GridPartType > gridPart(new GridPartType(*gridProvider->grid()));
// typedef Stuff::Gridboundaries< GridViewType > Gridboundaries;
// const std::shared_ptr< const GridBoundaryinfoType >
// boundaryInfo(Gridboundaries::create(Gridboundaries::available()[0],
// Gridboundaries::createSampleDescription(Gridboundaries::available()[0])));
// typedef Elliptic::Models< DomainFieldType, dimDomain, RangeFieldType, dimRange > EllipticModels;
// const std::string modelType = "model.linearelliptic.affineparametric.thermalblock";
// const std::shared_ptr< const ModelType >
// model(EllipticModels::create(modelType,
// EllipticModels::createSampleDescription(modelType)));
// SolverType solver(gridPart, boundaryInfo, model);
// SolverInterfaceType& solverAsInterface = static_cast< SolverInterfaceType& >(solver);
// // check for static information
// typedef typename SolverType::GridPartType TestGridPartType;
// const int DUNE_UNUSED(testPolOrder) = SolverType::polOrder;
// typedef typename SolverType::DomainFieldType TestDomainFieldType;
// const int DUNE_UNUSED(testDimDomain) = SolverType::dimDomain;
// typedef typename SolverType::RangeFieldType TestRangeFieldType;
// const int DUNE_UNUSED(testDimRange) = SolverType::dimRange;
// typedef typename SolverType::BoundaryInfoType TestBoundaryInfoType;
// typedef typename SolverType::ModelType TestModelType;
// typedef typename SolverType::ParamType ParamType;
// typedef typename SolverType::VectorType VectorType;
// const std::string DUNE_UNUSED(id) = SolverType::id();
// // check for functionality
// const std::shared_ptr< const TestGridPartType > DUNE_UNUSED(testGridPart) = solverAsInterface.gridPart();
// const std::shared_ptr< const TestBoundaryInfoType > DUNE_UNUSED(testBoundaryInfo) = solverAsInterface.boundaryInfo();
// const std::shared_ptr< const TestModelType > DUNE_UNUSED(testModel) = solverAsInterface.model();
// solverAsInterface.init(Dune::Stuff::Common::Logger().devnull(), "");
// if (!solverAsInterface.initialized())
// DUNE_THROW(Dune::InvalidStateException, "This should not happen!");
// std::shared_ptr< VectorType > vector = solverAsInterface.createVector();
// solverAsInterface.visualize(vector, "test_empty_vector", "empty vector", Dune::Stuff::Common::Logger().devnull(), "");
// const ParamType mu = model->paramRange()[0];
// solverAsInterface.solve(vector, mu, "bicgstab.ilut", 1e-6, 1000, Dune::Stuff::Common::Logger().devnull(), "");
// solverAsInterface.visualize(vector, "test_solution", "solution", Dune::Stuff::Common::Logger().devnull(), "");
// }
//}; // struct ParametricSolverCRTPtest
//TYPED_TEST_CASE(ParametricSolverCRTPtest, ParametricSolverTypes);
//TYPED_TEST(ParametricSolverCRTPtest, SolverCRTP)
//{
// this->check();
//}
int main(int argc, char** argv)
{
test_init(argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>#include "util.cpp"
struct Row {
int num, area, capacity;
};
bool sort_servers(const Server &a, const Server &b) {
if (a.capacity*b.size != b.capacity*a.size)
return a.capacity*b.size > b.capacity*a.size;
else
return a.size < b.size;
}
bool sort_rows(const Row &a, const Row &b) {
if (a.capacity*b.area != b.capacity*a.area)
return a.capacity*b.area < b.capacity*a.area;
else
return a.area < b.area;
}
void place_blocked_slots(vector<vector<int>>& field, Row &row, int row_index, vector<int>& slots) {
for (int i = 0; i < slots.size(); i++)
{
field[row_index][slots[i]] = 1;
row.area--;
}
}
bool assign_server_to_row(int s, vector<int>& field, Server &server) {
for (int i = 0; i <= s-server.size; i++)
{
int cnt_occ = 0;
for (int j = 0; j < server.size; j++)
cnt_occ += field[i+j];
if (cnt_occ == 0)
{
for (int j = 0; j < server.size; j++)
field[i+j] = 1;
server.slot = i;
return true;
}
}
return false;
}
void placeServers(Input &input) {
// sort servers
sort(input.servers.begin(),input.servers.end(),sort_servers);
// create field and rows
vector<vector<int>> field(input.r, vector<int>(input.s));
vector<Row> rows(input.r);
for (int i = 0; i < input.r; i++)
{
rows[i].num = i;
rows[i].capacity = 0;
rows[i].area = input.s;
place_blocked_slots(field,rows[i],i,input.blocked_slots[i]);
}
// iterate through all servers
for (int i = 0; i < input.m; i++)
{
sort(rows.begin(),rows.end(),sort_rows);
/*
cerr << "server: " << input.servers[i].capacity << ' ' << input.servers[i].size << endl;
for (int j = 0; j < rows.size(); j++)
cerr << rows[j].num << ' ' << rows[j].capacity << ' ' << rows[j].area << endl;;
cerr << endl;
for (int j = 0; j < input.r; j++)
{
for (int l = 0; l < input.s; l++)
cerr << field[j][l];
cerr << endl;
}*/
// try to assign each server to worst possible row
for (int j = 0; j < input.r; j++)
{
if (assign_server_to_row(input.s,field[rows[j].num],input.servers[i]))
{
rows[j].area -= input.servers[i].size;
rows[j].capacity += input.servers[i].capacity;
input.servers[i].row = rows[j].num;
break;
}
}
}
}
<commit_msg>improved placeservers.cpp<commit_after>#include "util.cpp"
struct Row {
int num, area, capacity;
};
bool sort_servers(const Server &a, const Server &b) {
if (a.capacity*b.size != b.capacity*a.size)
return a.capacity*b.size > b.capacity*a.size;
else
return a.size < b.size;
}
bool sort_rows(const Row &a, const Row &b) {
/*if (a.capacity*b.area != b.capacity*a.area)
return a.capacity*b.area < b.capacity*a.area;
else
return a.area < b.area;
*/
return a.capacity < b.capacity;
}
void place_blocked_slots(vector<vector<int>>& field, Row &row, int row_index, vector<int>& slots) {
for (int i = 0; i < slots.size(); i++)
{
field[row_index][slots[i]] = 1;
row.area--;
}
}
bool assign_server_to_row(int s, vector<int>& field, Server &server) {
for (int i = 0; i <= s-server.size; i++)
{
int cnt_occ = 0;
for (int j = 0; j < server.size; j++)
cnt_occ += field[i+j];
if (cnt_occ == 0)
{
for (int j = 0; j < server.size; j++)
field[i+j] = 1;
server.slot = i;
return true;
}
}
return false;
}
void placeServers(Input &input) {
// sort servers
sort(input.servers.begin(),input.servers.end(),sort_servers);
// create field and rows
vector<vector<int>> field(input.r, vector<int>(input.s));
vector<Row> rows(input.r);
for (int i = 0; i < input.r; i++)
{
rows[i].num = i;
rows[i].capacity = 0;
rows[i].area = input.s;
place_blocked_slots(field,rows[i],i,input.blocked_slots[i]);
}
// iterate through all servers
for (int i = 0; i < input.m; i++)
{
sort(rows.begin(),rows.end(),sort_rows);
/*
cerr << "server: " << input.servers[i].capacity << ' ' << input.servers[i].size << endl;
for (int j = 0; j < rows.size(); j++)
cerr << rows[j].num << ' ' << rows[j].capacity << ' ' << rows[j].area << endl;;
cerr << endl;
for (int j = 0; j < input.r; j++)
{
for (int l = 0; l < input.s; l++)
cerr << field[j][l];
cerr << endl;
}*/
// try to assign each server to worst possible row
for (int j = 0; j < input.r; j++)
{
if (assign_server_to_row(input.s,field[rows[j].num],input.servers[i]))
{
rows[j].area -= input.servers[i].size;
rows[j].capacity += input.servers[i].capacity;
input.servers[i].row = rows[j].num;
break;
}
}
}
int cnt = 1000;
while (cnt--)
{
sort(rows.begin(),rows.end(),sort_rows);
int cur_len = cnt%5+1;
int i_max, i_min, last = input.r-1;
for (i_max = 0; i_max < input.m; i_max++)
if (input.servers[i_max].row == rows[last].num && input.servers[i_max].size == cur_len)
break;
for (i_min = input.m-1; i_min >= 0; i_min--)
if (input.servers[i_min].row == rows[0].num && input.servers[i_min].size == cur_len)
break;
int cap_max = input.servers[i_max].capacity;
int cap_min = input.servers[i_min].capacity;
if (i_max < input.m && i_min >= 0 && cap_max > cap_min)
{
rows[0].capacity += cap_max;
rows[0].capacity -= cap_min;
rows[last].capacity -= cap_max;
rows[last].capacity += cap_min;
input.servers[i_max].row = rows[0].num;
input.servers[i_min].row = rows[last].num;
swap(input.servers[i_max].slot,input.servers[i_min].slot);
}
}
int total_cap = 0;
for (int i = 0; i < input.r; i++)
{
int row_cap = 0;
for (int j = 0; j < input.m; j++)
if (input.servers[j].row == i)
row_cap += input.servers[j].capacity;
cerr << "row #" << i << ": " << row_cap << endl;
}
cerr << "total: " << total_cap << endl;
}
<|endoftext|>
|
<commit_before>//---------------------------- sparse_ilu.cc ---------------------------
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- sparse_ilu.cc ---------------------------
#include <lac/sparse_ilu.h>
#include <lac/sparse_ilu.templates.h>
// explicit instantiations
template class SparseILU<double>;
template void SparseILU<double>::initialize<double> (const SparseMatrix<double> &,
const AdditionalData data);
template void SparseILU<double>::decompose<double> (const SparseMatrix<double> &,
const double);
template void SparseILU<double>::vmult <double> (Vector<double> &,
const Vector<double> &) const;
template void SparseILU<double>::initialize<float> (const SparseMatrix<float> &,
const AdditionalData data);
template void SparseILU<double>::decompose<float> (const SparseMatrix<float> &,
const double);
template void SparseILU<double>::vmult<float> (Vector<float> &,
const Vector<float> &) const;
template class SparseILU<float>;
template void SparseILU<float>::initialize<double> (const SparseMatrix<double> &,
const AdditionalData data);
template void SparseILU<float>::decompose<double> (const SparseMatrix<double> &,
const double);
template void SparseILU<float>::vmult<double> (Vector<double> &,
const Vector<double> &) const;
template void SparseILU<float>::initialize<float> (const SparseMatrix<float> &,
const AdditionalData data);
template void SparseILU<float>::decompose<float> (const SparseMatrix<float> &,
const double);
template void SparseILU<float>::vmult<float> (Vector<float> &,
const Vector<float> &) const;
<commit_msg>Remove unnecessary include statement.<commit_after>//---------------------------- sparse_ilu.cc ---------------------------
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- sparse_ilu.cc ---------------------------
#include <lac/sparse_ilu.templates.h>
// explicit instantiations
template class SparseILU<double>;
template void SparseILU<double>::initialize<double> (const SparseMatrix<double> &,
const AdditionalData data);
template void SparseILU<double>::decompose<double> (const SparseMatrix<double> &,
const double);
template void SparseILU<double>::vmult <double> (Vector<double> &,
const Vector<double> &) const;
template void SparseILU<double>::initialize<float> (const SparseMatrix<float> &,
const AdditionalData data);
template void SparseILU<double>::decompose<float> (const SparseMatrix<float> &,
const double);
template void SparseILU<double>::vmult<float> (Vector<float> &,
const Vector<float> &) const;
template class SparseILU<float>;
template void SparseILU<float>::initialize<double> (const SparseMatrix<double> &,
const AdditionalData data);
template void SparseILU<float>::decompose<double> (const SparseMatrix<double> &,
const double);
template void SparseILU<float>::vmult<double> (Vector<double> &,
const Vector<double> &) const;
template void SparseILU<float>::initialize<float> (const SparseMatrix<float> &,
const AdditionalData data);
template void SparseILU<float>::decompose<float> (const SparseMatrix<float> &,
const double);
template void SparseILU<float>::vmult<float> (Vector<float> &,
const Vector<float> &) const;
<|endoftext|>
|
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Adaptor.hh"
#include "Compression.hh"
#include "orc/Exceptions.hh"
#include "RLEv1.hh"
#include <algorithm>
namespace orc {
const int MINIMUM_REPEAT = 3;
const int MAXIMUM_REPEAT = 127 + MINIMUM_REPEAT;
const int BASE_128_MASK = 0x7f;
const int MAX_DELTA = 127;
const int MIN_DELTA = -128;
const int MAX_LITERAL_SIZE = 128;
RleEncoderV1::RleEncoderV1(
std::unique_ptr<BufferedOutputStream> outStream,
bool hasSigned):
outputStream(std::move(outStream)) {
isSigned = hasSigned;
literals = new int64_t[MAX_LITERAL_SIZE];
numLiterals = 0;
delta = 0;
repeat = false;
tailRunLength = 0;
bufferPosition = 0;
bufferLength = 0;
buffer = nullptr;
}
RleEncoderV1::~RleEncoderV1() {
delete [] literals;
}
void RleEncoderV1::add(const int64_t* data, uint64_t numValues,
const char* notNull) {
for (uint64_t i = 0; i < numValues; ++i) {
if (!notNull || notNull[i]) {
write(data[i]);
}
}
}
void RleEncoderV1::writeByte(char c) {
if (bufferPosition == bufferLength) {
int addedSize = 0;
if (!outputStream->Next(reinterpret_cast<void **>(&buffer), &addedSize)) {
throw std::bad_alloc();
}
bufferPosition = 0;
bufferLength = addedSize;
}
buffer[bufferPosition++] = c;
}
void RleEncoderV1::writeValues() {
if (numLiterals != 0) {
if (repeat) {
writeByte(static_cast<char>
(static_cast<uint64_t>(numLiterals) - MINIMUM_REPEAT));
writeByte(static_cast<char>(delta));
if (isSigned) {
writeVslong(literals[0]);
} else {
writeVulong(literals[0]);
}
} else {
writeByte(static_cast<char>(-numLiterals));
for(int i=0; i < numLiterals; ++i) {
if (isSigned) {
writeVslong(literals[i]);
} else {
writeVulong(literals[i]);
}
}
}
repeat = false;
numLiterals = 0;
tailRunLength = 0;
}
}
uint64_t RleEncoderV1::flush() {
writeValues();
outputStream->BackUp(bufferLength - bufferPosition);
uint64_t dataSize = outputStream->flush();
bufferLength = bufferPosition = 0;
return dataSize;
}
void RleEncoderV1::write(int64_t value) {
if (numLiterals == 0) {
literals[numLiterals++] = value;
tailRunLength = 1;
} else if (repeat) {
if (value == literals[0] + delta * numLiterals) {
numLiterals += 1;
if (numLiterals == MAXIMUM_REPEAT) {
writeValues();
}
} else {
writeValues();
literals[numLiterals++] = value;
tailRunLength = 1;
}
} else {
if (tailRunLength == 1) {
delta = value - literals[numLiterals - 1];
if (delta < MIN_DELTA || delta > MAX_DELTA) {
tailRunLength = 1;
} else {
tailRunLength = 2;
}
} else if (value == literals[numLiterals - 1] + delta) {
tailRunLength += 1;
} else {
delta = value - literals[numLiterals - 1];
if (delta < MIN_DELTA || delta > MAX_DELTA) {
tailRunLength = 1;
} else {
tailRunLength = 2;
}
}
if (tailRunLength == MINIMUM_REPEAT) {
if (numLiterals + 1 == MINIMUM_REPEAT) {
repeat = true;
numLiterals += 1;
} else {
numLiterals -= static_cast<int>(MINIMUM_REPEAT - 1);
long base = literals[numLiterals];
writeValues();
literals[0] = base;
repeat = true;
numLiterals = MINIMUM_REPEAT;
}
} else {
literals[numLiterals++] = value;
if (numLiterals == MAX_LITERAL_SIZE) {
writeValues();
}
}
}
}
void RleEncoderV1::writeVslong(int64_t val) {
writeVulong((val << 1) ^ (val >> 63));
}
void RleEncoderV1::writeVulong(int64_t val) {
while (true) {
if ((val & ~0x7f) == 0) {
writeByte(static_cast<char>(val));
return;
} else {
writeByte(static_cast<char>(0x80 | (val & 0x7f)));
// cast val to unsigned so as to force 0-fill right shift
val = (static_cast<uint64_t>(val) >> 7);
}
}
}
void RleEncoderV1::recordPosition(PositionRecorder* recorder) const {
uint64_t flushedSize = outputStream->getSize();
uint64_t unflushedSize = static_cast<uint64_t>(bufferPosition);
if (outputStream->isCompressed()) {
recorder->add(flushedSize);
recorder->add(unflushedSize);
} else {
flushedSize -= static_cast<uint64_t>(bufferLength);
recorder->add(flushedSize + unflushedSize);
}
recorder->add(static_cast<uint64_t>(numLiterals));
}
signed char RleDecoderV1::readByte() {
if (bufferStart == bufferEnd) {
int bufferLength;
const void* bufferPointer;
if (!inputStream->Next(&bufferPointer, &bufferLength)) {
throw ParseError("bad read in readByte");
}
bufferStart = static_cast<const char*>(bufferPointer);
bufferEnd = bufferStart + bufferLength;
}
return *(bufferStart++);
}
uint64_t RleDecoderV1::readLong() {
uint64_t result = 0;
int64_t offset = 0;
signed char ch = readByte();
if (ch >= 0) {
result = static_cast<uint64_t>(ch);
} else {
result = static_cast<uint64_t>(ch) & BASE_128_MASK;
while ((ch = readByte()) < 0) {
offset += 7;
result |= (static_cast<uint64_t>(ch) & BASE_128_MASK) << offset;
}
result |= static_cast<uint64_t>(ch) << (offset + 7);
}
return result;
}
void RleDecoderV1::skipLongs(uint64_t numValues) {
while (numValues > 0) {
if (readByte() >= 0) {
--numValues;
}
}
}
void RleDecoderV1::readHeader() {
signed char ch = readByte();
if (ch < 0) {
remainingValues = static_cast<uint64_t>(-ch);
repeating = false;
} else {
remainingValues = static_cast<uint64_t>(ch) + MINIMUM_REPEAT;
repeating = true;
delta = readByte();
value = isSigned
? unZigZag(readLong())
: static_cast<int64_t>(readLong());
}
}
RleDecoderV1::RleDecoderV1(std::unique_ptr<SeekableInputStream> input,
bool hasSigned)
: inputStream(std::move(input)),
isSigned(hasSigned),
remainingValues(0),
value(0),
bufferStart(nullptr),
bufferEnd(bufferStart),
delta(0),
repeating(false) {
}
void RleDecoderV1::seek(PositionProvider& location) {
// move the input stream
inputStream->seek(location);
// force a re-read from the stream
bufferEnd = bufferStart;
// read a new header
readHeader();
// skip ahead the given number of records
skip(location.next());
}
void RleDecoderV1::skip(uint64_t numValues) {
while (numValues > 0) {
if (remainingValues == 0) {
readHeader();
}
uint64_t count = std::min(numValues, remainingValues);
remainingValues -= count;
numValues -= count;
if (repeating) {
value += delta * static_cast<int64_t>(count);
} else {
skipLongs(count);
}
}
}
void RleDecoderV1::next(int64_t* const data,
const uint64_t numValues,
const char* const notNull) {
uint64_t position = 0;
// skipNulls()
if (notNull) {
// Skip over null values.
while (position < numValues && !notNull[position]) {
++position;
}
}
while (position < numValues) {
// If we are out of values, read more.
if (remainingValues == 0) {
readHeader();
}
// How many do we read out of this block?
uint64_t count = std::min(numValues - position, remainingValues);
uint64_t consumed = 0;
if (repeating) {
if (notNull) {
for (uint64_t i = 0; i < count; ++i) {
if (notNull[position + i]) {
data[position + i] = value + static_cast<int64_t>(consumed) * delta;
consumed += 1;
}
}
} else {
for (uint64_t i = 0; i < count; ++i) {
data[position + i] = value + static_cast<int64_t>(i) * delta;
}
consumed = count;
}
value += static_cast<int64_t>(consumed) * delta;
} else {
if (notNull) {
for (uint64_t i = 0 ; i < count; ++i) {
if (notNull[position + i]) {
data[position + i] = isSigned
? unZigZag(readLong())
: static_cast<int64_t>(readLong());
++consumed;
}
}
} else {
if (isSigned) {
for (uint64_t i = 0; i < count; ++i) {
data[position + i] = unZigZag(readLong());
}
} else {
for (uint64_t i = 0; i < count; ++i) {
data[position + i] = static_cast<int64_t>(readLong());
}
}
consumed = count;
}
}
remainingValues -= consumed;
position += count;
// skipNulls()
if (notNull) {
// Skip over null values.
while (position < numValues && !notNull[position]) {
++position;
}
}
}
}
} // namespace orc
<commit_msg>ORC-293: [C++] Fix RleEncoderV1 for case when sizeof(long) < sizeof(int64_t)<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Adaptor.hh"
#include "Compression.hh"
#include "orc/Exceptions.hh"
#include "RLEv1.hh"
#include <algorithm>
namespace orc {
const int MINIMUM_REPEAT = 3;
const int MAXIMUM_REPEAT = 127 + MINIMUM_REPEAT;
const int64_t BASE_128_MASK = 0x7f;
const int MAX_DELTA = 127;
const int MIN_DELTA = -128;
const int MAX_LITERAL_SIZE = 128;
RleEncoderV1::RleEncoderV1(
std::unique_ptr<BufferedOutputStream> outStream,
bool hasSigned):
outputStream(std::move(outStream)) {
isSigned = hasSigned;
literals = new int64_t[MAX_LITERAL_SIZE];
numLiterals = 0;
delta = 0;
repeat = false;
tailRunLength = 0;
bufferPosition = 0;
bufferLength = 0;
buffer = nullptr;
}
RleEncoderV1::~RleEncoderV1() {
delete [] literals;
}
void RleEncoderV1::add(const int64_t* data, uint64_t numValues,
const char* notNull) {
for (uint64_t i = 0; i < numValues; ++i) {
if (!notNull || notNull[i]) {
write(data[i]);
}
}
}
void RleEncoderV1::writeByte(char c) {
if (bufferPosition == bufferLength) {
int addedSize = 0;
if (!outputStream->Next(reinterpret_cast<void **>(&buffer), &addedSize)) {
throw std::bad_alloc();
}
bufferPosition = 0;
bufferLength = addedSize;
}
buffer[bufferPosition++] = c;
}
void RleEncoderV1::writeValues() {
if (numLiterals != 0) {
if (repeat) {
writeByte(static_cast<char>
(static_cast<uint64_t>(numLiterals) - MINIMUM_REPEAT));
writeByte(static_cast<char>(delta));
if (isSigned) {
writeVslong(literals[0]);
} else {
writeVulong(literals[0]);
}
} else {
writeByte(static_cast<char>(-numLiterals));
for(int i=0; i < numLiterals; ++i) {
if (isSigned) {
writeVslong(literals[i]);
} else {
writeVulong(literals[i]);
}
}
}
repeat = false;
numLiterals = 0;
tailRunLength = 0;
}
}
uint64_t RleEncoderV1::flush() {
writeValues();
outputStream->BackUp(bufferLength - bufferPosition);
uint64_t dataSize = outputStream->flush();
bufferLength = bufferPosition = 0;
return dataSize;
}
void RleEncoderV1::write(int64_t value) {
if (numLiterals == 0) {
literals[numLiterals++] = value;
tailRunLength = 1;
} else if (repeat) {
if (value == literals[0] + delta * numLiterals) {
numLiterals += 1;
if (numLiterals == MAXIMUM_REPEAT) {
writeValues();
}
} else {
writeValues();
literals[numLiterals++] = value;
tailRunLength = 1;
}
} else {
if (tailRunLength == 1) {
delta = value - literals[numLiterals - 1];
if (delta < MIN_DELTA || delta > MAX_DELTA) {
tailRunLength = 1;
} else {
tailRunLength = 2;
}
} else if (value == literals[numLiterals - 1] + delta) {
tailRunLength += 1;
} else {
delta = value - literals[numLiterals - 1];
if (delta < MIN_DELTA || delta > MAX_DELTA) {
tailRunLength = 1;
} else {
tailRunLength = 2;
}
}
if (tailRunLength == MINIMUM_REPEAT) {
if (numLiterals + 1 == MINIMUM_REPEAT) {
repeat = true;
numLiterals += 1;
} else {
numLiterals -= static_cast<int>(MINIMUM_REPEAT - 1);
int64_t base = literals[numLiterals];
writeValues();
literals[0] = base;
repeat = true;
numLiterals = MINIMUM_REPEAT;
}
} else {
literals[numLiterals++] = value;
if (numLiterals == MAX_LITERAL_SIZE) {
writeValues();
}
}
}
}
void RleEncoderV1::writeVslong(int64_t val) {
writeVulong((val << 1) ^ (val >> 63));
}
void RleEncoderV1::writeVulong(int64_t val) {
while (true) {
if ((val & ~BASE_128_MASK) == 0) {
writeByte(static_cast<char>(val));
return;
} else {
writeByte(static_cast<char>(0x80 | (val & BASE_128_MASK)));
// cast val to unsigned so as to force 0-fill right shift
val = (static_cast<uint64_t>(val) >> 7);
}
}
}
void RleEncoderV1::recordPosition(PositionRecorder* recorder) const {
uint64_t flushedSize = outputStream->getSize();
uint64_t unflushedSize = static_cast<uint64_t>(bufferPosition);
if (outputStream->isCompressed()) {
recorder->add(flushedSize);
recorder->add(unflushedSize);
} else {
flushedSize -= static_cast<uint64_t>(bufferLength);
recorder->add(flushedSize + unflushedSize);
}
recorder->add(static_cast<uint64_t>(numLiterals));
}
signed char RleDecoderV1::readByte() {
if (bufferStart == bufferEnd) {
int bufferLength;
const void* bufferPointer;
if (!inputStream->Next(&bufferPointer, &bufferLength)) {
throw ParseError("bad read in readByte");
}
bufferStart = static_cast<const char*>(bufferPointer);
bufferEnd = bufferStart + bufferLength;
}
return *(bufferStart++);
}
uint64_t RleDecoderV1::readLong() {
uint64_t result = 0;
int64_t offset = 0;
signed char ch = readByte();
if (ch >= 0) {
result = static_cast<uint64_t>(ch);
} else {
result = static_cast<uint64_t>(ch) & BASE_128_MASK;
while ((ch = readByte()) < 0) {
offset += 7;
result |= (static_cast<uint64_t>(ch) & BASE_128_MASK) << offset;
}
result |= static_cast<uint64_t>(ch) << (offset + 7);
}
return result;
}
void RleDecoderV1::skipLongs(uint64_t numValues) {
while (numValues > 0) {
if (readByte() >= 0) {
--numValues;
}
}
}
void RleDecoderV1::readHeader() {
signed char ch = readByte();
if (ch < 0) {
remainingValues = static_cast<uint64_t>(-ch);
repeating = false;
} else {
remainingValues = static_cast<uint64_t>(ch) + MINIMUM_REPEAT;
repeating = true;
delta = readByte();
value = isSigned
? unZigZag(readLong())
: static_cast<int64_t>(readLong());
}
}
RleDecoderV1::RleDecoderV1(std::unique_ptr<SeekableInputStream> input,
bool hasSigned)
: inputStream(std::move(input)),
isSigned(hasSigned),
remainingValues(0),
value(0),
bufferStart(nullptr),
bufferEnd(bufferStart),
delta(0),
repeating(false) {
}
void RleDecoderV1::seek(PositionProvider& location) {
// move the input stream
inputStream->seek(location);
// force a re-read from the stream
bufferEnd = bufferStart;
// read a new header
readHeader();
// skip ahead the given number of records
skip(location.next());
}
void RleDecoderV1::skip(uint64_t numValues) {
while (numValues > 0) {
if (remainingValues == 0) {
readHeader();
}
uint64_t count = std::min(numValues, remainingValues);
remainingValues -= count;
numValues -= count;
if (repeating) {
value += delta * static_cast<int64_t>(count);
} else {
skipLongs(count);
}
}
}
void RleDecoderV1::next(int64_t* const data,
const uint64_t numValues,
const char* const notNull) {
uint64_t position = 0;
// skipNulls()
if (notNull) {
// Skip over null values.
while (position < numValues && !notNull[position]) {
++position;
}
}
while (position < numValues) {
// If we are out of values, read more.
if (remainingValues == 0) {
readHeader();
}
// How many do we read out of this block?
uint64_t count = std::min(numValues - position, remainingValues);
uint64_t consumed = 0;
if (repeating) {
if (notNull) {
for (uint64_t i = 0; i < count; ++i) {
if (notNull[position + i]) {
data[position + i] = value + static_cast<int64_t>(consumed) * delta;
consumed += 1;
}
}
} else {
for (uint64_t i = 0; i < count; ++i) {
data[position + i] = value + static_cast<int64_t>(i) * delta;
}
consumed = count;
}
value += static_cast<int64_t>(consumed) * delta;
} else {
if (notNull) {
for (uint64_t i = 0 ; i < count; ++i) {
if (notNull[position + i]) {
data[position + i] = isSigned
? unZigZag(readLong())
: static_cast<int64_t>(readLong());
++consumed;
}
}
} else {
if (isSigned) {
for (uint64_t i = 0; i < count; ++i) {
data[position + i] = unZigZag(readLong());
}
} else {
for (uint64_t i = 0; i < count; ++i) {
data[position + i] = static_cast<int64_t>(readLong());
}
}
consumed = count;
}
}
remainingValues -= consumed;
position += count;
// skipNulls()
if (notNull) {
// Skip over null values.
while (position < numValues && !notNull[position]) {
++position;
}
}
}
}
} // namespace orc
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: property.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: vg $ $Date: 2007-01-15 14:44:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#if OSL_DEBUG_LEVEL > 0
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _CPPUHELPER_EXC_HLP_HXX_
#include <cppuhelper/exc_hlp.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_GENFUNC_H_
#include <com/sun/star/uno/genfunc.h>
#endif
#include <algorithm>
//.........................................................................
namespace comphelper
{
/** === begin UNO using === **/
using ::com::sun::star::uno::Reference;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::beans::XPropertySetInfo;
using ::com::sun::star::beans::Property;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Type;
using ::com::sun::star::uno::cpp_queryInterface;
using ::com::sun::star::uno::cpp_acquire;
using ::com::sun::star::uno::cpp_release;
/** === end UNO using === **/
namespace PropertyAttribute = ::com::sun::star::beans::PropertyAttribute;
//------------------------------------------------------------------
void copyProperties(const Reference<XPropertySet>& _rxSource,
const Reference<XPropertySet>& _rxDest)
{
if (!_rxSource.is() || !_rxDest.is())
{
OSL_ENSURE(sal_False, "copyProperties: invalid arguments !");
}
Reference< XPropertySetInfo > xSourceProps = _rxSource->getPropertySetInfo();
Reference< XPropertySetInfo > xDestProps = _rxDest->getPropertySetInfo();
Sequence< Property > aSourceProps = xSourceProps->getProperties();
const Property* pSourceProps = aSourceProps.getConstArray();
Property aDestProp;
for (sal_Int32 i=0; i<aSourceProps.getLength(); ++i, ++pSourceProps)
{
if ( xDestProps->hasPropertyByName(pSourceProps->Name) )
{
try
{
aDestProp = xDestProps->getPropertyByName(pSourceProps->Name);
if (0 == (aDestProp.Attributes & PropertyAttribute::READONLY))
_rxDest->setPropertyValue(pSourceProps->Name, _rxSource->getPropertyValue(pSourceProps->Name));
}
catch (Exception&)
{
#if OSL_DEBUG_LEVEL > 0
::rtl::OStringBuffer aBuffer;
aBuffer.append( "::comphelper::copyProperties: could not copy property '" );
aBuffer.append( ::rtl::OString( pSourceProps->Name.getStr(), pSourceProps->Name.getLength(), RTL_TEXTENCODING_ASCII_US ) );
aBuffer.append( "' to the destination set.\n" );
Any aException( ::cppu::getCaughtException() );
aBuffer.append( "Caught an exception of type '" );
::rtl::OUString sExceptionType( aException.getValueTypeName() );
aBuffer.append( ::rtl::OString( sExceptionType.getStr(), sExceptionType.getLength(), RTL_TEXTENCODING_ASCII_US ) );
aBuffer.append( "'" );
Exception aBaseException;
if ( ( aException >>= aBaseException ) && aBaseException.Message.getLength() )
{
aBuffer.append( ", saying '" );
aBuffer.append( ::rtl::OString( aBaseException.Message.getStr(), aBaseException.Message.getLength(), osl_getThreadTextEncoding() ) );
aBuffer.append( "'" );
}
aBuffer.append( "." );
OSL_ENSURE( sal_False, aBuffer.getStr() );
#endif
}
}
}
}
//------------------------------------------------------------------
sal_Bool hasProperty(const rtl::OUString& _rName, const Reference<XPropertySet>& _rxSet)
{
if (_rxSet.is())
{
// XPropertySetInfoRef xInfo(rxSet->getPropertySetInfo());
return _rxSet->getPropertySetInfo()->hasPropertyByName(_rName);
}
return sal_False;
}
//------------------------------------------------------------------
void RemoveProperty(Sequence<Property>& _rProps, const rtl::OUString& _rPropName)
{
sal_Int32 nLen = _rProps.getLength();
// binaere Suche
const Property* pProperties = _rProps.getConstArray();
const Property* pResult = ::std::lower_bound(pProperties, pProperties + nLen, _rPropName,PropertyStringLessFunctor());
// gefunden ?
if ( pResult && (pResult != pProperties + nLen) && (pResult->Name == _rPropName) )
{
OSL_ENSURE(pResult->Name.equals(_rPropName), "::RemoveProperty Properties nicht sortiert");
removeElementAt(_rProps, pResult - pProperties);
}
}
//------------------------------------------------------------------
void ModifyPropertyAttributes(Sequence<Property>& seqProps, const ::rtl::OUString& sPropName, sal_Int16 nAddAttrib, sal_Int16 nRemoveAttrib)
{
sal_Int32 nLen = seqProps.getLength();
// binaere Suche
Property* pProperties = seqProps.getArray();
Property* pResult = ::std::lower_bound(pProperties, pProperties + nLen,sPropName, PropertyStringLessFunctor());
// gefunden ?
if ( pResult && (pResult != pProperties + nLen) && (pResult->Name == sPropName) )
{
pResult->Attributes |= nAddAttrib;
pResult->Attributes &= ~nRemoveAttrib;
}
}
//------------------------------------------------------------------
sal_Bool tryPropertyValue(Any& _rConvertedValue, Any& _rOldValue, const Any& _rValueToSet, Any& _rCurrentValue, const Type& _rExpectedType)
{
sal_Bool bModified(sal_False);
if (_rCurrentValue.getValue() != _rValueToSet.getValue())
{
if ( _rValueToSet.hasValue() && ( !_rExpectedType.equals( _rValueToSet.getValueType() ) ) )
{
_rConvertedValue = Any( NULL, _rExpectedType.getTypeLibType() );
if ( !uno_type_assignData(
const_cast< void* >( _rConvertedValue.getValue() ), _rConvertedValue.getValueType().getTypeLibType(),
const_cast< void* >( _rValueToSet.getValue() ), _rValueToSet.getValueType().getTypeLibType(),
reinterpret_cast< uno_QueryInterfaceFunc >(
cpp_queryInterface),
reinterpret_cast< uno_AcquireFunc >(cpp_acquire),
reinterpret_cast< uno_ReleaseFunc >(cpp_release)
)
)
throw starlang::IllegalArgumentException();
}
else
_rConvertedValue = _rValueToSet;
if ( _rCurrentValue != _rConvertedValue )
{
_rOldValue = _rCurrentValue;
bModified = sal_True;
}
}
return bModified;
}
//.........................................................................
}
//.........................................................................
<commit_msg>INTEGRATION: CWS dba23c (1.9.42); FILE MERGED 2007/07/17 19:56:38 fs 1.9.42.1: #149583# copyProperties: don't crash on NULL arguments<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: property.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-07-31 14:02:24 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#if OSL_DEBUG_LEVEL > 0
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _CPPUHELPER_EXC_HLP_HXX_
#include <cppuhelper/exc_hlp.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_GENFUNC_H_
#include <com/sun/star/uno/genfunc.h>
#endif
#include <algorithm>
//.........................................................................
namespace comphelper
{
/** === begin UNO using === **/
using ::com::sun::star::uno::Reference;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::beans::XPropertySetInfo;
using ::com::sun::star::beans::Property;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Type;
using ::com::sun::star::uno::cpp_queryInterface;
using ::com::sun::star::uno::cpp_acquire;
using ::com::sun::star::uno::cpp_release;
/** === end UNO using === **/
namespace PropertyAttribute = ::com::sun::star::beans::PropertyAttribute;
//------------------------------------------------------------------
void copyProperties(const Reference<XPropertySet>& _rxSource,
const Reference<XPropertySet>& _rxDest)
{
if (!_rxSource.is() || !_rxDest.is())
{
OSL_ENSURE(sal_False, "copyProperties: invalid arguments !");
return;
}
Reference< XPropertySetInfo > xSourceProps = _rxSource->getPropertySetInfo();
Reference< XPropertySetInfo > xDestProps = _rxDest->getPropertySetInfo();
Sequence< Property > aSourceProps = xSourceProps->getProperties();
const Property* pSourceProps = aSourceProps.getConstArray();
Property aDestProp;
for (sal_Int32 i=0; i<aSourceProps.getLength(); ++i, ++pSourceProps)
{
if ( xDestProps->hasPropertyByName(pSourceProps->Name) )
{
try
{
aDestProp = xDestProps->getPropertyByName(pSourceProps->Name);
if (0 == (aDestProp.Attributes & PropertyAttribute::READONLY))
_rxDest->setPropertyValue(pSourceProps->Name, _rxSource->getPropertyValue(pSourceProps->Name));
}
catch (Exception&)
{
#if OSL_DEBUG_LEVEL > 0
::rtl::OStringBuffer aBuffer;
aBuffer.append( "::comphelper::copyProperties: could not copy property '" );
aBuffer.append( ::rtl::OString( pSourceProps->Name.getStr(), pSourceProps->Name.getLength(), RTL_TEXTENCODING_ASCII_US ) );
aBuffer.append( "' to the destination set.\n" );
Any aException( ::cppu::getCaughtException() );
aBuffer.append( "Caught an exception of type '" );
::rtl::OUString sExceptionType( aException.getValueTypeName() );
aBuffer.append( ::rtl::OString( sExceptionType.getStr(), sExceptionType.getLength(), RTL_TEXTENCODING_ASCII_US ) );
aBuffer.append( "'" );
Exception aBaseException;
if ( ( aException >>= aBaseException ) && aBaseException.Message.getLength() )
{
aBuffer.append( ", saying '" );
aBuffer.append( ::rtl::OString( aBaseException.Message.getStr(), aBaseException.Message.getLength(), osl_getThreadTextEncoding() ) );
aBuffer.append( "'" );
}
aBuffer.append( "." );
OSL_ENSURE( sal_False, aBuffer.getStr() );
#endif
}
}
}
}
//------------------------------------------------------------------
sal_Bool hasProperty(const rtl::OUString& _rName, const Reference<XPropertySet>& _rxSet)
{
if (_rxSet.is())
{
// XPropertySetInfoRef xInfo(rxSet->getPropertySetInfo());
return _rxSet->getPropertySetInfo()->hasPropertyByName(_rName);
}
return sal_False;
}
//------------------------------------------------------------------
void RemoveProperty(Sequence<Property>& _rProps, const rtl::OUString& _rPropName)
{
sal_Int32 nLen = _rProps.getLength();
// binaere Suche
const Property* pProperties = _rProps.getConstArray();
const Property* pResult = ::std::lower_bound(pProperties, pProperties + nLen, _rPropName,PropertyStringLessFunctor());
// gefunden ?
if ( pResult && (pResult != pProperties + nLen) && (pResult->Name == _rPropName) )
{
OSL_ENSURE(pResult->Name.equals(_rPropName), "::RemoveProperty Properties nicht sortiert");
removeElementAt(_rProps, pResult - pProperties);
}
}
//------------------------------------------------------------------
void ModifyPropertyAttributes(Sequence<Property>& seqProps, const ::rtl::OUString& sPropName, sal_Int16 nAddAttrib, sal_Int16 nRemoveAttrib)
{
sal_Int32 nLen = seqProps.getLength();
// binaere Suche
Property* pProperties = seqProps.getArray();
Property* pResult = ::std::lower_bound(pProperties, pProperties + nLen,sPropName, PropertyStringLessFunctor());
// gefunden ?
if ( pResult && (pResult != pProperties + nLen) && (pResult->Name == sPropName) )
{
pResult->Attributes |= nAddAttrib;
pResult->Attributes &= ~nRemoveAttrib;
}
}
//------------------------------------------------------------------
sal_Bool tryPropertyValue(Any& _rConvertedValue, Any& _rOldValue, const Any& _rValueToSet, Any& _rCurrentValue, const Type& _rExpectedType)
{
sal_Bool bModified(sal_False);
if (_rCurrentValue.getValue() != _rValueToSet.getValue())
{
if ( _rValueToSet.hasValue() && ( !_rExpectedType.equals( _rValueToSet.getValueType() ) ) )
{
_rConvertedValue = Any( NULL, _rExpectedType.getTypeLibType() );
if ( !uno_type_assignData(
const_cast< void* >( _rConvertedValue.getValue() ), _rConvertedValue.getValueType().getTypeLibType(),
const_cast< void* >( _rValueToSet.getValue() ), _rValueToSet.getValueType().getTypeLibType(),
reinterpret_cast< uno_QueryInterfaceFunc >(
cpp_queryInterface),
reinterpret_cast< uno_AcquireFunc >(cpp_acquire),
reinterpret_cast< uno_ReleaseFunc >(cpp_release)
)
)
throw starlang::IllegalArgumentException();
}
else
_rConvertedValue = _rValueToSet;
if ( _rCurrentValue != _rConvertedValue )
{
_rOldValue = _rCurrentValue;
bModified = sal_True;
}
}
return bModified;
}
//.........................................................................
}
//.........................................................................
<|endoftext|>
|
<commit_before><commit_msg>Fix hang as a result of host not answering or hanging up<commit_after><|endoftext|>
|
<commit_before>#include <stack>
#include "acmacs-base/read-file.hh"
#include "acmacs-whocc/csv-parser.hh"
enum class state {
cell,
quoted,
escaped
};
constexpr const char separator{','};
constexpr const char quote{'"'};
constexpr const char escape{'\\'};
// ----------------------------------------------------------------------
acmacs::xlsx::v1::csv::Sheet::Sheet(std::string_view filename)
{
const std::string src{acmacs::file::read(filename)};
const auto convert_cell = [&]() {};
const auto new_cell = [&]() {
convert_cell();
data_.back().emplace_back(std::string{});
};
const auto new_row = [&]() {
convert_cell();
number_of_columns_ = std::max(number_of_columns_, sheet::ncol_t{data_.back().size()});
data_.emplace_back().emplace_back(std::string{});
};
const auto append = [&](char sym) {
std::visit(
[sym]<typename Content>(Content& content) {
if constexpr (std::is_same_v<Content, std::string>)
content.push_back(sym);
},
data_.back().back());
};
std::stack<enum state> states;
states.push(state::cell);
data_.emplace_back().emplace_back(std::string{});
for (const char sym : src) {
if (states.top() == state::escaped) {
states.pop();
append(sym);
}
else {
switch (sym) {
case separator:
if (states.top() == state::quoted)
append(sym);
else
new_cell();
break;
case '\n':
if (states.top() == state::quoted)
append(sym);
else
new_row();
break;
case quote:
if (states.top() == state::quoted)
states.pop();
else
states.push(state::quoted);
break;
case escape:
states.push(state::escaped);
break;
default:
append(sym);
break;
}
}
}
AD_DEBUG("rows: {} cols: {}", number_of_rows(), number_of_columns());
for (const auto& row : data_) {
bool first{true};
for (const auto& cell : row) {
if (first)
first = false;
else
fmt::print("|");
fmt::print("{}", cell);
}
fmt::print("\n");
}
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>csv parser<commit_after>#include <stack>
#include "acmacs-base/read-file.hh"
#include "acmacs-whocc/csv-parser.hh"
enum class state {
cell,
quoted,
escaped
};
constexpr const char separator{','};
constexpr const char quote{'"'};
constexpr const char escape{'\\'};
// ----------------------------------------------------------------------
acmacs::xlsx::v1::csv::Sheet::Sheet(std::string_view filename)
{
const std::string src{acmacs::file::read(filename)};
const auto convert_cell = [&]() {};
const auto new_cell = [&]() {
convert_cell();
data_.back().emplace_back(std::string{});
};
const auto new_row = [&]() {
convert_cell();
number_of_columns_ = std::max(number_of_columns_, sheet::ncol_t{data_.back().size()});
data_.emplace_back().emplace_back(std::string{});
};
const auto append = [&](char sym) {
std::visit(
[sym]<typename Content>(Content& content) {
if constexpr (std::is_same_v<Content, std::string>)
content.push_back(sym);
},
data_.back().back());
};
std::stack<enum state> states;
states.push(state::cell);
data_.emplace_back().emplace_back(std::string{});
for (const char sym : src) {
if (states.top() == state::escaped) {
states.pop();
append(sym);
}
else {
switch (sym) {
case separator:
if (states.top() == state::quoted)
append(sym);
else
new_cell();
break;
case '\n':
if (states.top() == state::quoted)
append(sym);
else
new_row();
break;
case quote:
if (states.top() == state::quoted)
states.pop();
else
states.push(state::quoted);
break;
case escape:
states.push(state::escaped);
break;
default:
append(sym);
break;
}
}
}
if (!data_.empty() && data_.back().size() <= 1 && number_of_columns_ > sheet::ncol_t{1})
data_.erase(std::prev(data_.end()));
// normalize number of columns
for (auto& row : data_) {
while (row.size() < *number_of_columns_)
row.emplace_back(std::string{});
}
AD_INFO("csv: rows: {} cols: {}", number_of_rows(), number_of_columns());
// for (const auto& row : data_) {
// bool first{true};
// for (const auto& cell : row) {
// if (first)
// first = false;
// else
// fmt::print("|");
// fmt::print("{}", cell);
// }
// fmt::print("\n");
// }
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: breakiterator_cjk.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2006-10-24 13:53:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"
#define BREAKITERATOR_ALL
#include <breakiterator_cjk.hxx>
#include <i18nutil/unicode.hxx>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;
namespace com { namespace sun { namespace star { namespace i18n {
// ----------------------------------------------------
// class BreakIterator_CJK
// ----------------------------------------------------;
BreakIterator_CJK::BreakIterator_CJK() : dict(NULL)
{
cBreakIterator = "com.sun.star.i18n.BreakIterator_CJK";
}
Boundary SAL_CALL
BreakIterator_CJK::previousWord(const OUString& text, sal_Int32 anyPos,
const lang::Locale& nLocale, sal_Int16 wordType) throw(RuntimeException)
{
if (dict) {
result = dict->previousWord(text.getStr(), anyPos, text.getLength(), wordType);
// #109813# for non-CJK, single character word, fallback to ICU breakiterator.
if (result.endPos - result.startPos != 1 ||
getScriptType(text, result.startPos) == ScriptType::ASIAN)
return result;
else
return BreakIterator_Unicode::getWordBoundary(text, result.startPos, nLocale, wordType, true);
}
return BreakIterator_Unicode::previousWord(text, anyPos, nLocale, wordType);
}
Boundary SAL_CALL
BreakIterator_CJK::nextWord(const OUString& text, sal_Int32 anyPos,
const lang::Locale& nLocale, sal_Int16 wordType) throw(RuntimeException)
{
if (dict) {
result = dict->nextWord(text.getStr(), anyPos, text.getLength(), wordType);
// #109813# for non-CJK, single character word, fallback to ICU breakiterator.
if (result.endPos - result.startPos != 1 ||
getScriptType(text, result.startPos) == ScriptType::ASIAN)
return result;
else
return BreakIterator_Unicode::getWordBoundary(text, result.startPos, nLocale, wordType, true);
}
return BreakIterator_Unicode::nextWord(text, anyPos, nLocale, wordType);
}
Boundary SAL_CALL
BreakIterator_CJK::getWordBoundary( const OUString& text, sal_Int32 anyPos,
const lang::Locale& nLocale, sal_Int16 wordType, sal_Bool bDirection )
throw(RuntimeException)
{
if (dict) {
result = dict->getWordBoundary(text.getStr(), anyPos, text.getLength(), wordType, bDirection);
// #109813# for non-CJK, single character word, fallback to ICU breakiterator.
if (result.endPos - result.startPos != 1 ||
getScriptType(text, result.startPos) == ScriptType::ASIAN)
return result;
}
return BreakIterator_Unicode::getWordBoundary(text, anyPos, nLocale, wordType, bDirection);
}
LineBreakResults SAL_CALL BreakIterator_CJK::getLineBreak(
const OUString& Text, sal_Int32 nStartPos,
const lang::Locale& /*rLocale*/, sal_Int32 /*nMinBreakPos*/,
const LineBreakHyphenationOptions& /*hOptions*/,
const LineBreakUserOptions& bOptions ) throw(RuntimeException)
{
LineBreakResults lbr;
if (bOptions.allowPunctuationOutsideMargin &&
bOptions.forbiddenBeginCharacters.indexOf(Text[nStartPos]) != -1 &&
++nStartPos == Text.getLength()) {
; // do nothing
} else if (bOptions.applyForbiddenRules && 0 < nStartPos && nStartPos < Text.getLength()) {
while (nStartPos > 0 &&
(bOptions.forbiddenBeginCharacters.indexOf(Text[nStartPos]) != -1 ||
bOptions.forbiddenEndCharacters.indexOf(Text[nStartPos-1]) != -1))
nStartPos--;
}
lbr.breakIndex = nStartPos;
lbr.breakType = BreakType::WORDBOUNDARY;
return lbr;
}
// ----------------------------------------------------
// class BreakIterator_zh
// ----------------------------------------------------;
BreakIterator_zh::BreakIterator_zh()
{
dict = new xdictionary("zh");
cBreakIterator = "com.sun.star.i18n.BreakIterator_zh";
}
BreakIterator_zh::~BreakIterator_zh()
{
delete dict;
}
// ----------------------------------------------------
// class BreakIterator_ja
// ----------------------------------------------------;
BreakIterator_ja::BreakIterator_ja()
{
dict = new xdictionary("ja");
dict->setJapaneseWordBreak();
cBreakIterator = "com.sun.star.i18n.BreakIterator_ja";
}
BreakIterator_ja::~BreakIterator_ja()
{
delete dict;
}
// ----------------------------------------------------
// class BreakIterator_ko
// ----------------------------------------------------;
BreakIterator_ko::BreakIterator_ko()
{
cBreakIterator = "com.sun.star.i18n.BreakIterator_ko";
}
BreakIterator_ko::~BreakIterator_ko()
{
}
} } } }
<commit_msg>INTEGRATION: CWS i18n30 (1.14.32); FILE MERGED 2007/05/08 21:44:15 khong 1.14.32.1: #i76706# fix infinite loop for CJK word breakiterator for text mixed with Latin and CJK characters<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: breakiterator_cjk.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: ihi $ $Date: 2007-06-06 12:17:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"
#define BREAKITERATOR_ALL
#include <breakiterator_cjk.hxx>
#include <i18nutil/unicode.hxx>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;
namespace com { namespace sun { namespace star { namespace i18n {
// ----------------------------------------------------
// class BreakIterator_CJK
// ----------------------------------------------------;
BreakIterator_CJK::BreakIterator_CJK() : dict(NULL)
{
cBreakIterator = "com.sun.star.i18n.BreakIterator_CJK";
}
Boundary SAL_CALL
BreakIterator_CJK::previousWord(const OUString& text, sal_Int32 anyPos,
const lang::Locale& nLocale, sal_Int16 wordType) throw(RuntimeException)
{
if (dict) {
result = dict->previousWord(text.getStr(), anyPos, text.getLength(), wordType);
// #109813# for non-CJK, single character word, fallback to ICU breakiterator.
if (result.endPos - result.startPos != 1 ||
getScriptType(text, result.startPos) == ScriptType::ASIAN)
return result;
result = BreakIterator_Unicode::getWordBoundary(text, result.startPos, nLocale, wordType, true);
if (result.endPos < anyPos)
return result;
}
return BreakIterator_Unicode::previousWord(text, anyPos, nLocale, wordType);
}
Boundary SAL_CALL
BreakIterator_CJK::nextWord(const OUString& text, sal_Int32 anyPos,
const lang::Locale& nLocale, sal_Int16 wordType) throw(RuntimeException)
{
if (dict) {
result = dict->nextWord(text.getStr(), anyPos, text.getLength(), wordType);
// #109813# for non-CJK, single character word, fallback to ICU breakiterator.
if (result.endPos - result.startPos != 1 ||
getScriptType(text, result.startPos) == ScriptType::ASIAN)
return result;
result = BreakIterator_Unicode::getWordBoundary(text, result.startPos, nLocale, wordType, true);
if (result.startPos > anyPos)
return result;
}
return BreakIterator_Unicode::nextWord(text, anyPos, nLocale, wordType);
}
Boundary SAL_CALL
BreakIterator_CJK::getWordBoundary( const OUString& text, sal_Int32 anyPos,
const lang::Locale& nLocale, sal_Int16 wordType, sal_Bool bDirection )
throw(RuntimeException)
{
if (dict) {
result = dict->getWordBoundary(text.getStr(), anyPos, text.getLength(), wordType, bDirection);
// #109813# for non-CJK, single character word, fallback to ICU breakiterator.
if (result.endPos - result.startPos != 1 ||
getScriptType(text, result.startPos) == ScriptType::ASIAN)
return result;
}
return BreakIterator_Unicode::getWordBoundary(text, anyPos, nLocale, wordType, bDirection);
}
LineBreakResults SAL_CALL BreakIterator_CJK::getLineBreak(
const OUString& Text, sal_Int32 nStartPos,
const lang::Locale& /*rLocale*/, sal_Int32 /*nMinBreakPos*/,
const LineBreakHyphenationOptions& /*hOptions*/,
const LineBreakUserOptions& bOptions ) throw(RuntimeException)
{
LineBreakResults lbr;
if (bOptions.allowPunctuationOutsideMargin &&
bOptions.forbiddenBeginCharacters.indexOf(Text[nStartPos]) != -1 &&
++nStartPos == Text.getLength()) {
; // do nothing
} else if (bOptions.applyForbiddenRules && 0 < nStartPos && nStartPos < Text.getLength()) {
while (nStartPos > 0 &&
(bOptions.forbiddenBeginCharacters.indexOf(Text[nStartPos]) != -1 ||
bOptions.forbiddenEndCharacters.indexOf(Text[nStartPos-1]) != -1))
nStartPos--;
}
lbr.breakIndex = nStartPos;
lbr.breakType = BreakType::WORDBOUNDARY;
return lbr;
}
// ----------------------------------------------------
// class BreakIterator_zh
// ----------------------------------------------------;
BreakIterator_zh::BreakIterator_zh()
{
dict = new xdictionary("zh");
cBreakIterator = "com.sun.star.i18n.BreakIterator_zh";
}
BreakIterator_zh::~BreakIterator_zh()
{
delete dict;
}
// ----------------------------------------------------
// class BreakIterator_ja
// ----------------------------------------------------;
BreakIterator_ja::BreakIterator_ja()
{
dict = new xdictionary("ja");
dict->setJapaneseWordBreak();
cBreakIterator = "com.sun.star.i18n.BreakIterator_ja";
}
BreakIterator_ja::~BreakIterator_ja()
{
delete dict;
}
// ----------------------------------------------------
// class BreakIterator_ko
// ----------------------------------------------------;
BreakIterator_ko::BreakIterator_ko()
{
cBreakIterator = "com.sun.star.i18n.BreakIterator_ko";
}
BreakIterator_ko::~BreakIterator_ko()
{
}
} } } }
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: breakiterator_ctl.cxx,v $
* $Revision: 1.13 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"
#include <com/sun/star/i18n/CharacterIteratorMode.hpp>
#include <breakiterator_ctl.hxx>
#include <string.h> // for memset
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;
namespace com { namespace sun { namespace star { namespace i18n {
/**
* Constructor.
*/
BreakIterator_CTL::BreakIterator_CTL()
{
cBreakIterator = "com.sun.star.i18n.BreakIterator_CTL";
// to improve performance, alloc big enough memory in construct.
cellIndexSize = 512;
nextCellIndex = (sal_Int32*) calloc(cellIndexSize, sizeof(sal_Int32));
previousCellIndex = (sal_Int32*) calloc(cellIndexSize, sizeof(sal_Int32));
memset(nextCellIndex, 0, cellIndexSize * sizeof(sal_Int32));
}
/**
* Deconstructor.
*/
BreakIterator_CTL::~BreakIterator_CTL()
{
free(nextCellIndex);
free(previousCellIndex);
}
sal_Int32 SAL_CALL BreakIterator_CTL::previousCharacters( const OUString& Text,
sal_Int32 nStartPos, const lang::Locale& rLocale,
sal_Int16 nCharacterIteratorMode, sal_Int32 nCount, sal_Int32& nDone )
throw(RuntimeException)
{
if (nCharacterIteratorMode == CharacterIteratorMode::SKIPCELL ) {
nDone = 0;
if (nStartPos > 0) { // for others to skip cell.
makeIndex(Text, nStartPos);
if (nextCellIndex[nStartPos-1] == 0) // not a CTL character
return BreakIterator_Unicode::previousCharacters(Text, nStartPos, rLocale,
nCharacterIteratorMode, nCount, nDone);
else while (nCount > 0 && nextCellIndex[nStartPos - 1] > 0) {
nCount--; nDone++;
nStartPos = previousCellIndex[nStartPos - 1];
}
} else
nStartPos = 0;
} else { // for BS to delete one char.
nDone = (nStartPos > nCount) ? nCount : nStartPos;
nStartPos -= nDone;
}
return nStartPos;
}
sal_Int32 SAL_CALL BreakIterator_CTL::nextCharacters(const OUString& Text,
sal_Int32 nStartPos, const lang::Locale& rLocale,
sal_Int16 nCharacterIteratorMode, sal_Int32 nCount, sal_Int32& nDone)
throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
if (nCharacterIteratorMode == CharacterIteratorMode::SKIPCELL ) {
nDone = 0;
if (nStartPos < len) {
makeIndex(Text, nStartPos);
if (nextCellIndex[nStartPos] == 0) // not a CTL character
return BreakIterator_Unicode::nextCharacters(Text, nStartPos, rLocale,
nCharacterIteratorMode, nCount, nDone);
else while (nCount > 0 && nextCellIndex[nStartPos] > 0) {
nCount--; nDone++;
nStartPos = nextCellIndex[nStartPos];
}
} else
nStartPos = len;
} else {
nDone = (len - nStartPos > nCount) ? nCount : len - nStartPos;
nStartPos += nDone;
}
return nStartPos;
}
// This method should be overwritten by derived language specific class.
void SAL_CALL BreakIterator_CTL::makeIndex(const OUString& /*text*/, sal_Int32 /*pos*/)
throw(RuntimeException)
{
throw RuntimeException();
}
// Make sure line is broken on cell boundary if we implement cell iterator.
LineBreakResults SAL_CALL BreakIterator_CTL::getLineBreak(
const OUString& Text, sal_Int32 nStartPos,
const lang::Locale& rLocale, sal_Int32 nMinBreakPos,
const LineBreakHyphenationOptions& hOptions,
const LineBreakUserOptions& bOptions ) throw(RuntimeException)
{
LineBreakResults lbr = BreakIterator_Unicode::getLineBreak(Text, nStartPos,
rLocale, nMinBreakPos, hOptions, bOptions );
makeIndex(Text, lbr.breakIndex);
lbr.breakIndex = previousCellIndex[ lbr.breakIndex ];
return lbr;
}
} } } }
<commit_msg>INTEGRATION: CWS i18n41 (1.12.140); FILE MERGED 2008/06/05 22:18:26 khong 1.12.140.2: RESYNC: (1.12-1.13); FILE MERGED 2008/04/23 06:04:53 khong 1.12.140.1: i87530 avoid breaking line before un-completed cell<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: breakiterator_ctl.cxx,v $
* $Revision: 1.14 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"
#include <com/sun/star/i18n/CharacterIteratorMode.hpp>
#include <breakiterator_ctl.hxx>
#include <string.h> // for memset
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;
namespace com { namespace sun { namespace star { namespace i18n {
/**
* Constructor.
*/
BreakIterator_CTL::BreakIterator_CTL()
{
cBreakIterator = "com.sun.star.i18n.BreakIterator_CTL";
// to improve performance, alloc big enough memory in construct.
cellIndexSize = 512;
nextCellIndex = (sal_Int32*) calloc(cellIndexSize, sizeof(sal_Int32));
previousCellIndex = (sal_Int32*) calloc(cellIndexSize, sizeof(sal_Int32));
memset(nextCellIndex, 0, cellIndexSize * sizeof(sal_Int32));
}
/**
* Deconstructor.
*/
BreakIterator_CTL::~BreakIterator_CTL()
{
free(nextCellIndex);
free(previousCellIndex);
}
sal_Int32 SAL_CALL BreakIterator_CTL::previousCharacters( const OUString& Text,
sal_Int32 nStartPos, const lang::Locale& rLocale,
sal_Int16 nCharacterIteratorMode, sal_Int32 nCount, sal_Int32& nDone )
throw(RuntimeException)
{
if (nCharacterIteratorMode == CharacterIteratorMode::SKIPCELL ) {
nDone = 0;
if (nStartPos > 0) { // for others to skip cell.
makeIndex(Text, nStartPos);
if (nextCellIndex[nStartPos-1] == 0) // not a CTL character
return BreakIterator_Unicode::previousCharacters(Text, nStartPos, rLocale,
nCharacterIteratorMode, nCount, nDone);
else while (nCount > 0 && nextCellIndex[nStartPos - 1] > 0) {
nCount--; nDone++;
nStartPos = previousCellIndex[nStartPos - 1];
}
} else
nStartPos = 0;
} else { // for BS to delete one char.
nDone = (nStartPos > nCount) ? nCount : nStartPos;
nStartPos -= nDone;
}
return nStartPos;
}
sal_Int32 SAL_CALL BreakIterator_CTL::nextCharacters(const OUString& Text,
sal_Int32 nStartPos, const lang::Locale& rLocale,
sal_Int16 nCharacterIteratorMode, sal_Int32 nCount, sal_Int32& nDone)
throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
if (nCharacterIteratorMode == CharacterIteratorMode::SKIPCELL ) {
nDone = 0;
if (nStartPos < len) {
makeIndex(Text, nStartPos);
if (nextCellIndex[nStartPos] == 0) // not a CTL character
return BreakIterator_Unicode::nextCharacters(Text, nStartPos, rLocale,
nCharacterIteratorMode, nCount, nDone);
else while (nCount > 0 && nextCellIndex[nStartPos] > 0) {
nCount--; nDone++;
nStartPos = nextCellIndex[nStartPos];
}
} else
nStartPos = len;
} else {
nDone = (len - nStartPos > nCount) ? nCount : len - nStartPos;
nStartPos += nDone;
}
return nStartPos;
}
// This method should be overwritten by derived language specific class.
void SAL_CALL BreakIterator_CTL::makeIndex(const OUString& /*text*/, sal_Int32 /*pos*/)
throw(RuntimeException)
{
throw RuntimeException();
}
// Make sure line is broken on cell boundary if we implement cell iterator.
LineBreakResults SAL_CALL BreakIterator_CTL::getLineBreak(
const OUString& Text, sal_Int32 nStartPos,
const lang::Locale& rLocale, sal_Int32 nMinBreakPos,
const LineBreakHyphenationOptions& hOptions,
const LineBreakUserOptions& bOptions ) throw(RuntimeException)
{
LineBreakResults lbr = BreakIterator_Unicode::getLineBreak(Text, nStartPos,
rLocale, nMinBreakPos, hOptions, bOptions );
if (lbr.breakIndex < Text.getLength()) {
makeIndex(Text, lbr.breakIndex);
lbr.breakIndex = previousCellIndex[ lbr.breakIndex ];
}
return lbr;
}
} } } }
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_posh/internal/roudi_environment/roudi_environment.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"
#include "test.hpp"
using namespace ::testing;
using namespace iox::runtime;
using iox::roudi::RouDiEnvironment;
class PoshRuntime_test : public Test
{
public:
PoshRuntime_test()
{
}
virtual ~PoshRuntime_test()
{
}
virtual void SetUp(){};
virtual void TearDown(){};
void InterOpWait()
{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
iox::cxx::GenericRAII m_errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler(
[](const iox::Error, const std::function<void()>, const iox::ErrorLevel) { m_errorHandlerCalled = true; });
RouDiEnvironment m_roudiEnv{iox::RouDiConfig_t().setDefaults()};
PoshRuntime* m_receiverRuntime{&iox::runtime::PoshRuntime::getInstance("/receiver")};
PoshRuntime* m_senderRuntime{&iox::runtime::PoshRuntime::getInstance("/sender")};
MqMessage m_sendBuffer;
MqMessage m_receiveBuffer;
const iox::cxx::CString100 m_runnableName = iox::cxx::CString100("testRunnable");
const iox::cxx::CString100 m_invalidRunnableName = iox::cxx::CString100("invalidRunnable,");
static bool m_errorHandlerCalled;
};
bool PoshRuntime_test::m_errorHandlerCalled{false};
TEST_F(PoshRuntime_test, AppnameLength_TooLong)
{
const std::string string104chars =
"/MXIYXHyPF9KjXAPv9ev9jxofYDArZzTvf8FF5uaWWC4dwabcjW75DurqeN645IabAsXVfngor7784446vb4vhArwBxLZlN1k1Qmrtz";
EXPECT_DEATH({ PoshRuntime::getInstance(string104chars); },
"Application name has more than 100 characters, including null termination!");
}
TEST_F(PoshRuntime_test, AppnameLength_ok)
{
const std::string string100chars =
"/MXIYXHyPF9KjXAPv9ev9jxofYDArZzTvf8FF5uaWWC4dwabcjW75DurqeN645IabAsXVfngor7784446vb4vhArwBxLZlN1k1";
EXPECT_NO_FATAL_FAILURE({ PoshRuntime::getInstance(string100chars); });
}
TEST_F(PoshRuntime_test, NoAppname)
{
const std::string wrong("");
EXPECT_DEATH({ PoshRuntime::getInstance(wrong); },
"Cannot initialize runtime. Application name must not be empty!");
}
TEST_F(PoshRuntime_test, NoLeadingSlash_Appname)
{
const std::string wrong = "wrongname";
EXPECT_DEATH({ PoshRuntime::getInstance(wrong); },
"Cannot initialize runtime. Application name wrongname does not have the required leading slash '/'");
}
// test class creates instance of Poshruntime, so when getInstance() is called without name it reuturns extisting
// instance
TEST_F(PoshRuntime_test, DISABLED_AppnameEmpty)
{
EXPECT_DEATH({ iox::runtime::PoshRuntime::getInstance(); },
"Cannot initialize runtime. Application name has not been specified!");
}
TEST_F(PoshRuntime_test, GetInstanceName)
{
const std::string appname = "/app";
auto& sut = PoshRuntime::getInstance(appname);
EXPECT_EQ(sut.getInstanceName(), appname);
}
TEST_F(PoshRuntime_test, GetMiddlewareApplication_ReturnValue)
{
uint32_t uniqueIdCounter = iox::popo::BasePortData::s_uniqueIdCounter;
const auto applicationPortData = m_senderRuntime->getMiddlewareApplication();
EXPECT_EQ(std::string("/sender"), applicationPortData->m_processName);
EXPECT_EQ(iox::capro::ServiceDescription(0u, 0u, 0u), applicationPortData->m_serviceDescription);
EXPECT_EQ(false, applicationPortData->m_toBeDestroyed);
EXPECT_EQ(uniqueIdCounter, applicationPortData->m_uniqueId);
}
TEST_F(PoshRuntime_test, GetMiddlewareApplication_ApplicationlistOverflow)
{
m_errorHandlerCalled = false;
for (auto i = 0u; i < iox::MAX_PROCESS_NUMBER; ++i)
{
m_senderRuntime->getMiddlewareApplication();
}
EXPECT_TRUE(m_errorHandlerCalled);
}
TEST_F(PoshRuntime_test, GetMiddlewareInterface_ReturnValue)
{
const auto interfacePortData =
m_senderRuntime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL, m_runnableName);
EXPECT_EQ(std::string("/sender"), interfacePortData->m_processName);
EXPECT_EQ(iox::capro::ServiceDescription(0u, 0u, 0u), interfacePortData->m_serviceDescription);
EXPECT_EQ(false, interfacePortData->m_toBeDestroyed);
EXPECT_EQ(true, interfacePortData->m_doInitialOfferForward);
}
TEST_F(PoshRuntime_test, GetMiddlewareInterface_InterfacelistOverflow)
{
m_errorHandlerCalled = false;
for (auto i = 0u; i < iox::MAX_INTERFACE_NUMBER + 1u; ++i)
{
m_senderRuntime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL);
}
EXPECT_TRUE(m_errorHandlerCalled);
}
TEST_F(PoshRuntime_test, SendMessageToRouDi_ValidMessage)
{
m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << std::string("/sender")
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_runnableName;
const auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);
EXPECT_EQ(true, status);
}
TEST_F(PoshRuntime_test, SendMessageToRouDi_InvalidMessage)
{
m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << std::string()
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_invalidRunnableName;
const auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);
EXPECT_EQ(false, status);
}
TEST_F(PoshRuntime_test, SendMessageToRouDi_EmptyMessage)
{
const auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);
EXPECT_EQ(true, status);
}
TEST_F(PoshRuntime_test, SendRequestToRouDi_ValidMessage)
{
m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << std::string("/sender")
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_runnableName;
const auto status = m_senderRuntime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);
EXPECT_EQ(true, status);
}
TEST_F(PoshRuntime_test, SendRequestToRouDi_InvalidMessage)
{
m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << std::string("/sender")
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_invalidRunnableName;
const auto status = m_senderRuntime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);
EXPECT_EQ(false, status);
}
TEST_F(PoshRuntime_test, GetMiddlewareSender_ReturnValue)
{
const auto senderPort = m_senderRuntime->getMiddlewareSender(
iox::capro::ServiceDescription(99u, 1u, 20u), m_runnableName, iox::runtime::PortConfigInfo(11u, 22u, 33u));
EXPECT_EQ(iox::capro::ServiceDescription(99u, 1u, 20u), senderPort->m_serviceDescription);
EXPECT_EQ(22u, senderPort->m_memoryInfo.deviceId);
EXPECT_EQ(33u, senderPort->m_memoryInfo.memoryType);
}
TEST_F(PoshRuntime_test, GetMiddlewareSender_DefaultArgs)
{
const auto senderPort = m_senderRuntime->getMiddlewareSender(iox::capro::ServiceDescription(99u, 1u, 20u));
EXPECT_EQ(0u, senderPort->m_memoryInfo.deviceId);
EXPECT_EQ(0u, senderPort->m_memoryInfo.memoryType);
}
TEST_F(PoshRuntime_test, GetMiddlewareSender_SenderlistOverflow)
{
m_errorHandlerCalled = false;
for (uint32_t i = 0u; i < iox::MAX_PORT_NUMBER; ++i)
{
m_senderRuntime->getMiddlewareSender(iox::capro::ServiceDescription(i, i + 1u, i + 2u));
}
EXPECT_TRUE(m_errorHandlerCalled);
}
TEST_F(PoshRuntime_test, GetMiddlewareReceiver_ReturnValue)
{
auto receiverPort = m_receiverRuntime->getMiddlewareReceiver(
iox::capro::ServiceDescription(99u, 1u, 20u), m_runnableName, iox::runtime::PortConfigInfo(11u, 22u, 33u));
EXPECT_EQ(iox::capro::ServiceDescription(99u, 1u, 20u), receiverPort->m_serviceDescription);
EXPECT_EQ(22u, receiverPort->m_memoryInfo.deviceId);
EXPECT_EQ(33u, receiverPort->m_memoryInfo.memoryType);
}
TEST_F(PoshRuntime_test, GetMiddlewareReceiver_DefaultArgs)
{
auto receiverPort = m_receiverRuntime->getMiddlewareReceiver(iox::capro::ServiceDescription(99u, 1u, 20u));
EXPECT_EQ(0u, receiverPort->m_memoryInfo.deviceId);
EXPECT_EQ(0u, receiverPort->m_memoryInfo.memoryType);
}
TEST_F(PoshRuntime_test, GetMiddlewareReceiver_ReceiverlistOverflow)
{
m_errorHandlerCalled = false;
for (uint32_t i = 0u; i < iox::MAX_PORT_NUMBER + 1; ++i)
{
m_senderRuntime->getMiddlewareReceiver(iox::capro::ServiceDescription(i, i + 1u, i + 2u));
}
EXPECT_TRUE(m_errorHandlerCalled);
}
TEST_F(PoshRuntime_test, GetServiceRegistryChangeCounter_ReturnValue)
{
auto runnableData = m_senderRuntime->getServiceRegistryChangeCounter();
// Roudi internally calls 5 servieces before application registers its service
EXPECT_EQ(5u, *runnableData);
}
TEST_F(PoshRuntime_test, GetServiceRegistryChangeCounter_OfferStopOfferService)
{
auto initial_value = m_senderRuntime->getServiceRegistryChangeCounter();
EXPECT_EQ(5u, *initial_value);
m_senderRuntime->offerService({"service1", "instance1"});
this->InterOpWait();
auto runnableData = m_senderRuntime->getServiceRegistryChangeCounter();
EXPECT_EQ(6u, *runnableData);
m_senderRuntime->stopOfferService({"service1", "instance1"});
this->InterOpWait();
EXPECT_EQ(7u, *runnableData);
}
TEST_F(PoshRuntime_test, CreateRunnable_ReturnValue)
{
const uint32_t runnableDeviceIdentifier = 1u;
iox::runtime::RunnableProperty runnableProperty(iox::cxx::CString100("testRunnable"), runnableDeviceIdentifier);
auto runableData = m_senderRuntime->createRunnable(runnableProperty);
EXPECT_EQ(std::string("/sender"), runableData->m_process);
EXPECT_EQ(iox::cxx::CString100("testRunnable"), runableData->m_runnable);
/// @todo I am passing runnableDeviceIdentifier as 1, but it returns 0, is this expected?
// EXPECT_EQ(runnableDeviceIdentifier, runableData->m_runnableDeviceIdentifier);
}
<commit_msg>iox-#177: fix review points<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_posh/internal/roudi_environment/roudi_environment.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"
#include "test.hpp"
using namespace ::testing;
using namespace iox::runtime;
using iox::roudi::RouDiEnvironment;
class PoshRuntime_test : public Test
{
public:
PoshRuntime_test()
{
}
virtual ~PoshRuntime_test()
{
}
virtual void SetUp(){};
virtual void TearDown(){};
void InterOpWait()
{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
iox::cxx::GenericRAII m_errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler(
[](const iox::Error, const std::function<void()>, const iox::ErrorLevel) { m_errorHandlerCalled = true; });
RouDiEnvironment m_roudiEnv{iox::RouDiConfig_t().setDefaults()};
PoshRuntime* m_receiverRuntime{&iox::runtime::PoshRuntime::getInstance("/receiver")};
PoshRuntime* m_senderRuntime{&iox::runtime::PoshRuntime::getInstance("/sender")};
MqMessage m_sendBuffer;
MqMessage m_receiveBuffer;
const iox::cxx::CString100 m_runnableName{"testRunnable"};
const iox::cxx::CString100 m_invalidRunnableName{"invalidRunnable,"};
static bool m_errorHandlerCalled;
};
bool PoshRuntime_test::m_errorHandlerCalled{false};
TEST_F(PoshRuntime_test, ValidAppname)
{
std::string appName("/valid_name");
EXPECT_NO_FATAL_FAILURE({ PoshRuntime::getInstance(appName); });
}
TEST_F(PoshRuntime_test, AppnameLength_OutOfLimit)
{
std::string tooLongName(100, 's');
tooLongName.insert(0, 1, '/');
EXPECT_DEATH({ PoshRuntime::getInstance(tooLongName); },
"Application name has more than 100 characters, including null termination!");
}
TEST_F(PoshRuntime_test, MaxAppnameLength)
{
std::string maxValidName(99, 's');
maxValidName.insert(0, 1, '/');
EXPECT_NO_FATAL_FAILURE({ PoshRuntime::getInstance(maxValidName); });
}
TEST_F(PoshRuntime_test, NoAppname)
{
const std::string wrong("");
EXPECT_DEATH({ PoshRuntime::getInstance(wrong); },
"Cannot initialize runtime. Application name must not be empty!");
}
TEST_F(PoshRuntime_test, NoLeadingSlash_Appname)
{
const std::string wrong = "wrongname";
EXPECT_DEATH({ PoshRuntime::getInstance(wrong); },
"Cannot initialize runtime. Application name wrongname does not have the required leading slash '/'");
}
// test class creates instance of Poshruntime, so when getInstance() is called without name it reuturns extisting
// instance
TEST_F(PoshRuntime_test, DISABLED_AppnameEmpty)
{
EXPECT_DEATH({ iox::runtime::PoshRuntime::getInstance(); },
"Cannot initialize runtime. Application name has not been specified!");
}
TEST_F(PoshRuntime_test, GetInstanceName_ReturnValue)
{
const std::string appname = "/app";
auto& sut = PoshRuntime::getInstance(appname);
EXPECT_EQ(sut.getInstanceName(), appname);
}
TEST_F(PoshRuntime_test, GetMiddlewareApplication_ReturnValue)
{
uint32_t uniqueIdCounter = iox::popo::BasePortData::s_uniqueIdCounter;
const auto applicationPortData = m_senderRuntime->getMiddlewareApplication();
EXPECT_EQ(std::string("/sender"), applicationPortData->m_processName);
EXPECT_EQ(iox::capro::ServiceDescription(0u, 0u, 0u), applicationPortData->m_serviceDescription);
EXPECT_EQ(false, applicationPortData->m_toBeDestroyed);
EXPECT_EQ(uniqueIdCounter, applicationPortData->m_uniqueId);
}
TEST_F(PoshRuntime_test, GetMiddlewareApplication_ApplicationlistOverflow)
{
m_errorHandlerCalled = false;
for (auto i = 0u; i < iox::MAX_PROCESS_NUMBER; ++i)
{
m_senderRuntime->getMiddlewareApplication();
}
EXPECT_TRUE(m_errorHandlerCalled);
}
TEST_F(PoshRuntime_test, GetMiddlewareInterface_ReturnValue)
{
const auto interfacePortData =
m_senderRuntime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL, m_runnableName);
EXPECT_EQ(std::string("/sender"), interfacePortData->m_processName);
EXPECT_EQ(iox::capro::ServiceDescription(0u, 0u, 0u), interfacePortData->m_serviceDescription);
EXPECT_EQ(false, interfacePortData->m_toBeDestroyed);
EXPECT_EQ(true, interfacePortData->m_doInitialOfferForward);
}
TEST_F(PoshRuntime_test, GetMiddlewareInterface_InterfacelistOverflow)
{
m_errorHandlerCalled = false;
for (auto i = 0u; i < iox::MAX_INTERFACE_NUMBER + 1u; ++i)
{
m_senderRuntime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL);
}
EXPECT_TRUE(m_errorHandlerCalled);
}
TEST_F(PoshRuntime_test, SendMessageToRouDi_ValidMessage)
{
m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << std::string("/sender")
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_runnableName;
const auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);
EXPECT_EQ(true, status);
}
TEST_F(PoshRuntime_test, SendMessageToRouDi_InvalidMessage)
{
m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << std::string()
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_invalidRunnableName;
const auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);
EXPECT_EQ(false, status);
}
TEST_F(PoshRuntime_test, SendMessageToRouDi_EmptyMessage)
{
const auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);
EXPECT_EQ(true, status);
}
TEST_F(PoshRuntime_test, SendRequestToRouDi_ValidMessage)
{
m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << std::string("/sender")
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_runnableName;
const auto status = m_senderRuntime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);
EXPECT_EQ(true, status);
}
TEST_F(PoshRuntime_test, SendRequestToRouDi_InvalidMessage)
{
m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << std::string("/sender")
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_invalidRunnableName;
const auto status = m_senderRuntime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);
EXPECT_EQ(false, status);
}
TEST_F(PoshRuntime_test, GetMiddlewareSender_ReturnValue)
{
const auto senderPort = m_senderRuntime->getMiddlewareSender(
iox::capro::ServiceDescription(99u, 1u, 20u), m_runnableName, iox::runtime::PortConfigInfo(11u, 22u, 33u));
EXPECT_EQ(iox::capro::ServiceDescription(99u, 1u, 20u), senderPort->m_serviceDescription);
EXPECT_EQ(22u, senderPort->m_memoryInfo.deviceId);
EXPECT_EQ(33u, senderPort->m_memoryInfo.memoryType);
}
TEST_F(PoshRuntime_test, GetMiddlewareSender_DefaultArgs)
{
const auto senderPort = m_senderRuntime->getMiddlewareSender(iox::capro::ServiceDescription(99u, 1u, 20u));
EXPECT_EQ(0u, senderPort->m_memoryInfo.deviceId);
EXPECT_EQ(0u, senderPort->m_memoryInfo.memoryType);
}
TEST_F(PoshRuntime_test, GetMiddlewareSender_SenderlistOverflow)
{
m_errorHandlerCalled = false;
for (uint32_t i = 0u; i < iox::MAX_PORT_NUMBER; ++i)
{
m_senderRuntime->getMiddlewareSender(iox::capro::ServiceDescription(i, i + 1u, i + 2u));
}
EXPECT_TRUE(m_errorHandlerCalled);
}
TEST_F(PoshRuntime_test, GetMiddlewareReceiver_ReturnValue)
{
auto receiverPort = m_receiverRuntime->getMiddlewareReceiver(
iox::capro::ServiceDescription(99u, 1u, 20u), m_runnableName, iox::runtime::PortConfigInfo(11u, 22u, 33u));
EXPECT_EQ(iox::capro::ServiceDescription(99u, 1u, 20u), receiverPort->m_serviceDescription);
EXPECT_EQ(22u, receiverPort->m_memoryInfo.deviceId);
EXPECT_EQ(33u, receiverPort->m_memoryInfo.memoryType);
}
TEST_F(PoshRuntime_test, GetMiddlewareReceiver_DefaultArgs)
{
auto receiverPort = m_receiverRuntime->getMiddlewareReceiver(iox::capro::ServiceDescription(99u, 1u, 20u));
EXPECT_EQ(0u, receiverPort->m_memoryInfo.deviceId);
EXPECT_EQ(0u, receiverPort->m_memoryInfo.memoryType);
}
TEST_F(PoshRuntime_test, GetMiddlewareReceiver_ReceiverlistOverflow)
{
m_errorHandlerCalled = false;
for (uint32_t i = 0u; i < iox::MAX_PORT_NUMBER + 1; ++i)
{
m_senderRuntime->getMiddlewareReceiver(iox::capro::ServiceDescription(i, i + 1u, i + 2u));
}
EXPECT_TRUE(m_errorHandlerCalled);
}
TEST_F(PoshRuntime_test, GetServiceRegistryChangeCounter_OfferStopOfferService)
{
auto initialValue = m_senderRuntime->getServiceRegistryChangeCounter();
EXPECT_EQ(5u, *initialValue);
m_senderRuntime->offerService({"service1", "instance1"});
this->InterOpWait();
auto counter = m_senderRuntime->getServiceRegistryChangeCounter();
EXPECT_EQ(6u, *counter);
m_senderRuntime->stopOfferService({"service1", "instance1"});
this->InterOpWait();
EXPECT_EQ(7u, *counter);
}
TEST_F(PoshRuntime_test, CreateRunnable_ReturnValue)
{
const uint32_t runnableDeviceIdentifier = 1u;
iox::runtime::RunnableProperty runnableProperty(iox::cxx::CString100("testRunnable"), runnableDeviceIdentifier);
auto runableData = m_senderRuntime->createRunnable(runnableProperty);
EXPECT_EQ(std::string("/sender"), runableData->m_process);
EXPECT_EQ(iox::cxx::CString100("testRunnable"), runableData->m_runnable);
/// @todo I am passing runnableDeviceIdentifier as 1, but it returns 0, is this expected?
// EXPECT_EQ(runnableDeviceIdentifier, runableData->m_runnableDeviceIdentifier);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_utils/cxx/deadline_timer.hpp"
#include "iceoryx_utils/internal/posix_wrapper/mutex.hpp"
#include "test.hpp"
#include <thread>
using namespace ::testing;
using namespace iox::units::duration_literals;
class Mutex_test : public Test
{
public:
class MutexMock : public iox::posix::mutex
{
public:
MutexMock(const bool isRecursive)
: iox::posix::mutex(isRecursive)
{
}
};
void SetUp() override
{
internal::CaptureStderr();
}
void TearDown() override
{
std::string output = internal::GetCapturedStderr();
if (Test::HasFailure())
{
std::cout << output << std::endl;
}
}
iox::posix::mutex sut{false};
};
TEST_F(Mutex_test, TryLockWithNoLock)
{
EXPECT_THAT(sut.try_lock(), Eq(true));
EXPECT_THAT(sut.unlock(), Eq(true));
}
TEST_F(Mutex_test, TryLockWithLock)
{
EXPECT_THAT(sut.lock(), Eq(true));
EXPECT_THAT(sut.try_lock(), Eq(false));
EXPECT_THAT(sut.unlock(), Eq(true));
}
TEST_F(Mutex_test, LockAndUnlock)
{
EXPECT_THAT(sut.lock(), Eq(true));
EXPECT_THAT(sut.unlock(), Eq(true));
}
// in qnx you can destroy a locked mutex, without error if the thread holding the lock is destructing it.
TEST_F(Mutex_test, DestructorFailsOnLockedMutex)
{
std::string output = internal::GetCapturedStderr();
std::set_terminate([]() { std::cout << "", std::abort(); });
EXPECT_DEATH(
{
std::thread* t;
{
iox::posix::mutex mtx{false};
constexpr iox::units::Duration mutexTimerDuration = 1000_ms;
constexpr iox::units::Duration threadTimerDuration = 5000_ms;
iox::cxx::DeadlineTimer mutexTimer(mutexTimerDuration);
t = new std::thread([&] {
mtx.lock();
iox::cxx::DeadlineTimer ct(threadTimerDuration);
std::this_thread::sleep_for(std::chrono::milliseconds(2 * threadTimerDuration.milliSeconds()));
});
std::this_thread::sleep_for(std::chrono::milliseconds(2 * mutexTimerDuration.milliSeconds()));
}
t->join();
delete t;
},
".*");
internal::CaptureStderr();
}
<commit_msg>iox-#484 remove the thread usage for the posix lock mutex test<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_utils/cxx/deadline_timer.hpp"
#include "iceoryx_utils/internal/posix_wrapper/mutex.hpp"
#include "test.hpp"
#include <thread>
using namespace ::testing;
using namespace iox::units::duration_literals;
class Mutex_test : public Test
{
public:
class MutexMock : public iox::posix::mutex
{
public:
MutexMock(const bool isRecursive)
: iox::posix::mutex(isRecursive)
{
}
};
void SetUp() override
{
internal::CaptureStderr();
}
void TearDown() override
{
std::string output = internal::GetCapturedStderr();
if (Test::HasFailure())
{
std::cout << output << std::endl;
}
}
iox::posix::mutex sut{false};
};
TEST_F(Mutex_test, TryLockWithNoLock)
{
EXPECT_THAT(sut.try_lock(), Eq(true));
EXPECT_THAT(sut.unlock(), Eq(true));
}
TEST_F(Mutex_test, TryLockWithLock)
{
EXPECT_THAT(sut.lock(), Eq(true));
EXPECT_THAT(sut.try_lock(), Eq(false));
EXPECT_THAT(sut.unlock(), Eq(true));
}
TEST_F(Mutex_test, LockAndUnlock)
{
EXPECT_THAT(sut.lock(), Eq(true));
EXPECT_THAT(sut.unlock(), Eq(true));
}
// in qnx you can destroy a locked mutex, without error if the thread holding the lock is destructing it.
TEST_F(Mutex_test, DestructorFailsOnLockedMutex)
{
std::string output = internal::GetCapturedStderr();
std::set_terminate([]() { std::cout << "", std::abort(); });
EXPECT_DEATH(
{
iox::posix::mutex mtx{false};
mtx.lock();
},
".*");
internal::CaptureStderr();
}
<|endoftext|>
|
<commit_before>#include "astutil.h"
#include "expr.h"
#include "passes.h"
#include "stmt.h"
#include "stringutil.h"
#include "optimizations.h"
//
// inlines the function called by 'call' at that call site
//
static void
inlineCall(CallExpr* call) {
currentFilename = call->filename;
currentLineno = call->lineno;
Expr* stmt = call->getStmtExpr();
FnSymbol* fn = call->isResolved();
//
// insert temporary symbols for all actuals that require one and
// calculate a map from actual symbols to formal symbols
//
// sjd: do we need these temporaries given those we insert inside a
// function during resolution to maintain copy semantics
//
ASTMap map;
for_formals_actuals(formal, actual, call) {
if (SymExpr* se = toSymExpr(actual)) {
map.put(formal, se->var);
} else {
//
// try to eliminate temporaries
//
if (formal->requiresCPtr())
INT_FATAL(actual, "illegal reference actual encountered in inlining");
VarSymbol* temp = new VarSymbol("_tmp", actual->typeInfo());
temp->isCompilerTemp = true;
stmt->insertBefore(new DefExpr(temp));
stmt->insertBefore(new CallExpr(PRIMITIVE_MOVE, temp, actual->remove()));
map.put(formal, temp);
}
}
//
// copy function body, inline it at call site, and update return
//
BlockStmt* block = fn->body->copy(&map);
reset_file_info(block, call->lineno, call->filename);
CallExpr* return_stmt = toCallExpr(block->body.last());
if (!return_stmt || !return_stmt->isPrimitive(PRIMITIVE_RETURN))
INT_FATAL(call, "function is not normalized");
Expr* return_value = return_stmt->get(1);
SymExpr* se = toSymExpr(return_value);
if (!se || isArgSymbol(se->var))
INT_FATAL(fn, "inlined function cannot return an argument symbol");
return_stmt->remove();
return_value->remove();
stmt->insertBefore(block);
if (fn->retType == dtVoid)
stmt->remove();
else
call->replace(return_value);
}
//
// inline function fn at all call sites
// add inlined function to inlinedSet
// inline any functions that are called from within this function and
// should be inlined first
//
static void
inlineFunction(FnSymbol* fn, Vec<FnSymbol*>& inlinedSet) {
inlinedSet.set_add(fn);
Vec<BaseAST*> asts;
collect_asts(&asts, fn);
forv_Vec(BaseAST, ast, asts) {
if (CallExpr* call = toCallExpr(ast)) {
if (FnSymbol* fn = call->isResolved()) {
if (call->parentSymbol && fn->hasPragma("inline")) {
if (inlinedSet.set_in(fn))
INT_FATAL(call, "recursive inlining detected");
inlineFunction(fn, inlinedSet);
}
}
}
}
collapseBlocks(fn->body);
removeUnnecessaryGotos(fn);
if (!fNoCopyPropagation)
localCopyPropagation(fn);
if (!fNoDeadCodeElimination)
deadVariableElimination(fn);
deadExpressionElimination(fn);
forv_Vec(CallExpr, call, *fn->calledBy) {
inlineCall(call);
if (report_inlining)
printf("chapel compiler: reporting inlining"
", %s function was inlined\n", fn->cname);
}
}
//
// inline all functions with the inline pragma
// remove unnecessary block statements and gotos
//
void
inlineFunctions(void) {
if (fNoInline) {
forv_Vec(FnSymbol, fn, gFns) {
collapseBlocks(fn->body);
removeUnnecessaryGotos(fn);
deadExpressionElimination(fn);
}
return;
}
compute_call_sites();
Vec<FnSymbol*> inlinedSet;
forv_Vec(FnSymbol, fn, gFns) {
if (fn->hasPragma("inline") && !inlinedSet.set_in(fn))
inlineFunction(fn, inlinedSet);
}
forv_Vec(FnSymbol, fn, gFns) {
if (fn->hasPragma("inline")) {
fn->defPoint->remove();
} else {
collapseBlocks(fn->body);
removeUnnecessaryGotos(fn);
}
}
}
<commit_msg>improved debug back-tracing through inlining<commit_after>#include "astutil.h"
#include "expr.h"
#include "passes.h"
#include "stmt.h"
#include "stringutil.h"
#include "optimizations.h"
//
// copyMap is useful for debugging when trying to determine where an
// expression or symbol came from; since it may be copied many times
// when inlining functions inside functions inside functions ..., the
// copyMap points to the original, a BaseAST that existed before this
// pass even started.
//
// example: If you want to see where a CallExpr, say with id ==
// 813899, came from before inlining, just trace it back in the
// copyMap when breaking at the end of inlineFunctions. You need to
// break before the next pass because the inlined functions will be
// deleted. To trace it back, use the following:
//
// (gdb) p copyMap.get(ast(813899))->id
// 809206
// (gdb) p copyMap.get(ast(809206))->id
// 809157
// (gdb) p copyMap.get(ast(809157))->id
// 663565
//
// Then to see the ast in the original function, use
//
// (gdb) lv ast(663565)
//
// To make the copyMap active, uncomment the line
//
//#define _INLINE_FUNCTIONS_USE_COPY_MAP_
//
#ifdef _INLINE_FUNCTIONS_USE_COPY_MAP_
static Map<BaseAST*,BaseAST*> copyMap;
#endif
//
// inlines the function called by 'call' at that call site
//
static void
inlineCall(CallExpr* call) {
currentFilename = call->filename;
currentLineno = call->lineno;
Expr* stmt = call->getStmtExpr();
FnSymbol* fn = call->isResolved();
//
// insert temporary symbols for all actuals that require one and
// calculate a map from actual symbols to formal symbols
//
// sjd: do we need these temporaries given those we insert inside a
// function during resolution to maintain copy semantics
//
ASTMap map;
for_formals_actuals(formal, actual, call) {
if (SymExpr* se = toSymExpr(actual)) {
map.put(formal, se->var);
} else {
//
// try to eliminate temporaries
//
if (formal->requiresCPtr())
INT_FATAL(actual, "illegal reference actual encountered in inlining");
VarSymbol* temp = new VarSymbol("_tmp", actual->typeInfo());
temp->isCompilerTemp = true;
stmt->insertBefore(new DefExpr(temp));
stmt->insertBefore(new CallExpr(PRIMITIVE_MOVE, temp, actual->remove()));
map.put(formal, temp);
}
}
//
// copy function body, inline it at call site, and update return
//
BlockStmt* block = fn->body->copy(&map);
#ifdef _INLINE_FUNCTIONS_USE_COPY_MAP_
form_Map(ASTMapElem, e, map) {
copyMap.put(e->value, e->key);
}
#endif
reset_file_info(block, call->lineno, call->filename);
CallExpr* return_stmt = toCallExpr(block->body.last());
if (!return_stmt || !return_stmt->isPrimitive(PRIMITIVE_RETURN))
INT_FATAL(call, "function is not normalized");
Expr* return_value = return_stmt->get(1);
SymExpr* se = toSymExpr(return_value);
if (!se || isArgSymbol(se->var))
INT_FATAL(fn, "inlined function cannot return an argument symbol");
return_stmt->remove();
return_value->remove();
stmt->insertBefore(block);
if (fn->retType == dtVoid)
stmt->remove();
else
call->replace(return_value);
}
//
// inline function fn at all call sites
// add inlined function to inlinedSet
// inline any functions that are called from within this function and
// should be inlined first
//
static void
inlineFunction(FnSymbol* fn, Vec<FnSymbol*>& inlinedSet) {
inlinedSet.set_add(fn);
Vec<BaseAST*> asts;
collect_asts(&asts, fn);
forv_Vec(BaseAST, ast, asts) {
if (CallExpr* call = toCallExpr(ast)) {
if (FnSymbol* fn = call->isResolved()) {
if (call->parentSymbol && fn->hasPragma("inline")) {
if (inlinedSet.set_in(fn))
INT_FATAL(call, "recursive inlining detected");
inlineFunction(fn, inlinedSet);
}
}
}
}
collapseBlocks(fn->body);
removeUnnecessaryGotos(fn);
if (!fNoCopyPropagation)
localCopyPropagation(fn);
if (!fNoDeadCodeElimination)
deadVariableElimination(fn);
deadExpressionElimination(fn);
forv_Vec(CallExpr, call, *fn->calledBy) {
inlineCall(call);
if (report_inlining)
printf("chapel compiler: reporting inlining"
", %s function was inlined\n", fn->cname);
}
}
//
// inline all functions with the inline pragma
// remove unnecessary block statements and gotos
//
void
inlineFunctions(void) {
if (fNoInline) {
forv_Vec(FnSymbol, fn, gFns) {
collapseBlocks(fn->body);
removeUnnecessaryGotos(fn);
deadExpressionElimination(fn);
}
return;
}
compute_call_sites();
Vec<FnSymbol*> inlinedSet;
forv_Vec(FnSymbol, fn, gFns) {
if (fn->hasPragma("inline") && !inlinedSet.set_in(fn))
inlineFunction(fn, inlinedSet);
}
forv_Vec(FnSymbol, fn, gFns) {
if (fn->hasPragma("inline")) {
fn->defPoint->remove();
} else {
collapseBlocks(fn->body);
removeUnnecessaryGotos(fn);
}
}
}
<|endoftext|>
|
<commit_before>#include <LineBuffer.hpp>
#include "catch.hpp"
using namespace yb;
TEST_CASE( "can create empty LineBuffer", "[LineBuffer.empty]") {
LineBuffer buf;
REQUIRE(buf.empty());
REQUIRE(buf.getPosition() == 0);
}
TEST_CASE( "can insert a char to the empty LineBuffer", "[LineBuffer.insert]" ) {
auto testCharacter = [=] (char c) {
LineBuffer buf;
buf.insert(c);
std::string result{buf.get()};
REQUIRE(buf.getChar() == 0);
REQUIRE(buf.getPosition() == 1);
REQUIRE(result == std::string{c});
REQUIRE_FALSE(buf.empty());
};
std::string domain = "abcdefghijklmnopqrstuvwxyz01234567890-_";
for_each(domain.begin(), domain.end(), testCharacter);
}
TEST_CASE( "can insert multiple chars", "[LineBuffer.multiple]" ) {
LineBuffer buf;
buf.insert('a');
REQUIRE(std::string{buf.get()} == "a");
REQUIRE(buf.getPosition() == 1);
buf.insert('b');
REQUIRE(std::string{buf.get()} == "ab");
REQUIRE(buf.getPosition() == 2);
buf.insert('c');
REQUIRE(std::string{buf.get()} == "abc");
REQUIRE(buf.getPosition() == 3);
}
TEST_CASE( "remove can't break it", "[LineBuffer.emptyRemove]" ) {
LineBuffer buf;
for (int i = 0; i < 100; i++) {
buf.remove();
REQUIRE(std::string{buf.get()} == "");
REQUIRE(buf.getPosition() == 0);
}
}
TEST_CASE( "can delete last character", "[LineBuffer.deleteLast]" ) {
LineBuffer buf;
buf.insert('a');
buf.insert('b');
buf.insert('c');
buf.insert('d');
buf.remove();
REQUIRE(std::string{buf.get()} == "abc");
buf.remove();
REQUIRE(std::string{buf.get()} == "ab");
buf.remove();
REQUIRE(std::string{buf.get()} == "a");
}
TEST_CASE( "can move in buffer and insert/delete characters", "[LineBuffer.move]" ) {
LineBuffer buf;
buf.insert('a');
buf.insert('b');
buf.insert('c');
buf.insert('d');
buf.move(-1);
REQUIRE(buf.getChar() == 'd');
buf.remove();
REQUIRE(std::string{buf.get()} == "abd");
buf.insert('z');
REQUIRE(std::string{buf.get()} == "abzd");
buf.insert('x');
REQUIRE(std::string{buf.get()} == "abzxd");
buf.move(1);
buf.insert('c');
REQUIRE(std::string{buf.get()} == "abzxdc");
}
<commit_msg>Add missing test for LineBuffer<commit_after>#include <LineBuffer.hpp>
#include "catch.hpp"
using namespace yb;
TEST_CASE( "can create empty LineBuffer", "[LineBuffer.empty]") {
LineBuffer buf;
REQUIRE(buf.empty());
REQUIRE(buf.getPosition() == 0);
}
TEST_CASE( "can insert a char to the empty LineBuffer", "[LineBuffer.insert]" ) {
auto testCharacter = [=] (char c) {
LineBuffer buf;
buf.insert(c);
std::string result{buf.get()};
REQUIRE(buf.getChar() == 0);
REQUIRE(buf.getPosition() == 1);
REQUIRE(result == std::string{c});
REQUIRE_FALSE(buf.empty());
};
std::string domain = "abcdefghijklmnopqrstuvwxyz01234567890-_";
for_each(domain.begin(), domain.end(), testCharacter);
}
TEST_CASE( "can insert multiple chars", "[LineBuffer.multiple]" ) {
LineBuffer buf;
buf.insert('a');
REQUIRE(std::string{buf.get()} == "a");
REQUIRE(buf.getPosition() == 1);
buf.insert('b');
REQUIRE(std::string{buf.get()} == "ab");
REQUIRE(buf.getPosition() == 2);
buf.insert('c');
REQUIRE(std::string{buf.get()} == "abc");
REQUIRE(buf.getPosition() == 3);
}
TEST_CASE( "remove can't break it", "[LineBuffer.emptyRemove]" ) {
LineBuffer buf;
for (int i = 0; i < 100; i++) {
buf.remove();
REQUIRE(std::string{buf.get()} == "");
REQUIRE(buf.getPosition() == 0);
}
}
TEST_CASE( "can delete last character", "[LineBuffer.deleteLast]" ) {
LineBuffer buf;
buf.insert('a');
buf.insert('b');
buf.insert('c');
buf.insert('d');
buf.remove();
REQUIRE(std::string{buf.get()} == "abc");
buf.remove();
REQUIRE(std::string{buf.get()} == "ab");
buf.remove();
REQUIRE(std::string{buf.get()} == "a");
}
TEST_CASE( "can move in buffer and insert/delete characters", "[LineBuffer.move]" ) {
LineBuffer buf;
buf.insert('a');
buf.insert('b');
buf.insert('c');
buf.insert('d');
buf.move(-1);
REQUIRE(buf.getChar() == 'd');
buf.remove();
REQUIRE(std::string{buf.get()} == "abd");
buf.insert('z');
REQUIRE(std::string{buf.get()} == "abzd");
buf.insert('x');
REQUIRE(std::string{buf.get()} == "abzxd");
buf.move(1);
buf.insert('c');
REQUIRE(std::string{buf.get()} == "abzxdc");
}
TEST_CASE( "moving backwards can't break LineBuffer", "[LineBuffer.moveCantBreak]") {
LineBuffer buf;
for (int i = 0; i < 1025; ++i) {
buf.move(-i);
REQUIRE(buf.getPosition() == 0);
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2015 Estimation and Control Library (ECL). All rights reserved.
*
* 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 ECL 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.
*
****************************************************************************/
/**
* @file vel_pos_fusion.cpp
* Function for fusing gps and baro measurements/
*
* @author Roman Bast <bapstroman@gmail.com>
*
*/
#include "ekf.h"
#include "mathlib.h"
void Ekf::fuseVelPosHeight()
{
bool fuse_map[6] = {}; // map of booelans true when [VN,VE,VD,PN,PE,PD] observations are available
bool innov_check_pass_map[6] = {}; // true when innovations consistency checks pass for [VN,VE,VD,PN,PE,PD] observations
float R[6] = {}; // observation variances for [VN,VE,VD,PN,PE,PD]
float gate_size[6] = {}; // innovation consistency check gate sizes for [VN,VE,VD,PN,PE,PD] observations
float Kfusion[24] = {}; // Kalman gain vector for any single observation - sequential fusion is used
// calculate innovations, innovations gate sizes and observation variances
if (_fuse_hor_vel) {
fuse_map[0] = fuse_map[1] = true;
// horizontal velocity innovations
_vel_pos_innov[0] = _state.vel(0) - _gps_sample_delayed.vel(0);
_vel_pos_innov[1] = _state.vel(1) - _gps_sample_delayed.vel(1);
// observation variance - use receiver reported accuracy with parameter setting the minimum value
R[0] = fmaxf(_params.gps_vel_noise, 0.01f);
R[0] = fmaxf(R[0], _gps_speed_accuracy);
R[0] = R[0] * R[0];
R[1] = R[0];
// innovation gate sizes
gate_size[0] = fmaxf(_params.vel_innov_gate, 1.0f);
gate_size[1] = gate_size[0];
}
if (_fuse_vert_vel) {
fuse_map[2] = true;
// vertical velocity innovation
_vel_pos_innov[2] = _state.vel(2) - _gps_sample_delayed.vel(2);
// observation variance - use receiver reported accuracy with parameter setting the minimum value
R[2] = fmaxf(_params.gps_vel_noise, 0.01f);
// use scaled horizontal speed accuracy assuming typical ratio of VDOP/HDOP
R[2] = 1.5f * fmaxf(R[2], _gps_speed_accuracy);
R[2] = R[2] * R[2];
// innovation gate size
gate_size[2] = fmaxf(_params.vel_innov_gate, 1.0f);
}
if (_fuse_pos) {
fuse_map[3] = fuse_map[4] = true;
// horizontal position innovations
_vel_pos_innov[3] = _state.pos(0) - _gps_sample_delayed.pos(0);
_vel_pos_innov[4] = _state.pos(1) - _gps_sample_delayed.pos(1);
// observation variance - user parameter defined
// if we are in flight and not using GPS, then use a specific parameter
if (!_control_status.flags.gps && _control_status.flags.in_air) {
R[3] = fmaxf(_params.pos_noaid_noise, 0.5f);
} else {
float lower_limit = fmaxf(_params.gps_pos_noise, 0.01f);
float upper_limit = fmaxf(_params.pos_noaid_noise, lower_limit);
R[3] = math::constrain(_gps_hpos_accuracy, lower_limit, upper_limit);
}
R[3] = R[3] * R[3];
R[4] = R[3];
// innovation gate sizes
gate_size[3] = fmaxf(_params.posNE_innov_gate, 1.0f);
gate_size[4] = gate_size[3];
}
if (_fuse_height) {
fuse_map[5] = true;
// vertical position innovation - baro measurement has opposite sign to earth z axis
_vel_pos_innov[5] = _state.pos(2) - (_baro_at_alignment - _baro_sample_delayed.hgt);
// observation variance - user parameter defined
R[5] = fmaxf(_params.baro_noise, 0.01f);
R[5] = R[5] * R[5];
// innovation gate size
gate_size[5] = fmaxf(_params.baro_innov_gate, 1.0f);
}
// calculate innovation test ratios
for (unsigned obs_index = 0; obs_index < 6; obs_index++) {
if (fuse_map[obs_index]) {
// compute the innovation variance SK = HPH + R
unsigned state_index = obs_index + 3; // we start with vx and this is the 4. state
_vel_pos_innov_var[obs_index] = P[state_index][state_index] + R[obs_index];
// Compute the ratio of innovation to gate size
_vel_pos_test_ratio[obs_index] = sq(_vel_pos_innov[obs_index]) / (sq(gate_size[obs_index]) * _vel_pos_innov_var[obs_index]);
}
}
// check position, velocity and height innovations
// treat 3D velocity, 2D position and height as separate sensors
// always pass position checks if using synthetic position measurements
bool vel_check_pass = (_vel_pos_test_ratio[0] <= 1.0f) && (_vel_pos_test_ratio[1] <= 1.0f)
&& (_vel_pos_test_ratio[2] <= 1.0f);
innov_check_pass_map[2] = innov_check_pass_map[1] = innov_check_pass_map[0] = vel_check_pass;
bool using_synthetic_measurements = !_control_status.flags.gps && !_control_status.flags.opt_flow;
bool pos_check_pass = ((_vel_pos_test_ratio[3] <= 1.0f) && (_vel_pos_test_ratio[4] <= 1.0f))
|| using_synthetic_measurements;
innov_check_pass_map[4] = innov_check_pass_map[3] = pos_check_pass;
innov_check_pass_map[5] = (_vel_pos_test_ratio[5] <= 1.0f);
// record the successful velocity fusion time
if (vel_check_pass && _fuse_hor_vel) {
_time_last_vel_fuse = _time_last_imu;
}
// record the successful position fusion time
if (pos_check_pass && _fuse_pos) {
_time_last_pos_fuse = _time_last_imu;
}
// record the successful height fusion time
if (innov_check_pass_map[5] && _fuse_height) {
_time_last_hgt_fuse = _time_last_imu;
}
for (unsigned obs_index = 0; obs_index < 6; obs_index++) {
// skip fusion if not requested or checks have failed
if (!fuse_map[obs_index] || !innov_check_pass_map[obs_index]) {
continue;
}
unsigned state_index = obs_index + 3; // we start with vx and this is the 4. state
// calculate kalman gain K = PHS, where S = 1/innovation variance
for (int row = 0; row <= 15; row++) {
Kfusion[row] = P[row][state_index] / _vel_pos_innov_var[obs_index];
}
// only update magnetic field states if we are fusing 3-axis observations
if (_control_status.flags.mag_3D) {
for (int row = 16; row <= 21; row++) {
Kfusion[row] = P[row][state_index] / _vel_pos_innov_var[obs_index];
}
} else {
for (int row = 16; row <= 21; row++) {
Kfusion[row] = 0.0f;
}
}
// only update wind states if we are doing wind estimation
if (_control_status.flags.wind) {
for (int row = 22; row <= 23; row++) {
Kfusion[row] = P[row][state_index] / _vel_pos_innov_var[obs_index];
}
} else {
for (int row = 22; row <= 23; row++) {
Kfusion[row] = 0.0f;
}
}
// by definition the angle error state is zero at the fusion time
_state.ang_error.setZero();
// fuse the observation
fuse(Kfusion, _vel_pos_innov[obs_index]);
// correct the nominal quaternion
Quaternion dq;
dq.from_axis_angle(_state.ang_error);
_state.quat_nominal = dq * _state.quat_nominal;
_state.quat_nominal.normalize();
// update covarinace matrix via Pnew = (I - KH)P
float KHP[_k_num_states][_k_num_states] = {};
for (unsigned row = 0; row < _k_num_states; row++) {
for (unsigned column = 0; column < _k_num_states; column++) {
KHP[row][column] = Kfusion[row] * P[state_index][column];
}
}
for (unsigned row = 0; row < _k_num_states; row++) {
for (unsigned column = 0; column < _k_num_states; column++) {
P[row][column] = P[row][column] - KHP[row][column];
}
}
makeSymmetrical();
limitCov();
}
}
<commit_msg>EKF: Add support for range-finder fusion as primary height reference<commit_after>/****************************************************************************
*
* Copyright (c) 2015 Estimation and Control Library (ECL). All rights reserved.
*
* 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 ECL 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.
*
****************************************************************************/
/**
* @file vel_pos_fusion.cpp
* Function for fusing gps and baro measurements/
*
* @author Roman Bast <bapstroman@gmail.com>
* @author Siddharth Bharat Purohit <siddharthbharatpurohit@gmail.com>
* @author Paul Riseborough <p_riseborough@live.com.au>
*
*/
#include "ekf.h"
#include "mathlib.h"
void Ekf::fuseVelPosHeight()
{
bool fuse_map[6] = {}; // map of booelans true when [VN,VE,VD,PN,PE,PD] observations are available
bool innov_check_pass_map[6] = {}; // true when innovations consistency checks pass for [VN,VE,VD,PN,PE,PD] observations
float R[6] = {}; // observation variances for [VN,VE,VD,PN,PE,PD]
float gate_size[6] = {}; // innovation consistency check gate sizes for [VN,VE,VD,PN,PE,PD] observations
float Kfusion[24] = {}; // Kalman gain vector for any single observation - sequential fusion is used
// calculate innovations, innovations gate sizes and observation variances
if (_fuse_hor_vel) {
fuse_map[0] = fuse_map[1] = true;
// horizontal velocity innovations
_vel_pos_innov[0] = _state.vel(0) - _gps_sample_delayed.vel(0);
_vel_pos_innov[1] = _state.vel(1) - _gps_sample_delayed.vel(1);
// observation variance - use receiver reported accuracy with parameter setting the minimum value
R[0] = fmaxf(_params.gps_vel_noise, 0.01f);
R[0] = fmaxf(R[0], _gps_speed_accuracy);
R[0] = R[0] * R[0];
R[1] = R[0];
// innovation gate sizes
gate_size[0] = fmaxf(_params.vel_innov_gate, 1.0f);
gate_size[1] = gate_size[0];
}
if (_fuse_vert_vel) {
fuse_map[2] = true;
// vertical velocity innovation
_vel_pos_innov[2] = _state.vel(2) - _gps_sample_delayed.vel(2);
// observation variance - use receiver reported accuracy with parameter setting the minimum value
R[2] = fmaxf(_params.gps_vel_noise, 0.01f);
// use scaled horizontal speed accuracy assuming typical ratio of VDOP/HDOP
R[2] = 1.5f * fmaxf(R[2], _gps_speed_accuracy);
R[2] = R[2] * R[2];
// innovation gate size
gate_size[2] = fmaxf(_params.vel_innov_gate, 1.0f);
}
if (_fuse_pos) {
fuse_map[3] = fuse_map[4] = true;
// horizontal position innovations
_vel_pos_innov[3] = _state.pos(0) - _gps_sample_delayed.pos(0);
_vel_pos_innov[4] = _state.pos(1) - _gps_sample_delayed.pos(1);
// observation variance - user parameter defined
// if we are in flight and not using GPS, then use a specific parameter
if (!_control_status.flags.gps && _control_status.flags.in_air) {
R[3] = fmaxf(_params.pos_noaid_noise, 0.5f);
} else {
float lower_limit = fmaxf(_params.gps_pos_noise, 0.01f);
float upper_limit = fmaxf(_params.pos_noaid_noise, lower_limit);
R[3] = math::constrain(_gps_hpos_accuracy, lower_limit, upper_limit);
}
R[3] = R[3] * R[3];
R[4] = R[3];
// innovation gate sizes
gate_size[3] = fmaxf(_params.posNE_innov_gate, 1.0f);
gate_size[4] = gate_size[3];
}
if (_fuse_height) {
if (_control_status.flags.baro_hgt) {
fuse_map[5] = true;
// vertical position innovation - baro measurement has opposite sign to earth z axis
_vel_pos_innov[5] = _state.pos(2) - (_hgt_at_alignment - _baro_sample_delayed.hgt);
// observation variance - user parameter defined
R[5] = fmaxf(_params.baro_noise, 0.01f);
R[5] = R[5] * R[5];
// innovation gate size
gate_size[5] = fmaxf(_params.baro_innov_gate, 1.0f);
} else if (_control_status.flags.rng_hgt && (_R_prev(2, 2) > 0.7071f)) {
fuse_map[5] = true;
// use range finder with tilt correction
_vel_pos_innov[5] = _state.pos(2) - (-math::max(_range_sample_delayed.rng *_R_prev(2, 2),
_params.rng_gnd_clearance));
// observation variance - user parameter defined
R[5] = fmaxf(_params.range_noise, 0.01f);
R[5] = R[5] * R[5];
// innovation gate size
gate_size[5] = fmaxf(_params.range_innov_gate, 1.0f);
}
}
// calculate innovation test ratios
for (unsigned obs_index = 0; obs_index < 6; obs_index++) {
if (fuse_map[obs_index]) {
// compute the innovation variance SK = HPH + R
unsigned state_index = obs_index + 3; // we start with vx and this is the 4. state
_vel_pos_innov_var[obs_index] = P[state_index][state_index] + R[obs_index];
// Compute the ratio of innovation to gate size
_vel_pos_test_ratio[obs_index] = sq(_vel_pos_innov[obs_index]) / (sq(gate_size[obs_index]) *
_vel_pos_innov_var[obs_index]);
}
}
// check position, velocity and height innovations
// treat 3D velocity, 2D position and height as separate sensors
// always pass position checks if using synthetic position measurements
bool vel_check_pass = (_vel_pos_test_ratio[0] <= 1.0f) && (_vel_pos_test_ratio[1] <= 1.0f)
&& (_vel_pos_test_ratio[2] <= 1.0f);
innov_check_pass_map[2] = innov_check_pass_map[1] = innov_check_pass_map[0] = vel_check_pass;
bool using_synthetic_measurements = !_control_status.flags.gps && !_control_status.flags.opt_flow;
bool pos_check_pass = ((_vel_pos_test_ratio[3] <= 1.0f) && (_vel_pos_test_ratio[4] <= 1.0f))
|| using_synthetic_measurements;
innov_check_pass_map[4] = innov_check_pass_map[3] = pos_check_pass;
innov_check_pass_map[5] = (_vel_pos_test_ratio[5] <= 1.0f);
// record the successful velocity fusion time
if (vel_check_pass && _fuse_hor_vel) {
_time_last_vel_fuse = _time_last_imu;
_tilt_err_vec.setZero();
}
// record the successful position fusion time
if (pos_check_pass && _fuse_pos) {
_time_last_pos_fuse = _time_last_imu;
_tilt_err_vec.setZero();
}
// record the successful height fusion time
if (innov_check_pass_map[5] && _fuse_height) {
_time_last_hgt_fuse = _time_last_imu;
}
for (unsigned obs_index = 0; obs_index < 6; obs_index++) {
// skip fusion if not requested or checks have failed
if (!fuse_map[obs_index] || !innov_check_pass_map[obs_index]) {
continue;
}
unsigned state_index = obs_index + 3; // we start with vx and this is the 4. state
// calculate kalman gain K = PHS, where S = 1/innovation variance
for (int row = 0; row <= 15; row++) {
Kfusion[row] = P[row][state_index] / _vel_pos_innov_var[obs_index];
}
// only update magnetic field states if we are fusing 3-axis observations
if (_control_status.flags.mag_3D) {
for (int row = 16; row <= 21; row++) {
Kfusion[row] = P[row][state_index] / _vel_pos_innov_var[obs_index];
}
} else {
for (int row = 16; row <= 21; row++) {
Kfusion[row] = 0.0f;
}
}
// only update wind states if we are doing wind estimation
if (_control_status.flags.wind) {
for (int row = 22; row <= 23; row++) {
Kfusion[row] = P[row][state_index] / _vel_pos_innov_var[obs_index];
}
} else {
for (int row = 22; row <= 23; row++) {
Kfusion[row] = 0.0f;
}
}
// sum the attitude error from velocity and position fusion only
// used as a metric for convergence monitoring
if (obs_index != 5) {
_tilt_err_vec += _state.ang_error;
}
// by definition the angle error state is zero at the fusion time
_state.ang_error.setZero();
// fuse the observation
fuse(Kfusion, _vel_pos_innov[obs_index]);
// correct the nominal quaternion
Quaternion dq;
dq.from_axis_angle(_state.ang_error);
_state.quat_nominal = dq * _state.quat_nominal;
_state.quat_nominal.normalize();
// update covarinace matrix via Pnew = (I - KH)P
float KHP[_k_num_states][_k_num_states] = {};
for (unsigned row = 0; row < _k_num_states; row++) {
for (unsigned column = 0; column < _k_num_states; column++) {
KHP[row][column] = Kfusion[row] * P[state_index][column];
}
}
for (unsigned row = 0; row < _k_num_states; row++) {
for (unsigned column = 0; column < _k_num_states; column++) {
P[row][column] = P[row][column] - KHP[row][column];
}
}
makeSymmetrical();
limitCov();
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* canvas_group.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "canvas_group.h"
void CanvasGroup::set_fit_margin(float p_fit_margin) {
ERR_FAIL_COND(p_fit_margin < 0.0);
fit_margin = p_fit_margin;
RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CANVAS_GROUP_MODE_TRANSPARENT, clear_margin, true, fit_margin, use_mipmaps);
update();
}
float CanvasGroup::get_fit_margin() const {
return fit_margin;
}
void CanvasGroup::set_clear_margin(float p_clear_margin) {
ERR_FAIL_COND(p_clear_margin < 0.0);
clear_margin = p_clear_margin;
RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CANVAS_GROUP_MODE_TRANSPARENT, clear_margin, true, clear_margin, use_mipmaps);
update();
}
float CanvasGroup::get_clear_margin() const {
return clear_margin;
}
void CanvasGroup::set_use_mipmaps(bool p_use_mipmaps) {
use_mipmaps = p_use_mipmaps;
RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CANVAS_GROUP_MODE_TRANSPARENT, clear_margin, true, fit_margin, use_mipmaps);
}
bool CanvasGroup::is_using_mipmaps() const {
return use_mipmaps;
}
void CanvasGroup::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_fit_margin", "fit_margin"), &CanvasGroup::set_fit_margin);
ClassDB::bind_method(D_METHOD("get_fit_margin"), &CanvasGroup::get_fit_margin);
ClassDB::bind_method(D_METHOD("set_clear_margin", "clear_margin"), &CanvasGroup::set_clear_margin);
ClassDB::bind_method(D_METHOD("get_clear_margin"), &CanvasGroup::get_clear_margin);
ClassDB::bind_method(D_METHOD("set_use_mipmaps", "use_mipmaps"), &CanvasGroup::set_use_mipmaps);
ClassDB::bind_method(D_METHOD("is_using_mipmaps"), &CanvasGroup::is_using_mipmaps);
ADD_GROUP("Tweaks", "");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fit_margin", PROPERTY_HINT_RANGE, "0,1024,1.0,or_greater"), "set_fit_margin", "get_fit_margin");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "clear_margin", PROPERTY_HINT_RANGE, "0,1024,1.0,or_greater"), "set_clear_margin", "get_clear_margin");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_mipmaps"), "set_use_mipmaps", "is_using_mipmaps");
}
CanvasGroup::CanvasGroup() {
set_fit_margin(10.0); //sets things
}
CanvasGroup::~CanvasGroup() {
}
<commit_msg>Remove memory leak in Canvas Group<commit_after>/*************************************************************************/
/* canvas_group.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "canvas_group.h"
void CanvasGroup::set_fit_margin(float p_fit_margin) {
ERR_FAIL_COND(p_fit_margin < 0.0);
fit_margin = p_fit_margin;
RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CANVAS_GROUP_MODE_TRANSPARENT, clear_margin, true, fit_margin, use_mipmaps);
update();
}
float CanvasGroup::get_fit_margin() const {
return fit_margin;
}
void CanvasGroup::set_clear_margin(float p_clear_margin) {
ERR_FAIL_COND(p_clear_margin < 0.0);
clear_margin = p_clear_margin;
RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CANVAS_GROUP_MODE_TRANSPARENT, clear_margin, true, clear_margin, use_mipmaps);
update();
}
float CanvasGroup::get_clear_margin() const {
return clear_margin;
}
void CanvasGroup::set_use_mipmaps(bool p_use_mipmaps) {
use_mipmaps = p_use_mipmaps;
RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CANVAS_GROUP_MODE_TRANSPARENT, clear_margin, true, fit_margin, use_mipmaps);
}
bool CanvasGroup::is_using_mipmaps() const {
return use_mipmaps;
}
void CanvasGroup::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_fit_margin", "fit_margin"), &CanvasGroup::set_fit_margin);
ClassDB::bind_method(D_METHOD("get_fit_margin"), &CanvasGroup::get_fit_margin);
ClassDB::bind_method(D_METHOD("set_clear_margin", "clear_margin"), &CanvasGroup::set_clear_margin);
ClassDB::bind_method(D_METHOD("get_clear_margin"), &CanvasGroup::get_clear_margin);
ClassDB::bind_method(D_METHOD("set_use_mipmaps", "use_mipmaps"), &CanvasGroup::set_use_mipmaps);
ClassDB::bind_method(D_METHOD("is_using_mipmaps"), &CanvasGroup::is_using_mipmaps);
ADD_GROUP("Tweaks", "");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fit_margin", PROPERTY_HINT_RANGE, "0,1024,1.0,or_greater"), "set_fit_margin", "get_fit_margin");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "clear_margin", PROPERTY_HINT_RANGE, "0,1024,1.0,or_greater"), "set_clear_margin", "get_clear_margin");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_mipmaps"), "set_use_mipmaps", "is_using_mipmaps");
}
CanvasGroup::CanvasGroup() {
set_fit_margin(10.0); //sets things
}
CanvasGroup::~CanvasGroup() {
RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CANVAS_GROUP_MODE_DISABLED);
}
<|endoftext|>
|
<commit_before>#include <stingray/toolkit/ThreadPool.h>
#include <stingray/toolkit/bind.h>
namespace stingray
{
ThreadPool::WorkerWrapper::WorkerWrapper(const std::string& name)
: _busy(false), _worker(ITaskExecutor::Create(name))
{ }
bool ThreadPool::WorkerWrapper::TryAddTask(const function<void()>& task)
{
MutexLock l(_mutex);
if (_busy)
return false;
_busy = true;
_worker->AddTask(bind(&ThreadPool::WorkerWrapper::TaskWrapper, this, task));
return true;
}
bool ThreadPool::WorkerWrapper::TryAddTaskWithTester(const function<void()>& task, const FutureExecutionTester& tester)
{
MutexLock l(_mutex);
if (_busy)
return false;
_busy = true;
_worker->AddTask(bind(&ThreadPool::WorkerWrapper::TaskWrapper, this, task), tester);
return true;
}
void ThreadPool::WorkerWrapper::TaskWrapper(const function<void()>& task)
{
task();
{
MutexLock l(_mutex);
TOOLKIT_CHECK(_busy, "Internal TaskExecutorPool error!");
_busy = false;
}
}
///////////////////////////////////////////////////////////////
ThreadPool::ThreadPool(const std::string& name, u32 maxThreads)
: _name(name), _maxThreads(maxThreads)
{ }
void ThreadPool::Queue(const function<void()>& task)
{ DoAddTask(bind(&WorkerWrapper::TryAddTask, _1, task)); }
void ThreadPool::Queue(const function<void()>& task, const FutureExecutionTester& tester)
{ DoAddTask(bind(&WorkerWrapper::TryAddTaskWithTester, _1, task, tester)); }
void ThreadPool::DoAddTask(const function<bool(WorkerWrapper*)>& tryAddTaskFunc)
{
MutexLock l(_mutex);
for (Workers::const_iterator it = _workers.begin(); it != _workers.end(); ++it)
{
if (tryAddTaskFunc(it->get()))
return;
}
if (_workers.size() < _maxThreads)
{
WorkerWrapperPtr w(new WorkerWrapper(StringBuilder() % _name % "_" % _workers.size()));
_workers.push_back(w);
TOOLKIT_CHECK(tryAddTaskFunc(w.get()), "Internal TaskExecutorPool error!");
}
else
{
TOOLKIT_THROW(NotImplementedException());
}
}
}
<commit_msg>Added exception handling<commit_after>#include <stingray/toolkit/ThreadPool.h>
#include <stingray/log/Logger.h>
#include <stingray/toolkit/bind.h>
namespace stingray
{
ThreadPool::WorkerWrapper::WorkerWrapper(const std::string& name)
: _busy(false), _worker(ITaskExecutor::Create(name))
{ }
bool ThreadPool::WorkerWrapper::TryAddTask(const function<void()>& task)
{
MutexLock l(_mutex);
if (_busy)
return false;
_busy = true;
_worker->AddTask(bind(&ThreadPool::WorkerWrapper::TaskWrapper, this, task));
return true;
}
bool ThreadPool::WorkerWrapper::TryAddTaskWithTester(const function<void()>& task, const FutureExecutionTester& tester)
{
MutexLock l(_mutex);
if (_busy)
return false;
_busy = true;
_worker->AddTask(bind(&ThreadPool::WorkerWrapper::TaskWrapper, this, task), tester);
return true;
}
void ThreadPool::WorkerWrapper::TaskWrapper(const function<void()>& task)
{
STINGRAY_TRY("Couldn't execute task", task());
{
MutexLock l(_mutex);
TOOLKIT_CHECK(_busy, "Internal TaskExecutorPool error!");
_busy = false;
}
}
///////////////////////////////////////////////////////////////
ThreadPool::ThreadPool(const std::string& name, u32 maxThreads)
: _name(name), _maxThreads(maxThreads)
{ }
void ThreadPool::Queue(const function<void()>& task)
{ DoAddTask(bind(&WorkerWrapper::TryAddTask, _1, task)); }
void ThreadPool::Queue(const function<void()>& task, const FutureExecutionTester& tester)
{ DoAddTask(bind(&WorkerWrapper::TryAddTaskWithTester, _1, task, tester)); }
void ThreadPool::DoAddTask(const function<bool(WorkerWrapper*)>& tryAddTaskFunc)
{
MutexLock l(_mutex);
for (Workers::const_iterator it = _workers.begin(); it != _workers.end(); ++it)
{
if (tryAddTaskFunc(it->get()))
return;
}
if (_workers.size() < _maxThreads)
{
WorkerWrapperPtr w(new WorkerWrapper(StringBuilder() % _name % "_" % _workers.size()));
_workers.push_back(w);
TOOLKIT_CHECK(tryAddTaskFunc(w.get()), "Internal TaskExecutorPool error!");
}
else
{
TOOLKIT_THROW(NotImplementedException());
}
}
}
<|endoftext|>
|
<commit_before>#if defined(_CARTO_GEOCODING_SUPPORT)
#include "MapBoxOnlineReverseGeocodingService.h"
#include "core/BinaryData.h"
#include "components/Exceptions.h"
#include "geocoding/MapBoxGeocodingProxy.h"
#include "projections/Projection.h"
#include "utils/GeneralUtils.h"
#include "utils/NetworkUtils.h"
#include "utils/Log.h"
#include <boost/lexical_cast.hpp>
namespace carto {
MapBoxOnlineReverseGeocodingService::MapBoxOnlineReverseGeocodingService(const std::string& accessToken) :
_accessToken(accessToken),
_language(),
_serviceURL(),
_mutex()
{
}
MapBoxOnlineReverseGeocodingService::~MapBoxOnlineReverseGeocodingService() {
}
std::string MapBoxOnlineReverseGeocodingService::getLanguage() const {
std::lock_guard<std::mutex> lock(_mutex);
return _language;
}
void MapBoxOnlineReverseGeocodingService::setLanguage(const std::string& lang) {
std::lock_guard<std::mutex> lock(_mutex);
_language = lang;
}
std::string MapBoxOnlineReverseGeocodingService::getCustomServiceURL() const {
std::lock_guard<std::mutex> lock(_mutex);
return _serviceURL;
}
void MapBoxOnlineReverseGeocodingService::setCustomServiceURL(const std::string& serviceURL) {
std::lock_guard<std::mutex> lock(_mutex);
_serviceURL = serviceURL;
}
std::vector<std::shared_ptr<GeocodingResult> > MapBoxOnlineReverseGeocodingService::calculateAddresses(const std::shared_ptr<ReverseGeocodingRequest>& request) const {
if (!request) {
throw NullArgumentException("Null request");
}
MapPos point = request->getProjection()->toWgs84(request->getLocation());
std::string baseURL;
std::map<std::string, std::string> params;
{
std::lock_guard<std::mutex> lock(_mutex);
std::map<std::string, std::string> tagMap;
tagMap["query"] = NetworkUtils::URLEncode(boost::lexical_cast<std::string>(point.getX()) + "," + boost::lexical_cast<std::string>(point.getY()));
tagMap["access_token"] = NetworkUtils::URLEncode(_accessToken);
baseURL = GeneralUtils::ReplaceTags(_serviceURL.empty() ? MAPBOX_SERVICE_URL : _serviceURL, tagMap);
if (!_language.empty()) {
params["language"] = _language;
}
}
std::string url = NetworkUtils::BuildURLFromParameters(baseURL, params);
Log::Debugf("MapBoxOnlineReverseGeocodingService::calculateAddresses: Loading %s", url.c_str());
std::shared_ptr<BinaryData> responseData;
if (!NetworkUtils::GetHTTP(url, responseData, Log::IsShowDebug())) {
throw NetworkException("Failed to fetch response");
}
std::string responseString;
if (responseData) {
responseString = std::string(reinterpret_cast<const char*>(responseData->data()), responseData->size());
} else {
throw GenericException("Empty response");
}
return MapBoxGeocodingProxy::ReadResponse(responseString, request->getProjection());
}
const std::string MapBoxOnlineReverseGeocodingService::MAPBOX_SERVICE_URL = "https://api.mapbox.com/geocoding/v5/mapbox.places/{query}.json?access_token={access_token}&types=address,poi";
}
#endif
<commit_msg>mapbox geocode<commit_after>#if defined(_CARTO_GEOCODING_SUPPORT)
#include "MapBoxOnlineReverseGeocodingService.h"
#include "core/BinaryData.h"
#include "components/Exceptions.h"
#include "geocoding/MapBoxGeocodingProxy.h"
#include "projections/Projection.h"
#include "utils/GeneralUtils.h"
#include "utils/NetworkUtils.h"
#include "utils/Log.h"
#include <boost/lexical_cast.hpp>
namespace carto {
MapBoxOnlineReverseGeocodingService::MapBoxOnlineReverseGeocodingService(const std::string& accessToken) :
_accessToken(accessToken),
_language(),
_serviceURL(),
_mutex()
{
}
MapBoxOnlineReverseGeocodingService::~MapBoxOnlineReverseGeocodingService() {
}
std::string MapBoxOnlineReverseGeocodingService::getLanguage() const {
std::lock_guard<std::mutex> lock(_mutex);
return _language;
}
void MapBoxOnlineReverseGeocodingService::setLanguage(const std::string& lang) {
std::lock_guard<std::mutex> lock(_mutex);
_language = lang;
}
std::string MapBoxOnlineReverseGeocodingService::getCustomServiceURL() const {
std::lock_guard<std::mutex> lock(_mutex);
return _serviceURL;
}
void MapBoxOnlineReverseGeocodingService::setCustomServiceURL(const std::string& serviceURL) {
std::lock_guard<std::mutex> lock(_mutex);
_serviceURL = serviceURL;
}
std::vector<std::shared_ptr<GeocodingResult> > MapBoxOnlineReverseGeocodingService::calculateAddresses(const std::shared_ptr<ReverseGeocodingRequest>& request) const {
if (!request) {
throw NullArgumentException("Null request");
}
MapPos point = request->getProjection()->toWgs84(request->getLocation());
std::string baseURL;
std::map<std::string, std::string> params;
{
std::lock_guard<std::mutex> lock(_mutex);
std::map<std::string, std::string> tagMap;
tagMap["query"] = NetworkUtils::URLEncode(boost::lexical_cast<std::string>(point.getX()) + "," + boost::lexical_cast<std::string>(point.getY()));
tagMap["access_token"] = NetworkUtils::URLEncode(_accessToken);
baseURL = GeneralUtils::ReplaceTags(_serviceURL.empty() ? MAPBOX_SERVICE_URL : _serviceURL, tagMap);
if (!_language.empty()) {
params["language"] = _language;
}
}
std::string url = NetworkUtils::BuildURLFromParameters(baseURL, params);
Log::Debugf("MapBoxOnlineReverseGeocodingService::calculateAddresses: Loading %s", url.c_str());
std::shared_ptr<BinaryData> responseData;
if (!NetworkUtils::GetHTTP(url, responseData, Log::IsShowDebug())) {
throw NetworkException("Failed to fetch response");
}
std::string responseString;
if (responseData) {
responseString = std::string(reinterpret_cast<const char*>(responseData->data()), responseData->size());
} else {
throw GenericException("Empty response");
}
return MapBoxGeocodingProxy::ReadResponse(responseString, request->getProjection());
}
const std::string MapBoxOnlineReverseGeocodingService::MAPBOX_SERVICE_URL = "https://api.mapbox.com/geocoding/v5/mapbox.places-permanent/{query}.json?access_token={access_token}";
}
#endif
<|endoftext|>
|
<commit_before>/*
* Ultrasonic.cpp - Library for HC-SR04 Ultrasonic Ranging Module.library
*
* Created by ITead studio. Apr 20, 2010.
* iteadstudio.com
*
* SVN Keywords
* ----------------------------------
* $Author$
* $Date$
* $Revision$
* ----------------------------------
*/
#include <stdlib.h>
#include <string.h>
#include <Ultrasonic.h>
Ultrasonic::Ultrasonic(int tp, int ep)
{
pinMode(tp, OUTPUT);
pinMode(ep, INPUT);
_trigPin = tp;
_echoPin = ep;
}
long Ultrasonic::timing()
{
digitalWrite(_trigPin, LOW);
delayMicroseconds(2);
digitalWrite(_trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(_trigPin, LOW);
return pulseIn(_echoPin, HIGH);
}
long Ultrasonic::convert(long microsec, int metric)
{
if(metric) return microsec / 29 / 2; // CM
else return microsec / 74 / 2; // IN
}
#ifdef COMPILE_STD_DEV
bool Ultrasonic::sampleCreate(size_t numBufs, ...)
{
bool result = false;
va_list ap;
_numBufs = numBufs;
if((_pBuffers = (BufCtl *) calloc(numBufs, sizeof(BufCtl))) != NULL)
{
va_start(ap, numBufs);
BufCtl *buf;
size_t smpSize;
for(size_t i = 0; i < _numBufs; i++)
{
buf = &_pBuffers[i];
smpSize = va_arg(ap, size_t);
if((buf->pBegin = (float *) calloc(smpSize, sizeof(float))) != NULL)
{
buf->pIndex = buf->pBegin;
buf->length = smpSize;
buf->filled = false;
result = true;
}
else
{
result = false;
break;
}
}
va_end(ap);
}
if(!result) _freeBuffers()
return result;
}
void Ultrasonic::sampleClear()
{
if(_pBuffers)
{
BufCtl *buf;
for(size_t i = 0; i < _numBufs; i++)
{
buf = &_pBuffers[i];
memset(buf, '\0', sizeof(float) * buf->length);
buf->pIndex = buf->pBegin;
buf->filled = false;
}
}
}
float Ultrasonic::unbiasedStdDev(long value, size_t bufNum)
{
float result = 0.0;
if(_pBuffers)
{
BufCtl *buf = &_pBuffers[bufNum];
if(buf->length > 1)
{
_sampleUpdate(buf, float(value));
if(buf->filled)
{
float sum = 0.0, mean, tmp;
for(size_t i = 0; i < buf->length; i++)
sum += buf->pBegin[i];
mean = sum / buf->length;
sum = 0.0;
for(size_t i = 0; i < buf->length; i++)
{
tmp = buf->pBegin[i] - mean;
sum += (tmp * tmp);
}
result = sqrt(sum / (buf->length - 1));
//Serial.print(bufNum);
//Serial.print(" : ");
//Serial.println(result);
}
}
}
return result;
}
void Ultrasonic::_sampleUpdate(BufCtl *buf, float msec)
{
if(buf->pIndex >= (buf->pBegin + buf->length))
{
buf->pIndex = buf->pBegin;
buf->filled = true;
}
*(buf->pIndex++) = msec;
}
void Ultrasonic::_freeBuffers()
{
if(_pBuffers)
{
BufCtl *buf;
for(size_t i = 0; i < _numBufs; i++)
{
buf = &_pBuffers[i];
free(buf->pBegin)
}
free(_pBuffers);
}
}
#endif // COMPILE_STD_DEV
<commit_msg>Opps forgot another semicolon.<commit_after>/*
* Ultrasonic.cpp - Library for HC-SR04 Ultrasonic Ranging Module.library
*
* Created by ITead studio. Apr 20, 2010.
* iteadstudio.com
*
* SVN Keywords
* ----------------------------------
* $Author$
* $Date$
* $Revision$
* ----------------------------------
*/
#include <stdlib.h>
#include <string.h>
#include <Ultrasonic.h>
Ultrasonic::Ultrasonic(int tp, int ep)
{
pinMode(tp, OUTPUT);
pinMode(ep, INPUT);
_trigPin = tp;
_echoPin = ep;
}
long Ultrasonic::timing()
{
digitalWrite(_trigPin, LOW);
delayMicroseconds(2);
digitalWrite(_trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(_trigPin, LOW);
return pulseIn(_echoPin, HIGH);
}
long Ultrasonic::convert(long microsec, int metric)
{
if(metric) return microsec / 29 / 2; // CM
else return microsec / 74 / 2; // IN
}
#ifdef COMPILE_STD_DEV
bool Ultrasonic::sampleCreate(size_t numBufs, ...)
{
bool result = false;
va_list ap;
_numBufs = numBufs;
if((_pBuffers = (BufCtl *) calloc(numBufs, sizeof(BufCtl))) != NULL)
{
va_start(ap, numBufs);
BufCtl *buf;
size_t smpSize;
for(size_t i = 0; i < _numBufs; i++)
{
buf = &_pBuffers[i];
smpSize = va_arg(ap, size_t);
if((buf->pBegin = (float *) calloc(smpSize, sizeof(float))) != NULL)
{
buf->pIndex = buf->pBegin;
buf->length = smpSize;
buf->filled = false;
result = true;
}
else
{
result = false;
break;
}
}
va_end(ap);
}
if(!result) _freeBuffers()
return result;
}
void Ultrasonic::sampleClear()
{
if(_pBuffers)
{
BufCtl *buf;
for(size_t i = 0; i < _numBufs; i++)
{
buf = &_pBuffers[i];
memset(buf, '\0', sizeof(float) * buf->length);
buf->pIndex = buf->pBegin;
buf->filled = false;
}
}
}
float Ultrasonic::unbiasedStdDev(long value, size_t bufNum)
{
float result = 0.0;
if(_pBuffers)
{
BufCtl *buf = &_pBuffers[bufNum];
if(buf->length > 1)
{
_sampleUpdate(buf, float(value));
if(buf->filled)
{
float sum = 0.0, mean, tmp;
for(size_t i = 0; i < buf->length; i++)
sum += buf->pBegin[i];
mean = sum / buf->length;
sum = 0.0;
for(size_t i = 0; i < buf->length; i++)
{
tmp = buf->pBegin[i] - mean;
sum += (tmp * tmp);
}
result = sqrt(sum / (buf->length - 1));
//Serial.print(bufNum);
//Serial.print(" : ");
//Serial.println(result);
}
}
}
return result;
}
void Ultrasonic::_sampleUpdate(BufCtl *buf, float msec)
{
if(buf->pIndex >= (buf->pBegin + buf->length))
{
buf->pIndex = buf->pBegin;
buf->filled = true;
}
*(buf->pIndex++) = msec;
}
void Ultrasonic::_freeBuffers()
{
if(_pBuffers)
{
BufCtl *buf;
for(size_t i = 0; i < _numBufs; i++)
{
buf = &_pBuffers[i];
free(buf->pBegin);
}
free(_pBuffers);
}
}
#endif // COMPILE_STD_DEV
<|endoftext|>
|
<commit_before>#include UserPlayer.h
#include <stdexcept>
#include <iostream>
#include <string>
#include <algorithm>//For equal method to compare characters/strings.
#include <cctype>//For toupper method.
#include <stdlib.h>//For strtol
/*
namespace Blackjack
{
class UserPlayer: public Player
{//A Blackjack player that plays with user input.
private:
public:
UserPlayer( unsigned int newID ) : Player( newID );//Constructor with only the ID.
UserPlayer( unsigned int newID, std::string newName ) : Player( newID, newName );//Constructor with the player's name and the ID.
UserPlayer( unsigned int newID, std::string newName, Dealer* newDealer ) : Player( newID, newName, newDealer );//Constructor with the player's name, the ID and the Dealer.
void play();//Play one round of blackjack with user input.
int askQuit();//Asks the user whether to quit and returns an int of value from playReturnValues based on the answer.
};
}
*/
namespace Blackjack
{
inline bool caseInsensitiveCharacterCompare( char first, char second )
{//Compare two characters, returns true if they're equal, false if they're not.
return std::toupper(first) == std::toupper(second);
}
bool caseInsensitiveStringCompare( const std::string& first, const std::string& second )
{
return (first.size() == second.size()) && equal(first.begin(), first.end(), second.begin(), caseInsensitiveCharacterCompare);
}
UserPlayer::UserPlayer( unsigned int newID ) : Player( newID )
{//Constructor with only the ID.
}
UserPlayer::UserPlayer( unsigned int newID, std::string newName ) : Player( newID, newName )
{//Constructor with the player's name and the ID.
}
UserPlayer::UserPlayer( unsigned int newID, std::string newName, Dealer* newDealer ) : Player( newID, newName, newDealer )
{//Constructor with the player's name, the ID and the Dealer.
}
void UserPlayer::play()
{//Play one round of blackjack with user input.
if( myDealer == NULL )
{//Check to make sure the dealer is set. If not, error out.
std::cerr << "Started the play method of UserPlayer without a set dealer." << std::endl;
throw std::runtime_error( "Started the play method of UserPlayer without a set dealer." );
}
if( getMoney() > 0 )
{//If the user has money left, let the user play.
//long bet = 0;//The amount of money the user wants to bet.
//TODO: Change bet to set the bet value in hand rather than the long value above.
if( collHands.numHands() == 0 )
{//If there aren't any hands yet, create the first one so that play can start.
Hand newHand;//Create the hand object itself.
newHand.addCard( myDealer->getRandomCard() );//Get the first random card of the hand.
newHand.addCard( myDealer->getRandomCard() );//Get the second random card of the hand.
collHands.addHand( newHand );//Add the new hand to the collection of hands.
}
for( HandList::iterator itr = collHands.begin(); itr != collHands.end(); itr++ )
{//Play each hand by iteration through them.
bool doneWithThisHand = false;//Used to keep track of wether the user has decided to stop playing this hand.
//bet = 0;//Reset the bet.
while( ((*itr).getBet() <= 0) || ((*itr).getBet() > getMoney()) )
{//Keep asking for a bet until you get a valid one (bet needs to be a positive number less than or equal to the amount of money the player has.
long tempBet;//Temporary variable to hold the value of the bet temporarily.
std::cout << "You have " << getMoney() << " money left. How much do you want to bet? ";
std::cin >> input;
tempBet = strtol( input.c_str(), NULL, 0 );
if( (tempBet <= 0) || (tempBet > getMoney()) )
{//The bet was invalid, give an error.
std::cerr << "The bet you entered, " << tempBet << ", was invalid, please try again with a number between 1 and " << getMoney() << "." << std::endl;
}
else
{//The bet is valid, set the bet and take the bet out of the player's money..
(*itr).setBet( tempBet );
money -= tempBet;
}
}
//Double Down
if( (*itr).getBet() * 2 <= getMoney() )
{//If the player has enough money, let the player double down.
std::string doubleDownInput;
do
{//Keep looping until get a y or a n from the user.
std::cout << *itr << std::endl;//Print out the hand to the user.
std::cout << "Points: " << *itr.getMaxPointsAtOrBelow21() << std::endl;//Print out the number of points for the user.
std::cout << "Money: " << getMoney() << std::endl;//Print out the amount of money the user has.
std::cout << "Do you want to double down? (y/n) ";
std::cin >> doubleDownInput;
if( caseInsensitiveStringCompare(doubleDownInput, "Y") )
{//If the user said yes, double down and take the additional bet amount out of the player's money.
//bet *= 2;
money -= (*itr).getBet();
(*itr).doubleBet();
doneWithThisHand = true;
}
else if( !caseInsensitiveStringCompare(doubleDownInput, "N") )
{//If the user didn't specify yes (previous if statement) or no (this if statement), give the user an error.
std::cerr << "Please input the character y or the character n." << std::endl;
}
}while( !caseInsensitiveStringCompare(splitInput, "Y") && !caseInsensitiveStringCompare(splitInput, "N") );
}
else
{//Let the user know the user can't souble down.
std::cout << "You don't have enough money to double down." << std::endl;
}
//Split
if( (*itr).canSplit() )
{//If the hand can be split, ask the user wether to do that.
std::string splitInput;
do
{//Keep looping until get a y or a n from the user.
std::cout << *itr << std::endl;//Print out the hand to the user.
std::cout << "Points: " << *itr.getMaxPointsAtOrBelow21() << std::endl;//Print out the number of points for the user.
std::cout << "This hand can be split. Do you want to split the hand? (y/n) ";
std::cin >> splitInput;
if( caseInsensitiveStringCompare(splitInput, "Y") )
{//If the user said yes, split the hand.
//Finish this code later
//std::cout << "This feature is still under construction." << std::endl;
split( itr );
}
else if( !caseInsensitiveStringCompare(splitInput, "N") )
{//If the user didn't specify yes (previous if statement) or no (this if statement), give the user an error.
std::cerr << "Please input the character y or the character n." << std::endl;
}
}while( !caseInsensitiveStringCompare(splitInput, "Y") && !caseInsensitiveStringCompare(splitInput, "N") );
}
while( (doneWithThisHand != true) && (*itr.getMaxPointsAtOrBelow21() < 21) )
{//While the user hasn't decided to stop playing this hand and the hand is below 21 points, keep playing this hand.
std::cout << *itr << std::endl;//Print out the hand to the user.
std::cout << "Points: " << *itr.getMaxPointsAtOrBelow21() << std::endl;//Print out the number of points for the user.
//if( *itr.getMaxPointsAtOrBelow21() < 21 )
//{//If the points for this hand are below 21, see if the user wants to keep going.
//Ask if the user wants to deal another card.
std::string dealInput;
do
{//Keep looping until get a y or a n from the user.
std::cout << *itr << std::endl;
std::cout << "Do you want to hit or stand? (h/s) ";
std::cin >> dealInput;
if( caseInsensitiveStringCompare(dealInput, "h") )
{//If the user said yes, deal a card.
//Finish this code later
//std::cout << "This feature is still under construction." << std::endl;
(*itr).addCard( myDealer->getRandomCard() );//Put in a random card.
}
else if( caseInsensitiveStringCompare(dealInput, "s") )
{//User selected stand, so done with this hand.
doneWithThisHand = true;
}
else
{//If the user didn't specify hit or stand, give the user an error.
std::cerr << "Please input the character y or the character n." << std::endl;
}
}while( !caseInsensitiveStringCompare(dealInput, "h") && !caseInsensitiveStringCompare(dealInput, "s") );
//}
}
//Print out the hand at the end of the play
std::cout << "This hand: " << std::endl;
std::cout << *itr << std::endl;//Print out the hand to the user.
std::cout << "Points: " << (*itr).getMaxPointsAtOrBelow21() << std::endl;//Print out the number of points for the user.
}
}
else
{//The user doesn't have any money left. Let the user know.
std::cout << "You have " << getMoney() << " money left. You can't play with that amount." << std::endl;
}
}
int UserPlayer::askQuit()
{//Asks the user whether to quit and returns an int of value from playReturnValues based on the answer.struct playReturnValues { quitPlaying, keepPlaying }
std::string input;
do
{//Keep asking for input until you get a valid answer.
std::cout << "You have " << getMoney() << " money left. Do you want to quit? (Y/N) ";
std::cin >> input;
if( caseInsensitiveStringCompare(input, "Y") )
{//If the user entered Y for yes, return quitPlaying
return playReturnValues.quitPlaying;
}
else if( caseInsensitiveStringCompare(input, "N") )
{//If the user entered N for no, return keepPlaying
return playReturnValues.keepPlaying;
}
else
{//Invalid response. Give an error.
std::cerr << "Your answer on whether to quit wasn't recognized, please try again." << std::endl;
}
}while( caseInsensitiveStringCompare(input, "Y") || caseInsensitiveStringCompare(input, "N") );
//Execution shouldn't get here, but in case the compiler will complian about the possibility of ending the method without a return value I'll put a default.
std::cerr << "Something unexpected happened in UserPlayer::askQuit(), quitting." << std::endl;
return playReturnValues.quitPlaying;
}
}
<commit_msg>Removed an unnecessary comment.<commit_after>#include UserPlayer.h
#include <stdexcept>
#include <iostream>
#include <string>
#include <algorithm>//For equal method to compare characters/strings.
#include <cctype>//For toupper method.
#include <stdlib.h>//For strtol
/*
namespace Blackjack
{
class UserPlayer: public Player
{//A Blackjack player that plays with user input.
private:
public:
UserPlayer( unsigned int newID ) : Player( newID );//Constructor with only the ID.
UserPlayer( unsigned int newID, std::string newName ) : Player( newID, newName );//Constructor with the player's name and the ID.
UserPlayer( unsigned int newID, std::string newName, Dealer* newDealer ) : Player( newID, newName, newDealer );//Constructor with the player's name, the ID and the Dealer.
void play();//Play one round of blackjack with user input.
int askQuit();//Asks the user whether to quit and returns an int of value from playReturnValues based on the answer.
};
}
*/
namespace Blackjack
{
inline bool caseInsensitiveCharacterCompare( char first, char second )
{//Compare two characters, returns true if they're equal, false if they're not.
return std::toupper(first) == std::toupper(second);
}
bool caseInsensitiveStringCompare( const std::string& first, const std::string& second )
{
return (first.size() == second.size()) && equal(first.begin(), first.end(), second.begin(), caseInsensitiveCharacterCompare);
}
UserPlayer::UserPlayer( unsigned int newID ) : Player( newID )
{//Constructor with only the ID.
}
UserPlayer::UserPlayer( unsigned int newID, std::string newName ) : Player( newID, newName )
{//Constructor with the player's name and the ID.
}
UserPlayer::UserPlayer( unsigned int newID, std::string newName, Dealer* newDealer ) : Player( newID, newName, newDealer )
{//Constructor with the player's name, the ID and the Dealer.
}
void UserPlayer::play()
{//Play one round of blackjack with user input.
if( myDealer == NULL )
{//Check to make sure the dealer is set. If not, error out.
std::cerr << "Started the play method of UserPlayer without a set dealer." << std::endl;
throw std::runtime_error( "Started the play method of UserPlayer without a set dealer." );
}
if( getMoney() > 0 )
{//If the user has money left, let the user play.
//long bet = 0;//The amount of money the user wants to bet.
if( collHands.numHands() == 0 )
{//If there aren't any hands yet, create the first one so that play can start.
Hand newHand;//Create the hand object itself.
newHand.addCard( myDealer->getRandomCard() );//Get the first random card of the hand.
newHand.addCard( myDealer->getRandomCard() );//Get the second random card of the hand.
collHands.addHand( newHand );//Add the new hand to the collection of hands.
}
for( HandList::iterator itr = collHands.begin(); itr != collHands.end(); itr++ )
{//Play each hand by iteration through them.
bool doneWithThisHand = false;//Used to keep track of wether the user has decided to stop playing this hand.
//bet = 0;//Reset the bet.
while( ((*itr).getBet() <= 0) || ((*itr).getBet() > getMoney()) )
{//Keep asking for a bet until you get a valid one (bet needs to be a positive number less than or equal to the amount of money the player has.
long tempBet;//Temporary variable to hold the value of the bet temporarily.
std::cout << "You have " << getMoney() << " money left. How much do you want to bet? ";
std::cin >> input;
tempBet = strtol( input.c_str(), NULL, 0 );
if( (tempBet <= 0) || (tempBet > getMoney()) )
{//The bet was invalid, give an error.
std::cerr << "The bet you entered, " << tempBet << ", was invalid, please try again with a number between 1 and " << getMoney() << "." << std::endl;
}
else
{//The bet is valid, set the bet and take the bet out of the player's money..
(*itr).setBet( tempBet );
money -= tempBet;
}
}
//Double Down
if( (*itr).getBet() * 2 <= getMoney() )
{//If the player has enough money, let the player double down.
std::string doubleDownInput;
do
{//Keep looping until get a y or a n from the user.
std::cout << *itr << std::endl;//Print out the hand to the user.
std::cout << "Points: " << *itr.getMaxPointsAtOrBelow21() << std::endl;//Print out the number of points for the user.
std::cout << "Money: " << getMoney() << std::endl;//Print out the amount of money the user has.
std::cout << "Do you want to double down? (y/n) ";
std::cin >> doubleDownInput;
if( caseInsensitiveStringCompare(doubleDownInput, "Y") )
{//If the user said yes, double down and take the additional bet amount out of the player's money.
//bet *= 2;
money -= (*itr).getBet();
(*itr).doubleBet();
doneWithThisHand = true;
}
else if( !caseInsensitiveStringCompare(doubleDownInput, "N") )
{//If the user didn't specify yes (previous if statement) or no (this if statement), give the user an error.
std::cerr << "Please input the character y or the character n." << std::endl;
}
}while( !caseInsensitiveStringCompare(splitInput, "Y") && !caseInsensitiveStringCompare(splitInput, "N") );
}
else
{//Let the user know the user can't souble down.
std::cout << "You don't have enough money to double down." << std::endl;
}
//Split
if( (*itr).canSplit() )
{//If the hand can be split, ask the user wether to do that.
std::string splitInput;
do
{//Keep looping until get a y or a n from the user.
std::cout << *itr << std::endl;//Print out the hand to the user.
std::cout << "Points: " << *itr.getMaxPointsAtOrBelow21() << std::endl;//Print out the number of points for the user.
std::cout << "This hand can be split. Do you want to split the hand? (y/n) ";
std::cin >> splitInput;
if( caseInsensitiveStringCompare(splitInput, "Y") )
{//If the user said yes, split the hand.
//Finish this code later
//std::cout << "This feature is still under construction." << std::endl;
split( itr );
}
else if( !caseInsensitiveStringCompare(splitInput, "N") )
{//If the user didn't specify yes (previous if statement) or no (this if statement), give the user an error.
std::cerr << "Please input the character y or the character n." << std::endl;
}
}while( !caseInsensitiveStringCompare(splitInput, "Y") && !caseInsensitiveStringCompare(splitInput, "N") );
}
while( (doneWithThisHand != true) && (*itr.getMaxPointsAtOrBelow21() < 21) )
{//While the user hasn't decided to stop playing this hand and the hand is below 21 points, keep playing this hand.
std::cout << *itr << std::endl;//Print out the hand to the user.
std::cout << "Points: " << *itr.getMaxPointsAtOrBelow21() << std::endl;//Print out the number of points for the user.
//if( *itr.getMaxPointsAtOrBelow21() < 21 )
//{//If the points for this hand are below 21, see if the user wants to keep going.
//Ask if the user wants to deal another card.
std::string dealInput;
do
{//Keep looping until get a y or a n from the user.
std::cout << *itr << std::endl;
std::cout << "Do you want to hit or stand? (h/s) ";
std::cin >> dealInput;
if( caseInsensitiveStringCompare(dealInput, "h") )
{//If the user said yes, deal a card.
//Finish this code later
//std::cout << "This feature is still under construction." << std::endl;
(*itr).addCard( myDealer->getRandomCard() );//Put in a random card.
}
else if( caseInsensitiveStringCompare(dealInput, "s") )
{//User selected stand, so done with this hand.
doneWithThisHand = true;
}
else
{//If the user didn't specify hit or stand, give the user an error.
std::cerr << "Please input the character y or the character n." << std::endl;
}
}while( !caseInsensitiveStringCompare(dealInput, "h") && !caseInsensitiveStringCompare(dealInput, "s") );
//}
}
//Print out the hand at the end of the play
std::cout << "This hand: " << std::endl;
std::cout << *itr << std::endl;//Print out the hand to the user.
std::cout << "Points: " << (*itr).getMaxPointsAtOrBelow21() << std::endl;//Print out the number of points for the user.
}
}
else
{//The user doesn't have any money left. Let the user know.
std::cout << "You have " << getMoney() << " money left. You can't play with that amount." << std::endl;
}
}
int UserPlayer::askQuit()
{//Asks the user whether to quit and returns an int of value from playReturnValues based on the answer.struct playReturnValues { quitPlaying, keepPlaying }
std::string input;
do
{//Keep asking for input until you get a valid answer.
std::cout << "You have " << getMoney() << " money left. Do you want to quit? (Y/N) ";
std::cin >> input;
if( caseInsensitiveStringCompare(input, "Y") )
{//If the user entered Y for yes, return quitPlaying
return playReturnValues.quitPlaying;
}
else if( caseInsensitiveStringCompare(input, "N") )
{//If the user entered N for no, return keepPlaying
return playReturnValues.keepPlaying;
}
else
{//Invalid response. Give an error.
std::cerr << "Your answer on whether to quit wasn't recognized, please try again." << std::endl;
}
}while( caseInsensitiveStringCompare(input, "Y") || caseInsensitiveStringCompare(input, "N") );
//Execution shouldn't get here, but in case the compiler will complian about the possibility of ending the method without a return value I'll put a default.
std::cerr << "Something unexpected happened in UserPlayer::askQuit(), quitting." << std::endl;
return playReturnValues.quitPlaying;
}
}
<|endoftext|>
|
<commit_before>//**************************************************************
//* OpenGLide - Glide->OpenGL Wrapper
//* OpenGL Extensions
//* Made by Glorfindel
//**************************************************************
#include "GlOgl.h"
#include "Glextensions.h"
#include <string.h>
//Functions
PFNGLMULTITEXCOORD4FARBPROC glMultiTexCoord4fARB = NULL;
PFNGLACTIVETEXTUREARBPROC glActiveTextureARB = NULL;
PFNGLSECONDARYCOLOR3UBVEXTPROC glSecondaryColor3ubvEXT = NULL;
PFNGLSECONDARYCOLOR3UBEXTPROC glSecondaryColor3ubEXT = NULL;
PFNGLSECONDARYCOLOR3FVEXTPROC glSecondaryColor3fvEXT = NULL;
PFNGLSECONDARYCOLOR3FEXTPROC glSecondaryColor3fEXT = NULL;
PFNGLSECONDARYCOLORPOINTEREXTPROC glSecondaryColorPointerEXT = NULL;
PFNGLFOGCOORDFEXTPROC glFogCoordfEXT = NULL;
PFNGLFOGCOORDPOINTEREXTPROC glFogCoordPointerEXT = NULL;
PFNGLCOLORTABLEEXTPROC glColorTableEXT = NULL;
PFNGLCOLORSUBTABLEEXTPROC glColorSubTableEXT = NULL;
PFNGLGETCOLORTABLEEXTPROC glGetColorTableEXT = NULL;
PFNGLGETCOLORTABLEPARAMETERIVEXTPROC glGetColorTableParameterivEXT = NULL;
PFNGLGETCOLORTABLEPARAMETERFVEXTPROC glGetColorTableParameterfvEXT = NULL;
// Declarations
void GLExtensions();
void APIENTRY DummyV( const void *a )
{
}
void APIENTRY DummyF( GLfloat a )
{
}
void APIENTRY Dummy3ub( GLubyte a, GLubyte b, GLubyte c )
{
}
// check to see if Extension is Supported
// code by Mark J. Kilgard of NVidia
int isExtensionSupported( const char *extension )
{
const char *extensions;
const char *start;
char *where, *terminator;
where = (char *) strchr( extension, ' ' );
if ( where || *extension == '\0' )
return 0;
extensions = (char*)glGetString( GL_EXTENSIONS );
start = extensions;
if (*start == '\0')
{
Error( "No OpenGL extension supported, using all emulated.\n" );
return 0;
}
for (;;)
{
where = (char *) strstr( start, extension );
if ( !where )
break;
terminator = where + strlen( extension );
if ( (where == start) || (*(where - 1) == ' ' ) )
if ( *terminator == ' ' || *terminator == '\0' )
return 1;
start = terminator;
}
return 0;
}
void ValidateUserConfig()
{
InternalConfig.FogEnable = UserConfig.FogEnable;
InternalConfig.InitFullScreen = UserConfig.InitFullScreen;
InternalConfig.PrecisionFixEnable = UserConfig.PrecisionFixEnable;
InternalConfig.Wrap565Enable = UserConfig.Wrap565Enable;
InternalConfig.BuildMipMaps = UserConfig.BuildMipMaps;
InternalConfig.MultiTextureEXTEnable = false;
InternalConfig.PaletteEXTEnable = false;
InternalConfig.PackedPixelsEXTEnable = false;
InternalConfig.TextureEnvEXTEnable = false;
InternalConfig.VertexArrayEXTEnable = false;
InternalConfig.SecondaryColorEXTEnable = false;
InternalConfig.FogCoordEXTEnable = false;
InternalConfig.PalettePrecision = 8;
InternalConfig.TextureMemorySize = 4;
InternalConfig.FrameBufferMemorySize = 2;
InternalConfig.MMXEnable = false;
InternalConfig.TDnowEnable = false;
int PalPrec = UserConfig.PalettePrecision;
if ((PalPrec > 0) && (PalPrec < 128))
{
InternalConfig.PalettePrecision = UserConfig.PalettePrecision;
}
int TexSize = UserConfig.TextureMemorySize;
if ((TexSize > 1) && (TexSize <= 16))
{
InternalConfig.TextureMemorySize = UserConfig.TextureMemorySize;
}
int FrameSize = UserConfig.FrameBufferMemorySize;
if ((FrameSize > 1) && (FrameSize <= 8))
{
InternalConfig.FrameBufferMemorySize = UserConfig.FrameBufferMemorySize;
}
InternalConfig.OGLVersion = glGetString( GL_VERSION )[ 2 ] - '0';
GlideMsg( "Using OpenGL version = %d\n", InternalConfig.OGLVersion );
if ( InternalConfig.OGLVersion >= 2 )
{
InternalConfig.BuildMipMaps = false;
}
if ( UserConfig.MultiTextureEXTEnable )
{
if ( isExtensionSupported( "GL_ARB_multitexture" ) )
{
InternalConfig.MultiTextureEXTEnable = true;
}
}
// if ( UserConfig.PaletteEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_shared_texture_palette" ) )
{
InternalConfig.PaletteEXTEnable = true;
}
}
if ( UserConfig.PackedPixelsEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_packed_pixels" ) )
{
InternalConfig.PackedPixelsEXTEnable = true;
}
}
if ( UserConfig.TextureEnvEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_texture_env_add" ) &&
isExtensionSupported( "GL_EXT_texture_env_combine" ) )
{
InternalConfig.TextureEnvEXTEnable = true;
}
}
if ( UserConfig.VertexArrayEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_vertex_array" ) )
{
InternalConfig.VertexArrayEXTEnable = true;
}
}
if ( UserConfig.SecondaryColorEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_secondary_color" ) )
{
InternalConfig.SecondaryColorEXTEnable = true;
}
}
if ( UserConfig.FogCoordEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_fog_coord" ) )
{
InternalConfig.FogCoordEXTEnable = true;
}
}
if ( UserConfig.MMXEnable )
{
if ( DetectMMX() )
{
InternalConfig.MMXEnable = true;
}
}
if ( UserConfig.TDnowEnable )
{
InternalConfig.TDnowEnable = true;
}
GLExtensions();
}
void GLExtensions()
{
GLint NumberOfTMUs;
glActiveTextureARB = NULL;
glMultiTexCoord4fARB = NULL;
glSecondaryColor3ubvEXT = (PFNGLSECONDARYCOLOR3UBVEXTPROC) DummyV;
glSecondaryColor3fvEXT = (PFNGLSECONDARYCOLOR3FVEXTPROC) DummyV;
glFogCoordfEXT = (PFNGLFOGCOORDFEXTPROC) DummyF;
if ( InternalConfig.MultiTextureEXTEnable )
{
glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &NumberOfTMUs );
GlideMsg( "MultiTexture Textures Units = %x\n", NumberOfTMUs );
OpenGL.MultiTextureTMUs = NumberOfTMUs;
glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC) wglGetProcAddress("glActiveTextureARB");
glMultiTexCoord4fARB = (PFNGLMULTITEXCOORD4FARBPROC) wglGetProcAddress("glMultiTexCoord4fARB");
if ((glActiveTextureARB == NULL) || (glMultiTexCoord4fARB == NULL))
{
Error( "Could not get the address of MultiTexture functions!\n" );
InternalConfig.MultiTextureEXTEnable = false;
}
}
if ( InternalConfig.SecondaryColorEXTEnable )
{
glSecondaryColor3ubvEXT = (PFNGLSECONDARYCOLOR3UBVEXTPROC) wglGetProcAddress("glSecondaryColor3ubvEXT");
glSecondaryColor3ubEXT = (PFNGLSECONDARYCOLOR3UBEXTPROC) wglGetProcAddress("glSecondaryColor3ubEXT");
glSecondaryColor3fvEXT = (PFNGLSECONDARYCOLOR3FVEXTPROC) wglGetProcAddress("glSecondaryColor3fvEXT");
glSecondaryColorPointerEXT = (PFNGLSECONDARYCOLORPOINTEREXTPROC) wglGetProcAddress("glSecondaryColorPointerEXT");
if ( ( glSecondaryColor3ubvEXT == NULL ) || ( glSecondaryColor3ubEXT == NULL ) ||
(glSecondaryColorPointerEXT == NULL ) || (glSecondaryColor3fvEXT == NULL))
{
Error( "Could not get address of function glSecondaryColorEXT.\n" );
InternalConfig.SecondaryColorEXTEnable = false;
}
else
{
glEnable( GL_COLOR_SUM_EXT );
if ( InternalConfig.VertexArrayEXTEnable )
{
glEnableClientState( GL_SECONDARY_COLOR_ARRAY_EXT );
}
}
}
if ( InternalConfig.FogCoordEXTEnable )
{
glFogCoordfEXT = (PFNGLFOGCOORDFEXTPROC) wglGetProcAddress("glFogCoordfEXT");
glFogCoordPointerEXT = (PFNGLFOGCOORDPOINTEREXTPROC) wglGetProcAddress("glFogCoordPointerEXT");
if ( (glFogCoordfEXT == NULL ) || ( glFogCoordPointerEXT == NULL ) )
{
Error( "Could not get address of function glFogCoordEXT.\n" );
InternalConfig.FogCoordEXTEnable = false;
}
else
{
glFogi( GL_FOG_COORDINATE_SOURCE_EXT, GL_FOG_COORDINATE_EXT );
glFogf( GL_FOG_MODE, GL_LINEAR );
glFogf( GL_FOG_START, 0.0f );
glFogf( GL_FOG_END, 1.0f );
if ( InternalConfig.VertexArrayEXTEnable )
{
glEnableClientState( GL_FOG_COORDINATE_ARRAY_EXT );
}
}
}
if ( InternalConfig.VertexArrayEXTEnable )
{
glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_COLOR_ARRAY );
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
RenderUpdateArrays();
}
if ( InternalConfig.PaletteEXTEnable )
{
glColorTableEXT = (PFNGLCOLORTABLEEXTPROC) wglGetProcAddress("glColorTableEXT");
glColorSubTableEXT = (PFNGLCOLORSUBTABLEEXTPROC) wglGetProcAddress("glColorSubTableEXT");
glGetColorTableEXT = (PFNGLGETCOLORTABLEEXTPROC) wglGetProcAddress("glGetColorTableEXT");
glGetColorTableParameterivEXT = (PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) wglGetProcAddress("glGetColorTableParameterivEXT");
glGetColorTableParameterfvEXT = (PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) wglGetProcAddress("glGetColorTableParameterfvEXT");
if ( ( glColorTableEXT == NULL ) || ( glColorSubTableEXT == NULL ) || ( glGetColorTableEXT == NULL ) ||
( glGetColorTableParameterivEXT == NULL ) || ( glGetColorTableParameterfvEXT == NULL ) )
{
Error( "Could not get address of function for PaletteEXT.\n" );
InternalConfig.PaletteEXTEnable = false;
}
else
{
GlideMsg( "Using Palette Extension.\n" );
glEnable( GL_SHARED_TEXTURE_PALETTE_EXT );
if ( glIsEnabled( GL_SHARED_TEXTURE_PALETTE_EXT ) == GL_FALSE )
{
GlideMsg( "Nao habilitou a Shared Palette Texture" );
}
}
}
#ifdef OPENGL_DEBUG
GLErro( "GLExtensions" );
#endif
}
<commit_msg>Hard-wire InternalConfig.PaletteEXTEnable off; screws up textures in TR I<commit_after>//**************************************************************
//* OpenGLide - Glide->OpenGL Wrapper
//* OpenGL Extensions
//* Made by Glorfindel
//**************************************************************
#include "GlOgl.h"
#include "Glextensions.h"
#include <string.h>
//Functions
PFNGLMULTITEXCOORD4FARBPROC glMultiTexCoord4fARB = NULL;
PFNGLACTIVETEXTUREARBPROC glActiveTextureARB = NULL;
PFNGLSECONDARYCOLOR3UBVEXTPROC glSecondaryColor3ubvEXT = NULL;
PFNGLSECONDARYCOLOR3UBEXTPROC glSecondaryColor3ubEXT = NULL;
PFNGLSECONDARYCOLOR3FVEXTPROC glSecondaryColor3fvEXT = NULL;
PFNGLSECONDARYCOLOR3FEXTPROC glSecondaryColor3fEXT = NULL;
PFNGLSECONDARYCOLORPOINTEREXTPROC glSecondaryColorPointerEXT = NULL;
PFNGLFOGCOORDFEXTPROC glFogCoordfEXT = NULL;
PFNGLFOGCOORDPOINTEREXTPROC glFogCoordPointerEXT = NULL;
PFNGLCOLORTABLEEXTPROC glColorTableEXT = NULL;
PFNGLCOLORSUBTABLEEXTPROC glColorSubTableEXT = NULL;
PFNGLGETCOLORTABLEEXTPROC glGetColorTableEXT = NULL;
PFNGLGETCOLORTABLEPARAMETERIVEXTPROC glGetColorTableParameterivEXT = NULL;
PFNGLGETCOLORTABLEPARAMETERFVEXTPROC glGetColorTableParameterfvEXT = NULL;
// Declarations
void GLExtensions();
void APIENTRY DummyV( const void *a )
{
}
void APIENTRY DummyF( GLfloat a )
{
}
void APIENTRY Dummy3ub( GLubyte a, GLubyte b, GLubyte c )
{
}
// check to see if Extension is Supported
// code by Mark J. Kilgard of NVidia
int isExtensionSupported( const char *extension )
{
const char *extensions;
const char *start;
char *where, *terminator;
where = (char *) strchr( extension, ' ' );
if ( where || *extension == '\0' )
return 0;
extensions = (char*)glGetString( GL_EXTENSIONS );
start = extensions;
if (*start == '\0')
{
Error( "No OpenGL extension supported, using all emulated.\n" );
return 0;
}
for (;;)
{
where = (char *) strstr( start, extension );
if ( !where )
break;
terminator = where + strlen( extension );
if ( (where == start) || (*(where - 1) == ' ' ) )
if ( *terminator == ' ' || *terminator == '\0' )
return 1;
start = terminator;
}
return 0;
}
void ValidateUserConfig()
{
InternalConfig.FogEnable = UserConfig.FogEnable;
InternalConfig.InitFullScreen = UserConfig.InitFullScreen;
InternalConfig.PrecisionFixEnable = UserConfig.PrecisionFixEnable;
InternalConfig.Wrap565Enable = UserConfig.Wrap565Enable;
InternalConfig.BuildMipMaps = UserConfig.BuildMipMaps;
InternalConfig.MultiTextureEXTEnable = false;
InternalConfig.PaletteEXTEnable = false;
InternalConfig.PackedPixelsEXTEnable = false;
InternalConfig.TextureEnvEXTEnable = false;
InternalConfig.VertexArrayEXTEnable = false;
InternalConfig.SecondaryColorEXTEnable = false;
InternalConfig.FogCoordEXTEnable = false;
InternalConfig.PalettePrecision = 8;
InternalConfig.TextureMemorySize = 4;
InternalConfig.FrameBufferMemorySize = 2;
InternalConfig.MMXEnable = false;
InternalConfig.TDnowEnable = false;
int PalPrec = UserConfig.PalettePrecision;
if ((PalPrec > 0) && (PalPrec < 128))
{
InternalConfig.PalettePrecision = UserConfig.PalettePrecision;
}
int TexSize = UserConfig.TextureMemorySize;
if ((TexSize > 1) && (TexSize <= 16))
{
InternalConfig.TextureMemorySize = UserConfig.TextureMemorySize;
}
int FrameSize = UserConfig.FrameBufferMemorySize;
if ((FrameSize > 1) && (FrameSize <= 8))
{
InternalConfig.FrameBufferMemorySize = UserConfig.FrameBufferMemorySize;
}
InternalConfig.OGLVersion = glGetString( GL_VERSION )[ 2 ] - '0';
GlideMsg( "Using OpenGL version = %d\n", InternalConfig.OGLVersion );
if ( InternalConfig.OGLVersion >= 2 )
{
InternalConfig.BuildMipMaps = false;
}
if ( UserConfig.MultiTextureEXTEnable )
{
if ( isExtensionSupported( "GL_ARB_multitexture" ) )
{
InternalConfig.MultiTextureEXTEnable = true;
}
}
// if ( UserConfig.PaletteEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_shared_texture_palette" ) )
{
InternalConfig.PaletteEXTEnable = false;
}
}
if ( UserConfig.PackedPixelsEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_packed_pixels" ) )
{
InternalConfig.PackedPixelsEXTEnable = true;
}
}
if ( UserConfig.TextureEnvEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_texture_env_add" ) &&
isExtensionSupported( "GL_EXT_texture_env_combine" ) )
{
InternalConfig.TextureEnvEXTEnable = true;
}
}
if ( UserConfig.VertexArrayEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_vertex_array" ) )
{
InternalConfig.VertexArrayEXTEnable = true;
}
}
if ( UserConfig.SecondaryColorEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_secondary_color" ) )
{
InternalConfig.SecondaryColorEXTEnable = true;
}
}
if ( UserConfig.FogCoordEXTEnable )
{
if ( isExtensionSupported( "GL_EXT_fog_coord" ) )
{
InternalConfig.FogCoordEXTEnable = true;
}
}
if ( UserConfig.MMXEnable )
{
if ( DetectMMX() )
{
InternalConfig.MMXEnable = true;
}
}
if ( UserConfig.TDnowEnable )
{
InternalConfig.TDnowEnable = true;
}
GLExtensions();
}
void GLExtensions()
{
GLint NumberOfTMUs;
glActiveTextureARB = NULL;
glMultiTexCoord4fARB = NULL;
glSecondaryColor3ubvEXT = (PFNGLSECONDARYCOLOR3UBVEXTPROC) DummyV;
glSecondaryColor3fvEXT = (PFNGLSECONDARYCOLOR3FVEXTPROC) DummyV;
glFogCoordfEXT = (PFNGLFOGCOORDFEXTPROC) DummyF;
if ( InternalConfig.MultiTextureEXTEnable )
{
glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &NumberOfTMUs );
GlideMsg( "MultiTexture Textures Units = %x\n", NumberOfTMUs );
OpenGL.MultiTextureTMUs = NumberOfTMUs;
glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC) wglGetProcAddress("glActiveTextureARB");
glMultiTexCoord4fARB = (PFNGLMULTITEXCOORD4FARBPROC) wglGetProcAddress("glMultiTexCoord4fARB");
if ((glActiveTextureARB == NULL) || (glMultiTexCoord4fARB == NULL))
{
Error( "Could not get the address of MultiTexture functions!\n" );
InternalConfig.MultiTextureEXTEnable = false;
}
}
if ( InternalConfig.SecondaryColorEXTEnable )
{
glSecondaryColor3ubvEXT = (PFNGLSECONDARYCOLOR3UBVEXTPROC) wglGetProcAddress("glSecondaryColor3ubvEXT");
glSecondaryColor3ubEXT = (PFNGLSECONDARYCOLOR3UBEXTPROC) wglGetProcAddress("glSecondaryColor3ubEXT");
glSecondaryColor3fvEXT = (PFNGLSECONDARYCOLOR3FVEXTPROC) wglGetProcAddress("glSecondaryColor3fvEXT");
glSecondaryColorPointerEXT = (PFNGLSECONDARYCOLORPOINTEREXTPROC) wglGetProcAddress("glSecondaryColorPointerEXT");
if ( ( glSecondaryColor3ubvEXT == NULL ) || ( glSecondaryColor3ubEXT == NULL ) ||
(glSecondaryColorPointerEXT == NULL ) || (glSecondaryColor3fvEXT == NULL))
{
Error( "Could not get address of function glSecondaryColorEXT.\n" );
InternalConfig.SecondaryColorEXTEnable = false;
}
else
{
glEnable( GL_COLOR_SUM_EXT );
if ( InternalConfig.VertexArrayEXTEnable )
{
glEnableClientState( GL_SECONDARY_COLOR_ARRAY_EXT );
}
}
}
if ( InternalConfig.FogCoordEXTEnable )
{
glFogCoordfEXT = (PFNGLFOGCOORDFEXTPROC) wglGetProcAddress("glFogCoordfEXT");
glFogCoordPointerEXT = (PFNGLFOGCOORDPOINTEREXTPROC) wglGetProcAddress("glFogCoordPointerEXT");
if ( (glFogCoordfEXT == NULL ) || ( glFogCoordPointerEXT == NULL ) )
{
Error( "Could not get address of function glFogCoordEXT.\n" );
InternalConfig.FogCoordEXTEnable = false;
}
else
{
glFogi( GL_FOG_COORDINATE_SOURCE_EXT, GL_FOG_COORDINATE_EXT );
glFogf( GL_FOG_MODE, GL_LINEAR );
glFogf( GL_FOG_START, 0.0f );
glFogf( GL_FOG_END, 1.0f );
if ( InternalConfig.VertexArrayEXTEnable )
{
glEnableClientState( GL_FOG_COORDINATE_ARRAY_EXT );
}
}
}
if ( InternalConfig.VertexArrayEXTEnable )
{
glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_COLOR_ARRAY );
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
RenderUpdateArrays();
}
if ( InternalConfig.PaletteEXTEnable )
{
glColorTableEXT = (PFNGLCOLORTABLEEXTPROC) wglGetProcAddress("glColorTableEXT");
glColorSubTableEXT = (PFNGLCOLORSUBTABLEEXTPROC) wglGetProcAddress("glColorSubTableEXT");
glGetColorTableEXT = (PFNGLGETCOLORTABLEEXTPROC) wglGetProcAddress("glGetColorTableEXT");
glGetColorTableParameterivEXT = (PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) wglGetProcAddress("glGetColorTableParameterivEXT");
glGetColorTableParameterfvEXT = (PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) wglGetProcAddress("glGetColorTableParameterfvEXT");
if ( ( glColorTableEXT == NULL ) || ( glColorSubTableEXT == NULL ) || ( glGetColorTableEXT == NULL ) ||
( glGetColorTableParameterivEXT == NULL ) || ( glGetColorTableParameterfvEXT == NULL ) )
{
Error( "Could not get address of function for PaletteEXT.\n" );
InternalConfig.PaletteEXTEnable = false;
}
else
{
GlideMsg( "Using Palette Extension.\n" );
glEnable( GL_SHARED_TEXTURE_PALETTE_EXT );
if ( glIsEnabled( GL_SHARED_TEXTURE_PALETTE_EXT ) == GL_FALSE )
{
GlideMsg( "Nao habilitou a Shared Palette Texture" );
}
}
}
#ifdef OPENGL_DEBUG
GLErro( "GLExtensions" );
#endif
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include <cstdio>
#if qPlatform_POSIX
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
#elif qPlatform_Windows
#include <WinSock2.h>
#include <WS2tcpip.h>
#endif
#include "../../Characters/Format.h"
#include "../../Containers/Collection.h"
#include "../../Execution/Exceptions.h"
#include "../../Execution/Finally.h"
#if qPlatform_Windows
#include "../../../Foundation/Execution/Platform/Windows/Exception.h"
#include "Platform/Windows/WinSock.h"
#endif
#include "../../Execution/Exceptions.h"
#include "SocketAddress.h"
#include "DNS.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
#if qPlatform_Windows
// API should return char* but MSFT returns WIDECHARS sometimes - undo that
#undef gai_strerror
#define gai_strerror gai_strerrorA
#endif // qW
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
namespace {
// @todo - somewhat rough draft - not sure if we need better default_error_condition, or equivilant() overrides
class getaddrinfo_error_category_ : public error_category { // categorize an error
public:
virtual const char* name () const noexcept override
{
return "getaddrinfo";
}
virtual error_condition default_error_condition (int ev) const noexcept override
{
switch (ev) {
#if EAI_ADDRFAMILY
case EAI_ADDRFAMILY:
return std::error_condition (errc::address_family_not_supported);
#endif
#if EAI_MEMORY
case EAI_MEMORY:
return error_condition (errc::not_enough_memory);
#endif
}
return error_condition (errc::bad_message); // no idea what to return here
}
virtual string message (int _Errval) const override
{
return ::gai_strerror (_Errval);
}
};
const getaddrinfo_error_category_ sgetaddrinfo_error_category_;
}
/*
********************************************************************************
************************** Network::GetInterfaces ******************************
********************************************************************************
*/
DNS DNS::Default ()
{
static DNS sDefaultDNS_;
return sDefaultDNS_;
}
DNS::DNS ()
{
#if qPlatform_Windows
IO::Network::Platform::Windows::WinSock::AssureStarted ();
#endif
}
DNS::HostEntry DNS::GetHostEntry (const String& hostNameOrAddress) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"DNS::HostEntry DNS::GetHostEntry", L"hostNameOrAddress=%s", Characters::ToString (hostNameOrAddress).c_str ())};
#endif
HostEntry result;
addrinfo hints{};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
#if defined(AI_IDN)
hints.ai_flags |= AI_IDN;
#endif
#if defined(AI_CANONIDN)
hints.ai_flags |= AI_CANONIDN;
#endif
string tmp = hostNameOrAddress.AsUTF8<string> (); // BAD - SB tstring - or??? not sure what... - I think need to map to Punycode
if (not tmp.empty () and tmp[0] == '[' and tmp[tmp.size () - 1] == ']' and isdigit (tmp[1])) {
// only allowed [] around numeric ip addresses
tmp = tmp.substr (1, tmp.size () - 2);
}
addrinfo* res = nullptr;
int errCode = ::getaddrinfo (tmp.c_str (), nullptr, &hints, &res);
[[maybe_unused]] auto&& cleanup = Execution::Finally ([res]() noexcept { ::freeaddrinfo (res); });
if (errCode != 0) {
// @todo - I think we need to capture erron as well if errCode == EAI_SYSTEM (see http://man7.org/linux/man-pages/man3/getaddrinfo.3.html)
Throw (SystemErrorException (errCode, sgetaddrinfo_error_category_));
// @todo get rid of the below - OBSOLETE CODE - LGP 2019-02-25
//Throw (Exception (Format (L"DNS-Error: %s (%d)", String::FromNarrowSDKString (::gai_strerror (errCode)).c_str (), errCode)));
}
AssertNotNull (res); // else would have thrown
// @todo proplerly support http://www.ietf.org/rfc/rfc3987.txt and UTF8 etc.
// See http://linux.die.net/man/3/getaddrinfo for info on glibc support for AI_IDN etc..
// and how todo on windows (or do myself portably?)
// MAYBER done OK?
//
// NI_IDN -- If this flag is used, then the name found in the lookup process is converted from IDN format
// to the locale's encoding if necessary. ASCII-only names are not affected by the conversion, which makes
// this flag usable in existing programs and environments.
//
if (res->ai_canonname != nullptr) {
// utf8 part a WAG
result.fCanonicalName = String::FromUTF8 (res->ai_canonname);
}
for (addrinfo* i = res; i != nullptr; i = i->ai_next) {
if (i != res and i->ai_canonname != nullptr and i->ai_canonname[0] != '\0') {
result.fAliases += String::FromUTF8 (i->ai_canonname);
}
SocketAddress sa{*i->ai_addr};
if (sa.IsInternetAddress ()) {
result.fAddressList += sa.GetInternetAddress ();
}
}
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"Lookup(%s)", hostNameOrAddress.c_str ());
DbgTrace (L"CANONNAME: %s", result.fCanonicalName.c_str ());
for (String i : result.fAliases) {
DbgTrace (L" ALIAS: %s", i.c_str ());
}
for (InternetAddress i : result.fAddressList) {
DbgTrace (L" ADDR: %s", i.As<String> ().c_str ());
}
#endif
return result;
}
optional<String> DNS::ReverseLookup (const InternetAddress& address) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"DNS::HostEntry DNS::ReverseLookup", L"address=%s", Characters::ToString (address).c_str ())};
#endif
char hbuf[NI_MAXHOST];
SocketAddress sa{address, 0};
sockaddr_storage sadata = sa.As<sockaddr_storage> ();
int flags = NI_NAMEREQD;
#if defined(NI_IDN)
flags |= NI_IDN;
#endif
int errCode = ::getnameinfo (reinterpret_cast<const sockaddr*> (&sadata), sizeof (sadata), hbuf, sizeof (hbuf), NULL, 0, flags);
switch (errCode) {
case 0:
//@todo handle I18N more carefully
// NI_IDN -- If this flag is used, then the name found in the lookup process is converted from IDN format
// to the locale's encoding if necessary. ASCII-only names are not affected by the conversion, which makes
// this flag usable in existing programs and environments.
return String::FromUTF8 (hbuf);
case EAI_NONAME:
return {};
default:
Throw (Exception (Format (L"DNS-Error: %s (%d)", String::FromNarrowSDKString (::gai_strerror (errCode)).c_str (), errCode)));
}
}
optional<String> DNS::QuietReverseLookup (const InternetAddress& address) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"DNS::HostEntry DNS::ReverseLookup", L"address=%s", Characters::ToString (address).c_str ())};
#endif
char hbuf[NI_MAXHOST];
SocketAddress sa{address, 0};
sockaddr_storage sadata = sa.As<sockaddr_storage> ();
int flags = NI_NAMEREQD;
#if defined(NI_IDN)
flags |= NI_IDN;
#endif
int errCode = ::getnameinfo (reinterpret_cast<const sockaddr*> (&sadata), sizeof (sadata), hbuf, sizeof (hbuf), NULL, 0, flags);
switch (errCode) {
case 0:
//@todo handle I18N more carefully
// NI_IDN -- If this flag is used, then the name found in the lookup process is converted from IDN format
// to the locale's encoding if necessary. ASCII-only names are not affected by the conversion, which makes
// this flag usable in existing programs and environments.
return String::FromUTF8 (hbuf);
default:
return {};
}
}
Sequence<InternetAddress> DNS::GetHostAddresses (const String& hostNameOrAddress) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"DNS::HostEntry DNS::GetHostAddresses", L"address=%s", Characters::ToString (address).c_str ())};
#endif
return GetHostEntry (hostNameOrAddress).fAddressList;
}
InternetAddress DNS::GetHostAddress (const String& hostNameOrAddress) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"DNS::HostEntry DNS::GetHostAddresses", L"address=%s", Characters::ToString (address).c_str ())};
#endif
auto h = GetHostEntry (hostNameOrAddress).fAddressList;
if (h.empty ()) {
Execution::Throw (Exception (L"No associated addresses"sv));
}
return h[0];
}
<commit_msg>small cleanups to DNS error handling code<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include <cstdio>
#if qPlatform_POSIX
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
#elif qPlatform_Windows
#include <WinSock2.h>
#include <WS2tcpip.h>
#endif
#include "../../Characters/Format.h"
#include "../../Containers/Collection.h"
#include "../../Execution/Exceptions.h"
#include "../../Execution/Finally.h"
#if qPlatform_Windows
#include "../../../Foundation/Execution/Platform/Windows/Exception.h"
#include "Platform/Windows/WinSock.h"
#endif
#include "../../Execution/Exceptions.h"
#include "SocketAddress.h"
#include "DNS.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
#if qPlatform_Windows
// API should return char* but MSFT returns WIDECHARS sometimes - undo that
#undef gai_strerror
#define gai_strerror gai_strerrorA
#endif // qW
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
namespace {
// @todo - somewhat rough draft - not sure if we need better default_error_condition, or equivilant() overrides
class getaddrinfo_error_category_ : public error_category { // categorize an error
public:
virtual const char* name () const noexcept override
{
return "DNS error"; // used to return return "getaddrinfo"; - but the name DNS is more widely recognized, and even though this could be from another source, this name is more clear
}
virtual error_condition default_error_condition (int ev) const noexcept override
{
switch (ev) {
#if EAI_ADDRFAMILY
case EAI_ADDRFAMILY:
return std::error_condition (errc::address_family_not_supported); // best approximartion I can find
#endif
#if EAI_NONAME
case EAI_NONAME:
return error_condition (errc::no_such_device); // best approximartion I can find
#endif
#if EAI_MEMORY
case EAI_MEMORY:
return error_condition (errc::not_enough_memory);
#endif
}
return error_condition (errc::bad_message); // no idea what to return here
}
virtual string message (int _Errval) const override
{
return ::gai_strerror (_Errval);
}
};
const getaddrinfo_error_category_ sgetaddrinfo_error_category_;
}
/*
********************************************************************************
************************** Network::GetInterfaces ******************************
********************************************************************************
*/
DNS DNS::Default ()
{
static const DNS kDefaultDNS_;
return kDefaultDNS_;
}
DNS::DNS ()
{
#if qPlatform_Windows
IO::Network::Platform::Windows::WinSock::AssureStarted ();
#endif
}
DNS::HostEntry DNS::GetHostEntry (const String& hostNameOrAddress) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"DNS::HostEntry DNS::GetHostEntry", L"hostNameOrAddress=%s", Characters::ToString (hostNameOrAddress).c_str ())};
#endif
HostEntry result;
addrinfo hints{};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
#if defined(AI_IDN)
hints.ai_flags |= AI_IDN;
#endif
#if defined(AI_CANONIDN)
hints.ai_flags |= AI_CANONIDN;
#endif
string tmp = hostNameOrAddress.AsUTF8<string> (); // BAD - SB tstring - or??? not sure what... - I think need to map to Punycode
if (not tmp.empty () and tmp[0] == '[' and tmp[tmp.size () - 1] == ']' and isdigit (tmp[1])) {
// only allowed [] around numeric ip addresses
tmp = tmp.substr (1, tmp.size () - 2);
}
addrinfo* res = nullptr;
int errCode = ::getaddrinfo (tmp.c_str (), nullptr, &hints, &res);
[[maybe_unused]] auto&& cleanup = Execution::Finally ([res]() noexcept { ::freeaddrinfo (res); });
if (errCode != 0) {
// @todo - I think we need to capture erron as well if errCode == EAI_SYSTEM (see http://man7.org/linux/man-pages/man3/getaddrinfo.3.html)
Throw (SystemErrorException (errCode, sgetaddrinfo_error_category_));
}
AssertNotNull (res); // else would have thrown
// @todo proplerly support http://www.ietf.org/rfc/rfc3987.txt and UTF8 etc.
// See http://linux.die.net/man/3/getaddrinfo for info on glibc support for AI_IDN etc..
// and how todo on windows (or do myself portably?)
// MAYBER done OK?
//
// NI_IDN -- If this flag is used, then the name found in the lookup process is converted from IDN format
// to the locale's encoding if necessary. ASCII-only names are not affected by the conversion, which makes
// this flag usable in existing programs and environments.
//
if (res->ai_canonname != nullptr) {
// utf8 part a WAG
result.fCanonicalName = String::FromUTF8 (res->ai_canonname);
}
for (addrinfo* i = res; i != nullptr; i = i->ai_next) {
if (i != res and i->ai_canonname != nullptr and i->ai_canonname[0] != '\0') {
result.fAliases += String::FromUTF8 (i->ai_canonname);
}
SocketAddress sa{*i->ai_addr};
if (sa.IsInternetAddress ()) {
result.fAddressList += sa.GetInternetAddress ();
}
}
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"Lookup(%s)", hostNameOrAddress.c_str ());
DbgTrace (L"CANONNAME: %s", result.fCanonicalName.c_str ());
for (String i : result.fAliases) {
DbgTrace (L" ALIAS: %s", i.c_str ());
}
for (InternetAddress i : result.fAddressList) {
DbgTrace (L" ADDR: %s", i.As<String> ().c_str ());
}
#endif
return result;
}
optional<String> DNS::ReverseLookup (const InternetAddress& address) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"DNS::HostEntry DNS::ReverseLookup", L"address=%s", Characters::ToString (address).c_str ())};
#endif
char hbuf[NI_MAXHOST];
SocketAddress sa{address, 0};
sockaddr_storage sadata = sa.As<sockaddr_storage> ();
int flags = NI_NAMEREQD;
#if defined(NI_IDN)
flags |= NI_IDN;
#endif
int errCode = ::getnameinfo (reinterpret_cast<const sockaddr*> (&sadata), sizeof (sadata), hbuf, sizeof (hbuf), NULL, 0, flags);
switch (errCode) {
case 0:
//@todo handle I18N more carefully
// NI_IDN -- If this flag is used, then the name found in the lookup process is converted from IDN format
// to the locale's encoding if necessary. ASCII-only names are not affected by the conversion, which makes
// this flag usable in existing programs and environments.
return String::FromUTF8 (hbuf);
case EAI_NONAME:
return {};
default:
Throw (Exception (Format (L"DNS-Error: %s (%d)", String::FromNarrowSDKString (::gai_strerror (errCode)).c_str (), errCode)));
}
}
optional<String> DNS::QuietReverseLookup (const InternetAddress& address) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"DNS::HostEntry DNS::ReverseLookup", L"address=%s", Characters::ToString (address).c_str ())};
#endif
char hbuf[NI_MAXHOST];
SocketAddress sa{address, 0};
sockaddr_storage sadata = sa.As<sockaddr_storage> ();
int flags = NI_NAMEREQD;
#if defined(NI_IDN)
flags |= NI_IDN;
#endif
int errCode = ::getnameinfo (reinterpret_cast<const sockaddr*> (&sadata), sizeof (sadata), hbuf, sizeof (hbuf), NULL, 0, flags);
switch (errCode) {
case 0:
//@todo handle I18N more carefully
// NI_IDN -- If this flag is used, then the name found in the lookup process is converted from IDN format
// to the locale's encoding if necessary. ASCII-only names are not affected by the conversion, which makes
// this flag usable in existing programs and environments.
return String::FromUTF8 (hbuf);
default:
return {};
}
}
Sequence<InternetAddress> DNS::GetHostAddresses (const String& hostNameOrAddress) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"DNS::HostEntry DNS::GetHostAddresses", L"address=%s", Characters::ToString (address).c_str ())};
#endif
return GetHostEntry (hostNameOrAddress).fAddressList;
}
InternetAddress DNS::GetHostAddress (const String& hostNameOrAddress) const
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"DNS::HostEntry DNS::GetHostAddresses", L"address=%s", Characters::ToString (address).c_str ())};
#endif
auto h = GetHostEntry (hostNameOrAddress).fAddressList;
if (h.empty ()) {
Execution::Throw (Exception (L"No associated addresses"sv));
}
return h[0];
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef STACK_HH_
#define STACK_HH_
#include "core/reactor.hh"
#include <boost/program_options.hpp>
namespace net {
boost::program_options::options_description
native_network_stack_program_options();
std::unique_ptr<network_stack>
create_native_network_stack(boost::program_options::options_description opts);
}
#endif /* STACK_HH_ */
<commit_msg>net: remove unused function from net/native-stack.hh<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef STACK_HH_
#define STACK_HH_
#include "core/reactor.hh"
#include <boost/program_options.hpp>
namespace net {
}
#endif /* STACK_HH_ */
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.