blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ce2135cc0b59acc04bba320081aebb354e96b723 | a3d1bf40a1ec6e6415badcbebd0cff6b008f4065 | /ZC_Label_System/AccountManagement/datactrl.cpp | 8949f0e5d1a3c5ddcbb43e5d88e8f8754bde3663 | [] | no_license | luxiaodao123/Label_system_lxd | 7b9f26df38f61aaa611bcdafb39c2fb92944e839 | fa9a7c9a909f940c190b84190df44acc97fd065d | refs/heads/master | 2020-03-14T02:14:39.476631 | 2018-04-28T09:31:25 | 2018-04-28T09:31:25 | 131,395,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,426 | cpp | datactrl.cpp | #include "datactrl.h"
DataCtrl::DataCtrl() : m_iQSqlDatabase(QSqlDatabase::addDatabase("QSQLITE"))
{
m_iQSqlDatabase.setDatabaseName("sqlite.dat");
m_iQSqlDatabase.open();
QSqlQuery("create table if not exists sqlite (usr TEXT primary key, pwd TEXT)", m_iQSqlDatabase).exec();
// if(!DataCtrl::verify("admin", QCryptographicHash::hash(QString("admin").toLocal8Bit(), QCryptographicHash::Md5).toHex()))
// {
// qDebug() << "in";
// DataCtrl::usrReg("admin", QCryptographicHash::hash(QString("admin").toLocal8Bit(), QCryptographicHash::Md5).toHex());
// }
if(!DataCtrl::verify("admin", "admin"))
{
qDebug() << "in";
DataCtrl::usrReg("admin", "admin");
}
}
DataCtrl::~DataCtrl()
{
m_iQSqlDatabase.commit();
m_iQSqlDatabase.close();
}
bool DataCtrl::verify(const QString &strName, const QString &strPwd)
{
QSqlQuery query(QString("select * from sqlite where usr = '%1' and pwd ='%2'").arg(strName, strPwd), m_iQSqlDatabase);
query.exec();
return query.next();
}
bool DataCtrl::usrReg(const QString &strName, const QString &strPwd)
{
QSqlQuery query(QString("replace into sqlite (usr, pwd) values('%1', '%2')").arg(strName, strPwd), m_iQSqlDatabase);
return query.exec();
}
bool DataCtrl::del(const QString &strName)
{
QSqlQuery query(QString("delete from sqlite where usr = '%1'").arg(strName), m_iQSqlDatabase);
return query.exec();
}
|
1a1b1ea8fe27858d0bfaf8b81e4fe64ff6ffabf6 | 96a3c97fe6fe0392718655fd3b0fb34f1ad2cbba | /node.cpp | 4a0139877ef4978c3e3d2c0fab6f474479c51560 | [] | no_license | nikulchikov/repo | 138b89f20eede798c8ae755e6ede141c38cb9b67 | 1fd9f2ecb4b43ddd73cbc755204f9ab77fc7f592 | refs/heads/master | 2021-01-23T21:28:01.660822 | 2014-11-14T13:53:38 | 2014-11-14T13:53:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,977 | cpp | node.cpp | #include "node.h"
#include <iostream>
using std::cerr;
using std::endl;
void node::init( unsigned long id, string name, short w, unsigned long srn, node *right_node, node *left_node,
node *right_plus_node, node *right_minus_node, node *left_plus_node, node *left_minus_node, message_sndr *msgr) {
this->id = id;
this->srn = srn;
this->way = w;
this->name = name;
this->station = 0;
short np = name.find( "n", 0);
if( np != std::string::npos)
this->station = atoi( name.substr( np + 1, name.length( ) - 1).c_str( ));
this->right_node = right_node;
this->left_node = left_node;
this->right_plus_node = right_plus_node;
this->left_plus_node = left_plus_node;
this->right_minus_node = right_minus_node;
this->left_minus_node = left_minus_node;
this->sndr = msgr;
}
node::node( unsigned long id, string name, short w, message_sndr *msgr) {
init( id, name, w, 0, 0, 0, 0, 0, 0, 0, msgr);
latest_busy_time = 0;
new_busy_interval = 15;
search_deep = 3;
}
node::node( const node &e) {
init( e.id, e.name, e.way, e.srn, e.right_node, e.left_node, e.right_plus_node, e.right_minus_node, e.left_plus_node, e.left_minus_node, e.sndr);
latest_busy_time = e.latest_busy_time;
new_busy_interval = e.new_busy_interval;
search_deep = e.search_deep;
}
node &node::operator=( const node &e) {
init( e.id, e.name, e.way, e.srn, e.right_node, e.left_node, e.right_plus_node, e.right_minus_node, e.left_plus_node, e.left_minus_node, e.sndr);
latest_busy_time = e.latest_busy_time;
new_busy_interval = e.new_busy_interval;
search_deep = e.search_deep;
}
bool node::operator==( short id) {
return ( this->id == id);
}
string node::get_name( ) {
return name;
}
unsigned long node::get_id( ) {
return id;
}
unsigned long node::check_srn( ) {
return srn;
}
unsigned long node::take_srn( short direction) {
if( station)
sndr->send( time( 0), srn, way, station, direction, Departed);
unsigned long retval = srn;
srn = 0;
return retval;
}
/// получение номера поезда
void node::set_tS0( ) {
long curr_time = time( 0);
/// проверка слишком частого повторного занятия - дребезг контактов и прочее отфильтруем
if( srn && ( curr_time - latest_busy_time) < new_busy_interval)
return;
short deep = search_deep;
if( !right_node || !left_node)
deep = 2;
short direction = -1;
long event_time_left, event_time_right;
long src_node_event_time = 0;
node *temp_left_node = left_node;
node *temp_right_node = right_node;
node *srn_src_node = 0;
for( short i = 0; i < deep; i++) {
if( temp_right_node && temp_right_node->check_srn( ) &&
temp_right_node->get_latest_busy_time( ) > ( src_node_event_time + PriorityTime * i)) {
src_node_event_time = temp_right_node->get_latest_busy_time( );
srn_src_node = temp_right_node;
direction = EvenDirection;
if( way == 2)
src_node_event_time += RightWayPriority;
}
if( temp_left_node && temp_left_node->check_srn( ) &&
temp_left_node->get_latest_busy_time( ) > ( src_node_event_time + PriorityTime * i)) {
src_node_event_time = temp_left_node->get_latest_busy_time( );
srn_src_node = temp_left_node;
direction = OddDirection;
if( way == 1)
src_node_event_time += RightWayPriority;
}
if( temp_left_node)
temp_left_node = left_node->get_lefter( );
if( temp_right_node)
temp_right_node = right_node->get_righter( );
}
if( srn_src_node)
srn = srn_src_node->take_srn( direction);
latest_busy_time = curr_time;
if( station)
sndr->send( curr_time, srn, way, station, direction, Arrived);
}
void node::set_right_plus( ) {
if( right_plus_node)
right_node = right_plus_node;
}
void node::set_left_plus( ) {
if( left_plus_node)
left_node = left_plus_node;
}
void node::set_right_minus( ) {
if( right_minus_node)
right_node = right_minus_node;
}
void node::set_left_minus( ) {
if( left_minus_node)
left_node = left_minus_node;
}
void node::set_right_node( node *n) {
right_node = n;
}
void node::set_left_node( node *n) {
left_node = n;
}
void node::set_right_plus_node( node *n) {
right_plus_node = n;
}
void node::set_left_plus_node( node *n) {
left_plus_node = n;
//if( n)
// cerr << "Node: " << name << " lefter plus node " << n->get_name( ) << endl;
}
node *node::get_lefter( ) {
return left_node;
}
node *node::get_righter( ) {
return right_node;
}
void node::set_right_minus_node( node *n) {
right_minus_node = n;
}
void node::set_left_minus_node( node *n) {
left_minus_node = n;
}
void node::set_new_busy_interval( short nby) {
new_busy_interval = nby;
}
void node::set_search_deep( short sd) {
search_deep = sd;
}
long node::get_latest_busy_time( ) {
return latest_busy_time;
}
|
16ac1a5ba5b4ec6a85391fcde454f830fb5578cd | 10265de3a7442a82f3a1ec100feeb36a21ece1a6 | /Workspace/VP9/Project/anpr_20180224/PlateRecognizationFramework/src/Crop/cropping_v2_color.cpp | d419d9c6e77be163ade31c31e0723e7f6b9a4291 | [] | no_license | zeklewa/Zeklewa_ANPR | 77f861ae7f3c60f6d64ecabbc0586ede8af78b3e | bea4ddc172ebca27e6175ca3d43d2256317023b1 | refs/heads/master | 2020-04-09T20:36:03.912406 | 2018-03-07T14:13:07 | 2018-03-07T14:13:07 | 124,242,757 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,331 | cpp | cropping_v2_color.cpp | #pragma once
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <sstream>
#include <functional>
#include <queue>
#include "common_function.h"
#include "cropping_v2_color.h"
using namespace cv;
using namespace std;
float check_score_color(Vec2f can_vl,Vec2f can_vr,Vec2f can_hu,Vec2f can_hd,Mat img,float ratio)
{
Point pt11,pt12,pt21,pt22,pt31,pt32,pt41,pt42; //the cordinate of 4 lines_end points
double a,b,x0,y0;
float v_distance=0; // the distance of angle between 2 vertical lines
float h_distance=0; // the distance of angle between 2 horizontal lines
float ratio_distance=0;// the distance in ration (in compare with the standard plate)
float angle_vl=can_vl[1];
float angle_vr=can_vr[1];
float angle_hd=can_hd[1];
float angle_hu=can_hu[1];
float rho_vl,rho_vr,rho_hu,rho_hd;
rho_vl=can_vl[0];
rho_vr=can_vr[0];
rho_hd=can_hd[0];
rho_hu=can_hu[0];
//------determine the candidate of line_end_point
a = cos(angle_vl); b = sin(angle_vl);
x0 = a*rho_vl; y0 = b*rho_vl;
pt11.x = cvRound(x0 + 1000*(-b));
pt11.y = cvRound(y0 + 1000*(a));
pt12.x = cvRound(x0 - 1000*(-b));
pt12.y = cvRound(y0 - 1000*(a));
a = cos(angle_vr); b = sin(angle_vr);
x0 = a*rho_vr; y0 = b*rho_vr;
pt21.x = cvRound(x0 + 1000*(-b));
pt21.y = cvRound(y0 + 1000*(a));
pt22.x = cvRound(x0 - 1000*(-b));
pt22.y = cvRound(y0 - 1000*(a));
a = cos(angle_hu); b = sin(angle_hu);
x0 = a*rho_hu; y0 = b*rho_hu;
pt31.x = cvRound(x0 + 1000*(-b));
pt31.y = cvRound(y0 + 1000*(a));
pt32.x = cvRound(x0 - 1000*(-b));
pt32.y = cvRound(y0 - 1000*(a));
a = cos(angle_hd); b = sin(angle_hd);
x0 = a*rho_hd; y0 = b*rho_hd;
pt41.x = cvRound(x0 + 1000*(-b));
pt41.y = cvRound(y0 + 1000*(a));
pt42.x = cvRound(x0 - 1000*(-b));
pt42.y = cvRound(y0 - 1000*(a));
//----------------------------------------------
Point cn1,cn2,cn3,cn4;
cn3=intersection(pt31,pt32,pt21,pt22);
cn4=intersection(pt41,pt42,pt21,pt22);
cn1=intersection(pt11,pt12,pt31,pt32);
cn2=intersection(pt11,pt12,pt41,pt42);
int height,width;
height=img.size().height;
width=img.size().width;
Mat img_affine;
Point2f a2(0, 0), b2(width, 0), c2(width, height),d2(0,height);
Point2f src_point[] = {cn1, cn2,cn3,cn4};
Point2f dst_point[] = {a2, d2, b2,c2};
//Mat warpMat = getAffineTransform(src_point, dst_point);
//warpAffine(img,img_affine, warpMat, img.size());
Mat warpMat = getPerspectiveTransform(src_point, dst_point);
warpPerspective(img,img_affine, warpMat, img.size());
//display_image(img_affine);
bool check;
check=check_plate(img_affine);
angle_vr=angle_vr* 180.0 / 3.14159;
angle_vl=angle_vl* 180.0 / 3.14159;
angle_hd=angle_hd* 180.0 / 3.14159;
angle_hu=angle_hu* 180.0 / 3.14159;
//----------------------------------------------
if ((angle_vr!=0)||(angle_vl!=0))
{
v_distance=abs(abs(angle_vl)-abs(angle_vr))/angle_threshold;
}
else
{
v_distance=0;
}
if ((angle_hu!=0)||(angle_hd!=0))
{
h_distance=abs(angle_hu-angle_hd)/angle_threshold;
}
else
{
h_distance=0;
}
float d_vl=norm(cn1-cn2);//length of vertical left line
float d_vr=norm(cn3-cn4);//length of vertical right line
float d_hu=norm(cn1-cn3);//length of horizontal up line
float d_hd=norm(cn2-cn4);//length of horizontal down line
float ratio_i=(d_hu+d_hd)/(d_vl+d_vr);
int height_approx,width_approx;
height_approx=height-2*region_extend;
width_approx=width-2*region_extend;
//ratio_distance=abs(ratio-ratio_long)/ratio_long;
ratio_distance=abs(ratio_i-ratio)/ratio;
float total_distance;
total_distance=9999;
if ((d_vl<1.2*height_approx)&&(d_vl>0.5*height_approx)&&(d_hu<1.2*width_approx)&&(d_hu>0.5*width_approx)&&(d_hd<1.2*width_approx)&&(d_hd>0.5*width_approx)&&(d_vr<1.2*height_approx)&&(d_vr>0.5*height_approx))
{
if ((v_distance<1)&&(h_distance<1)&&(ratio_i<1.7)&&(ratio_i>1)&&(check==1))
{
total_distance=v_distance+h_distance+ratio_distance;
}
else
{
total_distance=9999;
}
}
//printf("v=%f h=%f r=%f final =%f\n",v_distance,h_distance,ratio_distance,total_distance);
return(total_distance);
}
float croping_v2_color(Mat img_src,Point &cn1, Point &cn2, Point &cn3, Point &cn4,float ratio)
{
Mat img;
img=thresholding_color(img_src);
//display_image(img);
Mat img_t1;
adaptiveThreshold(img, img_t1, 255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 9,0 );
Mat img_canny;
Canny(img,img_canny,50,150,3);
/*img=img_src;
Mat img_t1;
adaptiveThreshold(img, img_t1, 255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 9,0 );
Mat img_canny;
display_image(img_t1);
Canny(img_t1,img_canny,60,180,3);*/
//display_image(img_canny);
int height=img.size().height;
int width=img.size().width;
vector<Vec2f> lines; //vector that stores all the lines detected by Hough Transform
vector<Vec2f> lines_hu; // vector that stores all the candidates for the upper horizontal line
vector<Vec2f> lines_hd;// vector that stores all the candidates for the lower horizontal line
vector<Vec2f> lines_vl;// vector that stores all the candidates for the left vertical line
vector<Vec2f> lines_vr;// vector that stores all the candidates for the right vertical line
int thres_vote=floor(height/5 );// minimum votes for a line (in Hough transform)
HoughLines(img_canny,lines, 1, CV_PI/180,thres_vote, 0, 0 ); // Hough transform to detect lines whose votes> thres_vote. All lines are saved into vector lines
//printf("thres_vote=%d,number of lines is %d\n",thres_vote,lines.size());
Point pt1,pt2,pt3,pt4,pt5,pt6; //pt3,pt4,pt5,pt6 are 4 points at conrner of the image
pt3.x=0; pt3.y=0; //top left corner;
pt4.x=0; pt4.y=height-1;// bottom left corner;
pt5.x=width-1;pt5.y=0;//top right cornenr
pt6.x=width-1;pt6.y=height-1;//bottom right corner
float interthres=0.5; //threshold to decide if a lines belong to hu,hd,vl,vr or not
//------------Detect line candidates and store them in the correspond vector-------------
Mat img_clone;
img_clone=img_src;
cvtColor(img_clone, img_clone, CV_GRAY2BGR);
for (int i=0;i<(int) lines.size();i++)
{
float rho,theta;
double a,b,x0,y0;
Point int1,int2;
rho = lines[i][0];
theta = lines[i][1];
a = cos(theta);
b = sin(theta);
x0 = a*rho;
y0 = b*rho;
pt1.x = cvRound(x0 + 1000*(-b));
pt1.y = cvRound(y0 + 1000*(a));
pt2.x = cvRound(x0 - 1000*(-b));
pt2.y = cvRound(y0 - 1000*(a));
if ( theta>CV_PI/180*155 || theta<CV_PI/180*25)
{
interthres=0.5;
int1=intersection(pt1,pt2,pt3,pt5);
int2=intersection(pt1,pt2,pt4,pt5);
line( img_clone, int1, int2, Scalar(0,255,0), 1, CV_AA);
if ((int1.x<interthres*width)&&(int2.x<interthres*width))
{
lines_vl.push_back(lines[i]);
}
else if ((int1.x>(1-interthres)*width)&&(int2.x>(1-interthres)*width))
{
lines_vr.push_back(lines[i]);
}
}
else if ( theta>CV_PI/180*65 && theta<CV_PI/180*115)
{
interthres=0.5;
int1=intersection(pt1,pt2,pt3,pt4);
int2=intersection(pt1,pt2,pt5,pt6);
if ((int1.y<interthres*height)&&(int2.y<interthres*height))
{
lines_hu.push_back(lines[i]);
}
else if ((int1.y>(1-interthres)*height)&&(int2.y>(1-interthres)*height))
{
lines_hd.push_back(lines[i]);
}
}
}
//display_image(img_clone);
//printf("vl=%d, vr=%d, hu=%d, hu=%d\n",lines_vl.size(),lines_vr.size(),lines_hd.size(),lines_hu.size());
//----------------- End of line detection------------------------------------------
//------------------Preparation to find the best set of lines to form the license plate-----------
unsigned int max_line=3; // We check "max_line" number of candidate from each vector
int num_vl=0; // The actual number of vertical left to be checked, this could be different from max_line if lines_vl.size()<max_line
int num_vr=0;
int num_hu=0;
int num_hd=0;
int num_lines=0;//Number of lines that can be detected
float rho,theta;
double a,b,x0,y0;
Point pt11,pt12,pt21,pt22,pt31,pt32,pt41,pt42; //the cordinate of 4 lines_end points
//int type=0; //type =1:miss vl, type =2: miss vr, type =3: miss hu, type =4: miss hd
max_line=4;
if (lines_vl.size()>0)
{
if (lines_vl.size()>max_line)
{
num_vl=max_line;
}
else
{
num_vl=lines_vl.size();
}
rho = lines_vl[0][0]; theta = lines_vl[0][1];
a = cos(theta); b = sin(theta);
x0 = a*rho; y0 = b*rho;
pt11.x = cvRound(x0 + 1000*(-b));
pt11.y = cvRound(y0 + 1000*(a));
pt12.x = cvRound(x0 - 1000*(-b));
pt12.y = cvRound(y0 - 1000*(a));
num_lines++;
}
else
{
pt11=pt3;pt12=pt4;
//type=1;
}
if (lines_vr.size()>0)
{
if (lines_vr.size()>max_line)
{
num_vr=max_line;
}
else
{
num_vr=lines_vr.size();
}
rho = lines_vr[0][0]; theta = lines_vr[0][1];
a = cos(theta); b = sin(theta);
x0 = a*rho; y0 = b*rho;
pt21.x = cvRound(x0 + 1000*(-b));
pt21.y = cvRound(y0 + 1000*(a));
pt22.x = cvRound(x0 - 1000*(-b));
pt22.y = cvRound(y0 - 1000*(a));
num_lines++;
}
else
{
pt21=pt5;pt22=pt6;
// type=2;
}
max_line=2;
if (lines_hu.size()>0)
{
if (lines_hu.size()>max_line)
{
num_hu=max_line;
}
else
{
num_hu=lines_hu.size();
}
rho = lines_hu[0][0]; theta = lines_hu[0][1];
a = cos(theta); b = sin(theta);
x0 = a*rho; y0 = b*rho;
pt31.x = cvRound(x0 + 1000*(-b));
pt31.y = cvRound(y0 + 1000*(a));
pt32.x = cvRound(x0 - 1000*(-b));
pt32.y = cvRound(y0 - 1000*(a));
num_lines++;
}
else
{
pt31=pt3;pt32=pt5;
//type=3;
}
if (lines_hd.size()>0)
{
if (lines_hd.size()>max_line)
{
num_hd=max_line;
}
else
{
num_hd=lines_hd.size();
}
rho = lines_hd[0][0]; theta = lines_hd[0][1];
a = cos(theta); b = sin(theta);
x0 = a*rho; y0 = b*rho;
pt41.x = cvRound(x0 + 1000*(-b));
pt41.y = cvRound(y0 + 1000*(a));
pt42.x = cvRound(x0 - 1000*(-b));
pt42.y = cvRound(y0 - 1000*(a));
num_lines++;
}
else
{
pt41=pt4;pt42=pt6;
// type=4;
}
//printf("vl=%d vr=%d hu=%d hd=%d\n",num_vl,num_vr,num_hd,num_hu);
//--------------Start to find the best set of candidate to form the plate-------------------------------
int index_vl,index_vr,index_hu,index_hd; //index of chosen line
float plate_score;
Vec2f can_vl,can_vr,can_hu,can_hd; // the candidate lines to be check
//float d1,d2,delta_x,delta_y;
//printf("num_lines=%d\n",num_lines);
if (num_lines==4)
{
plate_score=99999; //the score that determine how likely the candidates could form a plate. The smaller score is, the more confident we have
for (int i=0;i<num_vl;i++)
{
for (int j=0;j<num_vr;j++)
{
for (int k=0;k<num_hu;k++)
{
for (int h=0;h<num_hd;h++)
{
can_vl=lines_vl[i];
can_vr=lines_vr[j];
can_hu=lines_hu[k];
can_hd=lines_hd[h];
float score_tmp=check_score_color(can_vl,can_vr,can_hu,can_hd,img_src,ratio);
//printf("score=%f\n",score_tmp);
if (plate_score>score_tmp)
{
plate_score=score_tmp;
index_vl=i;
index_vr=j;
index_hu=k;
index_hd=h;
}
}
}
}
}
can_vl=lines_vl[index_vl];
can_vr=lines_vr[index_vr];
can_hu=lines_hu[index_hu];
can_hd=lines_hd[index_hd];
//printf("index,vl=%d,vr=%d,hu=%d,hd=%d\n",index_vl,index_vr,index_hu,index_hd);
float angle_vl=can_vl[1];
float angle_vr=can_vr[1];
float angle_hd=can_hd[1];
float angle_hu=can_hu[1];
float rho_vl,rho_vr,rho_hu,rho_hd;
rho_vl=can_vl[0];
rho_vr=can_vr[0];
rho_hd=can_hd[0];
rho_hu=can_hu[0];
//------determine the candidate of line_end_point
a = cos(angle_vl); b = sin(angle_vl);
x0 = a*rho_vl; y0 = b*rho_vl;
pt11.x = cvRound(x0 + 1000*(-b));
pt11.y = cvRound(y0 + 1000*(a));
pt12.x = cvRound(x0 - 1000*(-b));
pt12.y = cvRound(y0 - 1000*(a));
a = cos(angle_vr); b = sin(angle_vr);
x0 = a*rho_vr; y0 = b*rho_vr;
pt21.x = cvRound(x0 + 1000*(-b));
pt21.y = cvRound(y0 + 1000*(a));
pt22.x = cvRound(x0 - 1000*(-b));
pt22.y = cvRound(y0 - 1000*(a));
a = cos(angle_hu); b = sin(angle_hu);
x0 = a*rho_hu; y0 = b*rho_hu;
pt31.x = cvRound(x0 + 1000*(-b));
pt31.y = cvRound(y0 + 1000*(a));
pt32.x = cvRound(x0 - 1000*(-b));
pt32.y = cvRound(y0 - 1000*(a));
a = cos(angle_hd); b = sin(angle_hd);
x0 = a*rho_hd; y0 = b*rho_hd;
pt41.x = cvRound(x0 + 1000*(-b));
pt41.y = cvRound(y0 + 1000*(a));
pt42.x = cvRound(x0 - 1000*(-b));
pt42.y = cvRound(y0 - 1000*(a));
//----------------------------------------------
cn3=intersection(pt31,pt32,pt21,pt22);
cn4=intersection(pt41,pt42,pt21,pt22);
cn1=intersection(pt11,pt12,pt31,pt32);
cn2=intersection(pt11,pt12,pt41,pt42);
}
/*
else if (num_lines==3)
{
if (type==1)
{
cn3=intersection(pt31,pt32,pt21,pt22);
cn4=intersection(pt41,pt42,pt21,pt22);
d1=norm(cn3-cn4); //distance between cn3, cn4
d2=d1*ratio;
delta_x=d2/sqrt(1+pow((cn3.y-pt32.y)/(cn3.x-pt32.x),2));
delta_y=delta_x*(cn3.y-pt32.y)/(cn3.x-pt32.x);
cn1.x=cn3.x-delta_x;
cn1.y=cn3.y-delta_y;
cn2.x=cn4.x-delta_x;
cn2.y=cn4.y-delta_y;
}
else if (type==2)
{
cn1=intersection(pt11,pt12,pt31,pt32);
cn2=intersection(pt11,pt12,pt41,pt42);
d1=norm(cn1-cn2);
d2=d1*ratio;
delta_x=d2/sqrt(1+pow((cn1.y-pt32.y)/(cn1.x-pt32.x),2));
delta_y=delta_x*(cn1.y-pt32.y)/(cn1.x-pt32.x);
cn3.x=cn1.x+delta_x;
cn3.y=cn1.y+delta_y;
cn4.x=cn2.x+delta_x;
cn4.y=cn2.y+delta_y;
}
else if (type==3)
{
cn4=intersection(pt21,pt22,pt41,pt42);
cn2=intersection(pt11,pt12,pt41,pt42);
d1=norm(cn4-cn2);
d2=d1/ratio;
delta_y=d2/sqrt(1+pow((pt12.x-cn2.x)/(cn2.y-pt12.y),2));
delta_x=delta_y*(pt12.x-cn2.x)/(pt12.y-cn2.y);
cn1.x=cn2.x-delta_x;
cn1.y=cn2.y-delta_y;
cn3.x=cn4.x-delta_x;
cn3.y=cn4.y-delta_y;
}
else if (type==4)
{
cn1=intersection(pt11,pt12,pt31,pt32);
cn3=intersection(pt31,pt32,pt21,pt22);
d1=norm(cn1-cn3);
d2=d1/ratio;
delta_y=d2/sqrt(1+pow((pt12.x-cn1.x)/(cn1.y-pt12.y),2));
delta_x=delta_y*(pt12.x-cn1.x)/(pt12.y-cn1.y);
cn2.x=cn1.x+delta_x;
cn2.y=cn1.y+delta_y;
cn4.x=cn3.x+delta_x;
cn4.y=cn3.y+delta_y;
}
plate_score=100;
}
*/
else
{
plate_score=9999;
}
return(plate_score);
} |
921ee247bf0bcbec6d00b4d09580b0dd7b177c5d | 9d4f0b8c133b39762afc66eb2b7fd08c1fe28d2f | /day_2/task1.cpp | f828b31b47ebe4a006e9d1eb8b30b3e28e63e8c0 | [] | no_license | lvjonok/ibc_programming | 4274e8749d989a48191e46bf2177c9d02cf11cd6 | a45c1fe576d5f55c369c1a10661d3c02193a86a1 | refs/heads/master | 2022-11-29T17:49:05.649196 | 2020-08-14T18:57:49 | 2020-08-14T18:57:49 | 286,439,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | cpp | task1.cpp | #include <iostream>
#include <map>
using namespace std;
int get_path_cost(int vertices[4], int paths[4][4]){
int path_cost = 0;
for (int i = 0; i < 4; i++){
path_cost += paths[vertices[i]][vertices[(i + 1) % 4]];
}
return path_cost;
}
bool is__path_valid(int vertices[4]){
map<int, bool> contains;
for (int i = 0; i < 4; i++){
if (contains[vertices[i]]) return false;
contains[vertices[i]] = true;
}
return true;
}
int main(){
int matrix[4][4] = {
{0, 10, 8, 6},
{10, 0, 3, 7},
{8, 3, 0, 1},
{6, 7, 1, 0}
};
int min_path = 32000;
for (int v2 = 0; v2 < 4; v2++){
for (int v3 = 0; v3 < 4; v3++){
for (int v4 = 0; v4 < 4; v4++){
int path[4] = {0, v2, v3, v4};
if (is__path_valid(path)){
min_path = min(min_path, get_path_cost(path, matrix));
}
}
}
}
cout << min_path << endl;
return 0;
} |
d092af8c3eb19a78709ba9af6f13610eddd04b00 | 33d6d6f71587d5b840e99a12119a19f4ebffb2d8 | /example_prefetchers/ip_stride_prefetcher.cc | eda63e26e30b627ec64eec998e46a98d243fc1da | [] | no_license | nus-comparch/cs5222-lab-prefetcher | d31a8f58251678af9642b50c4d9ff03a5670892c | c685cc80d68869c7766bdcbe1d0784fe62007c6b | refs/heads/master | 2022-04-30T04:43:13.803621 | 2022-04-07T11:20:07 | 2022-04-07T11:20:07 | 129,469,047 | 3 | 10 | null | 2022-04-14T15:14:55 | 2018-04-14T01:12:29 | C++ | UTF-8 | C++ | false | false | 4,644 | cc | ip_stride_prefetcher.cc | //
// Data Prefetching Championship Simulator 2
// Seth Pugsley, seth.h.pugsley@intel.com
//
/*
This file describes an Instruction Pointer-based (Program Counter-based) stride prefetcher.
The prefetcher detects stride patterns coming from the same IP, and then
prefetches additional cache lines.
Prefetches are issued into the L2 or LLC depending on L2 MSHR occupancy.
*/
#include <stdio.h>
#include "../inc/prefetcher.h"
#define IP_TRACKER_COUNT 1024
#define PREFETCH_DEGREE 3
typedef struct ip_tracker
{
// the IP we're tracking
unsigned long long int ip;
// the last address accessed by this IP
unsigned long long int last_addr;
// the stride between the last two addresses accessed by this IP
long long int last_stride;
// use LRU to evict old IP trackers
unsigned long long int lru_cycle;
} ip_tracker_t;
ip_tracker_t trackers[IP_TRACKER_COUNT];
void l2_prefetcher_initialize(int cpu_num)
{
printf("IP-based Stride Prefetcher\n");
// you can inspect these knob values from your code to see which configuration you're runnig in
printf("Knobs visible from prefetcher: %d %d %d\n", knob_scramble_loads, knob_small_llc, knob_low_bandwidth);
int i;
for(i=0; i<IP_TRACKER_COUNT; i++)
{
trackers[i].ip = 0;
trackers[i].last_addr = 0;
trackers[i].last_stride = 0;
trackers[i].lru_cycle = 0;
}
}
void l2_prefetcher_operate(int cpu_num, unsigned long long int addr, unsigned long long int ip, int cache_hit)
{
// uncomment this line to see all the information available to make prefetch decisions
//printf("(%lld 0x%llx 0x%llx %d %d %d) ", get_current_cycle(0), addr, ip, cache_hit, get_l2_read_queue_occupancy(0), get_l2_mshr_occupancy(0));
// check for a tracker hit
int tracker_index = -1;
int i;
for(i=0; i<IP_TRACKER_COUNT; i++)
{
if(trackers[i].ip == ip)
{
trackers[i].lru_cycle = get_current_cycle(0);
tracker_index = i;
break;
}
}
if(tracker_index == -1)
{
// this is a new IP that doesn't have a tracker yet, so allocate one
int lru_index=0;
unsigned long long int lru_cycle = trackers[lru_index].lru_cycle;
int i;
for(i=0; i<IP_TRACKER_COUNT; i++)
{
if(trackers[i].lru_cycle < lru_cycle)
{
lru_index = i;
lru_cycle = trackers[lru_index].lru_cycle;
}
}
tracker_index = lru_index;
// reset the old tracker
trackers[tracker_index].ip = ip;
trackers[tracker_index].last_addr = addr;
trackers[tracker_index].last_stride = 0;
trackers[tracker_index].lru_cycle = get_current_cycle(0);
return;
}
// calculate the stride between the current address and the last address
// this bit appears overly complicated because we're calculating
// differences between unsigned address variables
long long int stride = 0;
if(addr > trackers[tracker_index].last_addr)
{
stride = addr - trackers[tracker_index].last_addr;
}
else
{
stride = trackers[tracker_index].last_addr - addr;
stride *= -1;
}
// don't do anything if we somehow saw the same address twice in a row
if(stride == 0)
{
return;
}
// only do any prefetching if there's a pattern of seeing the same
// stride more than once
if(stride == trackers[tracker_index].last_stride)
{
// do some prefetching
int i;
for(i=0; i<PREFETCH_DEGREE; i++)
{
unsigned long long int pf_address = addr + (stride*(i+1));
// only issue a prefetch if the prefetch address is in the same 4 KB page
// as the current demand access address
if((pf_address>>12) != (addr>>12))
{
break;
}
// check the MSHR occupancy to decide if we're going to prefetch to the L2 or LLC
if(get_l2_mshr_occupancy(0) < 8)
{
l2_prefetch_line(0, addr, pf_address, FILL_L2);
}
else
{
l2_prefetch_line(0, addr, pf_address, FILL_LLC);
}
}
}
trackers[tracker_index].last_addr = addr;
trackers[tracker_index].last_stride = stride;
}
void l2_cache_fill(int cpu_num, unsigned long long int addr, int set, int way, int prefetch, unsigned long long int evicted_addr)
{
// uncomment this line to see the information available to you when there is a cache fill event
//printf("0x%llx %d %d %d 0x%llx\n", addr, set, way, prefetch, evicted_addr);
}
void l2_prefetcher_heartbeat_stats(int cpu_num)
{
printf("Prefetcher heartbeat stats\n");
}
void l2_prefetcher_warmup_stats(int cpu_num)
{
printf("Prefetcher warmup complete stats\n\n");
}
void l2_prefetcher_final_stats(int cpu_num)
{
printf("Prefetcher final stats\n");
}
|
ca65fcebd4272fd2a59282373275949a1e198e8a | 9052c754d69b6fe46782551ae02d23d7fb460157 | /myinputpanel.h | 26de31aa3597f0b8b6cda88a74e8ca986349bb50 | [] | no_license | steamedbao/BeaglePhone | 77740a5151040ee82bc1038be90bdfc302dcfbdf | 2e2c5b4b622fee114df7272e991f38d2377bab5a | refs/heads/master | 2020-06-07T19:01:28.239176 | 2014-08-06T15:24:41 | 2014-08-06T15:24:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | h | myinputpanel.h | #ifndef MYINPUTPANEL_H
#define MYINPUTPANEL_H
#include <QtGui>
#include <QtCore>
#include "ui_myinputpanel.h"
class MyInputPanel : public QWidget
{
Q_OBJECT
public:
MyInputPanel();
signals:
void characterGenerated(QChar character);
void keyPressed(int key);
protected:
bool event(QEvent *e);
private slots:
void saveFocusWidget(QWidget *oldFocus, QWidget *newFocus);
void buttonClicked(QWidget *w);
private:
Ui::MyInputPanel form;
QWidget *lastFocusedWidget;
QSignalMapper signalMapper;
bool shiftClick;
void setKeyboardCaps();
void setKeyboardLower();
};
#endif // MYINPUTPANEL_H
|
d77791f223dc47458e0d043598e25dbaccaf14e0 | c6fa53212eb03017f9e72fad36dbf705b27cc797 | /L1Trigger/TrackTrigger/src/TTClusterAlgorithm_2d.cc | 2f642bef77b129c28ce51224415f4c7248546b03 | [] | no_license | gem-sw/cmssw | a31fc4ef2233b2157e1e7cbe9a0d9e6c2795b608 | 5893ef29c12b2718b3c1385e821170f91afb5446 | refs/heads/CMSSW_6_2_X_SLHC | 2022-04-29T04:43:51.786496 | 2015-12-16T16:09:31 | 2015-12-16T16:09:31 | 12,892,177 | 2 | 4 | null | 2018-11-22T13:40:31 | 2013-09-17T10:10:26 | C++ | UTF-8 | C++ | false | false | 9,830 | cc | TTClusterAlgorithm_2d.cc | /*! \brief Implementation of methods of TTClusterAlgorithm_2d
* \details Here, in the source file, the methods which do depend
* on the specific type <T> that can fit the template.
*
* \author Andrew W. Rose
* \date 2013, Jul 12
*
*/
#include "L1Trigger/TrackTrigger/interface/TTClusterAlgorithm_2d.h"
/// Clustering operations
template< >
void TTClusterAlgorithm_2d< Ref_PixelDigi_ >::Cluster( std::vector< std::vector< Ref_PixelDigi_ > > &output,
const std::vector< Ref_PixelDigi_ > &input ) const
{
/// Prepare the output
output.clear();
/// Prepare a proper hit container
std::map< std::pair< unsigned int, unsigned int>, pixelContainer< Ref_PixelDigi_ > > hitContainer;
typename std::map< std::pair< unsigned int, unsigned int >, pixelContainer< Ref_PixelDigi_ > >::iterator centralPixel;
/// First fill all, put the hits into a grid
/// Loop over all hits
typename std::vector< Ref_PixelDigi_ >::const_iterator inputIterator;
for( inputIterator = input.begin();
inputIterator != input.end();
++inputIterator )
{
/// Assign central Pixel
/// Assign kill bits
/// Assign neighbours
hitContainer[ std::make_pair( (**inputIterator).row(), (**inputIterator).column() ) ].centrePixel = &(*inputIterator);
hitContainer[ std::make_pair( (**inputIterator).row(), (**inputIterator).column() ) ].kill0 = false;
hitContainer[ std::make_pair( (**inputIterator).row(), (**inputIterator).column() ) ].kill1 = false;
hitContainer[ std::make_pair( (**inputIterator).row(), (**inputIterator).column() ) ].neighbours = 0x00;
} /// End of loop over all hits
/// Then search to see if neighbour hits exist
/// Loop over all central pixels
for( centralPixel = hitContainer.begin();
centralPixel != hitContainer.end();
++centralPixel )
{
/// Get the coordinates
unsigned int row = centralPixel->first.first;
unsigned int col = centralPixel->first.second;
/// Layout of the grid to understand what follows
/// a b c 0 1 2 -->r/phi = increasing row
/// d x e = 3 x 4 |
/// f g h 5 6 7 V z = decreasing column
/// Just check if there are neighbours and, if so,
/// assign the corresponding bit to be true/false
/// Column +1, rows from -1 to +1
centralPixel->second.neighbours[0] = ( hitContainer.find( std::make_pair( row-1, col+1 ) ) != hitContainer.end() );
centralPixel->second.neighbours[1] = ( hitContainer.find( std::make_pair( row , col+1 ) ) != hitContainer.end() );
centralPixel->second.neighbours[2] = ( hitContainer.find( std::make_pair( row+1, col+1 ) ) != hitContainer.end() );
/// Column 0, rows -1 and +1
centralPixel->second.neighbours[3] = ( hitContainer.find( std::make_pair( row-1, col ) ) != hitContainer.end() );
centralPixel->second.neighbours[4] = ( hitContainer.find( std::make_pair( row+1, col ) ) != hitContainer.end() );
/// Column -1, rows from -1 to +1
centralPixel->second.neighbours[5] = ( hitContainer.find( std::make_pair( row-1, col-1 ) ) != hitContainer.end() );
centralPixel->second.neighbours[6] = ( hitContainer.find( std::make_pair( row , col-1 ) ) != hitContainer.end() );
centralPixel->second.neighbours[7] = ( hitContainer.find( std::make_pair( row+1, col-1 ) ) != hitContainer.end() );
} /// End of loop over all central pixels
/// Then fill the kill bits
/// Loop over all central pixels
for( centralPixel = hitContainer.begin();
centralPixel != hitContainer.end();
++centralPixel )
{
/// KB 1) The first kill bit, kill0, prevents a cluster to be larger than 2 pixels in r-phi: if both columns
/// adf and ceh contain at least one pixel over threshold each, this bit is set to 1, otherwise it is set to 0
/// KB 2) The second kill bit, kill1, makes the cluster to be built only if pix is in the leftmostbottom position
/// within the cluster: if there is a pixel over threshold either in column adf or in position g,
/// this bit is set to 1, otherwise it is set to 0
/// Check row -1
bool adf = centralPixel->second.neighbours[0] | centralPixel->second.neighbours[3] | centralPixel->second.neighbours[5] ;
/// Check row +1
bool ceh = centralPixel->second.neighbours[2] | centralPixel->second.neighbours[4] | centralPixel->second.neighbours[7] ;
/// Kill bits are set here
centralPixel->second.kill0 = ( adf & ceh );
centralPixel->second.kill1 = ( adf | centralPixel->second.neighbours[6] );
} /// End of loop over all central pixels
/// Then cross check for the final kill bit
/// Loop over all central pixels
for( centralPixel = hitContainer.begin();
centralPixel != hitContainer.end();
++centralPixel )
{
/// Get the coordinates
unsigned int row = centralPixel->first.first;
unsigned int col = centralPixel->first.second;
/// KB 3) if at least one of the pixels, in ceh column, fired and features its kill0 = 1, let a^M /// third kill bit kill2 be 1, otherwise set it to 0
/// NOTE that kill2 prevents the pixel to report a cluster when looking at its size out of the 3x3
/// pixel window under examination
bool kill2 = false;
typename std::map< std::pair< unsigned int, unsigned int >, pixelContainer< Ref_PixelDigi_ > >::iterator rhs;
if ( ( rhs = hitContainer.find( std::make_pair( row+1, col-1 ) ) ) != hitContainer.end() ) kill2 |= rhs->second.kill0;
if ( ( rhs = hitContainer.find( std::make_pair( row+1, col ) ) ) != hitContainer.end() ) kill2 |= rhs->second.kill0;
if ( ( rhs = hitContainer.find( std::make_pair( row+1, col+1 ) ) ) != hitContainer.end() ) kill2 |= rhs->second.kill0;
/// If all the kill bits are fine,
/// then the Cluster can be prepared for output
if ( !centralPixel->second.kill0 && !centralPixel->second.kill1 && !kill2 )
{
/// Store the central pixel
std::vector< Ref_PixelDigi_ > temp;
temp.push_back( *hitContainer[ std::make_pair( row , col ) ].centrePixel );
/// Store all the neighbours
if( centralPixel->second.neighbours[0] ) temp.push_back ( *hitContainer[ std::make_pair( row-1, col+1 ) ].centrePixel );
if( centralPixel->second.neighbours[1] ) temp.push_back ( *hitContainer[ std::make_pair( row , col+1 ) ].centrePixel );
if( centralPixel->second.neighbours[2] ) temp.push_back ( *hitContainer[ std::make_pair( row+1, col+1 ) ].centrePixel );
if( centralPixel->second.neighbours[3] ) temp.push_back ( *hitContainer[ std::make_pair( row-1, col ) ].centrePixel );
if( centralPixel->second.neighbours[4] ) temp.push_back ( *hitContainer[ std::make_pair( row+1, col ) ].centrePixel );
if( centralPixel->second.neighbours[5] ) temp.push_back ( *hitContainer[ std::make_pair( row-1, col-1 ) ].centrePixel );
if( centralPixel->second.neighbours[6] ) temp.push_back ( *hitContainer[ std::make_pair( row , col-1 ) ].centrePixel );
if( centralPixel->second.neighbours[7] ) temp.push_back ( *hitContainer[ std::make_pair( row+1, col-1 ) ].centrePixel );
output.push_back(temp);
} /// End of "all the kill bits are fine"
} /// End of loop over all central pixels
/// Eventually, if needed, do the
/// test for double counting!
if( mDoubleCountingTest )
{
std::set< std::pair< unsigned int, unsigned int > > test;
std::set< std::pair< unsigned int, unsigned int > > doubles;
typename std::vector< std::vector< Ref_PixelDigi_ > >::iterator outputIterator1;
typename std::vector< Ref_PixelDigi_ >::iterator outputIterator2;
/// Loop over Clusters
for ( outputIterator1 = output.begin();
outputIterator1 != output.end();
++outputIterator1 )
{
/// Loop over Hits inside each Cluster
for ( outputIterator2 = outputIterator1->begin();
outputIterator2 != outputIterator1->end();
++outputIterator2 )
{
/// Are there Hits with same coordinates?
/// If yes, put in doubles vector, else in test one
if ( test.find( std::make_pair( (**outputIterator2).row(), (**outputIterator2).column() ) ) != test.end() )
doubles.insert( std::make_pair( (**outputIterator2).row(), (**outputIterator2).column() ) );
else
test.insert( std::make_pair( (**outputIterator2).row(), (**outputIterator2).column() ) );
} /// End of loop over Hits inside each Cluster
} /// End of loop over Clusters
/// If we found duplicates
/// WARNING is it really doing something
/// more than printout???????
if ( doubles.size() )
{
std::set< std::pair< unsigned int, unsigned int> >::iterator it;
std::stringstream errmsg;
/// Printout double Pixel
for ( it = doubles.begin(); it != doubles.end(); ++it )
{
errmsg << "Double counted pixel: (" << it->first << "," << it->second << ")\n";
}
/// Loop over Clusters
for ( outputIterator1 = output.begin();
outputIterator1 != output.end();
++outputIterator1 )
{
errmsg << "cluster: ";
/// Loop over Hits inside each Cluster
for ( outputIterator2 = outputIterator1->begin();
outputIterator2 != outputIterator1->end();
++outputIterator2 )
{
errmsg << "| (" << (**outputIterator2).row() <<","<< (**outputIterator2).column()<< ") ";
}
errmsg << "|\n";
} /// End of loop over Clusters
edm::LogError("TTClusterAlgorithm_2d") << errmsg.str();
} /// End of "if we found duplicates"
} /// End of test for double counting
} /// End of TTClusterAlgorithm_2d< ... >::Cluster( ... )
|
b74d7b996c44fe44f6f6cdd81ac1e516c96a3f24 | 7562c0c5db5fbfc936bfd602983f6b7323bf41ad | /Woods_Game/Dialog.cpp | 325e5d5f8e57fc78302aec133ff38a3df5ca12d5 | [] | no_license | brandr/Woods_Game | e25f928f687504bfa12a450ccbb1ff2e3caf1260 | 0c9ce565153e53d1d196a2156fcd39f5b6cd13d7 | refs/heads/master | 2021-06-05T23:48:30.637231 | 2020-05-26T02:05:55 | 2020-05-26T02:05:55 | 92,340,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,271 | cpp | Dialog.cpp | #include "Dialog.h"
#include "DialogTree.h"
#include "ImageLoader.h"
const int Dialog::current_num_characters()
{
return this->character_counter/this->get_dialog_text_scroll_frames();
}
const int Dialog::get_dialog_text_scroll_frames()
{
return DIALOG_TEXT_SCROLL_BASE_FRAMES / (this->text_speed * 2);
}
const bool Dialog::is_showing_full_page()
{
DialogPage * page = this->current_page();
if (page) {
return this->current_num_characters() >= page->total_num_characters();
}
return false;
}
const bool Dialog::has_current_page()
{
return this->page_map.find(this->page_num) != this->page_map.end();
}
const bool Dialog::current_page_has_options()
{
DialogPage * page = this->current_page();
if (page != NULL) {
return page->has_options();
}
return false;
}
DialogPage * Dialog::current_page()
{
return this->has_current_page() ? this->page_map[this->page_num] : NULL;
}
void Dialog::set_quest_updates_for_page(const int page_num, std::vector<QuestUpdate*> quest_updates)
{
if (this->page_map.find(page_num) == this->page_map.end()) {
this->page_map[page_num] = new DialogPage();
}
this->page_map[page_num]->set_quest_updates(quest_updates);
}
void Dialog::set_portrait_image_key_for_page(const int page_num, const std::string image_key)
{
if (this->page_map.find(page_num) == this->page_map.end()) {
this->page_map[page_num] = new DialogPage();
}
this->page_map[page_num]->set_portrait_image_key(image_key);
}
void Dialog::dialog_sound_update(DialogPage * page)
{
//TODO: different "voices"
// plays the audio of the last character (as long as it's a letter)
const int num_characters = this->current_num_characters();
const std::vector<std::string> text_lines = page->get_text_lines(num_characters);
const int num_lines = text_lines.size();
if (num_lines > 0) {
const std::string last_line = text_lines[num_lines - 1];
const int last_line_size = last_line.size();
if (last_line_size > 0) {
const char letter = last_line.back();
if (isalpha(letter)) {
this->play_syllable_audio(letter);
}
}
}
}
void Dialog::play_syllable_audio(const char letter)
{
std::string syllable_filename = this->get_dialog_sound_path();
if (!syllable_filename.empty()) {
syllable_filename += letter;
AudioManager::get_instance().stop_all_sfx(std::to_string(SOUND_KEY_DIALOG));
AudioManager::get_instance().play_sfx(syllable_filename, std::to_string(SOUND_KEY_DIALOG));
}
}
const std::string Dialog::get_dialog_sound_path()
{
std::string path = "";
if (!voice_key.empty()) {
path += "dialog_sounds/voices/" + voice_key + "/syllables/";
}
return path;
}
void Dialog::initialize_text_speed()
{
FileManager filemanager;
std::string filename = "resources/config";
Configurations * config = new Configurations();
filemanager.load_xml_content(config, filename, "SerializableClass", "ConfigurationsKey", "current_configurations");
this->text_speed = config->get_text_scroll_speed();
}
Dialog::Dialog()
{
this->option_arrow = ImageLoader::get_instance().get_image("ui/arrows/ui_arrow_small");
this->initialize_text_speed();
}
Dialog::~Dialog()
{
}
void Dialog::update()
{
if (this->should_scroll_text) {
DialogPage * page = this->current_page();
if (page && this->current_num_characters() < page->total_num_characters()) {
const int prev_chars = this->current_num_characters();
this->character_counter++;
const int new_chars = this->current_num_characters();
if (new_chars > prev_chars) {
this->dialog_sound_update(page);
}
}
}
}
void Dialog::mouse_cursor_update(ALLEGRO_FONT * font, const int mouse_x, const int mouse_y, const int x_off, const int y_off)
{
if (this->has_current_page()) {
DialogPage * page = this->page_map[this->page_num];
const bool page_has_options = page->has_options();
const int num_characters = this->should_scroll_text ? this->current_num_characters() : page->total_num_characters();
const std::vector<std::string> text_lines = page->get_text_lines(num_characters);
const int line_count = text_lines.size();
int option_index = 0;
int text_x_off = 0;
for (int l = 0; l < line_count; l++) {
const std::string text = text_lines[l];
const bool line_has_option = page->has_option(l);
if (line_has_option) {
const int opt_off = 34;
const int x = x_off + DIALOG_OFFSET_X + opt_off, y = y_off + DIALOG_OFFSET_Y + (l * DIALOG_LINE_SPACING);
const int text_width = al_get_text_width(font, text.c_str()), text_height = DIALOG_LINE_SPACING;
if (mouse_x >= x && mouse_y >= y && mouse_x < x + text_width && mouse_y < y + text_height) {
this->selected_option_index = option_index;
return;
}
option_index++;
}
}
}
}
const bool Dialog::mouse_option_is_selected(ALLEGRO_FONT * font, const int mouse_x, const int mouse_y, const int x_off, const int y_off) {
if (this->has_current_page()) {
DialogPage * page = this->page_map[this->page_num];
const bool page_has_options = page->has_options();
const int num_characters = this->should_scroll_text ? this->current_num_characters() : page->total_num_characters();
const std::vector<std::string> text_lines = page->get_text_lines(num_characters);
const int line_count = text_lines.size();
int option_index = 0;
int text_x_off = 0;
for (int l = 0; l < line_count; l++) {
const std::string text = text_lines[l];
const bool line_has_option = page->has_option(l);
if (line_has_option) {
const int opt_off = 34;
const int x = x_off + opt_off + DIALOG_OFFSET_X, y = y_off + DIALOG_OFFSET_Y + (l * DIALOG_LINE_SPACING);
const int text_width = font != NULL ? al_get_text_width(font, text.c_str()) : 120,
text_height = DIALOG_LINE_SPACING;
if (mouse_x >= x && mouse_y >= y && mouse_x < x + text_width && mouse_y < y + text_height) {
this->selected_option_index = option_index;
return true;
}
option_index++;
}
}
}
return false;
}
void Dialog::process_mouse_click_left(ALLEGRO_FONT * font, const int mouse_x, const int mouse_y, const int x_off, const int y_off)
{
// the actual advance dialog step happens in MainGameScreen
this->mouse_cursor_update(font, mouse_x, mouse_y, x_off, y_off);
}
void Dialog::add_line(const std::string line_text, const int page_num, const int next_page_num, const int line_num, const std::string option_action_key,
std::vector<InteractAction *> page_actions, DialogItemOption * option)
{
if (this->page_map.find(page_num) == this->page_map.end()) {
this->page_map[page_num] = new DialogPage();
this->page_map[page_num]->next_page_number = next_page_num;
}
if (!page_actions.empty()) {
this->page_map[page_num]->dialog_actions = page_actions;
}
DialogPage * page = this->page_map[page_num];
int size = page->lines.size();
while (line_num >= size) {
size = page->lines.size();
page->lines.push_back(new DialogLine());
}
page->lines[line_num]->text = line_text;
if (option != NULL) {
page->lines[line_num]->option_action_key = option->option_action_key.value();
page->lines[line_num]->option_page_num = option->next_page_index.value();
if (option->has_trigger_status()) {
page->lines[line_num]->trigger_status = &(option->trigger_status);
}
} else if (option_action_key != "") {
page->lines[line_num]->option_action_key = option_action_key;
}
}
void Dialog::parse_text(const std::string text)
{
FileManager manager;
std::string page_token = DIALOG_PAGE_TOKEN;
std::string line_token = DIALOG_LINE_TOKEN;
std::string option_token = DIALOG_OPTION_TOKEN;
std::string option_text_token = DIALOG_OPTION_TEXT_TOKEN;
std::string option_action_token = DIALOG_OPTION_ACTION_TOKEN;
const std::vector< std::string> pages = manager.parse_tags(text, page_token);
const int page_count = pages.size();
int page_index = 0;
for (int p = 0; p < page_count; p++) {
bool empty_page = true;
int line_index = 0;
const std::string page = pages[p];
const std::vector<std::string> lines = manager.parse_tags(page, line_token);
const int line_count = lines.size();
for (int l = 0; l < line_count; l++) {
const std::string line = lines[l];
if (line.size() > 0) {
std::string line_text = line;
std::string option_action_key = "";
const std::vector<std::string> options = manager.parse_tags(line, option_token);
if (options.size() > 0) {
// only one option per line
const std::string option = options[0];
line_text = manager.parse_tags(option, option_text_token)[0];
option_action_key = manager.parse_tags(option, option_action_token)[0];
}
this->add_line(line_text, page_index, -1, line_index, option_action_key, std::vector<InteractAction*>(), NULL);
line_index++;
empty_page = false;
}
}
if (!empty_page) {
page_index++;
}
}
}
void Dialog::parse_dialog(DialogItem * dialog_item, const std::string voice_key)
{
FileManager manager;
std::string page_token = DIALOG_PAGE_TOKEN;
std::string line_token = DIALOG_LINE_TOKEN;
std::string option_token = DIALOG_OPTION_TOKEN;
std::string option_text_token = DIALOG_OPTION_TEXT_TOKEN;
std::string option_action_token = DIALOG_OPTION_ACTION_TOKEN;
std::vector<DialogItemPage *> pages = dialog_item->get_pages();
const int page_count = pages.size();
for (int p = 0; p < page_count; p++) {
int line_index = 0;
DialogItemPage * page = pages[p];
const int page_index = page->get_page_number();
const int next_page_index = page->next_page_index.value();
std::vector<InteractAction *> page_actions = page->get_dialog_actions();
const std::vector<std::string> lines = manager.parse_tags(page->dialog_text.value(), line_token);
const int line_count = lines.size();
for (int l = 0; l < line_count; l++) {
const std::string line = lines[l];
if (line.size() > 0) {
std::string line_text = line;
this->add_line(line_text, page_index, next_page_index, line_index, "", page_actions, NULL);
line_index++;
}
}
std::vector<DialogItemOption *> options = page->get_options();
const int option_size = options.size();
for (int i = 0; i < option_size; i++) {
DialogItemOption * dio = options[i];
this->add_line(dio->option_text.value(), page_index, next_page_index, line_index, "", page_actions, dio);
line_index++;
}
std::vector<QuestUpdate *> quest_updates = page->get_quest_updates();
this->set_quest_updates_for_page(page_index, quest_updates);
this->set_portrait_image_key_for_page(page_index, page->get_portrait_image_key());
this->voice_key = voice_key;
}
}
const std::string Dialog::get_active_action_key()
{
return this->active_action_key;
}
void Dialog::set_active_action_key(const std::string action_key)
{
this->active_action_key = action_key;
}
std::vector<InteractAction *> Dialog::get_active_actions() {
return this->active_actions;
}
void Dialog::clear_active_actions()
{
this->active_actions.clear();
}
void Dialog::add_active_action(InteractAction * action)
{
this->active_actions.push_back(action);
}
TriggerStatus * Dialog::get_active_trigger_status() {
return this->active_trigger_status;
}
void Dialog::set_active_trigger_status(TriggerStatus * value)
{
this->active_trigger_status = value;
}
void Dialog::decrement_option()
{
DialogPage * page = this->page_map[this->page_num];
if (page != NULL && page->has_options()) {
const int option_count = page->options_count();
this->selected_option_index = (this->selected_option_index - 1) % option_count;
AudioManager::get_instance().play_menu_scroll_sound();
}
}
void Dialog::increment_option()
{
DialogPage * page = this->page_map[this->page_num];
if (page != NULL && page->has_options()) {
const int option_count = page->options_count();
this->selected_option_index = (this->selected_option_index + 1) % option_count;
AudioManager::get_instance().play_menu_scroll_sound();
}
}
void Dialog::set_should_scroll_text(const bool value)
{
this->should_scroll_text = value;
}
void Dialog::set_action_bindings(std::vector<ActionBinding*> bindings)
{
this->action_bindings = bindings;
}
std::vector<ActionBinding*> Dialog::get_action_bindings()
{
return this->action_bindings;
}
std::vector<QuestUpdate*> Dialog::get_pending_quest_updates()
{
return this->pending_quest_updates;
}
void Dialog::unset_pending_quest_updates()
{
// don't use clear() because I think that deletes the objects the pointers point to
this->pending_quest_updates = std::vector<QuestUpdate *>();
}
const bool Dialog::has_portrait_image()
{
if (this->has_current_page()) {
DialogPage * page = this->page_map[this->page_num];
return page->has_portrait_image();
}
return false;
}
ALLEGRO_BITMAP * Dialog::get_portrait_image()
{
if (this->has_current_page()) {
DialogPage * page = this->page_map[this->page_num];
return page->get_portrait_image();
}
return NULL;
}
void Dialog::draw(ALLEGRO_DISPLAY * display, ALLEGRO_FONT * font, const int x_off, const int y_off)
{
if (this->has_current_page()) {
DialogPage * page = this->page_map[this->page_num];
const bool page_has_options = page->has_options();
const int num_characters = this->should_scroll_text ? this->current_num_characters() : page->total_num_characters();
const std::vector<std::string> text_lines = page->get_text_lines(num_characters);
const int line_count = text_lines.size();
int option_index = 0;
int text_x_off = 0;
for (int l = 0; l < line_count; l++) {
const std::string text = text_lines[l];
const bool line_has_option = page->has_option(l);
const int opt_off = line_has_option ? 34 : 0;
const int x = x_off + DIALOG_OFFSET_X, y = y_off + DIALOG_OFFSET_Y + (l * DIALOG_LINE_SPACING);
if (line_has_option) {
if (this->selected_option_index == option_index) {
al_draw_bitmap(this->option_arrow, x + text_x_off, y, 0);
}
option_index++;
}
al_draw_text(font, al_map_rgb(0, 0, 0), x + opt_off + text_x_off, y, 0, text.c_str());
}
}
}
DialogPage::DialogPage()
{
}
void Dialog::advance_dialog()
{
if (this->should_scroll_text && !this->is_showing_full_page()) {
DialogPage * page = this->current_page();
if (page) {
this->character_counter = page->total_num_characters()*DIALOG_TEXT_SCROLL_BASE_FRAMES;
}
} else {
int next_page_num = -1;
bool should_advance = true;
DialogPage * page = this->current_page();
if (page != NULL) {
if (page->has_options()) {
next_page_num = page->option_next_page_num(this->selected_option_index);
const std::string action_key = page->option_action_key(this->selected_option_index);
if (action_key.length() > 0) {
this->active_action_key = action_key;
should_advance = false;
}
TriggerStatus * trigger_status = page->trigger_status(this->selected_option_index);
if (trigger_status != NULL) {
this->active_trigger_status = trigger_status;
}
}
if (page->has_quest_updates()) {
std::vector<QuestUpdate *> updates = page->quest_updates;
this->pending_quest_updates = updates;
}
if (!page->dialog_actions.empty()) {
this->active_actions = page->dialog_actions;
page->dialog_actions.clear();
}
}
if (!should_advance) {
return;
}
this->character_counter = 0;
AudioManager::get_instance().play_sfx("dialog_sounds/dialog_advance", "" + SOUND_KEY_DIALOG);
if (next_page_num < 0) {
next_page_num = page->next_page_number;
}
// use -2 to say the dialog should end
if (next_page_num == -2) {
this->page_num = -1;
} else if (next_page_num == -1) {
this->page_num = this->page_num + 1;
} else {
this->page_num = next_page_num;
}
}
}
const int DialogPage::total_num_characters()
{
int num_characters = 0;
const int line_count = this->lines.size();
for (int l = 0; l < line_count; l++) {
DialogLine * line = this->lines[l];
const std::string text = line->text;
num_characters += text.size();
}
return num_characters;
}
const std::vector<std::string> DialogPage::get_text_lines(const int num_characters)
{
std::vector<std::string> text_lines;
int characters_remaining = num_characters;
const int total_line_count = this->lines.size();
for (int l = 0; l < total_line_count && characters_remaining > 0; l++) {
const std::string full_text_line = this->lines[l]->text;
const int full_line_length = full_text_line.size();
const int line_length = std::min(full_line_length, characters_remaining);
text_lines.push_back(full_text_line.substr(0, line_length));
characters_remaining -= line_length;
}
return text_lines;
}
const std::string DialogPage::option_action_key(const int index)
{
const int line_count = this->lines.size();
int option_index = 0;
for (int i = 0; i < line_count; i++) {
if (this->lines[i]->has_option()) {
if (this->lines[i]->has_option_action() && option_index == index) {
return this->lines[i]->option_action_key;
}
option_index++;
}
}
return "";
}
const int DialogPage::option_next_page_num(const int index)
{
const int line_count = this->lines.size();
int option_index = 0;
for (int i = 0; i < line_count; i++) {
if (this->lines[i]->has_option()) {
if (this->lines[i]->has_option_page() && option_index == index) {
return this->lines[i]->option_page_num;
}
option_index++;
}
}
return -1;
}
TriggerStatus * DialogPage::trigger_status(const int index)
{
const int line_count = this->lines.size();
int option_index = 0;
for (int i = 0; i < line_count; i++) {
if (this->lines[i]->has_option()) {
if (this->lines[i]->has_option_trigger_status() && option_index == index) {
return this->lines[i]->trigger_status;
}
option_index++;
}
}
return NULL;
}
const bool DialogPage::has_option(const int index)
{
const int size = this->lines.size();
return index >= 0 && index < size && this->lines[index]->has_option();
}
const bool DialogPage::has_options()
{
const int size = this->lines.size();
for (int i = 0; i < size; i++) {
if (this->lines[i]->has_option()) {
return true;
}
}
return false;
}
const int DialogPage::options_count()
{
int count = 0;
const int size = this->lines.size();
for (int i = 0; i < size; i++) {
if (this->lines[i]->has_option()) {
count++;
}
}
return count;
}
const bool DialogPage::has_quest_updates()
{
return this->quest_updates.size() > 0;
}
void DialogPage::set_quest_updates(std::vector<QuestUpdate*> updates)
{
this->quest_updates.clear();
this->quest_updates = updates;
}
const bool DialogPage::has_portrait_image()
{
return !this->portrait_image_key.empty();
}
ALLEGRO_BITMAP * DialogPage::get_portrait_image()
{
if (this->has_portrait_image()) {
return ImageLoader::get_instance().get_image("portraits/" + this->portrait_image_key);
}
return NULL;
}
void DialogPage::set_portrait_image_key(const std::string image_key)
{
this->portrait_image_key = image_key;
if (!image_key.empty()) {
ImageLoader::get_instance().load_image("portraits/" + this->portrait_image_key);
}
}
const bool DialogLine::has_option()
{
return this->has_option_action() || this->has_option_page() || this->has_option_trigger_status();
}
const bool DialogLine::has_option_action()
{
return this->option_action_key.length() > 0;
}
const bool DialogLine::has_option_page()
{
return this->option_page_num >= 0;
}
const bool DialogLine::has_option_trigger_status()
{
return this->trigger_status != NULL && !this->trigger_status->is_empty();
}
|
247e1bf9b279eab38ec7f589903af9346e28d59e | e753f6af565509bbce5d7a3ace06e33789f15187 | /RobotWarsMain.h | 46e68ae9b17f852e9a73a53aa0750cc5211c7cb2 | [] | no_license | gvela024/EmbeddedGUI | 9528b6c677c1692bbf0cbe7f331757bfdb1061eb | 334fdd71caf95f6fdb44e4ac87d6d379e496508e | refs/heads/master | 2016-09-06T02:28:53.213070 | 2014-04-24T01:53:17 | 2014-04-24T01:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,766 | h | RobotWarsMain.h | /***************************************************************
* Name: RobotWarsMain.h
* Purpose: Defines Application Frame
* Author: Gabriel Velasco (gvela024@fiu.edu)
* Created: 2014-04-10
* Copyright: Gabriel Velasco (NA)
* License:
**************************************************************/
#ifndef ROBOTWARSMAIN_H
#define ROBOTWARSMAIN_H
//(*Headers(RobotWarsFrame)
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/menu.h>
#include <wx/textctrl.h>
#include <wx/panel.h>
#include <wx/button.h>
#include <wx/frame.h>
#include <wx/statusbr.h>
//*)
#include "Arena.h"
#include "tinyxml2.h"
class RobotWarsFrame: public wxFrame
{
public:
RobotWarsFrame(wxWindow* parent,wxWindowID id = -1);
virtual ~RobotWarsFrame();
private:
//(*Handlers(RobotWarsFrame)
void OnQuit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
void OnButtonStartClick(wxCommandEvent& event);
//*)
//(*Identifiers(RobotWarsFrame)
static const long ID_PANEL2;
static const long ID_STATICTEXT1;
static const long ID_TEXTCTRL1;
static const long ID_STATICTEXT2;
static const long ID_TEXTCTRL2;
static const long ID_STATICTEXT3;
static const long ID_STATICTEXT4;
static const long ID_STATICTEXT5;
static const long ID_STATICTEXT6;
static const long ID_STATICTEXT7;
static const long ID_TEXTCTRL3;
static const long ID_BUTTON1;
static const long ID_PANEL3;
static const long ID_PANEL1;
static const long idMenuQuit;
static const long idMenuAbout;
static const long ID_STATUSBAR1;
//*)
//(*Declarations(RobotWarsFrame)
wxTextCtrl* TextCtrl_prcntRobots;
wxStaticText* StaticText2;
wxTextCtrl* TextCtrl_obstacles;
wxStaticText* StaticText6;
wxPanel* Panel1;
wxStaticText* StaticText1;
wxStaticText* StaticText3;
wxTextCtrl* TextCtrl_numOfCycles;
wxStaticText* StaticText5;
wxStaticText* StaticText7;
wxStatusBar* StatusBar1;
wxButton* ButtonStart;
wxPanel* PanelArena;
wxPanel* PanelUserOptions;
wxStaticText* StaticText4;
//*)
Arena* arena;
int numberOfCycles;
wxTimer refreshTimer;
void OnTimer(wxTimerEvent& event);
static const long REFRESH_TIMER_ID;
void DrawBoard();
tinyxml2::XMLDocument doc;
tinyxml2::XMLElement* robotsElement;
tinyxml2::XMLElement* obsticleElement;
DECLARE_EVENT_TABLE()
};
#endif // ROBOTWARSMAIN_H
|
6f74c7e5a394e4f55733d327c131659d7f59079e | 586ed68eb4e9834fa62d3adc422640529a381de9 | /Old-Notes/2b/CS247/Tutorial/Resources6/examples/05-pixmaps/ex1/helloworld.h | 9b8bada5913b1104fa1ff675a723f43fd4e50bca | [] | no_license | larajanecka/notes | d0d8372f5fee372cdef4ec345ae765b60ea31db6 | 71a925720b662abe92fbc5e8efac457c81f4d5cb | refs/heads/master | 2021-06-13T07:21:07.153414 | 2017-04-13T17:59:09 | 2017-04-13T17:59:09 | 44,930,750 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 330 | h | helloworld.h | /*
* Displays an image in a window.
*/
#ifndef GTKMM_EXAMPLE_HELLOWORLD_H
#define GTKMM_EXAMPLE_HELLOWORLD_H
#include <gtkmm/image.h>
#include <gtkmm/window.h>
class HelloWorld : public Gtk::Window {
public:
HelloWorld();
virtual ~HelloWorld();
protected:
// Member widgets:
Gtk::Image image;
}; // HelloWorld
#endif
|
91b4b88b9880f76d73e4bb95fe4c5f8bdd5cf9d1 | 0de9688de651ee81660dee187291bd97e5da1ee2 | /tool/code/trunk/cxx/Common/Images/templates/ccipdRgbToScalarImage.hxx | 17e52e5e3e55f7b7373c0781a5dcc753624c3937 | [] | no_license | zengruizhao/Radiomics | 2845cd7f17a46fae95be5d68b135ceda76ed4e44 | 34c1f1bff12fb994c904eaab0691f33819067003 | refs/heads/master | 2022-04-26T11:56:59.338297 | 2020-05-01T08:15:12 | 2020-05-01T08:15:12 | 257,222,358 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | hxx | ccipdRgbToScalarImage.hxx |
//////////////////////////////////////////////////////////////////////////////////////////
// ccipd includes
#include "ccipdCore.h"
#include "ccipdBoundingBoxCreation.h"
// itk includes
#include "ccipdDisableWarningsMacro.h"
#include <itkImageBase.h>
#include <itkPointSet.h>
#include "ccipdEnableWarningsMacro.h"
//////////////////////////////////////////////////////////////////////////////////////////
namespace ccipd
{
} // namespace ccipd
|
467688edaf18e641b46b7cd08030dbc1c816afe3 | 8b2df36e3c0636e624bcaedae0d7651b9e3799fa | /Shape/openPolyline.cpp | 91a04f6bd05789c0f61ce2ce1886d1e8c9dc8a13 | [] | no_license | samueldesga/Lab5 | a3f449a8dace6e5b86eaaa97912b881318f4d62e | a3f71f3d1924bb8d70430be90ea30c61065323f1 | refs/heads/master | 2021-01-21T00:29:19.634705 | 2015-03-24T01:22:27 | 2015-03-24T01:22:27 | 31,971,060 | 0 | 0 | null | 2015-03-10T17:19:19 | 2015-03-10T17:19:18 | null | UTF-8 | C++ | false | false | 584 | cpp | openPolyline.cpp | #include "stdafx.h"
#include "openPolyline.h"
using namespace ShapeLibrary;
OpenPolyline::OpenPolyline()
{
}
OpenPolyline::OpenPolyline(IWindowAPI& _windowAPI)
{
windowAPI = &_windowAPI;
lineColor = Color::WHITE;
fillColor = Color::INVISIBLE;
}
void OpenPolyline::draw() //Pas sur que toute marche comme il faut
{
if (this->nbPoint < 2) throw runtime_error("Il doit y avoir au minimum 2 points");
this->windowAPI->setDrawingColor(lineColor);
vector<Point>::iterator it;
for (it = point.begin(); it < (point.end() - 1); it)
{
this->windowAPI->drawLine(*it, *(it++));
}
} |
9f922032cc6902dd42eacf2e455a6efd945a90ce | f908bd92b5651445d717028441e69a1b2959f81b | /src/main/FirstComeFirstServe.cpp | 60904a510d8a23d429619dfb35a000c939912337 | [] | no_license | rsingla92/CPUScheduler | 88d6a581225ffcfb82b3479e2e180a65df7eaa18 | b3cbc1ea661d5462d70018d79813dcc5325b1791 | refs/heads/master | 2021-01-10T04:31:12.942433 | 2013-03-19T22:27:03 | 2013-03-19T22:27:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,660 | cpp | FirstComeFirstServe.cpp | /*
* EECE 315 - Project 3 CPU Scheduler
*
* Authors : Lauren Fung, Jorden Hetherington
* Jeremy Lord, Rohit Singla
*/
#include "FirstComeFirstServe.hpp"
FirstComeFirstServe::FirstComeFirstServe(std::vector<ProcessControlBlock> rawData, int quantumTime) : Algorithm(rawData, quantumTime){
}
void FirstComeFirstServe::run() {
int firstTimeSlice = 0;
int pastReadyQueueSize = 0;
populateInitialQueues( isHigherPriority );
while( true ) {
checkWaitingProcesses();
if( _readyQueue.size() == 0 ) break;
breakUpCPUBurst( _readyQueue[0] );
if( _readyQueue[0].getCPUQuantumVec().size() != 0 )
{
std::vector<int> newCPUQuantumVec = _readyQueue[0].getCPUQuantumVec();
std::vector<int> deductedCPUBurst = _readyQueue[0].getCPUBursts();
firstTimeSlice = _readyQueue[0].getCPUQuantumVec()[0];
/* Remove the first element from the list of time slices */
newCPUQuantumVec.erase( newCPUQuantumVec.begin() );
_readyQueue[0].setCPUQuantumVec( newCPUQuantumVec );
deductedCPUBurst[0] -= firstTimeSlice;
_readyQueue[0].setCPUBursts( deductedCPUBurst );
pastReadyQueueSize = _readyQueue.size();
passTimeAndCheckWaiting( firstTimeSlice );
if(_readyQueue.size() - pastReadyQueueSize > 0) {
std::sort(_readyQueue.begin()+pastReadyQueueSize, _readyQueue.end(), arrivesEarlier);
}
}
if( _readyQueue[0].getCPUQuantumVec().size() == 0 ) // current CPU Burst has completed, send to IO queue
{
sendExecutingProcessToIO();
}
else // current CPU Burst has more time - push to back of ready queue
{
_readyQueue.push_back(_readyQueue[0]);
_readyQueue.erase(_readyQueue.begin());
}
}
}
|
a0b589d88e78d2a6d81f0cfcf51e6dc57d6d62ba | daa986f924dacd39fd99232f3aae8d9638f689e0 | /conjuntos.cpp | d43d19b077286c2ec54aef7150688203b874e152 | [] | no_license | mexcoder/conjuntosaut | 28e20fa861eb75a62747df25b4b8fcdb34ccd209 | f33d9cef26c95e1464123a2e35bdf09f05562195 | refs/heads/master | 2021-01-23T08:56:53.497688 | 2015-05-20T18:04:29 | 2015-05-20T18:04:29 | 35,131,648 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,231 | cpp | conjuntos.cpp | //
// conjuntos.cpp
//
//
// Created by OrozcoBianchi on 29/03/15.
//
//
#include "conjuntos.h"
#include <algorithm>
vector<string> conjuntos::getSetNames(){
vector<string> names;
names.reserve(this->sets.size());
for(auto kv : this->sets){
names.push_back(kv.first);
}
std::sort(names.begin(), names.end());
return names;
}
void conjuntos::addItem(string title, vector<string> item){
std::sort(item.begin(), item.end());
this->sets[string(title)] = item;
}
tr1::unordered_map< std::string, vector <string> > conjuntos::getSets(){
return this->sets;
}
vector <string> conjuntos::getSet(string set){
return this->sets[set];
}
void conjuntos::initVector(vector<string> *vec,int size){
vec->reserve(size);
//crazy bug
// reserve do not instansiate de class
// so all you get its a bunch of null pointers
// neither set_union does, so you end assigning an empty value(segment fault)
// to de null pointer
// so lets init the vector with empy strings and the bug its gone
//
for (int x=0; x<=size; x++) {
vec->push_back("");
}
}
vector<string> conjuntos::setUnion(vector<string> s1,vector<string> s2,vector<string> *dest){
std::vector<string>::iterator it;
int size =s1.size()+s2.size();
this->initVector(dest,size);
it = std::set_union (s1.begin(), s1.end(), s2.begin(), s2.end(), dest->begin());
dest->resize(it-dest->begin());
return *dest;
}
vector<string> conjuntos::Union(string s1,string s2){
return setUnion(this->sets[s1],this->sets[s2],new vector<string>());
}
vector<string> conjuntos::setUnion(string s1,string s2,string dest){
return setUnion(this->sets[s1],this->sets[s2],&this->sets[dest]);
}
vector<string> conjuntos::setResta(vector<string> s1,vector<string> s2,vector<string> *dest){
std::vector<string>::iterator it;
int size =s1.size()+s2.size();
this->initVector(dest,size);
it = std::set_difference (s1.begin(), s1.end(), s2.begin(), s2.end(), dest->begin());
dest->resize(it-dest->begin());
return *dest;
}
vector<string> conjuntos::resta(string s1,string s2){
return setResta(this->sets[s1],this->sets[s2],new vector<string>());
}
vector<string> conjuntos::setResta(string s1,string s2,string dest){
return setResta(this->sets[s1],this->sets[s2],&this->sets[dest]);
}
vector<string> conjuntos::setIntersection(vector<string> s1,vector<string> s2,vector<string> *dest){
std::vector<string>::iterator it;
int size =s1.size()+s2.size();
this->initVector(dest,size);
it = std::set_intersection (s1.begin(), s1.end(), s2.begin(), s2.end(), dest->begin());
dest->resize(it-dest->begin());
return *dest;
}
vector<string> conjuntos::intersection(string s1,string s2){
return setIntersection(this->sets[s1],this->sets[s2],new vector<string>());
}
vector<string> conjuntos::setIntersection(string s1,string s2,string dest){
return setIntersection(this->sets[s1],this->sets[s2],&this->sets[dest]);
}
|
40ee3eaca56dcecfe6f58bb3daa5b4bd4cc7a8f5 | f1dcb0633ec482317e2dcecc2d4d9a1dbdb5614a | /PolyFitTest.cpp | e234d55ed8178c25567b891af99671838c1e8d97 | [] | no_license | smhjn/predictiveFilter | b2e56c6d6b34f3cb9932f6eb5880e95bcb563f4c | 8e61f2354e3f44ae50d7aa3aed5ee1b14be93f02 | refs/heads/master | 2020-04-10T05:10:27.560964 | 2014-10-23T18:23:00 | 2014-10-23T18:23:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,369 | cpp | PolyFitTest.cpp | #include "PolyFit.h"
#include <iostream>
int main ()
{
cout << "Creating a poly fitter 9000!" << endl;
// We must padd the dataset with 0,0 first element for this
// 11 element set to work with the 1-indexed polyfit
/*
double data[12][2] = {{0.0000000000, 0.0000000000},
{0.0000000000, 0.0000000000},
{0.0600099840, 3.8650850800},
{0.1200017920, 2.6375739500},
{0.1799564800, 0.9647171460},
{0.2400128000, 0.5100284640},
{0.2999490560, 2.5608219600},
{0.3599777280, 4.2344544400},
{0.4199508480, 3.6824732600},
{0.4799424000, 1.5011326800},
{0.5399434240, -0.7833248330},
{0.6599360000, 0.0000000000}};
*/
double data2[4][2] =
{{0.000000, 0.000000},
{0.000000, 0.000000},
{0.999975, 72.366537},
{1.999913, -68.656711}};
double x[5] = {0.000000, 0.999975, 1.999913, 3, 17};
double y[5] = {0.000000, 72.366537, -68.656711, 115.689, 300};
//
// The correct answer should be:
// Creating a poly fitter 9000!
// Coeffs: 0 179.07 -106.705 0
// Calculation took: 95396 ns
// Test es fine!
//
long double coeffs[9];
polyfit( 3, x, y, 5, coeffs);
cout << "Coeffs: ";
for( int i = 0; i < 4; i++ )
cout << coeffs[i] << " ";
cout << endl;
// Should return "Coeffs: 1.10204 10.5739 -18.5839 -1.81836"
cout << "Test es fine!" << endl;
return 0;
} |
267a8008b2bdddf101d603a812c9203e1e83e7bc | b918d118c8ae4dcb78dc9b629216d6bef4f8e4cc | /Jurasic Park/Category.cpp | ba7e90fb17242a9ffa6c049f562ad001fec5fc2b | [] | no_license | martinikolaev00/Jurasic-park | 720ad7648a3a2fbffba5f3f408b271ddd93db0a0 | b75fee5302b3162a0e4825548c28da856b1378d3 | refs/heads/master | 2022-10-04T14:50:28.330628 | 2020-06-07T20:46:03 | 2020-06-07T20:46:03 | 270,427,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,350 | cpp | Category.cpp | #include "Category.hpp"
#include<cstring>
Categoryy::Categoryy():category(nullptr),types(nullptr),numoftypes(3)
{
numoftypes = 3;
category = new char[100];
category[99] = '\0';
types = new char* [numoftypes];
for (int i = 0; i < 3; ++i)
{
types[i] = new char[30];
}
}
Categoryy::Categoryy(const Categoryy& other)
{
numoftypes = 3;
category = new char[strlen(other.category)+1];
strcpy(category, other.category);
category[strlen(other.category)] = '\0';
types = new char* [numoftypes];
for (int i = 0; i < 3; ++i)
{
types[i] = new char[30];
}
copy(other);
}
Categoryy::Categoryy(char* category,int j,char type[][30])
{
numoftypes = 3;
this->category = new char[strlen(category)+1];
strcpy(this->category, category);
this->category[strlen(category)] = '\0';
this->types = new char* [numoftypes];
for (int i = 0; i < 3; ++i)
{
this->types[i] = new char[30];
}
for (int i = 0; i < 3; ++i)
{
strcpy(this->types[i], type[i+j*3]);
}
numinenum = j;
}
Categoryy& Categoryy::operator=(const Categoryy& other)
{
if (this != &other)
copy(other);
return *this;
}
Categoryy::~Categoryy()
{
del();
}
char* Categoryy::getcategory( char* buff)
{
buff = new char[strlen(category)];
strcpy(buff, category);
return buff;
}
char* Categoryy::gettype(char* buff, int idx)
{
if (idx <= numoftypes)
{
buff = new char[strlen(types[idx])];
strcpy(buff, types[idx]);
return buff;
}
else return nullptr;
}
int Categoryy::checktype(char* buff)
{
for (int i = 0; i < numoftypes; ++i)
{
if (!strcmp(types[i], buff))
{
//idxoftype = i;
return i;
}
}
return -1;
}
bool Categoryy::operator==(const Categoryy& other)
{
if (!strcmp(category, other.category))
{
for (int i = 0; i < numoftypes; ++i)
{
if (strcmp(types[i], other.types[i]))
return false;
else
return true;
}
}
return false;
}
void Categoryy::serialize(std::ofstream& ofs)
{
if (!ofs.is_open())
{
std::cout << "File is not opened" << std::endl;
return;
}
int cat = strlen(category);
ofs.write((const char*)&cat, sizeof(int));
ofs.write(category, cat);
ofs.write((const char*)&numoftypes, sizeof(int));
for (int i = 0; i < numoftypes; ++i)
{
int p = strlen(types[i]);
ofs.write((const char*)&p, sizeof(int));
ofs.write(types[i], p);
}
ofs.write((const char*)&idxoftype, sizeof(int));
ofs.write((const char*)&numinenum, sizeof(int));
}
void Categoryy::deserialize(std::ifstream& ifs)
{
if (!ifs.is_open())
{
std::cout << "File is not opened" << std::endl;
return;
}
del();
int cat;
ifs.read((char*)&cat, sizeof(int));
category = new char[cat + 1];
ifs.read(category, cat);
category[cat] = '\0';
ifs.read((char*)&numoftypes, sizeof(int));
types = new char* [3];
for (int i = 0; i < numoftypes; ++i)
{
int p;
ifs.read((char*)&p, sizeof(int));
types[i] = new char[p + 1];
ifs.read(types[i], p);
types[i][p] = '\0';
}
ifs.read(( char*)&idxoftype, sizeof(int));
ifs.read(( char*)&numinenum, sizeof(int));
}
void Categoryy::copy(const Categoryy& other)
{
strcpy(category, other.category);
category[strlen(other.category)] = '\0';
for (int i = 0; i < 3; ++i)
{
strcpy(types[i], other.types[i]);
}
numinenum = other.numinenum;
}
void Categoryy::del()
{
for (int i = 0; i < numoftypes; ++i)
delete[] types[i];
delete[] types;
delete[] category;
}
|
0131ca81a5693733e52298e2126990f5f0d0299c | 17cf96eac8698680b2b543a4f568bf9115cbd69e | /commands/removeitemfromtexturelistcommand.h | 30bcf1196c4dda56d10a9ae34b9ae1559115d519 | [] | no_license | GuiM0x/Mapox2D | 7b724d52f0cc566c736d3fb4ad75b44185ffc753 | 1085e6e648a211ecc22c24a355c4965414709cc9 | refs/heads/master | 2020-04-16T00:10:02.647657 | 2019-02-22T21:58:35 | 2019-02-22T21:58:35 | 165,128,537 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | h | removeitemfromtexturelistcommand.h | #ifndef REMOVEITEMFROMTEXTURELISTCOMMAND_H
#define REMOVEITEMFROMTEXTURELISTCOMMAND_H
#include "texturelist.h"
#include <QUndoCommand>
class RemoveItemFromTextureListCommand : public QUndoCommand
{
public:
RemoveItemFromTextureListCommand(TextureList *textureList,
const QString& textureName,
QUndoCommand *parent = nullptr);
public:
void undo() override;
void redo() override;
private:
TextureList *m_textureList{nullptr};
QListWidgetItem *m_itemTaken{nullptr};
};
#endif // REMOVEITEMFROMTEXTURELISTCOMMAND_H
|
5928c4d05b237b1b180f9a2af7bfcbf974d34847 | 62ecbf18f7516faf4b4240a6d0183e2bde231074 | /app.ino | 09ec36adea06d46b0ebc7278fecf18331375a8bc | [] | no_license | SuyKingsleigh/ModemArduino-STE | a619482e4568cc051927c48bd7616f9fc15f1364 | 2418266e6cbc9231b9f70971bf33668f05b915e9 | refs/heads/master | 2022-10-27T02:46:09.634059 | 2020-06-10T12:01:50 | 2020-06-10T12:01:50 | 267,407,614 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,431 | ino | app.ino | #include "src/menu.h"
#include "src/login.h"
#include "src/channel.h"
#include "src/ip_interface.h"
#include "src/mac_interface.h"
IpInterface *ip = new IpInterface();
MacInterface *mac = new MacInterface();
LoginInterface *login = new LoginInterface();
ChannelInterface *chan = new ChannelInterface(11, 22, 2412);
void setup(){
Serial.begin(9600);
while(!Serial) {;}
}
void loop(){
// fica bloqueado até o usuário logar
while(!login->is_authenticated())
login->log_in_interface();
// F() mantém as strings na PROGMEM ao invés de as copiar para o flash e sram
Serial.println(F("[1] Para interface MAC \
\n[2] Para interface IP \
\n[3] Para interface dos canais \
\n[4] Para interface do usuario"));
int select = -1;
while (select < 1)
select = Serial.parseInt();
switch (select) {
case 1: // interface mac
mac->show_menu();
delay(125);
break;
case 2: // interface IP
ip->show_menu();
delay(125);
break;
case 3: // interface Canais
chan->show_menu();
delay(125);
break;
case 4: // interface do usuario
login->show_menu();
delay(125);
break;
default:
break;
}
} |
cf437f3272cb0e12cc398012c6ff5a9098ed5e39 | c506e2707708f6b1d1c8b6a4761b3952cdf33c12 | /clients/shared/ServerId.cc | 09a079bb2cc99e008a4c986cc4ce5396be369118 | [
"Apache-2.0"
] | permissive | xuantan/viewfinder | 69e17d50228dd34fa34d79eea1c841cc80a869ff | 992209086d01be0ef6506f325cf89b84d374f969 | refs/heads/master | 2021-08-26T00:58:18.180445 | 2021-08-10T03:06:48 | 2021-08-10T03:06:48 | 19,481,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,369 | cc | ServerId.cc | // Copyright 2012 Viewfinder. All rights reserved.
// Author: Spencer Kimball.
#import "DB.h"
#import "Format.h"
#import "Logging.h"
#import "Mutex.h"
#import "ServerId.h"
#import "StringUtils.h"
namespace {
// NOTE: these should be kept up to date with the id prefixes used by
// the server. These can be found in backend/db/id_prefix.py.
const char* kActivityPrefix = "a";
const char* kCommentPrefix = "c";
const char* kEpisodePrefix = "e";
const char* kOperationPrefix = "o";
const char* kPhotoPrefix = "p";
const char* kViewpointPrefix = "v";
bool DecodeId(const char* prefix, const Slice& server_id, int64_t* device_id,
int64_t* local_id, WallTime* timestamp, bool reverse_timestamp) {
if (server_id.empty() ||
!server_id.starts_with(prefix)) {
return false;
}
const string decoded = Base64HexDecode(server_id.substr(1));
Slice s(decoded);
if (decoded.size() < 4) {
return false;
}
*timestamp = Fixed32Decode(&s);
if (reverse_timestamp) {
*timestamp = (1ULL << 32) - *timestamp - 1;
}
*device_id = Varint64Decode(&s);
*local_id = Varint64Decode(&s);
return true;
}
bool DecodeId(const char* prefix, const Slice& server_id,
int64_t* device_id, int64_t* local_id) {
if (server_id.empty() ||
!server_id.starts_with(prefix)) {
return false;
}
const string decoded = Base64HexDecode(server_id.substr(1));
Slice s(decoded);
*device_id = Varint64Decode(&s);
*local_id = Varint64Decode(&s);
return true;
}
string EncodeId(const char* prefix, int64_t device_id, int64_t local_id) {
string encoded;
Varint64Encode(&encoded, device_id);
Varint64Encode(&encoded, local_id);
return Format("%s%s", prefix, Base64HexEncode(encoded, false));
}
string EncodeId(const char* prefix, int64_t device_id, int64_t local_id,
WallTime timestamp, bool reverse_timestamp) {
if (timestamp < 0) {
// If timestamp is negative, just use the current time.
timestamp = WallTime_Now();
}
string encoded;
if (reverse_timestamp) {
timestamp = (1ULL << 32) - int(timestamp) - 1;
}
Fixed32Encode(&encoded, timestamp);
Varint64Encode(&encoded, device_id);
Varint64Encode(&encoded, local_id);
return Format("%s%s", prefix, Base64HexEncode(encoded, false));
}
} // namespace
string EncodeActivityId(int64_t device_id, int64_t local_id, WallTime timestamp) {
return EncodeId(kActivityPrefix, device_id, local_id, timestamp, true);
}
string EncodeCommentId(int64_t device_id, int64_t local_id, WallTime timestamp) {
return EncodeId(kCommentPrefix, device_id, local_id, timestamp, false);
}
string EncodeEpisodeId(int64_t device_id, int64_t local_id, WallTime timestamp) {
return EncodeId(kEpisodePrefix, device_id, local_id, timestamp, true);
}
string EncodePhotoId(int64_t device_id, int64_t local_id, WallTime timestamp) {
return EncodeId(kPhotoPrefix, device_id, local_id, timestamp, true);
}
string EncodeOperationId(int64_t device_id, int64_t local_id) {
return EncodeId(kOperationPrefix, device_id, local_id);
}
string EncodeViewpointId(int64_t device_id, int64_t local_id) {
return EncodeId(kViewpointPrefix, device_id, local_id);
}
bool DecodeActivityId(const Slice& server_id, int64_t* device_id,
int64_t* local_id, WallTime* timestamp) {
return DecodeId(kActivityPrefix, server_id, device_id, local_id, timestamp, true);
}
bool DecodeCommentId(const Slice& server_id, int64_t* device_id,
int64_t* local_id, WallTime* timestamp) {
return DecodeId(kCommentPrefix, server_id, device_id, local_id, timestamp, false);
}
bool DecodeEpisodeId(const Slice& server_id, int64_t* device_id,
int64_t* local_id, WallTime* timestamp) {
return DecodeId(kEpisodePrefix, server_id, device_id, local_id, timestamp, true);
}
bool DecodePhotoId(const Slice& server_id, int64_t* device_id,
int64_t* local_id, WallTime* timestamp) {
return DecodeId(kPhotoPrefix, server_id, device_id, local_id, timestamp, true);
}
bool DecodeOperationId(const Slice& server_id, int64_t* device_id, int64_t* local_id) {
return DecodeId(kOperationPrefix, server_id, device_id, local_id);
}
bool DecodeViewpointId(const Slice& server_id, int64_t* device_id, int64_t* local_id) {
return DecodeId(kViewpointPrefix, server_id, device_id, local_id);
}
|
e7ef2764cbed8109e0b8347c5feed2876db071ad | f2cb2ade64968e24a5cf078a2ae9d2a6ed66b5ea | /leet39.cpp | b656e895d283b89f4a769365e564dda7524246b2 | [] | no_license | flabby/acm | d40755a37c9c1c1ce310a295fd1d00c3af608e53 | d7887c3cf2241133f479a5455a96cc9933de61f7 | refs/heads/master | 2020-06-02T19:53:39.259075 | 2013-05-28T16:58:40 | 2013-05-28T16:58:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | cpp | leet39.cpp | /*
Combination Sum
*/
#include "header.h"
class Solution
{
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target)
{
int len = candidates.size();
sort (candidates.begin(), candidates.end());
// pr(candidates);
vector<vector<int> > ret;
vector<int> sl(len);
dfs(ret, sl, candidates, 0, target);
// cout << "ret size=" << ret.size() << endl;
// for (int i = 0; i < ret.size(); i++)
// pr(ret[i]);
return ret;
}
void dfs(vector<vector<int> > &ret, vector<int> &sl, vector<int> &candidates, int dep, int rem)
{
if (dep >= candidates.size() || rem <= 0)
{
if (rem == 0)
{
// cout << "rem == 0" << endl;
vector<int> tmp;
for (int i = 0; i < dep; i++)
for (int j = 0; j < sl[i]; j++)
tmp.push_back(candidates[i]);
ret.push_back(tmp);
// pr(sl);
}
return;
}
int cnt = rem / candidates[dep];
// printf ("cnt=%d rem=%d can[dep=%d]=%d\n", cnt, rem, dep, candidates[dep]);
for (int i = 0; i <= cnt; i++)
{
sl[dep] = i;
if (rem < i * candidates[dep])
break;
dfs(ret, sl, candidates, dep + 1, rem - i * candidates[dep]);
}
}
void pr(vector<int> &a)
{
for (int i = 0; i < a.size(); i++)
printf ("%d ", a[i]);
printf ("\n\n");
char ch;
scanf ("%c", &ch);
}
};
int main()
{
vector<int> a;
a.push_back(2);
a.push_back(3);
a.push_back(6);
a.push_back(7);
Solution s;
s.combinationSum(a, 7);
return 0;
}
|
b0a361518f6a133ad307d5486cf85bbc2279931f | 03b7338dc342e982d49904632d7d4952e9a354f0 | /DP/SCS.cpp | 5be896932d971fbb556c0670e865d35accfb6d69 | [] | no_license | XiaotianJin/Templates | cabcd746f3dacd5653ee169466a9fc97bb4a9a59 | afb0d0ed09f49666780c5f019467df7d40a8cfde | refs/heads/master | 2020-04-18T01:15:49.005567 | 2016-10-17T04:28:23 | 2016-10-17T04:28:23 | 167,112,102 | 3 | 0 | null | 2019-01-23T03:40:31 | 2019-01-23T03:40:30 | null | UTF-8 | C++ | false | false | 3,571 | cpp | SCS.cpp | //集合dp
//先把相互包含的串去掉,这样不会影响最终结果。
//然后建图,权值为前面串的后缀和后面串的后缀的公共长度。
//d[i][S] 表示以第i个串开头,已选状态为S的最大值
//d[j][S|j] = max(G[i][S]) + G[j][i] ((S&j) == 0)
//最后答案为( 总长 - max(d[i][1<<(n-1)] )
//题目要求输出字典序最小的一个串,dfs打印即可
//注意每次比较字典序大小是减去公共前缀的,而不是直接比较两个串
#include<cstdio>
#include<cstring>
#include<string>
#include<map>
#include<vector>
using namespace std;
const int maxn = 20;
vector<int> rec;
int d[maxn][1<<15],pos[maxn],vis[maxn];
int G[maxn][maxn];
int n;
char s[maxn][105];
inline int check(char *s1,char *s2)
{
int n1 = strlen(s1),n2 = strlen(s2);
if(n1<n2) swap(s1,s2),swap(n1,n2);
for(int i=0;i+n2-1<n1;++i)
{
bool flag = true;
for(int j=0;j<n2;++j)
if(s1[i+j]!=s2[j]){
flag = false;
break;
}
if(flag) return true;
}
return false;
}
inline int cal(char *s1,char *s2)
{
int n1 = strlen(s1),n2 = strlen(s2);
int mx = 0;
for(int i=max(0,n1-n2);i<n1;++i)
{
int cnt = 0;
for(int j=0;j<n2 && i+j<n1; ++j)
if(s1[i+j]!=s2[j])
{
cnt = 0;
break;
}
else ++cnt;
mx = max(mx,cnt);
}
return mx;
}
inline void gao()
{
map<string,int> id;
int cnt=0;
for(int i=0;i<n;++i)
for(int j=i+1;j<n;++j)
if(check(s[i],s[j]))
{
int n1 = strlen(s[i]),n2 = strlen(s[j]);
if(n1>=n2)
{
id[string(s[j])] = -1;
}
else
{
id[string(s[i])] = -1;
break;
}
}
for(int i=0;i<n;++i)
{
if(!id[string(s[i])]==-1) continue;
if(!id[string(s[i])])
id[string(s[i])] = ++cnt, pos[cnt-1] = i;
for(int j=0;j<n;++j)
{
if(i==j || id[string(s[j])]==-1) continue;
if(!id[string(s[j])])
id[string(s[j])] = ++cnt, pos[cnt-1] = j;
G[id[string(s[i])]-1][id[string(s[j])]-1] = cal(s[i],s[j]);
G[id[string(s[j])]-1][id[string(s[i])]-1] = cal(s[j],s[i]);
}
}
n = cnt;
}
void dfs(int u,int S,int ans)
{
vis[u] = 1;
int id = -1;
for(int i=0;i<n;++i)
{
if(vis[i]) continue;
if(ans - G[u][i] == d[i][S])
{
if(id==-1) id = i;
else
if(strcmp(s[pos[i]]+G[u][i],s[pos[id]]+G[u][id])<0)
id = i;
}
}
if(id==-1) return;
rec.push_back(id);
dfs(id,S^(1<<id),ans - G[u][id]);
}
inline void dp()
{
memset(d,-1,sizeof d);
for(int i=0;i<n;++i) d[i][1<<i] = 0;
for(int S=0;S<(1<<n);++S)
{
for(int i=0;i<n;++i)
{
if(d[i][S]==-1) continue;
if(d[i][S]==-1) d[i][S] = 0;
for(int j=0;j<n;++j)
{
if(i == j) continue;
if(!(S&(1<<j)))
{
d[j][S|(1<<j)] =
max(d[j][S|(1<<j)],d[i][S] + G[j][i]);
}
}
}
}
int ans = -1,id = 0;
for(int i=0;i<n;++i)
{
if(ans<=d[i][(1<<n)-1])
{
if(ans<d[i][(1<<n)-1])
{
ans = d[i][(1<<n)-1];
id = i;
}
if(strcmp(s[pos[i]],s[pos[id]])<0) id = i;
}
}
rec.clear();
rec.push_back(id);
memset(vis,0,sizeof vis);
dfs(id,((1<<n)-1)^(1<<id),ans);
for(int i=0;i<rec.size()-1;++i)
{
// printf("%d -- ",rec[i]);
int t = G[rec[i]][rec[i+1]];
// printf("%d\n",t);
for(int j=0;j<strlen(s[pos[rec[i]]])-t;++j)
putchar(s[pos[rec[i]]][j]);
}
// printf("%d\n",rec[rec.size()-1]);
printf("%s\n\n",s[pos[rec[rec.size()-1]]]);
}
int main()
{
// freopen("test.txt","r",stdin);
// freopen("out.txt","w",stdout);
int T;
scanf("%d",&T);
for(int z = 1;z<=T;++z)
{
printf("Scenario #%d:\n",z);
scanf("%d",&n);
for(int i=0;i<n;++i) scanf("%s",s[i]);
gao();
dp();
}
return 0;
}
|
6ffba173aa19eafc68fe67d14e6dcc276b4177d1 | bada30d01f229cbfb5c315d44f31b0038f15a523 | /_Project/BGMVolumeController.cpp | 251cb7e8f93d418a74c5206a2e9f01b69d7707b9 | [] | no_license | calmackenzie/VG1819 | 97d8c6d5823a1dbb618fd1ca7c21c5393fd8aff3 | 7bc8f3ba380209668ce281054fd9e024b4455d82 | refs/heads/master | 2021-10-26T12:24:19.940811 | 2019-04-11T19:59:10 | 2019-04-11T19:59:10 | 133,898,562 | 1 | 2 | null | 2019-04-11T01:21:31 | 2018-05-18T03:32:31 | C++ | UTF-8 | C++ | false | false | 893 | cpp | BGMVolumeController.cpp | #include "BGMVolumeController.h"
#include "util\MathUtil.h"
#include "settings_menu\PlayerPrefs.h"
BGMVolumeController::BGMVolumeController() : m_volume(0)
{
}
BGMVolumeController::~BGMVolumeController()
{
}
void BGMVolumeController::start()
{
auto children = getTransform().getChildren();
assert(!children.empty());
auto childrenEnd = children.cend();
for (auto it = children.begin(); it != childrenEnd; ++it)
{
m_textBox = (*it)->getAttachedGameObject().getComponent<puppy::TextBox>();
if (m_textBox != nullptr)
{
break;
}
}
assert(m_textBox != nullptr);
m_volume = PlayerPrefs::getBGMVolume();
m_textBox->setText(std::to_string(m_volume) + "%");
}
void BGMVolumeController::changeBGMVolume(int p_amount)
{
m_volume += p_amount;
m_volume = CLAMP(m_volume, 0, 200);
PlayerPrefs::setBGMVolume(m_volume);
m_textBox->setText(std::to_string(m_volume) + "%");
} |
1ee0a8bc391583e11fbc8bb13ff8f3236c71c564 | 0fe27e6c63a755fe7df003f36acc079490a338f3 | /src/cpp/Path-Sum-II.cpp | 74c047803cbae173ecd5e4c53f12a29e968f4dcd | [] | no_license | Finalcheat/leetcode | 83f9ceb7bd10783554133434347803a41260a713 | 985deb6142c6841aa7025c9b582010b33f694e6c | refs/heads/master | 2022-11-11T22:51:42.666150 | 2022-11-05T03:07:31 | 2022-11-05T03:07:31 | 53,241,690 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,830 | cpp | Path-Sum-II.cpp | /**
* @file Path-Sum-II.cpp
* @brief 二叉树根到叶子节点的路径和(https://leetcode.com/problems/path-sum/)
* @author Finalcheat
* @date 2016-04-26
*/
/**
* Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
* For example:
* Given the below binary tree and sum = 22,
* 5
* / \
* 4 8
* / / \
* 11 13 4
* / \ / \
* 7 2 5 1
* return
* [
* [5,4,11,2],
* [5,8,4,5]
* ]
*/
/**
* 递归解法,过程中减去当前节点的值并递归调用左右子树,最后把值相等的添加到结果。
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
std::vector<int> v;
std::vector<std::vector<int>> result;
_pathSum(root, sum, v, result);
return result;
}
private:
void _pathSum(TreeNode* node, int sum, std::vector<int> v, std::vector<std::vector<int>>& result) {
if (!node) {
return;
}
if (sum == node->val && (!node->left) && (!node->right)) {
v.push_back(node->val);
result.push_back(v);
return;
}
v.push_back(node->val);
if (node->left) {
_pathSum(node->left, sum - node->val, v, result);
}
if (node->right) {
_pathSum(node->right, sum - node->val, v, result);
}
}
};
|
93b09a2692a74e1cc71d87e1c903702492becc63 | 8fbbba3cd5241f3a4280880ba14e803b7714f503 | /BOJ/DFS BFS/13549 숨바꼭질3.cpp | d734cdf946538125a5ed8c365acab93955af1c6a | [] | no_license | Inryu/algorithm | 796407ef7f177d88caef9bf201a0bc2e93d54baa | a4f09ee7537c8e2cb5041d719a0a7c6399207078 | refs/heads/master | 2023-08-09T12:46:50.989612 | 2021-09-14T10:15:37 | 2021-09-14T10:15:37 | 295,729,909 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,015 | cpp | 13549 숨바꼭질3.cpp | #include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
#define MAX 100000
bool visited[MAX+1];
int N,K;
int bfs(int time, int pos){
deque<pair<int,int>> dq;
visited[pos]=true;
dq.push_back({time,pos});
while(!dq.empty()){
int curTime=dq.front().first;
int curPos=dq.front().second;
dq.pop_front();
if(curPos==K) return curTime;
//2*x
if(2*curPos<=MAX&&!visited[2*curPos]){
visited[2*curPos]= true;
dq.push_front({curTime,2*curPos}); // 이동거리 (time)이 0이므로 front에 넣어줘야함@@
}
//x-1
if(curPos>=1&&!visited[curPos-1]){
visited[curPos-1]=true;
dq.push_back({curTime+1,curPos-1});
}
//x+1
if(curPos<=MAX-1&&!visited[curPos+1]){
visited[curPos+1]= true;
dq.push_back({curTime+1,curPos+1});
}
}
}
int main(){
cin>>N>>K;
cout<<bfs(0, N)<<"\n";
return 0;
}
|
783003eb77000d154a6cdf094aae3f15a731fab2 | f2c3250674d484b91dd9385d7fac50017b034e4b | /nowcoder/887/B.cpp | f641e568e4bbbad1b1975dba2063bdd04b05d118 | [] | no_license | DQSSSSS/Algorithm-Competition-Code | a01d4e8b3a9b9da02a400eb5bb4e063eaade33c9 | 574a0806fadf1433fcb4fac4489a237c58daab3c | refs/heads/master | 2023-01-06T06:17:12.295671 | 2020-11-11T22:44:41 | 2020-11-11T22:44:41 | 309,434,336 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 842 | cpp | B.cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef long double LD;
typedef pair<int,int> pii;
typedef pair<LL,int> pli;
const int SZ = 1e5 + 10;
const int INF = 1e9 + 10;
const int mod = 1e9 + 7;
const LD eps = 1e-8;
LL read() {
LL n = 0;
char a = getchar();
bool flag = 0;
while(a > '9' || a < '0') { if(a == '-') flag = 1; a = getchar(); }
while(a <= '9' && a >= '0') { n = n * 10 + a - '0',a = getchar(); }
if(flag) n = -n;
return n;
}
int a[SZ];
int main() {
int T = read();
while(T --) {
int n = read();
for(int i = n;i >= 0;i --) a[i] = read();
if(n >= 3) puts("No");
else {
if(n <= 1) puts("Yes");
else if(n == 2 && 1ll * a[1] * a[1] - 4ll * a[2] * a[0] >= 0) puts("No");
else puts("Yes");
}
}
}
|
4c639bfdb6f015fdb88c8e3444465f4834728768 | 091afb7001e86146209397ea362da70ffd63a916 | /inst/include/nt2/include/functions/simd/tan.hpp | 3c15dde346fb80cc4cbb2ed6d297cafdbe585ada | [] | no_license | RcppCore/RcppNT2 | f156b58c08863243f259d1e609c9a7a8cf669990 | cd7e548daa2d679b6ccebe19744b9a36f1e9139c | refs/heads/master | 2021-01-10T16:15:16.861239 | 2016-02-02T22:18:25 | 2016-02-02T22:18:25 | 50,460,545 | 15 | 1 | null | 2019-11-15T22:08:50 | 2016-01-26T21:29:34 | C++ | UTF-8 | C++ | false | false | 173 | hpp | tan.hpp | #ifndef NT2_INCLUDE_FUNCTIONS_SIMD_TAN_HPP_INCLUDED
#define NT2_INCLUDE_FUNCTIONS_SIMD_TAN_HPP_INCLUDED
#include <nt2/trigonometric/include/functions/simd/tan.hpp>
#endif
|
2b6f793457e309d5d4412d22fc9861101177dd82 | 4e8a495df638573472de47f4775329def07e796a | /NetAnalyzer/src/gui/ncurses/elements/GTab.h | 5e31952699e917efe35363ba51fb631ad32a2e7b | [] | no_license | akira2009999/NetAnalyzer-analise-de-trafego | efb0e5da01e38ba27419f838a47726d9711d8b74 | af9dc421f46db2585d14f5d06569b6f429343b9e | refs/heads/master | 2020-04-24T07:13:53.089627 | 2014-03-05T13:25:56 | 2014-03-05T13:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 546 | h | GTab.h | /*
* GTab.h
*
* Created on: Apr 23, 2013
* Author: kazu
*/
#ifndef GTAB_H_
#define GTAB_H_
#include <string>
#include "GKeyListener.h"
#include "GPanel.h"
/**
* one Tab within a TabHost
*/
class GTab : public GPanel {
public:
/** ctor */
GTab(const std::string& title) : title(title) {
;
}
/** dtor */
~GTab() {
;
}
/** get the title of this tab to display in the tabhost */
const std::string getTitle() const {
return title;
}
private:
/** this tab's title */
std::string title;
};
#endif /* GTAB_H_ */
|
6d2caa245c59d32c0dad74757e83a269e6b4353d | 2734eee7b7d89f244138bcca022301717ad55ee9 | /facade/TCPServerFacade.cpp | 8851ec14ba12f6110f9d55a2af02e353722fbc7b | [] | no_license | zpb1992/FileTransport | dc0dcc00383c0e68621f425fb9b7ce99e6fa3e61 | d3070aa2da04d1f7064775478617d1381b727c8a | refs/heads/master | 2021-01-17T20:00:06.417774 | 2016-08-08T11:03:53 | 2016-08-08T11:03:53 | 64,835,602 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 477 | cpp | TCPServerFacade.cpp | //
// Created by zpb on 16-8-3.
//
#include "TCPServerFacade.h"
TCPServerFacade::TCPServerFacade() {
_server=new TCPServer();
_server->init();
_server->createSocket(AF_INET,SOCK_STREAM,0);
}
void TCPServerFacade::waitConnect(unsigned short port, std::string ip) {
_server->bindAddr(ip,port);
_server->listenTo(1);
_server->acceptConnection();
}
void TCPServerFacade::closeConnection() {
_server->close();
_server->cleanup();
delete _server;
}
|
0bee2593d0625134bf036b43962438b248ac5fbf | b4d1fc90b1c88f355c0cc165d73eebca4727d09b | /libcef_dll/wrapper/cef_stream_resource_handler.cc | 6c31e60a8bd3f5d3d2f99465cbadad0497635039 | [
"BSD-3-Clause"
] | permissive | chromiumembedded/cef | f03bee5fbd8745500490ac90fcba45616a29be6e | f808926fbda17c7678e21f1403d6f996e9a95138 | refs/heads/master | 2023-09-01T20:37:38.750882 | 2023-08-31T17:16:46 | 2023-08-31T17:28:27 | 87,006,077 | 2,600 | 454 | NOASSERTION | 2023-07-21T11:39:49 | 2017-04-02T18:19:23 | C++ | UTF-8 | C++ | false | false | 2,489 | cc | cef_stream_resource_handler.cc | // Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/wrapper/cef_stream_resource_handler.h"
#include <algorithm>
#include "include/base/cef_logging.h"
#include "include/cef_task.h"
#include "include/wrapper/cef_helpers.h"
CefStreamResourceHandler::CefStreamResourceHandler(
const CefString& mime_type,
CefRefPtr<CefStreamReader> stream)
: status_code_(200),
status_text_("OK"),
mime_type_(mime_type),
stream_(stream) {
DCHECK(!mime_type_.empty());
}
CefStreamResourceHandler::CefStreamResourceHandler(
int status_code,
const CefString& status_text,
const CefString& mime_type,
CefResponse::HeaderMap header_map,
CefRefPtr<CefStreamReader> stream)
: status_code_(status_code),
status_text_(status_text),
mime_type_(mime_type),
header_map_(header_map),
stream_(stream) {
DCHECK(!mime_type_.empty());
}
bool CefStreamResourceHandler::Open(CefRefPtr<CefRequest> request,
bool& handle_request,
CefRefPtr<CefCallback> callback) {
DCHECK(!CefCurrentlyOn(TID_UI) && !CefCurrentlyOn(TID_IO));
// Continue the request immediately.
handle_request = true;
return true;
}
void CefStreamResourceHandler::GetResponseHeaders(
CefRefPtr<CefResponse> response,
int64_t& response_length,
CefString& redirectUrl) {
CEF_REQUIRE_IO_THREAD();
response->SetStatus(status_code_);
response->SetStatusText(status_text_);
response->SetMimeType(mime_type_);
if (!header_map_.empty()) {
response->SetHeaderMap(header_map_);
}
response_length = stream_ ? -1 : 0;
}
bool CefStreamResourceHandler::Read(
void* data_out,
int bytes_to_read,
int& bytes_read,
CefRefPtr<CefResourceReadCallback> callback) {
DCHECK(!CefCurrentlyOn(TID_UI) && !CefCurrentlyOn(TID_IO));
DCHECK_GT(bytes_to_read, 0);
DCHECK(stream_);
// Read until the buffer is full or until Read() returns 0 to indicate no
// more data.
bytes_read = 0;
int read = 0;
do {
read = static_cast<int>(
stream_->Read(static_cast<char*>(data_out) + bytes_read, 1,
bytes_to_read - bytes_read));
bytes_read += read;
} while (read != 0 && bytes_read < bytes_to_read);
return (bytes_read > 0);
}
void CefStreamResourceHandler::Cancel() {}
|
4a6ca9993185c0ba5177fb674fb5cd2627d8ebcf | 1ee22832b8fe7af27144e4877912415d5dbcf84c | /pointer_to_structure.cpp | 931164eb1fab33bed506101e4717822af7dfd12f | [] | no_license | prashantmaurya1309/CplusPlus | 3f35a048c4fa62692787d204d01a115ca8b01a97 | f73ad21d61b937ea99cc2a2c12bfe26be0abae62 | refs/heads/main | 2023-04-30T03:44:36.333042 | 2021-05-23T07:46:53 | 2021-05-23T07:46:53 | 369,990,979 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | cpp | pointer_to_structure.cpp | #include<iostream>
using namespace std;
#include<string>
struct pointer_to_structure
{
/* data */
string name;
int age;
double salary;
};
int main()
{
pointer_to_structure p1;
cout<<"enter details of p1: "<<'\n';
cin>>p1.name;
cin>>p1.age;
cin>>p1.salary;
cout<<"entersed details of p1 are ::"<<'\n';
cout<<p1.name<<" "<<p1.age<<" "<<p1.salary;
pointer_to_structure *ptr;
ptr=&p1;
cout<<'\n'<<"details of p1 using pointer are:"<<'\n';
cout<<ptr->name<<' ';
cout<<ptr->age<<' ';
cout<<ptr->salary<<' ';
return 0;
}
|
62336b4a4bd2364b984aa015735a4fcc4a9b464b | f6606fc30fc01a27e9214434e174d803f06c131b | /ReferenceCast/main.cpp | 986e2508639915a4cbf7137bcae0f0c1de049c25 | [] | no_license | AnkaChan/MyTestCodes | dd6875e4b50bf66f416059b276f7b0ba9c230769 | 66c14bc068d32b60c0b39b8c26c7cfc525c8d612 | refs/heads/master | 2021-07-09T05:21:40.615786 | 2019-01-25T05:21:11 | 2019-01-25T05:21:11 | 109,557,015 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 660 | cpp | main.cpp | #include <iostream>
#include <vector>
#include <string>
#include <ctime>
using std::cout;
using std::endl;
using std::vector;
int main(int argc, char** argv) {
std::vector<long long*> vec1(1);
std::vector<long*> & vec1Ref = (std::vector<long*> &)vec1;
long long a = 0;
long long * pA = &a;
long & aRef = (long&)a;
vec1Ref.push_back((long*)pA);
vec1Ref.push_back((long*)pA);
vec1Ref.push_back((long*)pA);
vec1Ref.push_back((long*)pA);
vec1Ref.back() = NULL;
printf("The size of vec1: %d, the size of vec1Ref: %d.", vec1.size(), vec1Ref.size());
printf("The last element of vec1: %d, last element of vec1Ref: %d.", vec1.back(), vec1Ref.back());
} |
c3c942aa9c5667e202f880f7bef6016cc8dcc5f6 | 875bf57f5cab101c341b0ce38dcaf7a9f63e3534 | /tests/2015/23.cpp | e0eeffffe7f91d1fe9fadca5aad69d0cbdcba951 | [
"MIT"
] | permissive | voivoid/advent-of-code | 91c212137f60b9b619c3735816154c3c74ba3f18 | efc02f558ad7718d02dfc205fadeba6b857ce4ae | refs/heads/master | 2021-10-25T18:51:33.445956 | 2021-10-12T20:47:44 | 2021-10-12T20:47:44 | 136,576,573 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | 23.cpp | #include "boost/test/unit_test.hpp"
#include "AoC/2015/problem_23.h"
#include "aoc_fixture.h"
using namespace AoC_2015::problem_23;
namespace
{
auto get_input()
{
return R"(inc b
jio b, +2
tpl b
inc b)";
}
} // namespace
BOOST_FIXTURE_TEST_CASE( problem2015_23_1, AocFixture )
{
BOOST_CHECK_EQUAL( 2, run( &solve_1, get_input() ) );
}
|
1fd276df03508b8f5c31f63ced528b2da036aadc | 214a5df7ee9c3f1fb2506f32bcaa4d34c1abf732 | /src/include/Carna/qt/SpatialListModelDetails.h | ebd97bb835ca302cfdfb0bb02dd73b5d9815ebcb | [
"BSD-3-Clause"
] | permissive | HOOSHANKAVOSHBORNA/CarnaQt | 50a90deea5371554229699ad42805436455c3f1e | e805e4cf9027d06fcadb9189abe40e697358079a | refs/heads/master | 2023-03-17T13:01:55.007896 | 2015-12-18T14:30:44 | 2015-12-18T14:30:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,496 | h | SpatialListModelDetails.h | /*
* Copyright (C) 2010 - 2015 Leonid Kostrykin
*
* Chair of Medical Engineering (mediTEC)
* RWTH Aachen University
* Pauwelsstr. 20
* 52074 Aachen
* Germany
*
*/
#ifndef SPATIALLISTMODELDETAILS_H_0874895466
#define SPATIALLISTMODELDETAILS_H_0874895466
/** \file SpatialListModelDetails.h
* \brief Defines implementation details of \ref Carna::qt::SpatialListModel.
*/
#include <Carna/qt/SpatialListModel.h>
#include <Carna/base/NodeListener.h>
#include <QObject>
namespace Carna
{
namespace qt
{
// ----------------------------------------------------------------------------------
// SpatialListModel :: Details
// ----------------------------------------------------------------------------------
class SpatialListModel::Details : public QObject, public base::NodeListener
{
Q_OBJECT
public:
Details( SpatialListModel& self );
SpatialListModel& self;
const SpatialMapper* spatialMapper;
base::Node* root;
void removeRootListener();
virtual void onNodeDelete( const base::Node& node ) override;
virtual void onTreeChange( base::Node& node, bool inThisSubtree ) override;
virtual void onTreeInvalidated( base::Node& subtree ) override;
bool invalidated;
std::vector< base::Spatial* > spatials;
void invalidate();
public slots:
void update();
}; // SpatialListModel :: Details
} // namespace Carna :: qt
} // namespace Carna
#endif // SPATIALLISTMODELDETAILS_H_0874895466
|
f483a2947a6166b3c3e0ef4e6e0f5402bc863b5c | 2dbeb203b9d85e1af746f21fc62ec1abd21a72aa | /c/relationship_client/relationship_client.cpp | 71628fd181c489259e42fcf292e93202985c75f4 | [
"MIT"
] | permissive | ox-w-lbs/small-world-graph | 08c57499af1bac7dd8175da1c4468566b1e58a06 | 7fd5d1ac44dc9c88390d3396a13ec2dd03076e5d | refs/heads/master | 2023-04-01T07:50:25.343437 | 2021-03-30T18:05:16 | 2021-03-30T18:05:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,653 | cpp | relationship_client.cpp | /* Relationship Client Implementation */
#include "relationship_client.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <errno.h>
#include <err.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <netdb.h>
#include <errno.h>
/* For inet_ntoa. */
#include <arpa/inet.h>
/* Required by event.h. */
#include <sys/time.h>
#include <iostream>
#include <google/dense_hash_set>
#include "equality.h"
#include "thomas_wang_hash.h"
using namespace std;
using google::dense_hash_set;
typedef dense_hash_set<uint32_t,ThomasWangHash, eqint> dup_set_t;
int
RelationshipClient::net_connect()
{
int soc;
int res;
struct sockaddr_in addr;
long arg;
fd_set myset;
struct timeval tv;
int valopt;
socklen_t lon;
// Create socket
soc = socket(AF_INET, SOCK_STREAM, 0);
if (soc < 0) {
fprintf(stderr, "Error creating socket (%d %s)\n", errno, strerror(errno));
exit(0);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port_);
addr.sin_addr.s_addr = inet_addr(host_.c_str());
// Set non-blocking
if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) {
fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno));
exit(0);
}
arg |= O_NONBLOCK;
if( fcntl(soc, F_SETFL, arg) < 0) {
fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno));
exit(0);
}
// Trying to connect with timeout
res = connect(soc, (struct sockaddr *)&addr, sizeof(addr));
if (res < 0) {
if (errno == EINPROGRESS) {
do {
tv.tv_sec = 1;
tv.tv_usec = 0;
FD_ZERO(&myset);
FD_SET(soc, &myset);
res = select(soc+1, NULL, &myset, NULL, &tv);
if (res < 0 && errno != EINTR) {
fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno));
exit(0);
}
else if (res > 0) {
// Socket selected for write
lon = sizeof(int);
if (getsockopt(soc, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon) < 0) {
fprintf(stderr, "Error in getsockopt() %d - %s\n", errno, strerror(errno));
exit(0);
}
// Check the value returned...
if (valopt) {
fprintf(stderr, "Error in delayed connection() %d - %s\n", valopt, strerror(valopt));
exit(0);
}
break;
}
else {
fprintf(stderr, "Timeout in select() - Cancelling!\n");
exit(0);
}
} while (1);
}
else {
fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno));
exit(0);
}
}
// Set to blocking mode again...
if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) {
fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno));
exit(0);
}
arg &= (~O_NONBLOCK);
if( fcntl(soc, F_SETFL, arg) < 0) {
fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno));
exit(0);
}
return soc;
}
static bool buffered_read( int fd, char * buf, int len)
{
int res, err;
for ( ;; )
{
res = recv ( fd, buf, len, 0 );
if ( res<0 )
{
err = errno;
if ( err==EINTR || err==EWOULDBLOCK ) // FIXME! remove non-blocking mode here; add timeout
continue;
cout << "Error " << strerror(errno) << endl;
return false;
}
len -= res;
buf += res;
if ( len==0 )
return true;
if ( res==0 )
{
cout << "Incomplete Read" << endl;
return false;
}
}
}
static bool buffered_write(int fd, char* buf, int len)
{
int res, err;
for ( ;; )
{
res = send ( fd, buf, len, 0 );
if ( res<0 )
{
err = errno;
/*
if ( err==EINTR || err==EWOULDBLOCK ) // FIXME! remove non-blocking mode here; add timeout
continue;
*/
cout << "Error " << strerror(errno) << endl;
return false;
}
len -= res;
buf += res;
if ( len==0 )
return true;
if ( res==0 )
{
cout << "Incomplete Write" << endl;
return false;
}
}
}
struct int_array*
RelationshipClient::sites_close_to(u_int32_t site_id)
{
struct int_array* results;
bool rc;
int fd = net_connect();
char header[8];
char* send_message = (char*) malloc(12);
*(int*)(send_message) = htonl(4);
*(int*)(send_message + 4) = htonl(2);
*(int*)(send_message + 8) = htonl(site_id);
rc = buffered_write(fd,send_message,12);
if (!rc) {
cout << "Send Error " << strerror(errno) << endl;
}
free(send_message);
results = (struct int_array*) calloc(sizeof(struct int_array),1);
rc = buffered_read(fd,header,8);
if (!rc) {
return results;
}
u_int32_t payload_size = ntohl(*((int*) (header)));
if (!payload_size) {
return results;
}
char* recv_payload = (char*) malloc(payload_size);
rc = buffered_read( fd, recv_payload, payload_size);
if (!rc) {
free(recv_payload);
return results;
}
results->array = (u_int32_t*) malloc(payload_size);
results->length = payload_size / sizeof(u_int32_t);
for(size_t i=0; i < payload_size / 4; i++) {
results->array[i] = ntohl(*(((int*) recv_payload) + i));
}
free(recv_payload);
return results;
}
vector<Relationship>
RelationshipClient::distances(const vector<int>& ids)
{
vector<Relationship> rels;
bool rc;
int fd = net_connect();
char header[8];
dup_set_t dups(ids.size());
dups.set_empty_key(0);
for(size_t i=0; i < ids.size(); i++) {
dups.insert(ids[i]);
}
uint32_t send_payload_size = dups.size() * 4;
char* send_message = (char*) malloc(send_payload_size + 8);
*(int*)(send_message) = htonl(send_payload_size);
*(int*)(send_message + 4) = htonl(1);
char* send_payload = send_message + 8;
int counter = 0;
for(dup_set_t::const_iterator ii = dups.begin(); ii != dups.end(); ii++) {
*(int*)(send_payload + (counter * 4)) = htonl(*ii);
}
rc = buffered_write(fd,send_message,send_payload_size + 8);
if (!rc) {
cout << "Send Error " << strerror(errno) << endl;
}
free(send_message);
rc = buffered_read(fd,header,8);
if (!rc) {
return rels;
}
u_int32_t payload_size = ntohl(*((int*) (header)));
cout << "Received Payload:" << payload_size << endl;
if (payload_size > 0) {
char* recv_payload = (char *) malloc(payload_size);
rc = buffered_read( fd, recv_payload, payload_size);
int* recv_payload_ints = (int*) recv_payload;
if (!rc) {
free(recv_payload);
return rels;
}
for(size_t i = 0; i < payload_size / 4; i += 3) {
Relationship rel;
rel.site_id = ntohl(*(recv_payload_ints + i));
rel.other_site_id = ntohl(*(recv_payload_ints + (i + 1)));
rel.distance = ntohl(*(recv_payload_ints + (i + 2)));
rels.push_back(rel);
}
}
return rels;
}
vector<Relationship>
RelationshipClient::distances(const int_array_t* ids)
{
vector<Relationship> rels;
bool rc;
char header[8];
if (ids->length == 0 || ids->length == 1)
return rels;
int fd = net_connect();
dup_set_t dups(ids->length);
dups.set_empty_key(0);
for(size_t i=0; i < ids->length; i++) {
dups.insert(ids->array[i]);
}
uint32_t send_payload_size = dups.size() * 4;
char* send_message = (char*) malloc(send_payload_size + 8);
*(int*)(send_message) = htonl(send_payload_size);
*(int*)(send_message + 4) = htonl(1);
char* send_payload = send_message + 8;
int counter = 0;
for(dup_set_t::const_iterator ii = dups.begin(); ii != dups.end(); ii++) {
*(int*)(send_payload + (counter * 4)) = htonl(*ii);
counter++;
}
rc = buffered_write(fd,send_message,send_payload_size + 8);
if (!rc) {
cout << "Send Error " << strerror(errno) << endl;
free(send_message);
return rels;
}
free(send_message);
rc = buffered_read(fd,header,8);
if (!rc) {
return rels;
}
u_int32_t payload_size = ntohl(*((int*) (header)));
if (payload_size > 0) {
char* recv_payload = (char *) malloc(payload_size);
rc = buffered_read( fd, recv_payload, payload_size);
int* recv_payload_ints = (int*) recv_payload;
if (!rc) {
free(recv_payload);
return rels;
}
for(size_t i = 0; i < payload_size / 4; i += 3) {
Relationship rel;
rel.site_id = ntohl(*(recv_payload_ints + i));
rel.other_site_id = ntohl(*(recv_payload_ints + (i + 1)));
rel.distance = ntohl(*(recv_payload_ints + (i + 2)));
rels.push_back(rel);
}
free(recv_payload);
}
close(fd);
return rels;
}
|
f2a5979d49199bde7e7673bceff1c42412e87561 | cd0121f79d83c43058fade280e6cdc4ce971cc52 | /subarray_product.cpp | 19548284a4f19104e339e8b536853e1f82bf031a | [] | no_license | dpariag/leetcode | d88ef62f29b7546168adebe6749a561cfb1da889 | e34830429fd9a5695d9ac7f21a5334412f78e8c8 | refs/heads/master | 2021-01-11T08:43:25.205998 | 2019-12-02T05:36:53 | 2019-12-02T05:36:53 | 69,517,949 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,734 | cpp | subarray_product.cpp | // Leetcode: https://leetcode.com/problems/subarray-product-less-than-k/description/
// Given a non-empty array of positive integers, count the number of subarrays whose product is
// less than k.
// Brute Force: Generate all subarrays and compute their product. O(n^3) time.
// Better: Use a sliding window over the array, enlarge if product < k, shrink if product >= k.
// O(n) time and O(1) space.
#include <vector>
#include <numeric>
#include <iostream>
#include <assert.h>
// Accepted. 135ms. Beats 47.67% of submissions, ties 3.76% of submissions.
class Solution {
public:
int numSubarrayProductLessThanK(const std::vector<int>& nums, int k) {
int product = 1, count = 0;
int left = 0, right = 0;
while (right < nums.size()) {
product *= nums[right];
while (left <= right && product >= k) {
product /= nums[left++];
}
count += (right - left + 1);
++right;
}
return count;
}
};
void test_subarray_sums() {
Solution soln;
assert(soln.numSubarrayProductLessThanK({5,10,5,10}, 5) == 0);
assert(soln.numSubarrayProductLessThanK({10,5,2,6}, 100) == 8);
assert(soln.numSubarrayProductLessThanK({5,10,5,10}, 1000) == 9);
assert(soln.numSubarrayProductLessThanK({5,10,5,10}, 6) == 2);
assert(soln.numSubarrayProductLessThanK({5,1,1,10}, 2) == 3);
assert(soln.numSubarrayProductLessThanK({1,1,1,1}, 2) == 10);
assert(soln.numSubarrayProductLessThanK({1,1,1,1}, 1) == 0);
assert(soln.numSubarrayProductLessThanK({1,1,10,10}, 2) == 3);
}
int main(int argc, char** argv) {
test_subarray_sums();
std::cout << argv[0] + 2 << "...OK!" << std::endl;
return 0;
}
|
c333e236bfaa3be590c58cd93e0154fb591766ac | 8805f1f1850b022c5380a91d1f4e752d5b3c01fa | /989/E.cpp | a7287b906c266405e3f1a33820cc622c17f98f0e | [] | no_license | smhx/codeforces | 06f256736ed7f24cc956b887ac55c565be9cc2f7 | 17b76e1d9a07c1a4653d1b3487d68e447f51eda6 | refs/heads/master | 2020-03-16T20:21:32.688123 | 2018-08-03T14:08:55 | 2018-08-03T14:08:55 | 132,955,622 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,307 | cpp | E.cpp | #include <bits/stdc++.h>
#define LOCAL
#ifdef LOCAL
#define DEBUG(fmt, ...) printf(fmt, ##__VA_ARGS__)
#else
#define DEBUG(fmt, ...)
#endif
using namespace std;
#define szof(v) ((int)(v).size())
#define allof(v) begin(v), end(v)
typedef long long ll;
typedef long double ld;
typedef pair<int, int> ii;
typedef pair<ll, ll> pll;
const int MAX = 205, LOG = 15;
ld M[LOG][MAX][MAX];
int n, q;
ii pnts[MAX];
inline bool collinear(int i, int j, int k) {
return (pnts[k].second - pnts[j].second) *
(pnts[j].first - pnts[i].first) ==
(pnts[k].first - pnts[j].first) * (pnts[j].second - pnts[i].second);
}
int ds[MAX], dsz[MAX];
void precompute() {
vector<int> lines;
for (int i = 0; i < n; ++i) {
lines.clear();
for (int j = 0; j < n; ++j) {
ds[j] = j;
dsz[j] = 2;
}
for (int j = 0; j < n; ++j) {
if (i != j) {
for (int k : lines) {
if (collinear(i, j, k)) {
ds[j] = k;
++dsz[k];
}
}
if (ds[j] == j) {
lines.push_back(j);
}
}
}
M[0][i][i] = 1;
for (int j = 0; j < n; ++j) {
if (i == j) {
continue;
}
M[0][i][j] = ld(1) / ld(szof(lines) * dsz[ds[j]]);
M[0][i][i] -= M[0][i][j];
}
}
#ifdef LOCAL
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
DEBUG("%Lf ", M[0][i][j]);
}
DEBUG("\n");
}
#endif
for (int lg = 1; lg < LOG; ++lg) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
for (int k = 0; k < n; ++k) {
M[lg][i][j] =
M[lg][i][j] + M[lg - 1][i][k] * M[lg - 1][k][j];
}
}
}
}
}
ld res[MAX], tmp[MAX];
void generate(int u, int pow) {
for (int i = 0; i < n; ++i) {
res[i] = tmp[i] = 0;
}
res[u] = 1;
for (int k = 0; k < LOG; ++k) {
if (pow & (1 << k)) {
for (int i = 0; i < n; ++i) {
tmp[i] = res[i];
res[i] = 0;
}
for (int r = 0; r < n; ++r) {
for (int c = 0; c < n; ++c) {
res[r] += M[k][r][c] * tmp[c];
}
}
}
}
}
vector<vector<int>> all_lines;
bool used[MAX][MAX];
void locate_all_lines() {
for (int u = 0; u < n; ++u) {
for (int v = 0; v < n; ++v) {
if (u == v) {
continue;
}
if (!used[u][v]) {
all_lines.push_back({});
all_lines.back().push_back(u);
all_lines.back().push_back(v);
for (int w = 0; w < n; ++w) {
if (w != v && w != u && collinear(u, v, w)) {
all_lines.back().push_back(w);
}
}
for (int w1 : all_lines.back()) {
for (int w2 : all_lines.back()) {
used[w1][w2] = true;
}
}
}
}
}
#ifdef LOCAL
for (auto l : all_lines) {
DEBUG("line: ");
for (int v : l) {
DEBUG("%d ", v);
}
DEBUG("\n");
}
#endif
}
int main() {
#ifdef LOCAL
freopen("data.txt", "r", stdin);
#endif
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d%d", &pnts[i].first, &pnts[i].second);
}
locate_all_lines();
precompute();
scanf("%d", &q);
for (int i = 0; i < q; ++i) {
int u, m;
scanf("%d%d", &u, &m);
--u;
generate(u, m - 1);
DEBUG("destination is %d, vector is: ", u);
#ifdef LOCAL
for (int v = 0; v < n; ++v) {
DEBUG("%Lf ", res[v]);
}
DEBUG("\n");
#endif
ld ans = 0;
for (auto l : all_lines) {
ld sum = 0;
for (int v : l) {
sum += res[v];
}
sum /= ld(szof(l));
ans = max(ans, sum);
}
cout << std::setprecision(10) << std::fixed << ans << "\n";
}
} |
ac53e3d1200ec65812be4f292d664edad27bdf55 | 5298705370c757d8846d409382f7dcb8450d48b8 | /wbs/src/UI/ImportDataDlg.h | 29a25e7b1473bcf65bc380e602a4e58c4a6ca148 | [
"MIT"
] | permissive | RNCan/WeatherBasedSimulationFramework | 3d63b6a5fd1548cc5e5bac840f9e7c5f442dcdb0 | 05719614d2460a8929066fb920517f75a6a3ed04 | refs/heads/master | 2023-07-19T21:37:08.139215 | 2023-07-13T02:29:11 | 2023-07-13T02:29:11 | 51,245,634 | 7 | 2 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 3,002 | h | ImportDataDlg.h | //******************************************************************************
// Project: Weather-based simulation framework (WBSF)
// Programmer: Rémi Saint-Amant
//
// It under the terms of the GNU General Public License as published by
// the Free Software Foundation
// It is provided "as is" without express or implied warranty.
//
//******************************************************************************
#pragma once
#include "Simulation/ImportData.h"
#include "UI/Common/UGEditCtrl.h"
#include "UI/Common/OpenDirEditCtrl.h"
#include "UI/Common/CommonCtrl.h"
#include "WeatherBasedSimulationUI.h"
namespace WBSF
{
class CImportVariablesCtrl : public CUGCtrl
{
public:
virtual void OnSetup();
void SetImportHeader(const std::string& header);
void GetData(CColumnLinkVector& data);
void SetData(const CColumnLinkVector& data);
virtual int OnCellTypeNotify(long ID, int col, long row, long msg, LONG_PTR param);
static void GetAutoSelect(const std::string& header, size_t& dimensionRef, size_t& dimensionField);
void OnDimensionChange(int row, size_t dimensionRef);
virtual int OnCanSizeRow(long row) { UNREFERENCED_PARAMETER(row); return FALSE; }
virtual int OnCanSizeTopHdg() { return FALSE; }
virtual void OnColSized(int col, int *width);
virtual int OnSideHdgSized(int *width);
private:
CString GetDimensionText(size_t dimension)const;
CString GetFieldText(size_t dimension, size_t field)const;
size_t GetDimension(CString str)const;
size_t GetField(size_t dimension, CString str)const;
CStringArrayEx DIMENSION_LABLE;
CStringArrayEx LOC_LABLE;
CStringArrayEx TIME_LABLE;
CStringArrayEx VARIABLES_LABLE;
};
// CImportDataDlg dialog
class CImportDataDlg : public CDialog
{
DECLARE_DYNAMIC(CImportDataDlg)
public:
friend CImportData;
CImportDataDlg(const CExecutablePtr& pParent, CWnd* pParentWnd); // standard constructor
virtual ~CImportDataDlg();
virtual BOOL OnInitDialog();
virtual void SetExecutable(CExecutablePtr pExecutable){ m_importData = GetImportData(pExecutable); }
virtual CExecutablePtr GetExecutable()const{ return m_importData.CopyObject(); }
// Dialog Data
enum { IDD = IDD_SIM_IMPORT_SIMULATION };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual void OnOK();
DECLARE_MESSAGE_MAP()
void OnSize(UINT nType, int cx, int cy);
void AdjustLayout();
CCFLComboBox m_nameCtrl;
CCFLComboBox m_descriptionCtrl;
CCFLComboBox m_fileNameCtrl;
CImportVariablesCtrl m_columnLink;
COpenDirEditCtrl m_defaultDirCtrl;
CCFLEdit m_internalNameCtrl;
void FillFileName();
CImportData m_importData;
CImportData& GetImportData(const CExecutablePtr& pItem){ ASSERT(pItem); return dynamic_cast<CImportData&>(*pItem); }
afx_msg void OnFileNameChange();
afx_msg void OnDestroy();
};
} |
0226040e07cd7e2a2a80f920bfad932caf638130 | 3be43bd478102c3a70d1944a1832da163d025e31 | /game/engine.h | 9ff3f3acdee662c7de9846d2660949437a8c0cb6 | [] | no_license | 10098/braveball | 8930704f9c8d213ad8ec9eeefd71a5da06031a39 | ddf211d5efec02fd8f842dde0c9661d95c771cb7 | refs/heads/master | 2016-08-08T11:51:43.868198 | 2013-01-02T21:33:45 | 2013-01-02T21:33:45 | 7,393,633 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,799 | h | engine.h | /// @file game/engine.h
/// @author grigoryj
#ifndef ENGINE_H
#define ENGINE_H
#include "game/scene.h"
#include "graphics/graphics.h"
#include "graphics/font.h"
#include "sound/sound_system.h"
#include "util/clock.h"
#include "util/resource_manager.h"
#include <unordered_map>
#include <memory>
namespace game
{
/// Maintains the game scenes and various engine subsystems.
class Engine
{
public:
/// Sets the active scene
/// @param name The name of the scene to set as active
/// @throw runtime_error if the specified scene does not exist
void setScene(const std::string& name);
/// @return the clock object
util::Clock& clock();
/// @return the graphics object
graphics::Graphics& graphics();
/// @return const version for graphics()
const graphics::Graphics& graphics() const;
/// @return the resource manager
const util::ResourceManager& resourceManager() const;
/// Performs all the necessary initializations and launches the game from the first scene.
/// Returns when the player exits the game.
void run(int argc, char* argv[], const std::string& window_title = "tractorengine");
private:
typedef std::unordered_map<std::string, std::unique_ptr<Scene> > SceneMap;
SceneMap m_scenes; /// Maps scene names to pointers to scenes
SceneMap::iterator m_currentScene; /// Points to the active scene
std::shared_ptr<graphics::Graphics> m_graph; /// Graphics subsystem
util::Clock m_clock; /// Clock
std::shared_ptr<util::ResourceManager> m_resMan; /// Resource manager
sound::SoundSystem m_sound; /// Sound subsystem
};
}
#endif // ENGINE_H
|
f98dab9c4e0c6f1ae5f5614964d92c694b420f39 | 23e1116a76b8a914eb40463f91b4a97a1c7f2b29 | /libs/chessx-pgn/database/bitboard.cpp | 5c29848508d51300d80dafad4b01f3e312caf973 | [
"MIT"
] | permissive | loloof64/ChessTrainingVsEngine | 6b69f16865a04095cc423319c8c31e49387d0904 | 6950b5f4adf6e6bc7745884f86f994e185c3ffb4 | refs/heads/master | 2023-02-17T12:08:29.678745 | 2021-01-15T19:49:29 | 2021-01-15T19:49:29 | 280,382,648 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 92,323 | cpp | bitboard.cpp | /***************************************************************************
* (C) 2003 Sune Fischer *
* (C) 2005-2006 Marius Roets <roets.marius@gmail.com> *
* (C) 2005-2009 Michal Rudolf <mrudolf@kdewebdev.org> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "bitboard.h"
#include "square.h"
#include "bitfind.h"
#ifdef _MSC_VER
#include <intrin.h>
#endif
#include <QtCore>
#if defined(_MSC_VER) && defined(_DEBUG)
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif // _MSC_VER
// Global data that is initialized early on and only read afterward
quint64 bb_PawnAttacks[2][64];
quint64 bb_PawnF1[2][64];
quint64 bb_PawnF2[2][64];
quint64 bb_PawnALL[2][64];
quint64 bb_PromotionRank[2];
quint64 bb_KnightAttacks[64];
quint64 bb_R45Attacks[64][64];
quint64 bb_L45Attacks[64][64];
quint64 bb_KingAttacks[64];
quint64 bb_RankAttacks[64][64];
quint64 bb_FileAttacks[64][64];
quint64 bb_fileMask[8];
quint64 bb_rankMask[8];
quint64 bb_Mask[64];
quint64 bb_MaskL90[64];
quint64 bb_MaskL45[64];
quint64 bb_MaskR45[64];
BitBoard getStandardPosition();
// Calling the function getStandardPosition for initialization avoids
// initialization side effects when using BitBoards in other translation
// units.
BitBoard standardPosition = getStandardPosition();
BitBoard clearedPosition;
bool bitBoardInitRun;
void bitBoardInit();
const quint64 A1 = 1, B1 = A1 << 1, C1 = B1 << 1, D1 = C1 << 1, E1 = D1 << 1, F1 = E1 << 1, G1 = F1 << 1, H1 = G1 << 1;
const quint64 A2 = H1 << 1, B2 = A2 << 1, C2 = B2 << 1, D2 = C2 << 1, E2 = D2 << 1, F2 = E2 << 1, G2 = F2 << 1, H2 = G2 << 1;
const quint64 A3 = H2 << 1, B3 = A3 << 1, C3 = B3 << 1, D3 = C3 << 1, E3 = D3 << 1, F3 = E3 << 1, G3 = F3 << 1, H3 = G3 << 1;
const quint64 A4 = H3 << 1, B4 = A4 << 1, C4 = B4 << 1, D4 = C4 << 1, E4 = D4 << 1, F4 = E4 << 1, G4 = F4 << 1, H4 = G4 << 1;
const quint64 A5 = H4 << 1, B5 = A5 << 1, C5 = B5 << 1, D5 = C5 << 1, E5 = D5 << 1, F5 = E5 << 1, G5 = F5 << 1, H5 = G5 << 1;
const quint64 A6 = H5 << 1, B6 = A6 << 1, C6 = B6 << 1, D6 = C6 << 1, E6 = D6 << 1, F6 = E6 << 1, G6 = F6 << 1, H6 = G6 << 1;
const quint64 A7 = H6 << 1, B7 = A7 << 1, C7 = B7 << 1, D7 = C7 << 1, E7 = D7 << 1, F7 = E7 << 1, G7 = F7 << 1, H7 = G7 << 1;
const quint64 A8 = H7 << 1, B8 = A8 << 1, C8 = B8 << 1, D8 = C8 << 1, E8 = D8 << 1, F8 = E8 << 1, G8 = F8 << 1, H8 = G8 << 1;
const unsigned int RotateL90[64] =
{
h1, h2, h3, h4, h5, h6, h7, h8,
g1, g2, g3, g4, g5, g6, g7, g8,
f1, f2, f3, f4, f5, f6, f7, f8,
e1, e2, e3, e4, e5, e6, e7, e8,
d1, d2, d3, d4, d5, d6, d7, d8,
c1, c2, c3, c4, c5, c6, c7, c8,
b1, b2, b3, b4, b5, b6, b7, b8,
a1, a2, a3, a4, a5, a6, a7, a8,
};
const unsigned int RotateR45[64] =
{
a1, b8, c7, d6, e5, f4, g3, h2,
a2, b1, c8, d7, e6, f5, g4, h3,
a3, b2, c1, d8, e7, f6, g5, h4,
a4, b3, c2, d1, e8, f7, g6, h5,
a5, b4, c3, d2, e1, f8, g7, h6,
a6, b5, c4, d3, e2, f1, g8, h7,
a7, b6, c5, d4, e3, f2, g1, h8,
a8, b7, c6, d5, e4, f3, g2, h1
};
const unsigned int RotateL45[64] =
{
a2, b3, c4, d5, e6, f7, g8, h1,
a3, b4, c5, d6, e7, f8, g1, h2,
a4, b5, c6, d7, e8, f1, g2, h3,
a5, b6, c7, d8, e1, f2, g3, h4,
a6, b7, c8, d1, e2, f3, g4, h5,
a7, b8, c1, d2, e3, f4, g5, h6,
a8, b1, c2, d3, e4, f5, g6, h7,
a1, b2, c3, d4, e5, f6, g7, h8
};
const unsigned char Castle[64] =
{
0xFB, 255, 255, 255, 0xFA, 255, 255, 0xFE,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
0xF7, 255, 255, 255, 0xF5, 255, 255, 0xFD
};
const quint64 fileA = A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8;
const quint64 fileB = B1 | B2 | B3 | B4 | B5 | B6 | B7 | B8;
const quint64 fileG = G1 | G2 | G3 | G4 | G5 | G6 | G7 | G8;
const quint64 fileH = H1 | H2 | H3 | H4 | H5 | H6 | H7 | H8;
const quint64 rank4 = A4 | B4 | C4 | D4 | E4 | F4 | G4 | H4;
const quint64 rank5 = A5 | B5 | C5 | D5 | E5 | F5 | G5 | H5;
const quint64 fileNotA = ~ fileA;
const quint64 fileNotH = ~ fileH;
const quint64 fileNotAB = ~(fileA | fileB);
const quint64 fileNotGH = ~(fileG | fileH);
#define SetBitL90(s) (bb_MaskL90[s])
#define SetBitL45(s) (bb_MaskL45[s])
#define SetBitR45(s) (bb_MaskR45[s])
#define ShiftDown(b) ((b)>>8)
#define Shift2Down(b) ((b)>>16)
#define ShiftUp(b) ((b)<<8)
#define Shift2Up(b) ((b)<<16)
#define ShiftRight(b) (((b)<<1)&fileNotA)
#define Shift2Right(b) (((b)<<2)&fileNotAB)
#define ShiftLeft(b) (((b)>>1)&fileNotH)
#define Shift2Left(b) (((b)>>2)&fileNotGH)
#define ShiftUpLeft(b) (((b)<<7)&fileNotH)
#define ShiftUpRight(b) (((b)<<9)&fileNotA)
#define ShiftDownLeft(b) (((b)>>9)&fileNotH)
#define ShiftDownRight(b) (((b)>>7)&fileNotA)
#define SetBit(s) (bb_Mask[s])
/** Initialize a new bitboard, and ensure global data has been initialized */
BitBoard::BitBoard()
{
memset(this, 0, sizeof(BitBoard));
if(!bitBoardInitRun)
{
bitBoardInit();
}
m_epSquare = NoEPSquare;
}
bool BitBoard::isCheckmate() const
{
MoveList moves(generateMoves());
for(int i = 0; i < moves.size(); ++i)
{
if(!isIntoCheck(moves[i]))
{
return false;
}
}
return isCheck();
}
bool BitBoard::isStalemate() const
{
MoveList moves(generateMoves());
for(int i = 0; i < moves.size(); ++i)
{
if(!isIntoCheck(moves[i]))
{
return false;
}
}
return !isCheck();
}
void BitBoard::removeIllegal(const Move& move, quint64& b) const
{
quint64 mask = 1;
Move m = move;
for(int sq = 0; sq < 64; ++sq)
{
if(b & mask)
{
m.setFrom(Square(sq));
if(isIntoCheck(m))
{
b &= ~mask;
}
}
mask <<= 1;
}
}
inline QString sanPiece(int piece, bool translate = false)
{
if(!translate)
{
return QString(" KQRBN"[piece]);
}
/*
* Removed by loloof64
* QString pieceString = AppSettings->getValue("/GameText/PieceString").toString();
if(pieceString.length() == 6)
{
return QString(pieceString.at(piece));
}
*/
switch(piece)
{
case 0:
return " ";
case 1:
return "♔";
case 2:
return "♕";
case 3:
return "♖";
case 4:
return "♗";
case 5:
return "♘";
}
return " ";
}
QString BitBoard::moveToSan(const Move& move, bool translate, bool extend) const
{
QString san;
Square from = move.from();
Square to = move.to();
bool isPawn = m_piece[from] == Pawn;
if (extend)
{
san = QString("%1.").arg(m_moveNumber);
if (blackToMove())
{
san += "..";
}
}
if(move.isNullMove())
{
san += "--";
return san;
}
if(move.isCastling())
{
if (File(to)==File(g1))
{
san += "O-O";
}
else
{
san += "O-O-O";
}
}
else
{
if(!isPawn)
{
san += sanPiece(m_piece[from], translate);
// We may need disambiguation
quint64 others = 0;
switch(m_piece[from])
{
case Knight:
others = m_knights & knightAttacksFrom(to);
break;
case Bishop:
others = m_bishops & bishopAttacksFrom(to);
break;
case Rook:
others = m_rooks & rookAttacksFrom(to);
break;
case Queen:
others = m_queens & queenAttacksFrom(to);
break;
case King:
others = m_kings & kingAttacksFrom(to);
break;
default:
break; // Something really wrong
}
others ^= SetBit(from);
others &= m_occupied_co[m_stm];
// Do not disambiguate with moves that put oneself in check.
// This is an expensive operation of dubious value, but people seem to want it
if(others)
{
removeIllegal(move, others);
}
if(others)
{
bool row = false, column = false;
if(others & bb_rankMask[Rank(from)])
{
column = true;
}
if(others & bb_fileMask[File(from)])
{
row = true;
}
else
{
column = true;
}
if(column)
{
san += 'a' + File(from);
}
if(row)
{
san += '1' + Rank(from);
}
}
}
//capture x
if(m_piece[to] || (move.isEnPassant()))
{
if(isPawn)
{
san += 'a' + File(from);
}
san += 'x';
}
//destination square
san += 'a' + File(to);
san += '1' + Rank(to);
}
if(move.isPromotion())
{
san += '=';
san += sanPiece(move.promoted(), translate);
}
BitBoard check(*this);
check.doMove(move);
if(check.isCheck())
{
if(check.isCheckmate())
{
san += '#';
}
else
{
san += '+';
}
}
return san;
}
void BitBoard::clear()
{
*this = clearedPosition;
}
void BitBoard::setStandardPosition()
{
*this = standardPosition;
}
void BitBoard::clearEnPassantSquare()
{
m_epFile = 0;
m_epSquare = NoEPSquare;
}
void BitBoard::setEnPassantSquare(const Square s)
{
m_epSquare = s;
m_epFile = File(s);
}
void BitBoard::setEnPassantFile(int f)
{
if ((f>=0) && (f<=7))
{
m_epFile = f+1;
epFile2Square();
}
else
{
clearEnPassantSquare();
}
}
bool BitBoard::isMovable(const Square from) const
{
Q_ASSERT(from < 64);
if(m_occupied_co[m_stm] & SetBit(from))
{
quint64 squares = 0;
switch(m_piece[from])
{
case Pawn:
squares = pawnMovesFrom(from);
break;
case Knight:
squares = knightAttacksFrom(from);
break;
case Bishop:
squares = bishopAttacksFrom(from);
break;
case Rook:
squares = rookAttacksFrom(from);
break;
case Queen:
squares = queenAttacksFrom(from);
break;
case King:
squares = kingAttacksFrom(m_ksq[m_stm]);
if (m_stm == White)
{
squares |= SetBit(g1);
squares |= SetBit(c1);
}
else if (m_stm == Black)
{
squares |= SetBit(g8);
squares |= SetBit(c8);
}
break;
default:
break;
}
squares &= ~m_occupied_co[m_stm];
while(squares)
{
Square to = getFirstBitAndClear64<Square>(squares);
if(prepareMove(from, to).isLegal())
{
return true;
}
}
}
return false;
}
void BitBoard::setAt(const Square s, const Piece p)
{
Q_ASSERT(s < 64);
Q_ASSERT(isValidPiece(p) || p == Empty);
quint64 bit = SetBit(s);
if(m_occupied & bit)
{
removeAt(s);
}
PieceType pt = pieceType(p);
if(pt == None)
{
return;
}
Color _color = pieceColor(p);
++m_pieceCount[_color];
switch(pt)
{
case Pawn:
m_pawns |= bit;
++m_pawnCount[_color];
break;
case Knight:
m_knights |= bit;
break;
case Bishop:
m_bishops |= bit;
break;
case Rook:
m_rooks |= bit;
break;
case Queen:
m_queens |= bit;
break;
case King:
if(m_kings & m_occupied_co[_color])
{
removeAt(m_ksq[_color]);
}
m_kings |= bit;
m_ksq[_color] = s;
break;
default:
break; // ERROR
}
m_piece[s] = pt;
m_occupied ^= bit;
m_occupied_co[_color] ^= bit;
m_occupied_l90 ^= SetBitL90(s);
m_occupied_l45 ^= SetBitL45(s);
m_occupied_r45 ^= SetBitR45(s);
}
void BitBoard::removeAt(const Square s)
{
Q_ASSERT(s < 64);
quint64 bit = SetBit(s);
if(!(m_occupied & bit))
{
return;
}
Color _color = (m_occupied_co[White] & bit) ? White : Black;
--m_pieceCount[_color];
switch(m_piece[s])
{
case Pawn:
m_pawns ^= bit;
--m_pawnCount[_color];
break;
case Knight:
m_knights ^= bit;
break;
case Bishop:
m_bishops ^= bit;
break;
case Rook:
m_rooks ^= bit;
if (!chess960())
{
m_castle &= Castle[s];
}
else
{
if (m_castlingRooks & bit)
{
destroyCastleInDirection(_color, s);
}
}
break;
case Queen:
m_queens ^= bit;
break;
case King:
m_kings ^= bit;
m_ksq[_color] = InvalidSquare;
destroyCastle(_color);
break;
default:
break; // ERROR
}
m_piece[s] = Empty;
m_occupied ^= bit;
m_occupied_co[_color] ^= bit;
m_occupied_l90 ^= SetBitL90(s);
m_occupied_l45 ^= SetBitL45(s);
m_occupied_r45 ^= SetBitR45(s);
}
bool BitBoard::isValidFen(const QString& fen) const
{
return BitBoard().fromGoodFen(fen, chess960());
}
bool BitBoard::fromFen(const QString& fen)
{
if(isValidFen(fen))
{
return fromGoodFen(fen, chess960());
}
return false;
}
BoardStatus BitBoard::validate() const
{
unsigned int wk = 0, bk = 0, wp = 0, bp = 0, bo = 0, wo = 0;
for(unsigned int i = 0; i < 64; ++i)
{
Piece p = pieceAt(Square(i));
if(p == WhiteKing)
{
++wk;
}
else if(p == BlackKing)
{
++bk;
}
else if(p == WhitePawn)
{
if(i <= h1 || i >= a8) // Pawns on 1st or 8th
{
return PawnsOn18;
}
else
{
++wp;
}
}
else if(p == BlackPawn)
{
if(i <= h1 || i >= a8) // Pawns on 1st or 8th
{
return PawnsOn18;
}
else
{
++bp;
}
}
else if(isWhite(p))
{
++wo;
}
else if(isBlack(p))
{
++bo;
}
}
Q_ASSERT(wp == m_pawnCount[White]);
Q_ASSERT(bp == m_pawnCount[Black]);
Q_ASSERT(wp + wk + wo == m_pieceCount[White]);
Q_ASSERT(bp + bk + bo == m_pieceCount[Black]);
// Exactly one king per side
if(wk == 0)
{
return NoWhiteKing;
}
if(bk == 0)
{
return NoBlackKing;
}
if(wk != 1 || bk != 1)
{
return TooManyKings;
}
// No more than 8 pawns per side
if(wp > 8)
{
return TooManyWhitePawns;
}
if(bp > 8)
{
return TooManyBlackPawns;
}
// Maximum 16 pieces per side
if((wk + wp + wo) > 16)
{
return TooManyWhite;
}
if((bk + bp + bo) > 16)
{
return TooManyBlack;
}
// Bad checks
bool check = isAttackedBy(m_stm ^ 1, m_ksq[m_stm]);
bool check2 = isAttackedBy(m_stm, m_ksq[m_stm ^ 1]);
if(check && check2)
{
return DoubleCheck;
}
if(check2)
{
return OppositeCheck;
}
// Can't castle with missing rook
if (!m_chess960)
{
if(canCastleLong(White) && pieceAt(a1) != WhiteRook)
{
return BadCastlingRights;
}
if(canCastleShort(White) && pieceAt(h1) != WhiteRook)
{
return BadCastlingRights;
}
if(canCastleLong(Black) && pieceAt(a8) != BlackRook)
{
return BadCastlingRights;
}
if(canCastleShort(Black) && pieceAt(h8) != BlackRook)
{
return BadCastlingRights;
}
// Can't castle if king has moved
if(canCastle(White) && pieceAt(e1) != WhiteKing)
{
return BadCastlingRights;
}
if(canCastle(Black) && pieceAt(e8) != BlackKing)
{
return BadCastlingRights;
}
}
else
{
// Can't castle if king is not on row 1 / 8
if(canCastle(White) && !(SetBit(m_ksq[White]) & 0x00000000000000FFuLL))
{
return BadCastlingRights;
}
if(canCastle(Black) && !(SetBit(m_ksq[Black]) & 0xFF00000000000000uLL))
{
return BadCastlingRights;
}
if(canCastleLong(White) && !HasRookForCastling(0))
{
return BadCastlingRights;
}
if(canCastleShort(White) && !HasRookForCastling(1))
{
return BadCastlingRights;
}
if(canCastleLong(Black) && !HasRookForCastling(2))
{
return BadCastlingRights;
}
if(canCastleShort(Black) && !HasRookForCastling(3))
{
return BadCastlingRights;
}
if (canCastle(White) && canCastle(Black))
{
if (File(m_ksq[White]) != File(m_ksq[Black]))
{
return BadCastlingRights;
}
}
if (canCastleShort(White) && canCastleShort(Black))
{
if (File(CastlingRook(1)) != File(CastlingRook(3)))
{
return BadCastlingRights;
}
}
if (canCastleLong(White) && canCastleLong(Black))
{
if (File(CastlingRook(0)) != File(CastlingRook(2)))
{
return BadCastlingRights;
}
}
}
// Detect unreasonable ep square
if(m_epSquare != NoEPSquare)
{
if(m_stm == White && (m_epSquare < a6 || m_epSquare > h6))
{
return InvalidEnPassant;
}
if(m_stm == Black && (m_epSquare < a3 || m_epSquare > h3))
{
return InvalidEnPassant;
}
}
// Don't allow triple(or more) checks.
// FIXME -- need code here to return MultiCheck
return Valid;
}
bool BitBoard::isKingOnRow(Piece p, Square start, Square stop) const
{
for (Square square=start; square<=stop; ++square)
{
if (pieceAt(square) == p) return true;
}
return false;
}
bool BitBoard::canTakeEnPassant() const
{
if(m_stm == Black)
{
quint64 movers = m_pawns & m_occupied_co[Black];
if(m_epSquare != NoEPSquare)
{
quint64 moves = bb_PawnAttacks[White][m_epSquare] & movers;
return (moves != 0);
}
}
else
{
quint64 movers = m_pawns & m_occupied_co[White];
if(m_epSquare != NoEPSquare)
{
quint64 moves = bb_PawnAttacks[Black][m_epSquare] & movers;
return (moves != 0);
}
}
return 0;
}
// Why QString throws asserts for access past end of string and
// refuses to return a real c++ char type is beyond me...
class SaneString : public QString
{
public:
SaneString(const QString& q) : QString(q) {};
char operator[](const int index) const
{
if(index < this->length())
{
return QString::operator[](index).toLatin1();
}
return 0;
}
};
bool BitBoard::fromGoodFen(const QString& qfen, bool chess960)
{
SaneString fen(qfen);
int i;
unsigned int s;
char c = fen[0];
memset(this, 0, sizeof(BitBoard));
setChess960(chess960);
m_moveNumber = 1;
m_epSquare = NoEPSquare;
// Piece position
i = 0;
s = 56;
while(c && c != ' ' && s <= 64)
{
switch(c)
{
case '/':
s -= 16;
break;
case '1':
s += 1;
break;
case '2':
s += 2;
break;
case '3':
s += 3;
break;
case '4':
s += 4;
break;
case '5':
s += 5;
break;
case '6':
s += 6;
break;
case '7':
s += 7;
break;
case '8':
s += 8;
break;
case 'p':
m_piece[s] = Pawn;
m_pawns |= SetBit(s);
m_occupied_co[Black] |= SetBit(s);
++m_pawnCount[Black];
++m_pieceCount[Black];
s++;
break;
case 'n':
m_piece[s] = Knight;
m_knights |= SetBit(s);
m_occupied_co[Black] |= SetBit(s);
++m_pieceCount[Black];
s++;
break;
case 'b':
m_piece[s] = Bishop;
m_bishops |= SetBit(s);
m_occupied_co[Black] |= SetBit(s);
++m_pieceCount[Black];
s++;
break;
case 'r':
m_piece[s] = Rook;
m_rooks |= SetBit(s);
m_occupied_co[Black] |= SetBit(s);
++m_pieceCount[Black];
s++;
break;
case 'q':
m_piece[s] = Queen;
m_queens |= SetBit(s);
m_occupied_co[Black] |= SetBit(s);
++m_pieceCount[Black];
s++;
break;
case 'k':
m_piece[s] = King;
m_kings |= SetBit(s);
m_occupied_co[Black] |= SetBit(s);
m_ksq[Black] = Square(s);
++m_pieceCount[Black];
s++;
break;
case 'P':
m_piece[s] = Pawn;
m_pawns |= SetBit(s);
m_occupied_co[White] |= SetBit(s);
++m_pawnCount[White];
++m_pieceCount[White];
s++;
break;
case 'N':
m_piece[s] = Knight;
m_knights |= SetBit(s);
m_occupied_co[White] |= SetBit(s);
++m_pieceCount[White];
s++;
break;
case 'B':
m_piece[s] = Bishop;
m_bishops |= SetBit(s);
m_occupied_co[White] |= SetBit(s);
++m_pieceCount[White];
s++;
break;
case 'R':
m_piece[s] = Rook;
m_rooks |= SetBit(s);
m_occupied_co[White] |= SetBit(s);
++m_pieceCount[White];
s++;
break;
case 'Q':
m_piece[s] = Queen;
m_queens |= SetBit(s);
m_occupied_co[White] |= SetBit(s);
++m_pieceCount[White];
s++;
break;
case 'K':
m_piece[s] = King;
m_kings |= SetBit(s);
m_occupied_co[White] |= SetBit(s);
m_ksq[White] = Square(s);
++m_pieceCount[White];
s++;
break;
default:
return false;
}
c = fen[++i];
}
if(s != 8)
{
return false;
}
// Set remainder of bitboard data appropriately
m_occupied = m_occupied_co[White] + m_occupied_co[Black];
for(int i = 0; i < 64; ++i)
{
if(SetBit(i)&m_occupied)
{
m_occupied_l90 |= SetBitL90(i);
m_occupied_l45 |= SetBitL45(i);
m_occupied_r45 |= SetBitR45(i);
}
}
// Side to move
c = fen[++i];
if(c == 'w')
{
m_stm = White;
}
else if(c == 'b')
{
m_stm = Black;
}
else if(c == 0)
{
return true;
}
else
{
return false;
}
++i;
// Castling Rights
c = fen[++i];
if(c == 0)
{
return true;
}
m_castlingRooks = 0;
if(c != '-')
{
while(c != ' ')
{
switch(c)
{
case 'K':
setCastleShort(White);
break;
case 'Q':
setCastleLong(White);
break;
case 'k':
setCastleShort(Black);
break;
case 'q':
setCastleLong(Black);
break;
default:
{
if (c>='a' && c<='h')
{
Square x = SquareFromRankAndFile(7,c);
if (x<m_ksq[Black])
{
setChess960(true);
m_castlingRooks |= SetBit(x);
setCastleLong(Black);
}
else if (x>m_ksq[Black])
{
setChess960(true);
m_castlingRooks |= SetBit(x);
setCastleShort(Black);
}
}
else if (c>='A' && c<='H')
{
Square x = SquareFromRankAndFile(0,c);
if (x<m_ksq[White])
{
setChess960(true);
m_castlingRooks |= SetBit(x);
setCastleLong(White);
}
else if (x>m_ksq[White])
{
setChess960(true);
m_castlingRooks |= SetBit(x);
setCastleShort(White);
}
}
else
{
return false;
}
}
break;
}
c = fen[++i];
}
}
else
{
++i; // Bypass space
}
if (!m_castlingRooks)
{
setCastlingRooks();
}
else
{
fixCastlingRooks(true);
}
// EnPassant Square
c = fen[++i];
if(c == 0)
{
return true;
}
if(c != '-')
{
bool epgood = true;
if(c >= 'a' && c <= 'h')
{
m_epFile = c - 'a' + 1;
}
else if(c >= 'A' && c <= 'H')
{
m_epFile = c - 'A' + 1;
}
else if(c < '0' || c > '9')
{
return false;
}
else
{
epgood = false;
}
if(epgood)
{
c = fen[++i];
if(m_stm == White && c != '6')
{
return false;
}
else if(m_stm == Black && c != '3')
{
return false;
}
}
}
epFile2Square();
++i;
// Half move clock
c = fen[++i];
if(c == 0)
{
return true;
}
if (c=='-')
{
m_halfMoves = 0; // Workaround for some lazy generators
++i; // Eat ws
}
else
{
if(c < '0' || c > '9')
{
return false;
}
int j = i;
while(c >= '0' && c <= '9')
{
c = fen[++i];
}
m_halfMoves = fen.midRef(j, i - j).toInt();
}
// Move number
c = fen[++i];
if(c == 0)
{
return true;
}
if (c=='-')
{
m_moveNumber=1; // Workaround for some lazy generators
}
else
{
if(c < '0' || c > '9')
{
return false;
}
m_moveNumber = fen.midRef(i).toInt();
while(c >= '0' && c <= '9')
{
c = fen[++i];
}
if(m_moveNumber <= 0)
{
// Silently fix illegal movenumber
m_moveNumber = 1;
}
}
return true;
}
void BitBoard::setCastlingRooks(char file000, char file00)
{
if (chess960())
{
m_castlingRooks = m_rooks; // Keep a copy of the original rook positions for castling rights
}
else
{
m_castlingRooks = BitBoard::standardCastlingRooks();
return;
}
Color canCastleColor = NoColor;
if (canCastle(White))
{
canCastleColor = White;
}
else if (canCastle(Black))
{
canCastleColor = Black;
}
if (canCastleColor == NoColor)
{
m_castlingRooks = BitBoard::standardCastlingRooks();
return;
}
fixCastlingRooks(false, file000, file00);
}
void BitBoard::fixCastlingRooks(bool onlyMissingSections, char file000, char file00)
{
Square Sections[4][2] = { { a1, m_ksq[White] },
{ h1, m_ksq[White] },
{ a8, m_ksq[Black] },
{ h8, m_ksq[Black] }};
Square filesForSection[4] =
{
file000 ? SquareFromRankAndFile(0,file000) : Square(InvalidSquare),
file00 ? SquareFromRankAndFile(0,file00) : Square(InvalidSquare),
file000 ? SquareFromRankAndFile(7,file000) : Square(InvalidSquare),
file00 ? SquareFromRankAndFile(7,file00) : Square(InvalidSquare)
};
for (int section=0; section<4; ++section)
{
Square start = Sections[section][0];
Square stop = Sections[section][1];
Square iter = start;
do
{
quint64 x = SetBit(iter);
if (m_castlingRooks & x)
{
if (filesForSection[section] != InvalidSquare)
{
if (iter != filesForSection[section])
{
m_castlingRooks &= ~x;
}
else
{
break;
}
}
else
{
break;
}
}
iter += (start<stop) ? +1 : -1;
} while (iter != stop);
if (iter == stop)
{
// No bit set in section, fix this with arbitrary square
m_castlingRooks |= SetBit(start);
}
else if (!onlyMissingSections)
{
// One bit is set, clear all others
do
{
iter += (start<stop) ? +1 : -1;
quint64 x = SetBit(iter);
if (m_castlingRooks & x)
{
m_castlingRooks &= ~x;
}
} while (iter != stop);
}
}
}
bool BitBoard::hasAmbiguousCastlingRooks(char file000, char file00) const
{
if (!chess960()) return false;
Square Sections[4][2] = { { a1, m_ksq[White] },
{ h1, m_ksq[White] },
{ a8, m_ksq[Black] },
{ h8, m_ksq[Black] }};
bool testRequired[4] =
{
canCastleLong(White),
canCastleShort(White),
canCastleLong(Black),
canCastleShort(Black)
};
Square filesForSection[4] =
{
file000 ? SquareFromRankAndFile(0,file000) : Square(InvalidSquare),
file00 ? SquareFromRankAndFile(0,file00) : Square(InvalidSquare),
file000 ? SquareFromRankAndFile(7,file000) : Square(InvalidSquare),
file00 ? SquareFromRankAndFile(7,file00) : Square(InvalidSquare)
};
for (int section=0; section<4; ++section)
{
if (!testRequired[section]) continue;
bool found = false;
Square start = Sections[section][0];
Square stop = Sections[section][1];
Square iter = start;
do
{
quint64 x = SetBit(iter);
if (m_rooks & x)
{
if (filesForSection[section] != InvalidSquare )
{
if (iter != filesForSection[section])
{
return true;
}
else
{
// Outer rook is allowed rook -> unambiguous
break;
}
}
else
{
if (found) return true;
found = true;
}
}
iter += (start<stop) ? +1 : -1;
} while (iter != stop);
}
return false;
}
unsigned int BitBoard::countSetBits(quint64 n) const
{
unsigned int count = 0;
while (n)
{
n &= (n-1);
count++;
}
return count;
}
void BitBoard::fromChess960pos(int i)
{
setChess960(true);
if (i<0 || i>959)
{
setStandardPosition();
return;
}
#define scanc(x) {while (f[c] != 0) c++; while (n>0) if (f[++c] == 0) n--;f[c] = x;}
int n, c, knights[10][2] = {{0,0},{0,1},{0,2},{0,3},{1,0},{1,1},{1,2},{2,0},{2,1},{3,0}};
char f[9];
memset(&f[0],0,sizeof(f));
n = i % 4; i /= 4; f[n*2+1]='b';
n = i % 4; i /= 4; f[n*2]='b';
n = i % 6; i /= 6; c = 0; scanc('q');
n = knights[i][0]; c=0; scanc('n');
n = knights[i][1]; scanc('n');
c=0; scanc('r'); c=0; scanc('k'); c=0; scanc('r');
QString fen(f);
QString qfen = QString("%1/pppppppp/8/8/8/8/PPPPPPPP/%2 w KQkq - 0 1")
.arg(fen).arg(fen.toUpper());
fromGoodFen(qfen, true);
}
int BitBoard::chess960Pos() const
{
int ccPos = 0;
if (m_occupied & 0x0000FFFFFFFF0000uLL)
{
return -1;
}
if (((m_pawns & m_occupied_co[White]) != 0x000000000000FF00uLL) ||
((m_pawns & m_occupied_co[Black]) != 0x00FF000000000000uLL))
{
return -1;
}
if ((m_pieceCount[White] != 16) || (m_pieceCount[Black] != 16))
{
return -1;
}
if (countSetBits(m_bishops) != 4) return -1;
if (countSetBits(m_rooks) != 4) return -1;
if (countSetBits(m_knights) != 4) return -1;
if (countSetBits(m_queens) != 2) return -1;
if (countSetBits(m_kings) != 2) return -1;
quint64 x = (m_bishops & (2+8+32+128));
if (x==0)
return -1;
quint64 bs1 = (getFirstBitAndClear64<Square>(x)-1)/2;
ccPos += bs1;
x = m_bishops & (1+4+16+64);
if (x==0)
return -1;
quint64 bs2 = getFirstBitAndClear64<Square>(x)*2;
ccPos += bs2;
int q = 0;
bool qf = false;
int n0 = 0;
int n1 = 0;
bool n0f = false;
bool n1f = false;
int rf = 0;
int n0s[] = { 0,4,7,9 };
for (Square square=a1; square<=h1; ++square)
{
if (pieceAt(square) == WhiteQueen)
{
qf = true;
}
else if ((pieceAt(square) == WhiteRook) || (pieceAt(square) == WhiteKing))
{
if (pieceAt(square) == WhiteKing)
{
if (rf!=1) return -1;
}
else
{
++rf;
}
if (!qf) { ++q; };
if (!n0f) { ++n0; } else { if (!n1f) ++n1; }
}
else if (pieceAt(square) == WhiteKnight)
{
if (!qf) { ++q; };
if (!n0f) { n0f = true; } else { n1f = true; }
}
}
if ((n0<4) && n1f && qf)
{
ccPos += q*16;
int krn = n0s[n0]+n1;
ccPos += krn*96;
return ccPos;
}
return -1;
}
bool BitBoard::chess960() const
{
return m_chess960;
}
void BitBoard::setChess960(bool chess960)
{
m_chess960 = chess960;
}
MoveList BitBoard::generateMoves() const
{
// This function is not ready for Chess960
// don't care the way it is used for the moment
Square from, to;
quint64 moves, movers;
MoveList p;
if(m_stm == White)
{
// castle moves
if(canCastle(White))
{
if(canCastleShort(White) && !((F1 | G1)&m_occupied))
if(!isAttackedBy(Black, e1) &&
!isAttackedBy(Black, f1)
&& !isAttackedBy(Black, g1))
{
p.add().genWhiteOO();
}
if(canCastleLong(White) && !((B1 | C1 | D1)&m_occupied))
if(!isAttackedBy(Black, c1) &&
!isAttackedBy(Black, d1)
&& !isAttackedBy(Black, e1))
{
p.add().genWhiteOOO();
}
}
// pawn en passant moves
movers = m_pawns & m_occupied_co[White];
if(m_epSquare != NoEPSquare)
{
moves = bb_PawnAttacks[Black][m_epSquare] & movers;
while(moves)
{
from = getFirstBitAndClear64<Square>(moves);
p.add().genEnPassant(from, m_epSquare);
}
}
// pawn captures
moves = ShiftUpRight(movers) & m_occupied_co[Black];
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
if(Rank(to) != 7)
{
p.add().genPawnMove(to - 9, to, m_piece[to]);
}
else
{
p.add().genCapturePromote(to - 9, to, Queen, m_piece[to]);
p.add().genCapturePromote(to - 9, to, Knight, m_piece[to]);
p.add().genCapturePromote(to - 9, to, Rook, m_piece[to]);
p.add().genCapturePromote(to - 9, to, Bishop, m_piece[to]);
}
}
moves = ShiftUpLeft(movers) & m_occupied_co[Black];
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
if(Rank(to) != 7)
{
p.add().genPawnMove(to - 7, to, m_piece[to]);
}
else
{
p.add().genCapturePromote(to - 7, to, Queen, m_piece[to]);
p.add().genCapturePromote(to - 7, to, Knight, m_piece[to]);
p.add().genCapturePromote(to - 7, to, Rook, m_piece[to]);
p.add().genCapturePromote(to - 7, to, Bishop, m_piece[to]);
}
}
// pawns 1 forward
moves = ShiftUp(movers) & ~m_occupied;
movers = moves;
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
if(Rank(to) != 7)
{
p.add().genOneForward(to - 8, to);
}
else
{
p.add().genPromote(to - 8, to, Queen);
p.add().genPromote(to - 8, to, Knight);
p.add().genPromote(to - 8, to, Rook);
p.add().genPromote(to - 8, to, Bishop);
}
}
// pawns 2 forward
moves = ShiftUp(movers) & rank4 & ~m_occupied;
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
p.add().genTwoForward(to - 16, to);
}
}
else
{
// castle moves
if(canCastle(Black))
{
if(canCastleShort(Black) && !((F8 | G8)&m_occupied))
if(!isAttackedBy(White, e8) &&
!isAttackedBy(White, f8) &&
!isAttackedBy(White, g8))
{
p.add().genBlackOO();
}
if(canCastleLong(Black) && !((B8 | C8 | D8)&m_occupied))
if(!isAttackedBy(White, e8) &&
!isAttackedBy(White, d8) &&
!isAttackedBy(White, c8))
{
p.add().genBlackOOO();
}
}
// pawn en passant moves
movers = m_pawns & m_occupied_co[Black];
if(m_epSquare != NoEPSquare)
{
moves = bb_PawnAttacks[White][m_epSquare] & movers;
while(moves)
{
from = getFirstBitAndClear64<Square>(moves);
p.add().genEnPassant(from, m_epSquare);
}
}
// pawn captures
moves = ShiftDownLeft(movers) & m_occupied_co[White];
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
if(Rank(to) != 0)
{
p.add().genPawnMove(to + 9, to, m_piece[to]);
}
else
{
p.add().genCapturePromote(to + 9, to, Queen, m_piece[to]);
p.add().genCapturePromote(to + 9, to, Knight, m_piece[to]);
p.add().genCapturePromote(to + 9, to, Rook, m_piece[to]);
p.add().genCapturePromote(to + 9, to, Bishop, m_piece[to]);
}
}
moves = ShiftDownRight(movers) & m_occupied_co[White];
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
if(Rank(to) != 0)
{
p.add().genPawnMove(to + 7, to, m_piece[to]);
}
else
{
p.add().genCapturePromote(to + 7, to, Queen, m_piece[to]);
p.add().genCapturePromote(to + 7, to, Knight, m_piece[to]);
p.add().genCapturePromote(to + 7, to, Rook, m_piece[to]);
p.add().genCapturePromote(to + 7, to, Bishop, m_piece[to]);
}
}
// pawns 1 forward
moves = ShiftDown(movers) & ~m_occupied;
movers = moves;
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
if(Rank(to) != 0)
{
p.add().genOneForward(to + 8, to);
}
else
{
p.add().genPromote(to + 8, to, Queen);
p.add().genPromote(to + 8, to, Knight);
p.add().genPromote(to + 8, to, Rook);
p.add().genPromote(to + 8, to, Bishop);
}
}
// pawns 2 forward
moves = ShiftDown(movers) & rank5 & ~m_occupied;
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
p.add().genTwoForward(to + 16, to);
}
}
// knight moves
movers = m_knights & m_occupied_co[m_stm];
while(movers)
{
from = getFirstBitAndClear64<Square>(movers);
moves = knightAttacksFrom(from) & ~m_occupied_co[m_stm];
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
p.add().genKnightMove(from, to, m_piece[to]);
}
}
// bishop moves
movers = m_bishops & m_occupied_co[m_stm];
while(movers)
{
from = getFirstBitAndClear64<Square>(movers);
moves = bishopAttacksFrom(from) & ~m_occupied_co[m_stm];
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
p.add().genBishopMove(from, to, m_piece[to]);
}
}
// rook moves
movers = m_rooks & m_occupied_co[m_stm];
while(movers)
{
from = getFirstBitAndClear64<Square>(movers);
moves = rookAttacksFrom(from) & ~m_occupied_co[m_stm];
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
p.add().genRookMove(from, to, m_piece[to]);
}
}
// queen moves
movers = m_queens & m_occupied_co[m_stm];
while(movers)
{
from = getFirstBitAndClear64<Square>(movers);
moves = queenAttacksFrom(from) & ~m_occupied_co[m_stm];
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
p.add().genQueenMove(from, to, m_piece[to]);
}
}
// king moves
moves = kingAttacksFrom(m_ksq[m_stm]) & ~m_occupied_co[m_stm];
while(moves)
{
to = getFirstBitAndClear64<Square>(moves);
if(!isAttackedBy(m_stm ^ 1, to))
{
p.add().genKingMove(m_ksq[m_stm], to, m_piece[to]);
}
}
return p;
}
bool BitBoard::isIntoCheck(const Move& move) const
{
BitBoard peek(*this);
peek.doMove(move);
peek.swapToMove();
return peek.isCheck();
}
// Create a null move (a2a2)
// A Null Move is represented in pgn by a "--" although illegal
// it is often used in ebooks to annotate ideas
Move BitBoard::nullMove() const
{
Move m;
m.setNullMove();
if(m_stm == Black)
{
m.setBlack();
}
m.u = m_halfMoves;
m.u |= (((unsigned short) m_castle & 0xF) << 8);
m.u |= (((unsigned short) m_epFile & 0xF) << 12);
return m;
}
Move BitBoard::parseMove(const QString& algebraic) const
{
const QByteArray& bs(algebraic.toLatin1());
const char *san = bs.constData();
const char* s = san;
char c = *(s++);
quint64 match;
Square fromSquare = InvalidSquare;
Square toSquare = InvalidSquare;
int fromFile = -1;
int fromRank = -1;
Move move;
unsigned int type;
if (algebraic=="none")
return move;
// Castling
if(c == 'o' || c == 'O' || c == '0')
{
if (strlen(san)>=5)
{
if(strncmp(san, "o-o-o", 5) == 0 || strncmp(san, "O-O-O", 5) == 0 || strncmp(san, "0-0-0", 5) == 0)
{
Square k = m_chess960 ? m_ksq[m_stm] : ((m_stm == White) ? e1 : e8);
Square to = m_chess960 ? CastlingRook(2*(int)m_stm) : ((m_stm == White) ? c1 : c8);
return prepareMove(k, to);
}
}
else if (strlen(san)>=3)
{
if(strncmp(san, "o-o", 3) == 0 || strncmp(san, "O-O", 3) == 0 || strncmp(san, "0-0", 3) == 0)
{
Square k = m_chess960 ? m_ksq[m_stm] : ((m_stm == White) ? e1 : e8);
Square to = m_chess960 ? CastlingRook(1+2*(int)m_stm) : ((m_stm == White) ? g1 : g8);
return prepareMove(k, to);
}
}
return move;
}
// Null Move
if(c == '-')
{
if(strncmp(san, "--", 2) == 0)
{
return nullMove();
}
}
// Piece
switch(c)
{
case 'Q':
type = Queen;
c = *(s++);
break;
case 'R':
type = Rook;
c = *(s++);
break;
case 'B':
type = Bishop;
c = *(s++);
break;
case 'N':
type = Knight;
c = *(s++);
break;
case 'K':
type = King;
c = *(s++);
break;
case 'P':
c = *(s++); // Fall through
type = Pawn;
break;
default:
type = Empty;
break;
}
// Check for disambiguation
if(isFile(c))
{
fromFile = c - 'a';
c = *(s++);
if(isRank(c))
{
fromSquare = Square((c - '1') * 8 + fromFile);
fromFile = -1;
c = *(s++);
}
}
else if(isRank(c))
{
fromRank = c - '1';
c = *(s++);
}
// Capture indicator (or dash in the case of a LAN move)
if(c == 'x' || c == '-' || c == ':')
{
c = *(s++);
}
// Destination square
if(isFile(c))
{
int f = c - 'a';
c = *(s++);
if(!isRank(c))
{
return move;
}
toSquare = Square((c - '1') * 8 + f);
c = *(s++);
}
else
{
toSquare = fromSquare;
fromSquare = InvalidSquare;
}
if(toSquare == InvalidSquare)
{
return move;
}
if (type == Empty)
{
// either a pawn or a piece, is determined by source location
if (fromSquare == InvalidSquare)
type = Pawn;
else
{
type = m_piece[fromSquare];
if (type == Empty)
{
return move; // There is no piece here
}
}
}
if(type == Pawn)
{
PieceType promotePiece = None;
// Promotion as in bxc8=Q or bxc8(Q) or bxc8(Q)
if(c == '=' || c == '(' || QString("QRBN").indexOf(toupper(c))>=0)
{
if(c == '=' || c == '(')
{
c = *(s++);
}
switch(toupper(c))
{
case 'Q':
promotePiece = Queen;
break;
case 'R':
promotePiece = Rook;
break;
case 'B':
promotePiece = Bishop;
break;
case 'N':
promotePiece = Knight;
break;
default:
{
int lastRank = (m_stm == White ? 7 : 0);
if (lastRank == Rank(toSquare))
{
return move;
}
}
break;
}
}
if(fromSquare == InvalidSquare)
{
int base = (m_stm == White ? -8 : 8);
if(fromFile < 0)
{
fromSquare = toSquare + base;
quint64 bit = SetBit(fromSquare);
if(!(m_occupied_co[m_stm] & bit))
{
fromSquare += base;
}
}
else if(fromFile <= (int) File(toSquare))
{
fromSquare = toSquare + (base - 1);
}
else
{
fromSquare = toSquare + (base + 1);
}
}
// This isn't a hugely efficient way to go from here
move = prepareMove(fromSquare, toSquare);
if(move.isPromotion() && promotePiece)
{
move.setPromoted(promotePiece);
}
return move;
}
if(fromSquare == InvalidSquare)
{
switch(type)
{
case Queen:
match = queenAttacksFrom(toSquare) & m_queens;
break;
case Rook:
match = rookAttacksFrom(toSquare) & m_rooks;
break;
case Bishop:
match = bishopAttacksFrom(toSquare) & m_bishops;
break;
case Knight:
match = knightAttacksFrom(toSquare) & m_knights;
break;
case King:
match = kingAttacksFrom(toSquare) & m_kings;
break;
default:
return move;
}
match &= m_occupied_co[m_stm];
if(fromRank >= 0)
{
match &= bb_rankMask[fromRank];
}
else if(fromFile >= 0)
{
match &= bb_fileMask[fromFile];
}
if(match)
{
fromSquare = getFirstBitAndClear64<Square>(match);
}
else
{
return move;
}
// If not yet fully disambiguated, all but one move must be illegal
// Cycle through them, and pick the first legal move.
while(match)
{
if(prepareMove(fromSquare, toSquare).isLegal())
{
break;
}
fromSquare = getFirstBitAndClear64<Square>(match);
}
}
if(type != m_piece[fromSquare])
{
return move;
}
return prepareMove(fromSquare, toSquare);
}
bool BitBoard::doMove(const Move& m)
{
Square from = m.from();
Square to = m.to();
unsigned int sntm = m_stm ^ 1; // side not to move
quint64 bb_from = SetBit(from);
quint64 bb_to = SetBit(to);
Square rook_from = InvalidSquare, rook_to = InvalidSquare;
m_epFile = 0;
m_halfMoves++; // Number of moves since last capture or pawn move
bool cleanupFrom = true;
unsigned int action = m.action();
if (!m.isNullMove()) switch(action)
{
case Pawn:
m_halfMoves = 0;
m_pawns ^= bb_from ^ bb_to;
m_piece[to] = Pawn;
break;
case Knight:
m_knights ^= bb_from ^ bb_to;
m_piece[to] = Knight;
break;
case Bishop:
m_bishops ^= bb_from ^ bb_to;
m_piece[to] = Bishop;
break;
case Rook:
m_rooks ^= bb_from ^ bb_to;
m_piece[to] = Rook;
if(canCastle(m_stm) && (m_castlingRooks & bb_from)) // a rook is moving, destroy castle flags if needed
{
destroyCastleInDirection(m_stm, from);
}
break;
case Queen:
m_queens ^= bb_from ^ bb_to;
m_piece[to] = Queen;
break;
case King:
m_kings ^= bb_from ^ bb_to;
m_ksq[m_stm] = to;
m_piece[to] = King;
destroyCastle(m_stm); // king is moving so definitely destroy castle stuff!
break;
case Move::CASTLE:
destroyCastle(m_stm);
if (!m_chess960)
{
switch(to)
{
case c1:
rook_from = a1;
rook_to = d1;
break;
case g1:
rook_from = h1;
rook_to = f1;
break;
case c8:
rook_from = a8;
rook_to = d8;
break;
case g8:
rook_from = h8;
rook_to = f8;
break;
default:
return false;
}
}
else
{
switch(to)
{
case c1:
rook_from = CastlingRook(0);
rook_to = d1;
break;
case g1:
rook_from = CastlingRook(1);
rook_to = f1;
break;
case c8:
rook_from = CastlingRook(2);
rook_to = d8;
break;
case g8:
rook_from = CastlingRook(3);
rook_to = f8;
break;
default:
return false;
}
}
if (bb_from != bb_to)
{
m_kings ^= bb_from ^ bb_to;
m_ksq[m_stm] = to;
m_piece[to] = King;
}
else
{
cleanupFrom = false;
}
if (from == rook_to) cleanupFrom = false;
if (rook_from != rook_to)
{
if (to != rook_from) m_piece[rook_from] = Empty;
m_piece[rook_to] = Rook;
m_rooks ^= SetBit(rook_from) ^ SetBit(rook_to);
m_occupied_co[m_stm] ^= SetBit(rook_from) ^ SetBit(rook_to);
m_occupied_l90 ^= SetBitL90(rook_from) ^ SetBitL90(rook_to);
m_occupied_l45 ^= SetBitL45(rook_from) ^ SetBitL45(rook_to);
m_occupied_r45 ^= SetBitR45(rook_from) ^ SetBitR45(rook_to);
}
break;
case Move::TWOFORWARD:
m_halfMoves = 0;
m_pawns ^= bb_from ^ bb_to;
m_piece[to] = Pawn;
// According to PGN standard, ep square should be always set.
m_epFile = File(to) + 1;
break;
case Move::PROMOTE:
m_halfMoves = 0;
m_pawns ^= bb_from;
--m_pawnCount[m_stm];
switch(m.promoted())
{
case Knight:
m_knights ^= bb_to;
m_piece[to] = Knight;
break;
case Bishop:
m_bishops ^= bb_to;
m_piece[to] = Bishop;
break;
case Rook:
m_rooks ^= bb_to;
m_piece[to] = Rook;
break;
case Queen:
m_queens ^= bb_to;
m_piece[to] = Queen;
break;
default: // can't promote to other piece types;
break;
}
break;
}
switch(m.removal())
{
case Empty:
if (to != from)
{
m_occupied_l90 ^= SetBitL90(to); // extra cleanup needed for non-captures
m_occupied_l45 ^= SetBitL45(to);
m_occupied_r45 ^= SetBitR45(to);
}
break;
case Pawn:
--m_pawnCount[sntm];
--m_pieceCount[sntm];
m_halfMoves = 0;
m_pawns ^= bb_to;
m_occupied_co[sntm] ^= bb_to;
break;
case Knight:
--m_pieceCount[sntm];
m_halfMoves = 0;
m_knights ^= bb_to;
m_occupied_co[sntm] ^= bb_to;
break;
case Bishop:
--m_pieceCount[sntm];
m_halfMoves = 0;
m_bishops ^= bb_to;
m_occupied_co[sntm] ^= bb_to;
break;
case Rook:
--m_pieceCount[sntm];
m_halfMoves = 0;
m_rooks ^= bb_to;
m_occupied_co[sntm] ^= bb_to;
if(canCastle(sntm) && (m_castlingRooks & bb_to))
{
destroyCastleInDirection(sntm, to);
}
break;
case Queen:
--m_pieceCount[sntm];
m_halfMoves = 0;
m_queens ^= bb_to;
m_occupied_co[sntm] ^= bb_to;
break;
case Move::ENPASSANT:
--m_pawnCount[sntm];
--m_pieceCount[sntm];
m_halfMoves = 0;
unsigned int epsq = to + (m_stm == White ? -8 : 8); // annoying move, the capture is not on the 'to' square
m_piece[epsq] = Empty;
m_pawns ^= SetBit(epsq);
m_occupied_co[sntm] ^= SetBit(epsq);
m_occupied_l90 ^= SetBitL90(to) ^ SetBitL90(epsq);
m_occupied_l45 ^= SetBitL45(to) ^ SetBitL45(epsq);
m_occupied_r45 ^= SetBitR45(to) ^ SetBitR45(epsq);
break;
} // ...no I did not forget the king :)
if(!m.isNullMove())
{
if (cleanupFrom)
{
m_piece[from] = Empty;
}
if (bb_from != bb_to)
{
m_occupied_co[m_stm] ^= bb_from ^ bb_to;
m_occupied_l90 ^= SetBitL90(from);
m_occupied_l45 ^= SetBitL45(from);
m_occupied_r45 ^= SetBitR45(from);
}
m_occupied = m_occupied_co[White] + m_occupied_co[Black];
}
if(m_stm == Black)
{
++m_moveNumber;
}
m_stm ^= 1; // toggle side to move
epFile2Square();
return true;
}
void BitBoard::undoMove(const Move& m)
{
Square from = m.from();
Square to = m.to();
unsigned int sntm = m_stm ^ 1; // side not to move
quint64 bb_from = SetBit(from);
quint64 bb_to = SetBit(to);
Square rook_from = InvalidSquare, rook_to = InvalidSquare;
bool cleanupFrom = true;
unsigned int action = m.action();
if(!m.isNullMove()) switch(action)
{
case Pawn:
case Move::TWOFORWARD:
m_pawns ^= bb_from ^ bb_to;
m_piece[from] = Pawn;
break;
case Knight:
m_knights ^= bb_from ^ bb_to;
m_piece[from] = Knight;
break;
case Bishop:
m_bishops ^= bb_from ^ bb_to;
m_piece[from] = Bishop;
break;
case Rook:
m_rooks ^= bb_from ^ bb_to;
m_piece[from] = Rook;
break;
case Queen:
m_queens ^= bb_from ^ bb_to;
m_piece[from] = Queen;
break;
case King:
m_kings ^= bb_from ^ bb_to;
m_ksq[sntm] = from;
m_piece[from] = King;
break;
case Move::CASTLE:
if (bb_from != bb_to)
{
m_kings ^= bb_from ^ bb_to;
m_ksq[sntm] = from;
m_piece[from] = King;
}
else
{
cleanupFrom = false;
}
if (!chess960())
{
switch(to)
{
case c1:
rook_from = a1;
rook_to = d1;
break;
case g1:
rook_from = h1;
rook_to = f1;
break;
case c8:
rook_from = a8;
rook_to = d8;
break;
case g8:
rook_from = h8;
rook_to = f8;
break;
default:
return;
}
}
else
{
switch(to)
{
case c1:
rook_from = CastlingRook(0);
rook_to = d1;
break;
case g1:
rook_from = CastlingRook(1);
rook_to = f1;
break;
case c8:
rook_from = CastlingRook(2);
rook_to = d8;
break;
case g8:
rook_from = CastlingRook(3);
rook_to = f8;
break;
default:
return;
}
}
if (rook_from == to) cleanupFrom = false;
if (rook_from != rook_to)
{
if (rook_to != from) m_piece[rook_to] = Empty;
m_piece[rook_from] = Rook;
m_rooks ^= SetBit(rook_from) ^ SetBit(rook_to);
m_occupied_co[sntm] ^= SetBit(rook_from) ^ SetBit(rook_to);
m_occupied_l90 ^= SetBitL90(rook_from) ^ SetBitL90(rook_to);
m_occupied_l45 ^= SetBitL45(rook_from) ^ SetBitL45(rook_to);
m_occupied_r45 ^= SetBitR45(rook_from) ^ SetBitR45(rook_to);
}
break;
case Move::PROMOTE:
m_pawns ^= bb_from;
m_piece[from] = Pawn;
++m_pawnCount[sntm];
switch(m.promoted())
{
case Knight:
m_knights ^= bb_to;
break;
case Bishop:
m_bishops ^= bb_to;
break;
case Rook:
m_rooks ^= bb_to;
break;
case Queen:
m_queens ^= bb_to;
break;
default: // can't promote to other piece types;
break;
}
break;
}
unsigned int replace = m.capturedType();
switch(m.removal()) // Reverse captures
{
case Empty:
if (to != from)
{
m_occupied_l90 ^= SetBitL90(to); // extra cleanup needed for non-captures
m_occupied_l45 ^= SetBitL45(to);
m_occupied_r45 ^= SetBitR45(to);
}
break;
case Pawn:
++m_pawnCount[m_stm];
++m_pieceCount[m_stm];
m_pawns ^= bb_to;
m_occupied_co[m_stm] ^= bb_to;
break;
case Knight:
++m_pieceCount[m_stm];
m_knights ^= bb_to;
m_occupied_co[m_stm] ^= bb_to;
break;
case Bishop:
++m_pieceCount[m_stm];
m_bishops ^= bb_to;
m_occupied_co[m_stm] ^= bb_to;
break;
case Rook:
++m_pieceCount[m_stm];
m_rooks ^= bb_to;
m_occupied_co[m_stm] ^= bb_to;
break;
case Queen:
++m_pieceCount[m_stm];
m_queens ^= bb_to;
m_occupied_co[m_stm] ^= bb_to;
break;
case Move::ENPASSANT:
++m_pawnCount[m_stm];
++m_pieceCount[m_stm];
replace = Empty;
unsigned int epsq = to + (sntm == White ? -8 : 8); // annoying move, the capture is not on the 'to' square
m_piece[epsq] = Pawn;
m_pawns ^= SetBit(epsq);
m_occupied_co[m_stm] ^= SetBit(epsq);
m_occupied_l90 ^= SetBitL90(to) ^ SetBitL90(epsq);
m_occupied_l45 ^= SetBitL45(to) ^ SetBitL45(epsq);
m_occupied_r45 ^= SetBitR45(to) ^ SetBitR45(epsq);
break;
} // ...no I did not forget the king :)
if(!m.isNullMove())
{
if (cleanupFrom)
{
m_piece[to] = replace;
}
if (bb_from != bb_to)
{
m_occupied_co[sntm] ^= bb_from ^ bb_to;
m_occupied_l90 ^= SetBitL90(from);
m_occupied_l45 ^= SetBitL45(from);
m_occupied_r45 ^= SetBitR45(from);
}
m_occupied = m_occupied_co[White] + m_occupied_co[Black];
}
m_stm ^= 1; // toggle side to move
if(m_stm == Black)
{
--m_moveNumber;
}
m_halfMoves = m.u & 0xFF;
m_castle = (m.u >> 8) & 0xF;
m_epFile = (m.u >> 12) & 0xF;
epFile2Square();
}
bool BitBoard::HasRookForCastling(int index) const
{
quint64 cr = m_castlingRooks;
Square x = InvalidSquare;
for (int i=0; i<=index; ++i)
{
x = getFirstBitAndClear64<Square>(cr);
}
return (m_rooks & SetBit(x));
}
Square BitBoard::CastlingRook(int index) const
{
quint64 cr = m_castlingRooks;
Square x = InvalidSquare;
for (int i=0; i<=index; ++i)
{
x = getFirstBitAndClear64<Square>(cr);
}
return x;
}
int BitBoard::CastlingRookIndex(Square rook) const
{
quint64 cr = m_castlingRooks;
for (int i=0; i<=3; ++i)
{
Square x = getFirstBitAndClear64<Square>(cr);
if (x == rook) return i;
}
return -1;
}
bool BitBoard::HasRookOnFileForCastling(unsigned char file, bool castle000) const
{
if (castle000)
{
if (file > File(m_ksq[White]) && (file > File(m_ksq[Black]))) return false;
}
else
{
if (file < File(m_ksq[White]) && (file < File(m_ksq[Black]))) return false;
}
Square w = SquareFromRankAndFile(0,file);
Square b = SquareFromRankAndFile(7,file);
quint64 x = SetBit(w) | SetBit(b);
return (m_rooks & x);
}
Square BitBoard::CastlingKingTarget(int rookIndex) const
{
if ((rookIndex<0) || (rookIndex>3)) return InvalidSquare;
static const Square kingTargets[] = { c1,g1,c8,g8 };
return kingTargets[rookIndex];
}
Square BitBoard::CastlingRookTarget(int rookIndex) const
{
if ((rookIndex<0) || (rookIndex>3)) return InvalidSquare;
static const Square rookTargets[] = { d1,f1,d8,f8 };
return rookTargets[rookIndex];
}
quint64 BitBoard::castlingRooks() const
{
return m_castlingRooks;
}
quint64 BitBoard::standardCastlingRooks()
{
return (A1 | H1 | A8 | H8);
}
quint64 BitBoard::pawnMovesFrom(const Square s) const
{
quint64 targets = bb_PawnF1[m_stm][s] & ~m_occupied;
if(targets)
{
targets |= bb_PawnF2[m_stm][s] & ~m_occupied;
}
if(m_epSquare == NoEPSquare)
{
targets |= bb_PawnAttacks[m_stm][s] & m_occupied_co[m_stm ^ 1];
}
else
{
targets |= bb_PawnAttacks[m_stm][s] & (m_occupied_co[m_stm ^ 1] | SetBit(m_epSquare));
}
return targets;
}
Move BitBoard::prepareMove(const Square& from, const Square& to) const
{
if ((from >= 64) || (to >= 64))
{
return Move();
}
quint64 src = SetBit(from);
quint64 dest = SetBit(to);
Move move(from, to);
unsigned char p = m_piece[from];
bool nullMove = Move(from,to).isNullMove();
if (!nullMove)
{
// Check for Illegal Move
// first the source square must not be vacant
if(!(m_occupied_co[m_stm] & src))
{
return move;
}
// Check for Illegal Move
// If the destination square is a piece of the moving color
if(m_occupied_co[m_stm] & dest)
{
if ((p!=King) || (m_piece[to] != Rook))
{
// Can't be castling move
return move;
}
move.SetCastlingBit();
}
move.setPieceType(p);
unsigned char pCaptured = m_piece[to];
move.setCaptureType(pCaptured);
if(p == King)
{
if (move.isCastling())
{
if (!prepareCastle(move))
{
return move;
}
}
else if (!prepareCastle(move) && !(kingAttacksFrom(to) & src))
{
return move;
}
}
else if(p == Pawn)
{
if(!(pawnMovesFrom(from) & dest))
{
return move;
}
else if(to == m_epSquare)
{
move.setEnPassant();
}
else if(dest & bb_PawnF2[m_stm][from])
{
move.setTwoForward();
}
else if(dest & bb_PromotionRank[m_stm])
{
move.setPromoted(Queen);
}
}
else
{
quint64 reach = 0;
if(p == Queen)
{
reach = queenAttacksFrom(to);
}
else if(p == Rook)
{
reach = rookAttacksFrom(to);
}
else if(p == Bishop)
{
reach = bishopAttacksFrom(to);
}
else if(p == Knight)
{
reach = knightAttacksFrom(to);
}
if(!(reach & src))
{
return move;
}
}
}
BitBoard peek(*this);
peek.doMove(move);
peek.swapToMove();
if(peek.isCheck()) // Don't allow move into check even if its a null move
{
return move;
}
if(m_stm == Black)
{
move.setBlack();
}
move.u = m_halfMoves;
move.u |= (((unsigned short) m_castle & 0xF) << 8);
move.u |= (((unsigned short) m_epFile & 0xF) << 12);
move.setLegalMove();
return move;
}
bool BitBoard::prepareCastle(Move& move) const
{
if(!canCastle(m_stm))
{
return false;
}
if (chess960())
{
if (!move.isCastling())
{
return false;
}
return prepareCastle960(move);
}
Square to = move.to();
if(m_stm == White)
{
if((((to == h1) && (H1&m_occupied)) || (to == g1)) && canCastleShort(White) && !((F1 | G1)&m_occupied))
{
if(!isAttackedBy(Black, e1) && !isAttackedBy(Black, f1))
{
move.genWhiteOO();
return true;
}
}
else if((((to == a1) && (A1&m_occupied)) || (to == c1)) && canCastleLong(White) && !((B1 | C1 | D1)&m_occupied))
{
if(!isAttackedBy(Black, e1) && !isAttackedBy(Black, d1))
{
move.genWhiteOOO();
return true;
}
}
}
else
{
if((((to == h8) && (H8&m_occupied)) || to == g8) && canCastleShort(Black) && !((F8 | G8)&m_occupied))
{
if(!isAttackedBy(White, e8) && !isAttackedBy(White, f8))
{
move.genBlackOO();
return true;
}
}
else if((((to == a8) && (A8&m_occupied)) ||to == c8) && canCastleLong(Black) && !((B8 | C8 | D8)&m_occupied))
{
if(!isAttackedBy(White, e8) && !isAttackedBy(White, d8))
{
move.genBlackOOO();
return true;
}
}
}
return false;
}
bool BitBoard::isFreeForCastling960(Square from, Square to, Square rook_from, Square rook_to) const
{
Square square = from;
while(square!=to)
{
if ((square != from) && (square != rook_from))
{
if (pieceAt(square) != Empty) return false;
}
if (square!=to) square += (from<=to) ? 1:-1;
}
if ((to != from) && (to != rook_from))
{
Piece p = pieceAt(to);
if (p != Empty) return false;
}
square = rook_from;
while(square!=rook_to)
{
if ((square != rook_from) && (square != from))
{
if (pieceAt(square) != Empty) return false;
}
if (square!=rook_to) square += (rook_from<=rook_to) ? 1:-1;
}
if ((rook_from != rook_to) && (rook_to != from))
{
Piece p = pieceAt(rook_to);
if (p != Empty) return false;
}
return true; // Both ways, king and rook to target are free except for king/rook themselves
}
bool BitBoard::prepareCastle960(Move& move) const
{
int n = CastlingRookIndex(move.to());
if (n<0) return false; // No castling rook on target square (even though there is a rook)
Square to = CastlingKingTarget(n);
Square rook_to = CastlingRookTarget(n);
Square from = move.from();
Square rook_from = move.to();
if(m_stm == White)
{
if((to == g1 && canCastleShort(White)) ||
(to == c1 && canCastleLong(White)))
{
if (isFreeForCastling960(from, to, rook_from, rook_to))
{
if(!isAttackedBy(Black, from, to))
{
move.genKingMove(from, to, false);
move.SetCastlingBit();
return true;
}
}
}
}
else
{
if((to == g8 && canCastleShort(Black)) ||
(to == c8 && canCastleLong(Black)))
{
if (isFreeForCastling960(from, to, rook_from, rook_to))
{
if(!isAttackedBy(White, from, to))
{
move.genKingMove(from, to, false);
move.SetCastlingBit();
return true;
}
}
}
}
return false;
}
bool BitBoard::canBeReachedFrom(const BitBoard& target) const
{
if(m_pieceCount[White] > target.m_pieceCount[White] ||
m_pieceCount[Black] > target.m_pieceCount[Black] ||
m_pawnCount[White] > target.m_pawnCount[White] ||
m_pawnCount[Black] > target.m_pawnCount[Black])
{
return false;
}
return true;
}
bool BitBoard::insufficientMaterial() const
{
if (m_pawnCount[White]==0 && m_pawnCount[Black]==0)
{
if ((m_pieceCount[White] <= 2) && (m_pieceCount[Black] <= 2))
{
// now test for KB-K KN-K and KB-KB where the bishops have same color
if (m_queens || m_rooks)
{
return false;
}
if (m_pieceCount[White]+m_pieceCount[Black] == 3)
{
return true;
}
if (m_knights)
{
return false;
}
// Finally KB-KB
quint64 n = m_bishops;
quint64 n1 = getFirstBitAndClear64<Square>(n);
quint64 n2 = getFirstBitAndClear64<Square>(n);
int sum = n1+n2;
return (sum & 1);
}
}
return false;
}
Square BitBoard::kingSquare(Color color) const
{
return m_ksq[color];
}
Color BitBoard::colorAt(Square s) const
{
Q_ASSERT(s < 64);
quint64 bit = SetBit(s);
if(m_occupied & bit)
{
if(m_occupied_co[White] & bit)
{
return White;
}
else
{
return Black;
}
}
return NoColor;
}
Piece BitBoard::pieceAt(Square s) const
{
Q_ASSERT(s < 64);
quint64 bit = SetBit(s);
if(m_occupied & bit)
{
if(m_occupied_co[White] & bit)
{
return Piece(m_piece[s]);
}
else
{
return Piece(m_piece[s] + 6);
}
}
return Empty;
}
/** Return ASCII character for given piece to be used in FEN */
inline QChar pieceToChar(const Piece piece)
{
return piece > BlackPawn ? '?' : " KQRBNPkqrbnp"[piece];
};
/** Return ASCII character for given piece to be used in human FEN */
inline QChar pieceToHumanChar(const Piece piece)
{
return piece > BlackPawn ? '?' : " KQRBNPKQRBNP"[piece];
};
QString BitBoard::toFen(bool forceExtendedFEN) const
{
QString fen = "";
Piece piece;
int empty = 0;
//piece placement
for(int row = 7; row >= 0; row--)
{
for(unsigned char col = 0; col < 8; ++col)
{
piece = pieceAt(SquareFromRankAndFile(row,col));
if(piece != Empty)
{
if(empty != 0)
{
fen += QString::number(empty);
empty = 0;
}
fen += pieceToChar(piece);
}
else
{
empty++;
}
}
if(empty != 0)
{
fen += QString::number(empty);
empty = 0;
}
if(row != 0)
{
fen += '/';
}
}
//side to move
fen += m_stm == White ? " w " : " b ";
//castling rights
if(castlingRights() == NoRights)
{
fen += "- ";
}
else
{
char s00 = 0;
char s000 = 0;
if (canCastleShort(White))
{
s00 = 'a'+File(CastlingRook(1));
}
else if (canCastleShort(Black))
{
s00 = 'a'+File(CastlingRook(3));
}
if (canCastleLong(White))
{
s000 = 'a'+File(CastlingRook(0));
}
else if (canCastleLong(Black))
{
s000 = 'a'+File(CastlingRook(2));
}
if (forceExtendedFEN || hasAmbiguousCastlingRooks(s000, s00))
{
if(castlingRights() & WhiteQueenside)
{
fen += 'A'+File(CastlingRook(0));
}
if(castlingRights() & WhiteKingside)
{
fen += 'A'+File(CastlingRook(1));
}
if(castlingRights() & BlackQueenside)
{
fen += 'a'+File(CastlingRook(2));
}
if(castlingRights() & BlackKingside)
{
fen += 'a'+File(CastlingRook(3));
}
}
else
{
if(castlingRights() & WhiteKingside)
{
fen += 'K';
}
if(castlingRights() & WhiteQueenside)
{
fen += 'Q';
}
if(castlingRights() & BlackKingside)
{
fen += 'k';
}
if(castlingRights() & BlackQueenside)
{
fen += 'q';
}
}
fen += ' ';
}
//en passant square
if(m_epSquare == NoEPSquare)
{
fen += "- ";
}
else
{
fen += 'a' + (m_epSquare & 7);
fen += '1' + ((m_epSquare & 56) >> 3);
fen += ' ';
}
// half move clock
fen += QString::number(halfMoveClock());
fen += " ";
// move number
fen += QString::number(m_moveNumber <= 0 ? 1 : m_moveNumber);
return fen;
}
QString BitBoard::toHumanFen() const
{
QString fenFormat = QCoreApplication::translate("BitBoard", "w%1\nb%2\n%3 to move");
QMap<Piece, QStringList> charLists;
//piece placement
for(int row = 7; row >= 0; row--)
{
for(unsigned char col = 0; col < 8; ++col)
{
Piece piece = pieceAt(SquareFromRankAndFile(row,col));
if(piece != Empty)
{
charLists[piece].append(QString("%1%2").arg(QChar('a' + col)).arg(row + 1));
}
}
}
//side to move
QString toMove = (m_stm == White) ? QCoreApplication::translate("BitBoard", "White") : QCoreApplication::translate("BitBoard", "Black");
QString w, b;
for(Piece p = WhiteKing; p <= WhitePawn; ++p)
{
if(charLists.keys().contains(p))
{
if(!w.isEmpty())
{
w += ",";
}
w.append(pieceToHumanChar(p));
w.append(charLists[p].join(","));
}
}
for(Piece p = BlackKing; p != Empty; ++p)
{
if(charLists.keys().contains(p))
{
if(!b.isEmpty())
{
b += ",";
}
b.append(pieceToHumanChar(p));
b.append(charLists[p].join(","));
}
}
QString fen = fenFormat.arg(w).arg(b).arg(toMove);
fen.append(QString(" (%1+%2).").arg(m_pieceCount[White]).arg(m_pieceCount[Black]));
return fen;
}
/** Calculate global bit board values before starting */
void bitBoardInit()
{
bitBoardInitRun = true;
int i, q;
quint64 mask;
// Square masks
mask = 1;
for(i = 0; i < 64; ++i)
{
bb_Mask[i] = mask << i;
}
for(i = 0; i < 64; ++i)
{
bb_MaskL90[i] = SetBit(RotateL90[i]);
bb_MaskL45[i] = SetBit(RotateL45[i]);
bb_MaskR45[i] = SetBit(RotateR45[i]);
}
// Pawn moves and attacks
for(i = 0; i < 64; ++i)
{
mask = SetBit(i);
bb_PawnAttacks[White][i] = ShiftUpLeft(mask);
bb_PawnAttacks[White][i] |= ShiftUpRight(mask);
bb_PawnAttacks[Black][i] = ShiftDownLeft(mask);
bb_PawnAttacks[Black][i] |= ShiftDownRight(mask);
bb_PawnF1[White][i] = ShiftUp(mask);
bb_PawnF2[White][i] = Shift2Up(mask) & rank4;
bb_PawnF1[Black][i] = ShiftDown(mask);
bb_PawnF2[Black][i] = Shift2Down(mask) & rank5;
bb_PawnALL[White][i] = bb_PawnAttacks[White][i] |
bb_PawnF1[White][i] |
bb_PawnF2[White][i];
bb_PawnALL[Black][i] = bb_PawnAttacks[Black][i] |
bb_PawnF1[Black][i] |
bb_PawnF2[Black][i];
}
// Knight attacks
for(i = 0; i < 64; ++i)
{
mask = SetBit(i);
bb_KnightAttacks[i] = ShiftLeft(Shift2Up(mask));
bb_KnightAttacks[i] |= ShiftRight(Shift2Up(mask));
bb_KnightAttacks[i] |= ShiftLeft(Shift2Down(mask));
bb_KnightAttacks[i] |= ShiftRight(Shift2Down(mask));
bb_KnightAttacks[i] |= Shift2Left(ShiftUp(mask));
bb_KnightAttacks[i] |= Shift2Right(ShiftUp(mask));
bb_KnightAttacks[i] |= Shift2Left(ShiftDown(mask));
bb_KnightAttacks[i] |= Shift2Right(ShiftDown(mask));
}
// Diagonal attacks
for(int s = 0; s < 64; ++s)
{
for(int b = 0; b < 64; ++b)
{
mask = 0;
q = s;
while(File(q) > 0 && Rank(q) < 7)
{
q += 7;
mask |= SetBit(q);
if(b & (SetBit(RotateL45[q]) >> bb_ShiftL45[s]))
{
break;
}
}
q = s;
while(File(q) < 7 && Rank(q) > 0)
{
q -= 7;
mask |= SetBit(q);
if(b & (SetBit(RotateL45[q]) >> bb_ShiftL45[s]))
{
break;
}
}
bb_L45Attacks[s][b] = mask;
mask = 0;
q = s;
while(File(q) < 7 && Rank(q) < 7)
{
q += 9;
mask |= SetBit(q);
if(b & (SetBit(RotateR45[q]) >> bb_ShiftR45[s]))
{
break;
}
}
q = s;
while(File(q) > 0 && Rank(q) > 0)
{
q -= 9;
mask |= SetBit(q);
if(b & (SetBit(RotateR45[q]) >> bb_ShiftR45[s]))
{
break;
}
}
bb_R45Attacks[s][b] = mask;
}
}
// Rank and File attacks
memset(bb_RankAttacks, 0, sizeof(bb_RankAttacks));
memset(bb_FileAttacks, 0, sizeof(bb_FileAttacks));
int file, rank;
for(int sq = 0; sq < 64; ++sq)
{
for(int bitrow = 0; bitrow < 64; ++bitrow)
{
file = File(sq);
q = sq + 1;
while(++file < 8)
{
bb_RankAttacks[sq][bitrow] |= SetBit(q);
if((1 << file) & (bitrow << 1))
{
break;
}
++q;
}
file = File(sq);
q = sq - 1;
while(--file >= 0)
{
bb_RankAttacks[sq][bitrow] |= SetBit(q);
if((1 << file) & (bitrow << 1))
{
break;
}
--q;
}
rank = Rank(sq);
q = sq + 8;
while(++rank < 8)
{
bb_FileAttacks[sq][bitrow] |= SetBit(q);
if((1 << (7 - rank)) & (bitrow << 1))
{
break;
}
q += 8;
}
rank = Rank(sq);
q = sq - 8;
while(--rank >= 0)
{
bb_FileAttacks[sq][bitrow] |= SetBit(q);
if((1 << (7 - rank)) & (bitrow << 1))
{
break;
}
q -= 8;
}
}
}
// King:
for(i = 0; i < 64; ++i)
{
mask = SetBit(i);
bb_KingAttacks[i] = ShiftLeft(mask);
bb_KingAttacks[i] |= ShiftRight(mask);
bb_KingAttacks[i] |= ShiftUp(mask);
bb_KingAttacks[i] |= ShiftDown(mask);
bb_KingAttacks[i] |= ShiftUpLeft(mask);
bb_KingAttacks[i] |= ShiftUpRight(mask);
bb_KingAttacks[i] |= ShiftDownLeft(mask);
bb_KingAttacks[i] |= ShiftDownRight(mask);
}
// File and rank masks
quint64 rseed = 0xFF00000000000000ULL;
quint64 fseed = 0x8080808080808080ULL;
for(i = 7; i >= 0; --i)
{
bb_rankMask[i] = rseed;
rseed >>= 8;
bb_fileMask[i] = fseed;
fseed >>= 1;
}
// Pawn promotion ranks
bb_PromotionRank[White] = bb_rankMask[7];
bb_PromotionRank[Black] = bb_rankMask[0];
// Now that global data has been calculated, we can create a start position
standardPosition.fromFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
}
BitBoard getStandardPosition()
{
BitBoard b;
b.fromFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
return b;
}
QString BitBoard::moveToFullSan(const Move &move, bool translate) const
{
QString dots = whiteToMove() ? "." : "...";
return QString("%1%2%3").arg(m_moveNumber).arg(dots).arg(moveToSan(move,translate));
}
//a charboard is a 64 length board that looks something like this:
//-----B----p------p---k-pq---N---r-----P-------P--P----K---Q-----
//dashes: empty space
bool BitBoard::from64Char(const QString& qcharboard)
{
QStringList l = qcharboard.split(' ');
if (l.size() < 30) return false;
int n = 7;
for (int i=C64_ROW8; i<=C64_ROW1; ++i,--n)
{
QString s = l[i];
for (int j=7;j>=0;--j)
{
QChar c = s[j];
Square sq = Square(n*8+j);
switch (c.toLatin1())
{
case 'p': setAt(sq, BlackPawn); break;
case 'n': setAt(sq, BlackKnight); break;
case 'b': setAt(sq, BlackBishop); break;
case 'r': setAt(sq, BlackRook); break;
case 'q': setAt(sq, BlackQueen); break;
case 'k': setAt(sq, BlackKing); break;
case 'P': setAt(sq, WhitePawn); break;
case 'N': setAt(sq, WhiteKnight); break;
case 'B': setAt(sq, WhiteBishop); break;
case 'R': setAt(sq, WhiteRook); break;
case 'Q': setAt(sq, WhiteQueen); break;
case 'K': setAt(sq, WhiteKing); break;
default: removeAt(sq); break;
}
}
}
if (l[C64_COLOR_TO_MOVE]=="W")
{
setToMove(White);
}
else if (l[C64_COLOR_TO_MOVE]=="B")
{
setToMove(Black);
}
int ep = l[C64_COL_DOUBLE_PAWN_PUSH].toInt();
setEnPassantFile(ep);
if (l[C64_CASTLE_W_00].toInt()) setCastleShort(White);
if (l[C64_CASTLE_W_000].toInt()) setCastleLong(White);
if (l[C64_CASTLE_B_00].toInt()) setCastleShort(Black);
if (l[C64_CASTLE_B_000].toInt()) setCastleLong(Black);
setCastlingRooks();
setMoveNumber(l[C64_NEXT_MOVE_NUMBER].toInt());
return true;
}
int BitBoard::numAttackedBy(const unsigned int color, Square square) const
{
int num = 0;
num += countSetBits(bb_PawnAttacks[color ^ 1][square] & m_pawns & m_occupied_co[color]);
num += countSetBits(knightAttacksFrom(square) & m_knights & m_occupied_co[color]);
num += countSetBits(bishopAttacksFrom(square) & (m_bishops | m_queens) & m_occupied_co[color]);
num += countSetBits(rookAttacksFrom(square) & (m_rooks | m_queens) & m_occupied_co[color]);
num += countSetBits(kingAttacksFrom(square) & m_kings & m_occupied_co[color]);
return num;
};
void BitBoard::setMoveNumber(unsigned int moveNumber)
{
m_moveNumber = moveNumber;
}
void BitBoard::setToMove(const Color &c)
{
m_stm = c;
}
bool BitBoard::positionIsSame(const BitBoard &target) const
{
if(m_occupied_co[White] != target.m_occupied_co[White] ||
m_occupied_co[Black] != target.m_occupied_co[Black] ||
m_pawns != target.m_pawns ||
m_knights != target.m_knights ||
m_bishops != target.m_bishops ||
m_rooks != target.m_rooks ||
m_queens != target.m_queens ||
m_kings != target.m_kings ||
m_stm != target.m_stm)
{
return false;
}
return true;
}
void BitBoard::swapToMove()
{
m_stm ^= 1;
}
void BitBoard::setCastlingRights(CastlingRights cr)
{
m_castle = cr;
}
|
f112d64003a542177a8671f9dd48599ecbc6d4f7 | 0d423538336b5067781fb76c0fb6ac1daa3d0ccb | /1_NMLT/LyThuyet-T4/ktra_SNT.cpp | 528f357a8a95fef58f66c1b00f7b7646b4b42571 | [
"MIT"
] | permissive | NhatPhuong02/HCMUS-Lectures | 73f098c6322133116dc9f57423f1433bf32a5730 | b376e144e2601a73684e2ff437ab5c94a943909c | refs/heads/master | 2022-01-13T01:52:40.707561 | 2018-06-16T17:22:19 | 2018-06-16T17:22:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | cpp | ktra_SNT.cpp | #include "ktra_SNT.h"
#include <math.h>
#include <stdio.h>
int ktra_SNT(int n)
// xuat ra 1 neu la so nguyen to
// xuat ra 0 neu khong phai so nguyen to
{
if (n == 1)
return 0;
for (int i = 2; i <= sqrt((double)n); ++i) {
if (n % i == 0) {
return 0;
}
}
return 1;
} |
635562f7bfd2e32f2f01a5ace926fc5c279f0898 | 92a6d7a3f39c94873334af1e0e08b092efe2dfe2 | /tests/rwlock/rwlock_test.cc | d9991b78b58a10d8a754d8e39926309d2d0bb0f7 | [
"Apache-2.0"
] | permissive | blockspacer/platform | 7d86a69aa7ec9283a13e48cd0eacc225279c584a | 615a51a743832458bae79a866f4c7943bf7d252e | refs/heads/master | 2023-02-08T06:21:57.093076 | 2021-01-05T10:06:23 | 2021-01-05T14:50:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,733 | cc | rwlock_test.cc | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2019 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <platform/rwlock.h>
#include <folly/SharedMutex.h>
#include <folly/portability/GTest.h>
#include <shared_mutex>
/**
* Templated death test which tests the interoperability of two lock types.
* When run under TSan (they are skipped otherwise), tests should crash due to
* TSan detecting the expected threading errors.
*
* @tparam LOCKS The two locks to test. Should expose LockA and LockB nested
* types.
*/
template <typename Locks>
class LockDeathTest : public ::testing::Test {
public:
void SetUp() override {
// Check out preconditions - require that TSan is configured to halt
// immediately on an error.
auto* tsanOptions = getenv("TSAN_OPTIONS");
ASSERT_TRUE(tsanOptions) << "LockDeathTests require that TSAN_OPTIONS "
"is defined (and contains "
"'halt_on_error=1')";
ASSERT_TRUE(std::string(tsanOptions).find("halt_on_error=1") !=
std::string::npos)
<< "LockDeathTests require that ThreadSanitizer is run with "
"'halt_on_error' enabled. Check that the TSAN_OPTIONS env "
"var contains 'halt_on_error=1'";
}
typename Locks::LockA lockA;
typename Locks::LockB lockB;
};
/// Subclass for exclusive locks
template <typename Locks>
class ExclusiveLockDeathTest : public LockDeathTest<Locks> {};
/// Subclass for shared (reader-writer) locks
template <typename Locks>
class SharedLockDeathTest : public LockDeathTest<Locks> {};
template <typename A, typename B>
struct LockPair {
using LockA = A;
using LockB = B;
};
/// Lock types to test for exclusive access.
// macOS's C++ standard library doesn't appear to have annotations
// for std::mutex etc - so TSan fails to detect lock-order issues.
// As such some combinations cannot be checked on macOS.
using LockTypes = ::testing::Types<
// Identity tests (same - same)
#if !defined(__APPLE__)
LockPair<std::mutex, std::mutex>,
LockPair<std::shared_timed_mutex, std::shared_timed_mutex>,
LockPair<folly::SharedMutex, folly::SharedMutex>,
#endif
LockPair<cb::RWLock, cb::RWLock>,
// Each mutex with each other mutex, in both orders (A,B) & (B,A).
// While you'd _think_ that it would be sufficient to just check each
// pair once, given in the test we call:
// A.lock(),
// B.lock(),
// unlock
// ...
// B.lock(),
// A.lock()
// It turns out that on macOS at least TSan can detect lock inversions
// in _one_ order but not the other - ¯\_(ツ)_/¯
#if !defined(__APPLE__)
LockPair<std::mutex, std::shared_timed_mutex>,
LockPair<std::mutex, cb::RWLock>,
LockPair<std::mutex, folly::SharedMutex>,
LockPair<std::shared_timed_mutex, std::mutex>,
LockPair<std::shared_timed_mutex, cb::RWLock>,
LockPair<std::shared_timed_mutex, folly::SharedMutex>,
#endif
LockPair<cb::RWLock, std::mutex>,
#if !defined(__APPLE__)
LockPair<cb::RWLock, std::shared_timed_mutex>,
#endif
LockPair<cb::RWLock, folly::SharedMutex>,
LockPair<folly::SharedMutex, std::mutex>,
#if !defined(__APPLE__)
LockPair<folly::SharedMutex, std::shared_timed_mutex>,
#endif
LockPair<folly::SharedMutex, cb::RWLock>>;
/// Lock types to test for shared access
using SharedLockTypes = ::testing::Types<
#if !defined(__APPLE__)
LockPair<std::shared_timed_mutex, std::shared_timed_mutex>,
LockPair<cb::RWLock, cb::RWLock>,
LockPair<cb::RWLock, std::shared_timed_mutex>,
LockPair<cb::RWLock, folly::SharedMutex>,
LockPair<folly::SharedMutex, std::shared_timed_mutex>,
#endif // defined(__APPLE__)
LockPair<folly::SharedMutex, folly::SharedMutex>>;
TYPED_TEST_SUITE(ExclusiveLockDeathTest, LockTypes);
TYPED_TEST_SUITE(SharedLockDeathTest, SharedLockTypes);
// The following tests all rely on ThreadSanitizer (they are checking
// that our different locks interact correctly with TSan)
#if defined(THREAD_SANITIZER)
// Acquire Lock1 and Lock2, and release; then acquire in opposite order.
// Expect TSan to report a lock inversion order.
TYPED_TEST(ExclusiveLockDeathTest, LockOrderInversion12) {
typename TypeParam::LockA lock1;
typename TypeParam::LockB lock2;
ASSERT_DEATH(
{
lock1.lock();
lock2.lock();
lock2.unlock();
lock1.unlock();
lock2.lock();
lock1.lock();
lock1.unlock();
lock2.unlock();
},
".*WARNING: ThreadSanitizer: lock-order-inversion .*");
}
// Acquire Lock1(read) and Lock2(write), and release; then acquire in opposite
// order.
// Expect TSan to report a lock inversion order.
TYPED_TEST(SharedLockDeathTest, RWInversion) {
typename TypeParam::LockA lock1;
typename TypeParam::LockB lock2;
ASSERT_DEATH(
{
lock1.lock_shared();
lock2.lock();
lock2.unlock();
lock1.unlock_shared();
lock2.lock();
lock1.lock_shared();
lock1.unlock_shared();
lock2.unlock();
},
".*WARNING: ThreadSanitizer: lock-order-inversion .*");
}
// Acquire Lock1(write) and Lock2(read), and release; then acquire in opposite
// order.
// Expect TSan to report a lock inversion order.
TYPED_TEST(SharedLockDeathTest, WRInversion) {
typename TypeParam::LockA lock1;
typename TypeParam::LockB lock2;
ASSERT_DEATH(
{
lock1.lock();
lock2.lock_shared();
lock2.unlock_shared();
lock1.unlock();
lock2.lock_shared();
lock1.lock();
lock1.unlock();
lock2.unlock_shared();
},
".*WARNING: ThreadSanitizer: lock-order-inversion .*");
}
#endif // defined(THREAD_SANITIZER)
|
378701ed7fcdf905245aaf0250ab6b1efbd44dba | 1bf3acaa0749a332101e69bc54304d9833a45666 | /CPP08/ex02/mutantstack.hpp | ffcc7da0d620ce90ae6d28d16e5b7274931fc8c9 | [] | no_license | mspinnet/CPP_modules | 7ba0644177180d8265fb312abf706383ebecd5fb | 77567125c983840ceea05224326b3c544cde676a | refs/heads/master | 2023-06-07T03:39:50.318969 | 2021-07-02T09:33:33 | 2021-07-02T09:33:33 | 382,296,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,989 | hpp | mutantstack.hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mutantstack.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mspinnet <mspinnet@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/10 12:31:46 by mspinnet #+# #+# */
/* Updated: 2021/05/10 14:49:21 by mspinnet ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MUTANTSTACK_H
# define MUTANTSTACK_H
# include <iostream>
# include <stack>
# include <algorithm>
# include <exception>
template <typename T>
class MutantStack : public std::stack<T>
{
private:
T *_begin;
T *_end;
public:
MutantStack(void);
MutantStack(MutantStack const &);
MutantStack &operator= (MutantStack const &);
~MutantStack(void);
class iterator
{
private:
T *_cur_pos;
T *_start;
T *_finish;
public:
iterator(void);
iterator(T *start, T *finish);
iterator(iterator const &iter);
iterator &operator= (iterator const &iter);
~iterator(void);
T &operator*(void);
iterator &operator++(void);
iterator &operator--(void);
bool operator!= (iterator const &iter) const;
bool operator== (iterator const &iter) const;
};
class MyException : public std::exception
{
public:
virtual const char *what() const throw()
{
const char *str = "Exception!";
return str;
}
};
iterator begin(void);
iterator end(void);
void pop(void);
void push(T element);
};
#endif
|
74453b34182c66feb2e4b97fefa7a6ea48dc0545 | 1c7348d7860eff80b149699bc17e4d64317a24bd | /touphScript/kernel/kernel.cpp | 4dffbfaa90924ac40441dcffe3999fd5b72ef891 | [] | no_license | ser-pounce/ff7-tools | 9d1d239584602800281f745d897ebf71139c8621 | aaf61dfe0ab3da73d2b5ddc3246eb38ca7fec268 | refs/heads/master | 2021-01-20T18:39:22.722767 | 2016-08-06T12:56:39 | 2016-08-06T12:56:39 | 65,082,377 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,470 | cpp | kernel.cpp | #include "touphScript/kernel/kernel.h"
#include "touphScript/string.h"
#include "ff7/kernel/kernel.h"
#include "ff7/kernel/init_data.h"
#include "util/copy.h"
#include "util/filesystem.h"
#include <fstream>
namespace fs = boost::filesystem;
void touphScript::kernel::dump(std::string const& kernel,
std::string const& textPath)
{
std::ifstream file{kernel, file.binary};
std::vector<char> data{
std::istreambuf_iterator<char>{file},
std::istreambuf_iterator<char>{}
};
auto unc = ff7::kernel::split(data);
ff7::kernel::Init init;
util::read(util::make_checked(unc[3]), init);
std::ofstream out((fs::path{textPath}/"kernel.bin.xml").string(), out.binary);
out << "<!DOCTYPE kernel SYSTEM \"ts_kernel.dtd\">\n\n"
<< "<kernel>\n\n";
for (auto i = 0u; i < init.characters.size(); ++i) {
out << "<name>";
for (auto c : init.characters[i].name)
out << string::getc(c);
out << "</name>\n";
}
out << "\n</kernel>\n\n";
}
void touphScript::kernel::encode(std::string const& kernel,
std::string const& textPath)
{
namespace rxml = rapidxml;
std::ifstream file{kernel, file.binary};
std::vector<char> data{
std::istreambuf_iterator<char>{file},
std::istreambuf_iterator<char>{}
};
std::ifstream xml_file{(fs::path{textPath}/"kernel.bin.xml").string(),
xml_file.binary};
std::string xml{
std::istreambuf_iterator<char>{xml_file},
std::istreambuf_iterator<char>{}
};
auto unc = ff7::kernel::split(data);
ff7::kernel::Init init;
util::read(util::make_checked(unc[3]), init);
rxml::xml_document<> doc;
doc.parse<rxml::parse_default>(&xml[0]);
auto root = doc.first_node("kernel");
if (!root)
throw error{"Root node kernel not found"};
auto name = root->first_node("name");
for (auto i = 0u; i < init.characters.size();
name = name->next_sibling("name"), ++i) {
if (!name)
throw error{"Insufficient string tags in kernel"};
std::vector<char> text;
string::read_text(name->first_node(), text);
if (text.size() > init.characters[i].name.size() - 1)
throw error{"Kernel name " + std::to_string(i) + " too long"};
text.resize(init.characters[i].name.size(), static_cast<char>(0xFF));
std::copy(text.begin(), text.end(), init.characters[i].name.data());
}
util::write(unc[3].data(), init);
auto cmp = ff7::kernel::join(unc);
std::ofstream{kernel, std::ios_base::binary}.write(cmp.data(), cmp.size());
}
|
a22fb767644bab6f2520fbacc3c8f4e33f59fafd | 832aa1de93c1f275b9b161b10cfacbad9e3d999e | /Mezzanine/src/Network/ftpmessage.cpp | a4c84a39a4e3d6947a931d5a7cbef010b5ff4afa | [] | no_license | BlackToppStudios/Mezzanine | 45253d2affffe00128dab4d151b81ace0faed8b1 | 023fcc56a0e6762cc342c0ec70467fd52209dc39 | refs/heads/master | 2021-06-22T11:18:17.628354 | 2021-02-03T04:16:49 | 2021-02-03T04:16:49 | 2,908,531 | 13 | 5 | null | 2018-09-22T06:18:02 | 2011-12-04T03:19:59 | C++ | WINDOWS-1252 | C++ | false | false | 7,411 | cpp | ftpmessage.cpp | // © Copyright 2010 - 2017 BlackTopp Studios Inc.
/* This file is part of The Mezzanine Engine.
The Mezzanine Engine 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.
The Mezzanine Engine 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 The Mezzanine Engine. If not, see <http://www.gnu.org/licenses/>.
*/
/* The original authors have included a copy of the license specified above in the
'Docs' folder. See 'gpl.txt'
*/
/* We welcome the use of the Mezzanine engine to anyone, including companies who wish to
Build professional software and charge for their product.
However there are some practical restrictions, so if your project involves
any of the following you should contact us and we will try to work something
out:
- DRM or Copy Protection of any kind(except Copyrights)
- Software Patents You Do Not Wish to Freely License
- Any Kind of Linking to Non-GPL licensed Works
- Are Currently In Violation of Another Copyright Holder's GPL License
- If You want to change our code and not add a few hundred MB of stuff to
your distribution
These and other limitations could cause serious legal problems if you ignore
them, so it is best to simply contact us or the Free Software Foundation, if
you have any questions.
Joseph Toppi - toppij@gmail.com
John Blackwood - makoenergy02@gmail.com
*/
#ifndef _networkftpmessage_cpp
#define _networkftpmessage_cpp
#include "Network/ftpmessage.h"
#include "stringtool.h"
#include "exception.h"
namespace Mezzanine
{
namespace Network
{
Boole FTPMessage::IsEndOfLine(const StringIterator CurrIt) const
{ return ( (*CurrIt) == '\r' && *(CurrIt + 1) == '\n' ); }
///////////////////////////////////////////////////////////////////////////////
// Convenience Conversion Methods
String FTPMessage::ConvertToAddress(const SystemAddress& ToConvert)
{
StringStream Ret;
IPAddress IPToConvert = ToConvert.GetAddress();
if( IPToConvert.GetProtocol() == Network::NLP_IPv4 ) {
// Format is a1,a2,a3,a4,p1,p2
// Get the address in it's raw form. Then loop over it and convert the binary values to String.
const IPAddress::AddressContainer& IPContainer = IPToConvert.GetBinaryAddress();
UInt16 PortNum = ToConvert.GetPort(true);
// Address
Ret << IPContainer[0] << ',';
Ret << IPContainer[1] << ',';
Ret << IPContainer[2] << ',';
Ret << IPContainer[3] << ',';
// Port
Ret << PortNum / 256 << ',';
Ret << PortNum % 256;
}
return Ret.str();
}
SystemAddress FTPMessage::ConvertFromAddress(const String& ToConvert)
{
String::const_iterator CurrIt = ToConvert.begin();
return FTPMessage::ConvertFromAddress(CurrIt,ToConvert.end());
}
SystemAddress FTPMessage::ConvertFromAddress(StringIterator& CurrIt, const StringIterator EndIt)
{
SystemAddress Ret;
String Component;
Whole ComponentIndex = 0;
UInt16 ConvertedPort = 0;
IPAddress::AddressContainer ConvertedIP(IPAddress::IPv4BinaryLength,0);
while( CurrIt != EndIt && ComponentIndex < 6 )
{
if( StringTools::IsDigit( *CurrIt ) ) {
Component.push_back( *CurrIt );
}else if( (*CurrIt) == ',' ) {
Int8 ComponentVal = StringTools::ConvertToInt8(Component);
if( ComponentIndex <= 3 ) {
ConvertedIP[ComponentIndex] = ComponentVal;
Ret.GetAddress().SetBinaryAddress(ConvertedIP);
}else if( ComponentIndex == 4 ) {
ConvertedPort = ComponentVal * 256;
}else{
ConvertedPort += ComponentVal;
Ret.SetPort(ConvertedPort,true);
}
++ComponentIndex;
}else{
MEZZ_EXCEPTION(ExceptionBase::PARAMETERS_EXCEPTION,"Only digits and commas are expected in an IPv4 address expressed in a PORT/PASV command according to RFC 959.");
}
++CurrIt;
}
return Ret;
}
String FTPMessage::ConvertToExtendedAddress(const SystemAddress& ToConvert)
{
StringStream Ret;
IPAddress IPToConvert = ToConvert.GetAddress();
if( IPToConvert.GetProtocol() == Network::NLP_IPv4 || IPToConvert.GetProtocol() == Network::NLP_IPv6 ) {
Ret << '|';
Ret << ( IPToConvert.GetProtocol() == Network::NLP_IPv4 ? 1 : 2 );
Ret << '|';
Ret << IPToConvert.GetAsString();
Ret << '|';
Ret << ToConvert.GetPort();
Ret << '|';
}
return Ret.str();
}
SystemAddress FTPMessage::ConvertFromExtendedAddress(const String& ToConvert)
{
String::const_iterator CurrIt = ToConvert.begin();
return FTPMessage::ConvertFromExtendedAddress(CurrIt,ToConvert.end());
}
SystemAddress FTPMessage::ConvertFromExtendedAddress(StringIterator& CurrIt, const StringIterator EndIt)
{
SystemAddress Ret;
if( CurrIt != EndIt && (*CurrIt) == '|' ) {
// Handle the Address Family
StringIterator NextSeparator = std::find(++CurrIt,EndIt,'|');
if( NextSeparator != EndIt ) {
//UInt16 AddressFamily = StringTools::ConvertToUInt16( String(CurrIt,NextSeparator) );
CurrIt = NextSeparator + 1;
}
// Handle the Address
if( CurrIt != EndIt ) {
NextSeparator = std::find(++CurrIt,EndIt,'|');
if( NextSeparator != EndIt ) {
String AddressStr(CurrIt,NextSeparator);
Ret.SetAddress( IPAddress( AddressStr ) );
CurrIt = NextSeparator + 1;
}
}
// Handle the Port
if( CurrIt != EndIt ) {
NextSeparator = std::find(++CurrIt,EndIt,'|');
if( NextSeparator != EndIt ) {
String PortStr(CurrIt,NextSeparator);
Ret.SetPort( StringTools::ConvertToUInt16(PortStr) );
CurrIt = NextSeparator + 1;
}
}
}
return Ret;
}
///////////////////////////////////////////////////////////////////////////////
// Core Operations
}//Network
}//Mezzanine
#endif
|
80a0166d45aef3a179d15b636a4fedc8b19cffe5 | 066c3b3104410a4baf9308ff9e16205a2c88bb74 | /src/lexical/classifier.cpp | e81480be3e69c1562c13641f4b1ee3b5402e9bad | [
"Unlicense"
] | permissive | notYuriy/ionlang | 9e56b1b37b80845050cffde376b6659132fbf711 | c15755554266cdb39f2158f4839eb016955dd626 | refs/heads/master | 2022-12-29T03:52:10.881985 | 2020-09-30T02:23:49 | 2020-09-30T02:23:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,113 | cpp | classifier.cpp | #include <ionlang/lexical/classifier.h>
namespace ionlang {
bool Classifier::isSymbol(TokenKind tokenKind) {
return TokenConst::getSymbols().contains(tokenKind);
}
bool Classifier::isNumeric(TokenKind tokenKind) {
// TODO: Need to define numeric group.
return false;
}
bool Classifier::isOperator(TokenKind tokenKind) {
return TokenConst::getOperators().contains(tokenKind);
}
bool Classifier::isBuiltInType(TokenKind tokenKind) {
return TokenConst::contains(TokenConst::getBuiltInTypes(), tokenKind);
}
bool Classifier::isUnsignedIntegerType(TokenKind tokenKind) {
// return tokenKind == TokenKind::TypeUnsignedInt8
// || tokenKind == TokenKind::TypeUnsignedInt16
// || tokenKind == TokenKind::TypeUnsignedInt32
// || tokenKind == TokenKind::TypeUnsignedInt64;
// TODO
return false;
}
bool Classifier::isIntegerType(TokenKind tokenKind) {
return tokenKind == TokenKind::TypeInt8
|| tokenKind == TokenKind::TypeInt16
|| tokenKind == TokenKind::TypeInt32
|| tokenKind == TokenKind::TypeInt64
|| Classifier::isUnsignedIntegerType(tokenKind);
}
bool Classifier::isKeyword(TokenKind tokenKind) {
return TokenConst::getKeywords().contains(tokenKind);
}
bool Classifier::isLiteral(TokenKind tokenKind) {
return tokenKind == TokenKind::LiteralInteger
|| tokenKind == TokenKind::LiteralDecimal
|| tokenKind == TokenKind::LiteralCharacter
|| tokenKind == TokenKind::LiteralString;
}
bool Classifier::isStatement(TokenKind tokenKind, std::optional<TokenKind> nextTokenKind) {
return Classifier::isBuiltInType(tokenKind)
|| (
nextTokenKind.has_value()
&& tokenKind == TokenKind::Identifier
&& nextTokenKind.value() == TokenKind::SymbolEqual
)
|| tokenKind == TokenKind::KeywordIf
|| tokenKind == TokenKind::KeywordReturn;
}
}
|
7101c7db318264c32ca6767d65355d60d978adf1 | e05d5ccfc46bdc20657097ca68cf98d7749fbb0e | /Math/Number Theory/UVA10193 - All You Need Is Love/Code.cpp | 6ea03d3b2509e0e8171fb38be35c521ffd7556be | [
"MIT"
] | permissive | adelnobel/Training-for-ACM-ICPC-problems | 9abef9705e0e15a15fc04c264bc61237262a4a09 | 8030d24ab3ce1f50821b22647bf9195b41f932b1 | refs/heads/master | 2020-05-02T06:10:14.761012 | 2014-10-30T10:49:32 | 2014-10-30T10:49:32 | 10,177,129 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cpp | Code.cpp | #include <vector>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cctype>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <bitset>
#include <map>
#include <complex>
#include <ctime>
#include <numeric>
using namespace std;
typedef long long ll;
char s1[40], s2[40];
int conv(char s[], int l){
int ret = 0;
for(int i = 0; i < l; i++){
if(s[i] == '1')
ret |= (1 << (l-i-1));
}
return ret;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.in", "r", stdin);
#endif
int t, a, b, c = 1;
scanf("%d", &t);
while(t--){
scanf("%s %s", s1, s2);
a = conv(s1, strlen(s1));
b = conv(s2, strlen(s2));
printf("Pair #%d: ", c++);
printf(__gcd(a, b) > 1 ? "All you need is love!\n" : "Love is not all you need!\n");
}
return 0;
} |
ca2d4300e1dc64569997c30e616039b2b48d78ba | 4bb0da690d5ffdc6d9caf38ae8ff4edfebf435d6 | /uva_260.cpp | 1897785f085ab0ddf719635e933a87182a6dc315 | [] | no_license | RakeshIIITD/Uva | eb509ede9bf3c4e9d993376396ca26426bb719bc | 4eb23439ab1a2d757ad6334ddf49aa48b31f7d52 | refs/heads/master | 2020-07-29T21:09:14.193282 | 2019-12-28T13:44:52 | 2019-12-28T13:44:52 | 209,959,738 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,553 | cpp | uva_260.cpp | // `roCKy FireBirD
#include<stdio.h>
#include<iostream>
#include<sstream>
#include<string>
#include<string.h>
#include<limits.h>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
using namespace std ;
#define FOR(i,a,b) for( int i = int(a) ; i<=int(b) ; i++)
int visited[201][201] ;
int arr[201][201] ;
int d ,result;
bool safe(int i,int j)
{
if(i<0||j<0||j>d||i>d) return 0 ;
else return 1 ;
}
void dfs(int i ,int j)
{
visited[i][j]=1 ;
if(i==d&&arr[i][j]) result = 1 ;
if(safe(i,j+1)&&arr[i][j+1]&&!visited[i][j+1]) dfs(i,j+1) ;
if(safe(i+1,j)&&arr[i+1][j]&&!visited[i+1][j]) dfs(i+1,j) ;
if(safe(i,j-1)&&arr[i][j-1]&&!visited[i][j-1]) dfs(i,j-1) ;
if(safe(i-1,j)&&arr[i-1][j]&&!visited[i-1][j]) dfs(i-1,j) ;
if(safe(i+1,j+1)&&arr[i+1][j+1]&&!visited[i+1][j+1]) dfs(i+1,j+1) ;
if(safe(i-1,j-1)&&arr[i-1][j-1]&&!visited[i-1][j-1]) dfs(i-1,j-1) ;
}
int main()
{
int n ;
int testcase = 0 ;
char s[201] ;
while(1)
{
testcase++ ;
memset(visited,0,sizeof(visited)) ;
scanf("%d",&n) ;
if(n==0) break ;
d = n-1 ;
for(int i=0;i<n ; i++)
{
scanf("%s",s) ;
for(int j=0;j<n;j++)
{
if(s[j]=='b') arr[i][j] = 1 ;
else arr[i][j] = 0 ;
}
}
int k ;
result = 0 ;
for(int i=0;i<n ; i++)
{
if(arr[0][i]==1)
{
dfs(0,i) ;
if(result==1) break;
}
}
if(result)
{
printf("%d B\n",testcase) ;
}
else
{
printf("%d W\n",testcase) ;
}
}
return 0 ;
}
|
e4b8d1ae646b9bc41f8707a8ad91acf4b74a135f | 7d579dfb059b32e259427440b9fbed690efc9f52 | /Files/SCHEDULE/SCHEDULE-13045916.cpp | 23a5a85964e0b0f364a55f107b93605078b98cc1 | [
"MIT"
] | permissive | nishant-khanorkar/CodeChef-Submissions | d6e571d79b73e8f888d28cfd7ae942c643717fa9 | 4019e859d95bfa7fe763acf330c98f5f54b7b185 | refs/heads/master | 2020-03-19T22:10:49.238701 | 2018-09-19T15:56:47 | 2018-09-19T15:56:47 | 136,958,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,138 | cpp | SCHEDULE-13045916.cpp | #include <bits/stdc++.h>
#include <stdlib.h>
#define ll long long
using namespace std;
typedef struct foo
{
ll len;
ll max;
ll kdis;
ll pre;
}foo;
foo tpl;
int cmp(const void* a,const void* b)
{
foo *k1=(foo *)a;
foo *k2=(foo *)b;
if(k1->pre < k2->pre)
return 1;
else
return -1;
}
int main()
{
ll n,t,k,i,j,s00,s01,sm,x,y,pt;
char a[1000005];
cin>>t;
while(t--)
{
foo setp[1000005];
cin>>n>>k;
s00=s01=0;
for(i=0;i<n;i++)
{
scanf(" %c ",&a[i]);
if(i%2==0)
{
if(a[i]=='0')
s00++;
else
s01++;
}
else
{
if(a[i]=='0')
s01++;
else
s00++;
}
}
a[i]='\0';
s00=n-s00;
s01=n-s01;
if(k>=s00 || k>=s01)
{
cout<<1<<endl;
continue;
}
n--;
pt=0;
for(i=0;i<n;i++)
{
if(a[i]==a[i+1])
{
sm=1;
while(a[i]==a[i+1])
{
i++;
sm++;
}
tpl.len=sm;
tpl.pre=sm;
tpl.max=(sm-1)/2;
tpl.kdis=0;
setp[pt++]=tpl;
}
}
qsort(setp,pt,sizeof(foo),cmp);
while(k>0 && setp[0].kdis<setp[0].max)
{
k--;
setp[0].kdis++;
x=setp[0].len-setp[0].kdis;
y=setp[0].kdis+1;
sm=x/y + ( x%y==0 ? 0 : 1);
setp[0].pre=sm;
i=1;
while(k>0 && i<pt && setp[i].kdis<setp[i].max && setp[i].pre>=sm)
{
k--;
setp[i].kdis++;
x=setp[i].len-setp[i].kdis;
y=setp[i].kdis+1;
setp[i].pre=x/y + (x%y==0 ? 0 : 1);
i++;
}
qsort(setp,pt,sizeof(foo),cmp);
}
cout<<setp[0].pre<<endl;
}
return 0;
} |
b0690e6f80f783c9535cd51ea1ac2549a3ed69ed | bd2c7d8e4728d04115c772f43b878db562e76638 | /lab4/corgi.h | c34e6e7e7982d83b2973c48f052d8886f0dee131 | [] | no_license | billpwchan/COMP-2012-Programs | c86c92d681cf00d9abca431e3fb915dc7afffaab | 726fc3b0695a28187acc548033b452ad4def3f25 | refs/heads/main | 2023-02-05T02:54:20.869804 | 2020-12-27T20:44:02 | 2020-12-27T20:44:02 | 324,845,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 817 | h | corgi.h | #ifndef CORGI_HPP_
#define CORGI_HPP_
#include "dog.h"
class Corgi : protected Dog {
public:
//Constructor of Corgi
Corgi(int heartbeat, int max_heartbeat, int min_heartbeat, int weight, int speed);
//Destructor of Corgi
~Corgi();
//print the info of the Corgi, this function will call Dog::print_heart_info(), refer to the output for the details
void print();
//This function will move the Corgi for the given time duration with the speed, refer to the output for the details
void move(int time);
//get the weight and speed information of the Corgi
int get_weight();
int get_speed();
//change the state of heart these two function should call the corresponding functions in the Heart class
void boost_heartbeat();
void decrease_heartbeat();
};
#endif
|
c771be471230485779d00b42874622b4da2e178c | 71cae6e39c666be24a1e5c55e110a15a0d65faed | /Stars/main.cpp | 54cf5845ceea2e57b565d4da8d7bc8a66dd37e2e | [] | no_license | crazyjerryh/Practice | 18bb7a885e7652ba867fbbe8cf844d56cf19eb29 | e8862083d37066dac1a395c652e2f36793ab48e3 | refs/heads/master | 2021-01-18T13:57:26.490761 | 2015-10-29T14:08:45 | 2015-10-29T14:08:45 | 33,871,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cpp | main.cpp | #include <stdio.h>
#include <memory.h>
#include <algorithm>
using namespace std;
#define maxn 32010
struct _point{
int x,y;
}a[maxn];
typedef struct _point point;
int n;
int tree[maxn],sum[maxn];
int m;
void update(int x,int num){
while(x<=m){
tree[x]+=num;
x=x+(x&-x);
}
}
int getsum(int x){
int ans=0;
while(x){
ans+=tree[x];
x=x-(x&-x);
}
return ans;
}
void solve(){
memset(sum,0,sizeof(sum));
memset(tree,0,sizeof(tree));
for(int i=0;i<n;i++){
update(a[i].x,1);
int ans=getsum(a[i].x); //get the result of the sequence
sum[ans-1]++;
}
for(int i=0;i<n;i++)
printf("%d\n",sum[i]);
}
int main(void)
{
//freopen("debug.txt","r",stdin);
while(scanf("%d",&n)!=EOF){
m=-1;
for(int i=0;i<n;i++){
int x,y;
scanf("%d%d",&x,&y);
a[i].x=x+1,a[i].y=y+1;
if(a[i].x>m)
m=a[i].x;
}
solve();
}
return 0;
}
|
19c8281c4e989e4634a3a6fd27869dedb6ed85dc | fa1ad2e2ac7e376fc7cb3b3a6e1bb88eed3e80be | /olap/ByConity/src/Functions/uptime.cpp | 02454df4de522079634776023245ac358aaf6298 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | alldatacenter/alldata | 7bc7713c9f1d56ad6b8e59ea03206d1073b7e047 | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | refs/heads/master | 2023-08-05T07:32:25.442740 | 2023-08-03T13:17:24 | 2023-08-03T13:17:24 | 213,321,771 | 774 | 250 | Apache-2.0 | 2023-09-06T17:35:32 | 2019-10-07T07:36:18 | null | UTF-8 | C++ | false | false | 1,245 | cpp | uptime.cpp | #include <Functions/IFunction.h>
#include <Functions/FunctionFactory.h>
#include <DataTypes/DataTypesNumber.h>
#include <Interpreters/Context.h>
namespace DB
{
/** Returns server uptime in seconds.
*/
class FunctionUptime : public IFunction
{
public:
static constexpr auto name = "uptime";
static FunctionPtr create(ContextPtr context)
{
return std::make_shared<FunctionUptime>(context->getUptimeSeconds());
}
explicit FunctionUptime(time_t uptime_) : uptime(uptime_)
{
}
String getName() const override
{
return name;
}
size_t getNumberOfArguments() const override
{
return 0;
}
DataTypePtr getReturnTypeImpl(const DataTypes & /*arguments*/) const override
{
return std::make_shared<DataTypeUInt32>();
}
bool isDeterministic() const override { return false; }
ColumnPtr executeImpl(const ColumnsWithTypeAndName &, const DataTypePtr &, size_t input_rows_count) const override
{
return DataTypeUInt32().createColumnConst(input_rows_count, static_cast<UInt64>(uptime));
}
private:
time_t uptime;
};
void registerFunctionUptime(FunctionFactory & factory)
{
factory.registerFunction<FunctionUptime>();
}
}
|
88aa843201f3d5e89c77a9321d8702f3617b0cb8 | cb721728f664341789c372f5f56b6e6852bc33e6 | /test/bindings/wren_bindings.h | bc013d928912b731e5f04cf90517db0dac759e40 | [
"MIT"
] | permissive | darmie/wrenegade | ed9115d63a13bafbc13ddb94030916d776ffa81a | cbe874a6c87be6684e65d8d9d1c4562f3d6b2674 | refs/heads/master | 2020-05-03T09:41:04.785758 | 2019-08-01T19:22:30 | 2019-08-01T19:22:30 | 178,560,768 | 18 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 350 | h | wren_bindings.h | #ifndef _WREN_BINDINGS_
#define _WREN_BINDINGS_
extern "C"
{
#include <wren.h>
}
namespace wrenegade {static const char* BIND_PATH = "bindings/wren";
void bindClass(const char* module, const char* className, WrenForeignClassMethods* methods);
WrenForeignMethodFn bindMethod(const char* module, const char *className, const char* signature);}
#endif |
a0453c9187e2e6adfca11c4b04519c4e9b3c8306 | dc215a163a9a1ca4808be876cf4a7e491886f5eb | /src/raytracing/bvh/SplitBVHBuilder.h | 70ded9b4a6fcaa2ad3f65f5e043840c00660cd30 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | Victorique-GOSICK/EAVL | d30df5dfb425ebf476ad7cf7caf6bcd44179b110 | 114924a92aed4f1adfcf4f751151d9355c593944 | refs/heads/master | 2021-05-14T19:05:13.455171 | 2017-09-26T13:34:08 | 2017-09-26T13:34:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,789 | h | SplitBVHBuilder.h | /*
* Copyright (c) 2009-2011, NVIDIA Corporation
* 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 NVIDIA Corporation 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
//#include "bvh/BVH.hpp"
//#include "base/Timer.hpp"
#include "Util.h"
#include "Array.h"
#include <limits>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include "eavlVector3i.h"
using namespace std;
#define NON_LEAF_SIZE 16
#define LEAF_FLAG 0xFF800000
using FW::Vec3f;
using FW::Vec3i;
using FW::AABB;
class SplitBVHBuilder
{
private:
enum
{
MaxDepth = 64,
MaxSpatialDepth = 48,
NumSpatialBins = 128,
};
struct Reference
{
int triIdx;
AABB bounds;
Reference(void) : triIdx(-1) {}
};
struct NodeSpec
{
int numRef;
AABB bounds;
NodeSpec(void) : numRef(0) {}
};
struct ObjectSplit
{
float sah;
int sortDim;
int numLeft;
AABB leftBounds;
AABB rightBounds;
ObjectSplit(void) : sah(std::numeric_limits<float>::max()), sortDim(0), numLeft(0) {}
};
struct SpatialSplit
{
float sah;
int dim;
float pos;
SpatialSplit(void) : sah(std::numeric_limits<float>::max()), dim(0), pos(0.0f) {}
};
struct SpatialBin
{
AABB bounds;
int enter;
int exit;
};
public:
SplitBVHBuilder (float *verts,int numPrimitives, const BuildParams& params, int primitveType);
~SplitBVHBuilder (void);
BVHNode* run (void);
int getSAH (BVHNode *);
void bvhToFlatArray (BVHNode * root, int &innerSize, int &leafSize, float*& innerNodes, float*& leafNodes);
private:
static bool sortCompare (void* data, int idxA, int idxB);
static void sortSwap (void* data, int idxA, int idxB);
BVHNode* buildNode (NodeSpec spec, int level, float progressStart, float progressEnd);
BVHNode* createLeaf (const NodeSpec& spec);
ObjectSplit findObjectSplit (const NodeSpec& spec, float nodeSAH);
void performObjectSplit (NodeSpec& left, NodeSpec& right, const NodeSpec& spec, const ObjectSplit& split);
SpatialSplit findSpatialSplit (const NodeSpec& spec, float nodeSAH);
void performSpatialSplit (NodeSpec& left, NodeSpec& right, const NodeSpec& spec, const SpatialSplit& split);
void splitReference (Reference& left, Reference& right, const Reference& ref, int dim, float pos);
void assignParentPointers(BVHNode*);
void traverseRecursive (BVHNode* node, BVHNode* parent);
bool hasReference (int index);
private:
SplitBVHBuilder (const SplitBVHBuilder&); // forbidden
SplitBVHBuilder& operator= (const SplitBVHBuilder&); // forbidden
private:
//BVH& m_bvh;
Platform m_platform;
const BuildParams& m_params;
float * m_verts; /* This may not be the best way of pointing, could just make it a float ptr */
Array<Reference> m_refStack;
float m_minOverlap;
Array<AABB> m_rightBounds;
int m_sortDim;
SpatialBin m_bins[3][NumSpatialBins];
//Timer m_progressTimer;
int m_numDuplicates;
int m_numPrimitives;
int m_innerNodeCount;
int m_leafNodeCount;
int m_maxDepth;
int m_primitiveType;
bool m_doSpacialSplits;
int numR;
int numL; //todo: delete these
int megaCounter;
Array<int> m_triIndices; //Maybe seg fault??
};
//------------------------------------------------------------------------
//------------------------------------------------------------------------
/*
primitives types :
0 = triangle
1 = sphere
*/
inline SplitBVHBuilder::SplitBVHBuilder(float *verts, int numPrimitives, const BuildParams& params, int primitveType)
: //m_bvh (bvh),
m_primitiveType(primitveType),
m_params (params),
m_minOverlap (0),
m_sortDim (-1),
m_verts (verts),
m_numPrimitives (numPrimitives)
{
//Platform* p=new Platform();
m_platform=*(new Platform());
m_innerNodeCount=0;
m_leafNodeCount=0;
m_maxDepth=0;
if ( m_primitiveType == 0 ) m_doSpacialSplits=true;
else if ( m_primitiveType == 1 ) m_doSpacialSplits=false;
else if ( m_primitiveType == 2 )
{
m_doSpacialSplits=false;
m_platform=*(new Platform(1)); /* Only one cell per leafNode */
}
else if( m_primitiveType == 3) m_doSpacialSplits=false;
//todo remove
megaCounter=0;
}
//------------------------------------------------------------------------
inline SplitBVHBuilder::~SplitBVHBuilder(void)
{
//delete m_platform;
}
inline int SplitBVHBuilder::getSAH(BVHNode *root)
{
float sah=0;
root->computeSubtreeProbabilities(m_platform,1.f,sah);
return sah;
}
//------------------------------------------------------------------------
inline bool SplitBVHBuilder::hasReference(int index)
{
for(int i=0; i<m_refStack.getSize();i++)
{
if(m_refStack[i].triIdx==index) return true;
}
return false;
}
inline BVHNode* SplitBVHBuilder::run(void)
{
// Initialize reference stack and determine root bounds.
NodeSpec rootSpec;
rootSpec.numRef = m_numPrimitives;
m_refStack.resize(rootSpec.numRef);
eavlVector3 *triPtr = (eavlVector3 *)&m_verts[0];
eavlVector4 *spherePtr = (eavlVector4 *)&m_verts[0];
eavlVector4 *tetPtr = (eavlVector4 *)&m_verts[0];
eavlVector4 *cylPtr = (eavlVector4 *)&m_verts[0];
for (int i = 0; i < rootSpec.numRef; i++)
{
m_refStack[i].triIdx = i;
/* Insert methods here for creating bounding boxes of different primitives */
if(m_primitiveType == 0 )
{
for (int j = 0; j < 3; j++) m_refStack[i].bounds.grow(Vec3f(triPtr[i*4+j].x, triPtr[i*4+j].y,triPtr[i*4+j].z));
}
else if ( m_primitiveType == 1 )
{
Vec3f temp(0,0,0);
Vec3f center( spherePtr[i].x, spherePtr[i].y, spherePtr[i].z );
float radius = spherePtr[i].w;
temp.x = radius;
temp.y = 0;
temp.z = 0;
m_refStack[i].bounds.grow(center+temp);
m_refStack[i].bounds.grow(center-temp);
temp.x = 0;
temp.y = radius;
temp.z = 0;
m_refStack[i].bounds.grow(center+temp);
m_refStack[i].bounds.grow(center-temp);
temp.x = 0;
temp.y = 0;
temp.z = radius;
m_refStack[i].bounds.grow(center+temp);
m_refStack[i].bounds.grow(center-temp);
}
else if ( m_primitiveType == 2 )
{
for(int j = 0; j < 4; j++)
{
Vec3f v( tetPtr[i*4 + j].x, tetPtr[i*4 + j].y, tetPtr[i*4 + j].z );
m_refStack[i].bounds.grow(v);
}
}
else if( m_primitiveType == 3 )
{
/* insert conservative bounding capsule*/
Vec3f temp(0,0,0);
Vec3f base( cylPtr[i*2].x, cylPtr[i*2].y, cylPtr[i*2].z );
float radius = cylPtr[i*2].w;
Vec3f axis( cylPtr[i*2+1].x, cylPtr[i*2+1].y, cylPtr[i*2+1].z );
float height = cylPtr[i*2+1].w;
Vec3f top = base + axis * height;
temp.x = radius;
temp.y = 0;
temp.z = 0;
m_refStack[i].bounds.grow(base+temp);
m_refStack[i].bounds.grow(base-temp);
m_refStack[i].bounds.grow(top +temp);
m_refStack[i].bounds.grow(top -temp);
temp.x = 0;
temp.y = radius;
temp.z = 0;
m_refStack[i].bounds.grow(base+temp);
m_refStack[i].bounds.grow(base-temp);
m_refStack[i].bounds.grow(top +temp);
m_refStack[i].bounds.grow(top -temp);
temp.x = 0;
temp.y = 0;
temp.z = radius;
m_refStack[i].bounds.grow(base+temp);
m_refStack[i].bounds.grow(base-temp);
m_refStack[i].bounds.grow(top +temp);
m_refStack[i].bounds.grow(top -temp);
}
rootSpec.bounds.grow(m_refStack[i].bounds);
}
// Initialize rest of the members.
m_minOverlap = rootSpec.bounds.area() * m_params.splitAlpha;
m_rightBounds.reset(max(rootSpec.numRef, (int)NumSpatialBins) - 1);
m_numDuplicates = 0;
//m_progressTimer.start();
// Build recursively.
BVHNode* root = buildNode(rootSpec, 0, 0.0f, 1.0f);
float s=0;
root->computeSubtreeProbabilities(m_platform,1.f,s);
//cout<<" ------------------BVH Stats--------------------------------"<<endl;
//cout<<"Bounds "<<rootSpec.bounds.area()<<" SAH : "<<s<<endl;
//cout<<"Num Primitive Refs "<<m_numPrimitives+m_numDuplicates<<" InnerNodes "<<m_innerNodeCount<<" leaf nodes "<<m_leafNodeCount<<" Max Depth "<<m_maxDepth<<endl;
//if (m_params.enablePrints)
// printf("duplicates %.0f%% Spacial Splits %d\n" , (float)m_numDuplicates / (float)m_numPrimitives * 100.0f, numSpacialSplits);
//cout<<" ------------------End BVH Stats----------------------------"<<endl;
//m_params.stats->SAHCost = sah;
//cout<<"Leaf Count "<<root->getSubtreeSize(BVH_STAT_LEAF_COUNT)<<endl;
//cout<<"Inner Count "<<root->getSubtreeSize(BVH_STAT_INNER_COUNT)<<endl;;
//cout<<"Tri Count "<<root->getSubtreeSize(BVH_STAT_TRIANGLE_COUNT)<<endl;;
//cout<<"Child Count "<<root->getSubtreeSize(BVH_STAT_CHILDNODE_COUNT)<<endl;;
//printf("Platform Stuff\n");
//printf("TriCost : %f\n",m_platform.getSAHTriangleCost());
// printf("NodeCost : %f\n",m_platform.getSAHTriangleCost());
//printf("TriBatchSize : %d\n",m_platform.getTriangleBatchSize());
//printf("NodeBatchSize : %d\n",m_platform.getNodeBatchSize());
//printf("MinSize : %d\n",m_platform.getMinLeafSize());
//printf("MaxSize : %d\n",m_platform.getMaxLeafSize());
return root;
}
//------------------------------------------------------------------------
inline bool SplitBVHBuilder::sortCompare(void* data, int idxA, int idxB)
{
const SplitBVHBuilder* ptr = (const SplitBVHBuilder*)data;
int dim = ptr->m_sortDim;
const Reference& ra = ptr->m_refStack[idxA];
const Reference& rb = ptr->m_refStack[idxB];
float ca = ra.bounds.min()[dim] + ra.bounds.max()[dim];
float cb = rb.bounds.min()[dim] + rb.bounds.max()[dim];
return (ca < cb || (ca == cb && ra.triIdx < rb.triIdx));
}
//------------------------------------------------------------------------
inline void SplitBVHBuilder::sortSwap(void* data, int idxA, int idxB)
{
SplitBVHBuilder* ptr = (SplitBVHBuilder*)data;
swap(ptr->m_refStack[idxA], ptr->m_refStack[idxB]);
}
//------------------------------------------------------------------------
inline BVHNode* SplitBVHBuilder::buildNode(NodeSpec spec, int level, float progressStart, float progressEnd)
{
m_maxDepth=max(level,m_maxDepth);
// Remove degenerates.
{
int firstRef = m_refStack.getSize() - spec.numRef;
for (int i = m_refStack.getSize() - 1; i >= firstRef; i--)
{
Vec3f size = m_refStack[i].bounds.max() - m_refStack[i].bounds.min();
float minExtent= min(size.x,min(size.y,size.z));
float maxExtent= max(size.x,max(size.y,size.z));
float sum =size.x+size.y+size.z;
if (minExtent < 0.0f || sum == maxExtent)
{
m_refStack.removeSwap(i);
}
}
spec.numRef = m_refStack.getSize() - firstRef;
}
// Small enough or too deep => create leaf.
if (spec.numRef <= m_platform.getMinLeafSize() || level >= MaxDepth)
return createLeaf(spec);
// Find split candidates.
float area = spec.bounds.area();
float leafSAH = area * m_platform.getTriangleCost(spec.numRef);
float nodeSAH = area * m_platform.getNodeCost(2);
ObjectSplit object = findObjectSplit(spec, nodeSAH);
SpatialSplit spatial;
if (level < MaxSpatialDepth)
{
AABB overlap = object.leftBounds;
overlap.intersect(object.rightBounds);
if (overlap.area() >= m_minOverlap && m_doSpacialSplits) //only for triangles
spatial = findSpatialSplit(spec, nodeSAH);
}
// Leaf SAH is the lowest => create leaf.
float minSAH = min(leafSAH, min(object.sah, spatial.sah));
if (minSAH == leafSAH && spec.numRef <= m_platform.getMaxLeafSize())
return createLeaf(spec);
// Perform split.
NodeSpec left, right;
if (minSAH == spatial.sah)
{ performSpatialSplit(left, right, spec, spatial); }
if (!left.numRef || !right.numRef)
{ performObjectSplit(left, right, spec, object); }
// Create inner node.
m_numDuplicates += left.numRef + right.numRef - spec.numRef;
float progressMid = lerp(progressStart, progressEnd, (float)right.numRef / (float)(left.numRef + right.numRef));
BVHNode* rightNode = buildNode(right, level + 1, progressStart, progressMid);
BVHNode* leftNode = buildNode(left, level + 1, progressMid, progressEnd);
m_innerNodeCount++;
return new InnerNode(spec.bounds, leftNode, rightNode);
}
//------------------------------------------------------------------------
inline BVHNode* SplitBVHBuilder::createLeaf(const NodeSpec& spec)
{
m_leafNodeCount++;
for (int i = 0; i < spec.numRef; i++)
{
m_triIndices.add(m_refStack.removeLast().triIdx);
}
return new LeafNode(spec.bounds, m_triIndices.getSize() - spec.numRef, m_triIndices.getSize());
}
//------------------------------------------------------------------------
inline SplitBVHBuilder::ObjectSplit SplitBVHBuilder::findObjectSplit(const NodeSpec& spec, float nodeSAH)
{
ObjectSplit split;
const Reference* refPtr = m_refStack.getPtr(m_refStack.getSize() - spec.numRef);
float bestTieBreak = std::numeric_limits<float>::max();
// Sort along each dimension.
for (m_sortDim = 0; m_sortDim < 3; m_sortDim++)
{
sort(this, m_refStack.getSize() - spec.numRef, m_refStack.getSize(), sortCompare, sortSwap);
// Sweep right to left and determine bounds.
AABB rightBounds;
for (int i = spec.numRef - 1; i > 0; i--)
{
rightBounds.grow(refPtr[i].bounds);
m_rightBounds[i - 1] = rightBounds;
}
// Sweep left to right and select lowest SAH.
AABB leftBounds;
for (int i = 1; i < spec.numRef; i++)
{
leftBounds.grow(refPtr[i - 1].bounds);
float sah = nodeSAH + leftBounds.area() * m_platform.getTriangleCost(i) + m_rightBounds[i - 1].area() * m_platform.getTriangleCost(spec.numRef - i);
float tieBreak = ((float)i)*((float)i) + ((float)(spec.numRef - i))*((float)(spec.numRef - i));
if (sah < split.sah || (sah == split.sah && tieBreak < bestTieBreak))
{
split.sah = sah;
split.sortDim = m_sortDim;
split.numLeft = i;
split.leftBounds = leftBounds;
split.rightBounds = m_rightBounds[i - 1];
bestTieBreak = tieBreak;
}
}
}
return split;
}
//------------------------------------------------------------------------
inline void SplitBVHBuilder::performObjectSplit(NodeSpec& left, NodeSpec& right, const NodeSpec& spec, const ObjectSplit& split)
{
m_sortDim = split.sortDim;
sort(this, m_refStack.getSize() - spec.numRef, m_refStack.getSize(), sortCompare, sortSwap);
left.numRef = split.numLeft;
left.bounds = split.leftBounds;
right.numRef = spec.numRef - split.numLeft;
right.bounds = split.rightBounds;
}
//------------------------------------------------------------------------
inline SplitBVHBuilder::SpatialSplit SplitBVHBuilder::findSpatialSplit(const NodeSpec& spec, float nodeSAH)
{
// Initialize bins.
Vec3f origin = spec.bounds.min();
Vec3f binSize = (spec.bounds.max() - origin) * (1.0f / (float)NumSpatialBins);
Vec3f invBinSize = 1.0f / binSize;
for (int dim = 0; dim < 3; dim++)
{
for (int i = 0; i < NumSpatialBins; i++)
{
SpatialBin& bin = m_bins[dim][i];
bin.bounds = AABB();
bin.enter = 0;
bin.exit = 0;
}
}
// Chop references into bins.
for (int refIdx = m_refStack.getSize() - spec.numRef; refIdx < m_refStack.getSize(); refIdx++)
{
const Reference& ref = m_refStack[refIdx];
Vec3i firstBin = clamp(Vec3i((ref.bounds.min() - origin) * invBinSize), 0, NumSpatialBins - 1);
Vec3i lastBin = clamp(Vec3i((ref.bounds.max() - origin) * invBinSize), firstBin, NumSpatialBins - 1);
for (int dim = 0; dim < 3; dim++)
{
Reference currRef = ref;
for (int i = firstBin[dim]; i < lastBin[dim]; i++)
{
Reference leftRef, rightRef;
splitReference(leftRef, rightRef, currRef, dim, origin[dim] + binSize[dim] * (float)(i + 1));
m_bins[dim][i].bounds.grow(leftRef.bounds);
currRef = rightRef;
}
m_bins[dim][lastBin[dim]].bounds.grow(currRef.bounds);
m_bins[dim][firstBin[dim]].enter++;
m_bins[dim][lastBin[dim]].exit++;
}
}
// Select best split plane.
SpatialSplit split;
for (int dim = 0; dim < 3; dim++)
{
// Sweep right to left and determine bounds.
AABB rightBounds;
for (int i = NumSpatialBins - 1; i > 0; i--)
{
rightBounds.grow(m_bins[dim][i].bounds);
m_rightBounds[i - 1] = rightBounds;
}
// Sweep left to right and select lowest SAH.
AABB leftBounds;
int leftNum = 0;
int rightNum = spec.numRef;
for (int i = 1; i < NumSpatialBins; i++)
{
leftBounds.grow(m_bins[dim][i - 1].bounds);
leftNum += m_bins[dim][i - 1].enter;
rightNum -= m_bins[dim][i - 1].exit;
float sah = nodeSAH + leftBounds.area() * m_platform.getTriangleCost(leftNum) + m_rightBounds[i - 1].area() * m_platform.getTriangleCost(rightNum);
if (sah < split.sah)
{
split.sah = sah;
split.dim = dim;
split.pos = origin[dim] + binSize[dim] * (float)i;
}
}
}
return split;
}
//------------------------------------------------------------------------
inline void SplitBVHBuilder::performSpatialSplit(NodeSpec& left, NodeSpec& right, const NodeSpec& spec, const SpatialSplit& split)
{
// Categorize references and compute bounds.
//
// Left-hand side: [leftStart, leftEnd[
// Uncategorized/split: [leftEnd, rightStart[
// Right-hand side: [rightStart, refs.getSize()[
Array<Reference>& refs = m_refStack;
int leftStart = refs.getSize() - spec.numRef;
int leftEnd = leftStart;
int rightStart = refs.getSize();
left.bounds = right.bounds = AABB();
for (int i = leftEnd; i < rightStart; i++)
{
// Entirely on the left-hand side?
if (refs[i].bounds.max()[split.dim] <= split.pos)
{
left.bounds.grow(refs[i].bounds);
swap(refs[i], refs[leftEnd++]);
}
// Entirely on the right-hand side?
else if (refs[i].bounds.min()[split.dim] >= split.pos)
{
right.bounds.grow(refs[i].bounds);
swap(refs[i--], refs[--rightStart]);
}
}
// Duplicate or unsplit references intersecting both sides.
while (leftEnd < rightStart)
{
// Split reference.
Reference lref, rref;
splitReference(lref, rref, refs[leftEnd], split.dim, split.pos);
// Compute SAH for duplicate/unsplit candidates.
AABB lub = left.bounds; // Unsplit to left: new left-hand bounds.
AABB rub = right.bounds; // Unsplit to right: new right-hand bounds.
AABB ldb = left.bounds; // Duplicate: new left-hand bounds.
AABB rdb = right.bounds; // Duplicate: new right-hand bounds.
lub.grow(refs[leftEnd].bounds);
rub.grow(refs[leftEnd].bounds);
ldb.grow(lref.bounds);
rdb.grow(rref.bounds);
float lac = m_platform.getTriangleCost(leftEnd - leftStart);
float rac = m_platform.getTriangleCost(refs.getSize() - rightStart);
float lbc = m_platform.getTriangleCost(leftEnd - leftStart + 1);
float rbc = m_platform.getTriangleCost(refs.getSize() - rightStart + 1);
float unsplitLeftSAH = lub.area() * lbc + right.bounds.area() * rac;
float unsplitRightSAH = left.bounds.area() * lac + rub.area() * rbc;
float duplicateSAH = ldb.area() * lbc + rdb.area() * rbc;
float minSAH = min(unsplitLeftSAH, min(unsplitRightSAH, duplicateSAH));
// Unsplit to left?
if (minSAH == unsplitLeftSAH)
{
left.bounds = lub;
leftEnd++;
//cout<<"unsplit left"<<endl;
}
// Unsplit to right?
else if (minSAH == unsplitRightSAH)
{
//cout<<" unsplit right "<<endl;
right.bounds = rub;
swap(refs[leftEnd], refs[--rightStart]);
}
// Duplicate?
else
{ //cout<<"Diplicate"<<endl;
left.bounds = ldb;
right.bounds = rdb;
refs[leftEnd++] = lref;
refs.add(rref);
}
}
left.numRef = leftEnd - leftStart;
right.numRef = refs.getSize() - rightStart;
}
//------------------------------------------------------------------------
inline void SplitBVHBuilder::splitReference(Reference& left, Reference& right, const Reference& ref, int dim, float pos)
{
// Initialize references.
left.triIdx = right.triIdx = ref.triIdx;
left.bounds = right.bounds = AABB();
Vec3f *verts= (Vec3f*)&m_verts[0];
// Loop over vertices/edges.
//const Vec3i* tris = (const Vec3i*)m_bvh.getScene()->getTriVtxIndexBuffer().getPtr();
//const eavlVector3* verts = (const eavlVector3*)m_bvh.getScene()->getVtxPosBuffer().getPtr();
Vec3i inds(ref.triIdx*4, ref.triIdx*4+1, ref.triIdx*4+2);
const Vec3f* v1 = &verts[inds.z];
for (int i = 0; i < 3; i++)
{
const Vec3f* v0 = v1;
v1 = &verts[inds[i]];
float v0p = v0->get(dim);
float v1p = v1->get(dim);
// Insert vertex to the boxes it belongs to.
if (v0p <= pos)
left.bounds.grow(*v0);
if (v0p >= pos)
right.bounds.grow(*v0);
// Edge intersects the plane => insert intersection to both boxes.
if ((v0p < pos && v1p > pos) || (v0p > pos && v1p < pos))
{
Vec3f t = lerp(*v0, *v1, clamp((pos - v0p) / (v1p - v0p), 0.0f, 1.0f));
left.bounds.grow(t);
right.bounds.grow(t);
}
}
// Intersect with original bounds.
left.bounds.max()[dim] = pos;
right.bounds.min()[dim] = pos;
left.bounds.intersect(ref.bounds);
right.bounds.intersect(ref.bounds);
}
inline void SplitBVHBuilder::traverseRecursive(BVHNode* node, BVHNode* parent)
{
node->m_parent=parent;
if(node->isLeaf())
{
return;
}
for(int i=0;i<node->getNumChildNodes();i++)
traverseRecursive(node->getChildNode(i), node);
}
inline void SplitBVHBuilder::assignParentPointers(BVHNode* root)
{
if(root!=NULL)
{
traverseRecursive(root, NULL);
}
else
{
cerr<<"Cannot assign parent pointers. Null root. Bailing"<<endl;
exit(1);
}
}
inline void SplitBVHBuilder::bvhToFlatArray(BVHNode * root, int &innerSize, int &leafSize, float*& innerNodes, float*& leafNodes)
{
vector<float> *flat_inner_array = new vector<float>(m_innerNodeCount*16+16);// allocate some space.
//cout<<"Inner node array size "<<m_innerNodeCount*16+1<<endl;
vector<float> *flat_leaf_array = new vector<float>(m_leafNodeCount*(m_platform.getMaxLeafSize()*2+1));
//cout<<"leaf array size "<<m_leafNodeCount*(m_platform.getMaxLeafSize()+1)<<endl;
assignParentPointers(root);
root->m_index = 0;
stack<BVHNode*> tree;
tree.push(root);
BVHNode *current;
int currentIndex = 0;
int currentLeafIndex = -1; //negative values indicate this is a leaf
while(!tree.empty())
{
current = tree.top();
tree.pop();
if(!current->isLeaf())
{
current->m_index = currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(0)->m_bounds.min().x);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(0)->m_bounds.min().y);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(0)->m_bounds.min().z);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(0)->m_bounds.max().x);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(0)->m_bounds.max().y);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(0)->m_bounds.max().z);
++currentIndex;
//cerr<<"bbox 2"<<endl;
flat_inner_array->at(currentIndex) = (current->getChildNode(1)->m_bounds.min().x);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(1)->m_bounds.min().y);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(1)->m_bounds.min().z);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(1)->m_bounds.max().x);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(1)->m_bounds.max().y);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->getChildNode(1)->m_bounds.max().z);
++currentIndex;
//cerr<<"other"<<endl;
flat_inner_array->at(currentIndex) = -1;//leftchild
++currentIndex;
flat_inner_array->at(currentIndex) = -1;//rightchild Index
++currentIndex;
flat_inner_array->at(currentIndex) = -2;//pad
++currentIndex;
flat_inner_array->at(currentIndex) = -2;//pad
++currentIndex;
//cout<<" Done"<<endl;
}
else
{
current->m_index = currentLeafIndex;
flat_leaf_array->at(-currentLeafIndex) = (current->getNumTriangles());
--currentLeafIndex;
LeafNode* leaf = (LeafNode*)current;
for(int i=0; i < leaf->getNumTriangles();i++)
{
flat_leaf_array->at(-currentLeafIndex) = (m_triIndices[leaf->m_lo+i]);
--currentLeafIndex;
}
}
//tell your parent where you are
if(current->m_index != 0) //root has no parents
{
int nodeIdx=0;
if(current->m_index > -1) nodeIdx = current->m_index/4; // this is needed since we are loading the bvh inner nodes as float4s
else nodeIdx = current->m_index;
/* Special case where leaf is only node in the tree (i.e one primitive). Must create parent node so nothing segfaults.*/
if( current->m_parent == NULL)
{
currentIndex = 0;
flat_inner_array->at(currentIndex) = (current->m_bounds.min().x);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->m_bounds.min().y);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->m_bounds.min().z);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->m_bounds.max().x);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->m_bounds.max().y);
++currentIndex;
flat_inner_array->at(currentIndex) = (current->m_bounds.max().z);
++currentIndex;
flat_inner_array->at(currentIndex) = 0; /*TODO: maybe make this some really large value */
++currentIndex;
flat_inner_array->at(currentIndex) = 0;
++currentIndex;
flat_inner_array->at(currentIndex) = 0;
++currentIndex;
flat_inner_array->at(currentIndex) = 0;
++currentIndex;
flat_inner_array->at(currentIndex) = 0;
++currentIndex;
flat_inner_array->at(currentIndex) = 0;
++currentIndex;
flat_inner_array->at(currentIndex)=-1;//leftchild
++currentIndex;
flat_inner_array->at(currentIndex)=-1;//rightchild Index
++currentIndex;
flat_inner_array->at(currentIndex)=-2;//pad
++currentIndex;
flat_inner_array->at(currentIndex)=-2;//pad
++currentIndex;
}
else
{
if(current->m_parent->getChildNode(0) == current)
{
flat_inner_array->at(current->m_parent->m_index+12) = nodeIdx;
}
else if(current->m_parent->getChildNode(1) == current)
{
flat_inner_array->at(current->m_parent->m_index+13) = nodeIdx;
}
}
}
if (current->getChildNode(0)!=NULL) tree.push(current->getChildNode(0));
if (current->getChildNode(1)!=NULL) tree.push(current->getChildNode(1));
}
float *innerraw = new float[currentIndex];
float *leafraw = new float[-currentLeafIndex];
int numLeafVals=-currentLeafIndex;
for (int i = 0; i < currentIndex;i++)
{
innerraw[i] = flat_inner_array->at(i);
}
cout<<endl;
for (int i = 1; i < numLeafVals;i++)
{
leafraw[i - 1] = flat_leaf_array->at(i);
}
cout<<endl;
innerNodes = innerraw;
leafNodes = leafraw;
delete flat_inner_array;
delete flat_leaf_array;
innerSize = currentIndex;
leafSize = numLeafVals;
}
//---------
|
c8863af2a6c2ba44f3ab666a513f10bf02263851 | e10a6d844a286db26ef56469e31dc8488a8c6f0e | /scann/scann/base/single_machine_factory_options.cc | ffc6bb80645e1134e84021d3028fad22835a5463 | [
"Apache-2.0",
"CC-BY-4.0"
] | permissive | Jimmy-INL/google-research | 54ad5551f97977f01297abddbfc8a99a7900b791 | 5573d9c5822f4e866b6692769963ae819cb3f10d | refs/heads/master | 2023-04-07T19:43:54.483068 | 2023-03-24T16:27:28 | 2023-03-24T16:32:17 | 282,682,170 | 1 | 0 | Apache-2.0 | 2020-07-26T15:50:32 | 2020-07-26T15:50:31 | null | UTF-8 | C++ | false | false | 1,389 | cc | single_machine_factory_options.cc | // Copyright 2022 The Google Research 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 "scann/base/single_machine_factory_options.h"
#include "scann/utils/input_data_utils.h"
namespace research_scann {
StatusOr<DatapointIndex> SingleMachineFactoryOptions::ComputeConsistentSize(
const Dataset* dataset) const {
return ComputeConsistentNumPointsFromIndex(dataset, hashed_dataset.get(),
pre_quantized_fixed_point.get(),
crowding_attributes.get());
}
StatusOr<DimensionIndex>
SingleMachineFactoryOptions::ComputeConsistentDimensionality(
const HashConfig& config, const Dataset* dataset) const {
return ComputeConsistentDimensionalityFromIndex(
config, dataset, hashed_dataset.get(), pre_quantized_fixed_point.get());
}
} // namespace research_scann
|
602e9cb12ee16fb131bc3670f6919bad52ee6f95 | b2193143b181c2a4f3e9d1aaba73200fe0eb4948 | /ProcessManager/CMyDialogResource.cpp | 9478c8cfce831b38f0cb5c972f6efb3cd63f85ef | [] | no_license | qpal2837/processManage | 57d6fe9da1d4444d8b1d0abffd2ea1bbc9d46bf4 | 2411e58f4f7e624964167f1b878d0ad933e68e6c | refs/heads/main | 2023-03-26T08:13:18.065940 | 2021-03-30T13:14:02 | 2021-03-30T13:14:02 | 353,004,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,256 | cpp | CMyDialogResource.cpp | // CMyDialogResource.cpp: 实现文件
//
#include "pch.h"
#include "ProcessManager.h"
#include "CMyDialogResource.h"
#include "afxdialogex.h"
// CMyDialogResource 对话框
IMPLEMENT_DYNAMIC(CMyDialogResource, CDialogEx)
CMyDialogResource::CMyDialogResource(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_DIALOG1, pParent) {
}
CMyDialogResource::~CMyDialogResource() {
}
void CMyDialogResource::DoDataExchange(CDataExchange* pDX) {
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_TREE_RE, m_TreeCtrl);
}
BEGIN_MESSAGE_MAP(CMyDialogResource, CDialogEx)
ON_NOTIFY(TVN_SELCHANGED, IDC_TREE_RE, &CMyDialogResource::OnTvnSelchangedTreeRe)
END_MESSAGE_MAP()
// CMyDialogResource 消息处理程序
BOOL CMyDialogResource::OnInitDialog() {
CDialogEx::OnInitDialog();
// TODO: 在此添加额外的初始化
GetInfo();
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
VOID CMyDialogResource::GetInfo() {
GetResourceInfo(&resourceInfo, pPEstruct);
SetDlgItemInt(IDC_EDIT_RENAME, resourceInfo.rootNameCount);
SetDlgItemInt(IDC_EDIT_RE_ID, resourceInfo.rootIdCount);
for (int i = 0; i < resourceInfo.parentArray.size(); i++) {
CString value;
if (resourceInfo.parentArray[i].id == -1) {
value = resourceInfo.parentArray[i].name;
}
else {
value.Format(_T("%d"), resourceInfo.parentArray[i].id);
}
HTREEITEM item = m_TreeCtrl.InsertItem(value);
for (int j = 0; j < resourceInfo.parentArray[i].childArray.size(); j++) {
CString valueB;
if (resourceInfo.parentArray[i].childArray[j].id == -1) {
valueB = resourceInfo.parentArray[i].childArray[j].name;
}
else {
valueB.Format(_T("%d"), resourceInfo.parentArray[i].childArray[j].id);
}
m_TreeCtrl.InsertItem(valueB, item);
}
}
return VOID();
}
void CMyDialogResource::OnTvnSelchangedTreeRe(NMHDR* pNMHDR, LRESULT* pResult) {
LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
// TODO: 在此添加控件通知处理程序代码
HTREEITEM hitem = pNMTreeView->itemNew.hItem;
CString selectValue = m_TreeCtrl.GetItemText(hitem);
for (int i = 0; i < resourceInfo.parentArray.size(); i++) {
CString idValue;
idValue.Format(_T("%d"), resourceInfo.parentArray[i].id);
if (StrCmp(resourceInfo.parentArray[i].name, selectValue) == 0 || StrCmp(idValue, selectValue) == 0) {
SetDlgItemInt(IDC_EDIT_RE_CH_NAME, resourceInfo.parentArray[i].nameItem);
SetDlgItemInt(IDC_EDIT_RE_CH_ID, resourceInfo.parentArray[i].idItem);
break;
}
for (int j = 0; j < resourceInfo.parentArray[i].childArray.size(); j++) {
CString idValueB;
idValueB.Format(_T("%d"), resourceInfo.parentArray[i].childArray[j].id);
if (StrCmp(resourceInfo.parentArray[i].childArray[j].name, selectValue) == 0 || StrCmp(idValueB, selectValue) == 0) {
CString tempValue;
tempValue.Format(_T("%08X"), resourceInfo.parentArray[i].childArray[j].foa);
SetDlgItemText(IDC_EDIT_RE_FOA, tempValue);
tempValue.Format(_T("%08X"), resourceInfo.parentArray[i].childArray[j].rva);
SetDlgItemText(IDC_EDIT_RE_RVA, tempValue);
break;
}
}
}
*pResult = 0;
}
|
205d53d183d998f3aa8af0e41012e5992572361c | 6709d0dce1df61c44e90befdcfba07b100db1f2c | /libTicTacToe/ManualPlayer.h | 9415c7bbf581f36da138adf0625abc60701b2509 | [] | no_license | oclancy/GTest | 850e0fae41fa9eef383c925cc1bc1d214c4f0789 | 13d59485b266a7374ed37a022e3d540e459018ce | refs/heads/master | 2021-01-10T05:47:53.136346 | 2015-10-09T08:01:14 | 2015-10-09T08:01:14 | 43,941,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 486 | h | ManualPlayer.h | #pragma once
#include "Player.h"
namespace libTicTacToe
{
/// <summary>
/// Interactive implementation of CPlayer .
/// </summary>
class CManualPlayer : public CPlayer
{
public:
/// <summary>
/// Initializes a new instance of the <see cref="CManualPlayer"/> class.
/// </summary>
/// <param name="token">The token.</param>
CManualPlayer(char token)
: CPlayer(token)
{}
void TakeTurn(CBoard& board) override final;
void Learn(int reward) override final;
};
} |
d59b6ccb0762199db480b5e33b49815a6a07e91d | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/admin/wmi/wbem/providers/jobobjectprov/factory.cpp | 7bdbf1d6ce735211fcccee03988b23185b84127d | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 6,057 | cpp | factory.cpp | // Copyright (c) 2000-2001 Microsoft Corporation, All Rights Reserved
// Factory.cpp
#include "precomp.h"
#include <iostream.h>
#include <objbase.h>
#include "CUnknown.h"
#include "factory.h"
#include "Registry.h"
// Set static members
LONG CFactory::s_cServerLocks = 0L ; // Count of locks
HMODULE CFactory::s_hModule = NULL ; // DLL module handle
extern CFactoryData g_FactoryDataArray[];
/*****************************************************************************/
// Class factory constructor
/*****************************************************************************/
CFactory::CFactory(const CFactoryData* pFactoryData)
: m_cRef(1)
{
m_pFactoryData = pFactoryData ;
LockServer(TRUE);
}
/*****************************************************************************/
// Class factory IUnknown implementation
/*****************************************************************************/
STDMETHODIMP CFactory::QueryInterface(const IID& iid, void** ppv)
{
if ((iid == IID_IUnknown) || (iid == IID_IClassFactory))
{
*ppv = static_cast<IClassFactory*>(this) ;
}
else
{
*ppv = NULL ;
return E_NOINTERFACE ;
}
reinterpret_cast<IUnknown*>(*ppv)->AddRef() ;
return S_OK ;
}
STDMETHODIMP_(ULONG) CFactory::AddRef()
{
return InterlockedIncrement(&m_cRef) ;
}
STDMETHODIMP_(ULONG) CFactory::Release()
{
if (InterlockedDecrement(&m_cRef) == 0)
{
delete this ;
return 0 ;
}
return m_cRef ;
}
/*****************************************************************************/
// IClassFactory implementation
/*****************************************************************************/
STDMETHODIMP CFactory::CreateInstance(IUnknown* pUnknownOuter,
const IID& iid,
void** ppv)
{
HRESULT hr = S_OK;
// Cannot aggregate.
if (pUnknownOuter != NULL)
{
hr = CLASS_E_NOAGGREGATION;
}
if(SUCCEEDED(hr))
{
// Create component using the specific component's version of CreateInstance.
CUnknown* pNewComponent ;
hr = m_pFactoryData->CreateInstance(&pNewComponent) ;
if(SUCCEEDED(hr))
{
// Initialize the component
hr = pNewComponent->Init();
if(SUCCEEDED(hr))
{
// Get the requested interface.
hr = pNewComponent->QueryInterface(iid, ppv);
}
// Release the IUnknown pointer (the new AND the QI incremented the refcount on SUC.
// (If QueryInterface failed, component will delete itself.)
pNewComponent->Release();
}
}
return hr ;
}
/*****************************************************************************/
// Lock server
/*****************************************************************************/
STDMETHODIMP CFactory::LockServer(BOOL bLock)
{
if (bLock)
{
InterlockedIncrement(&s_cServerLocks) ;
}
else
{
InterlockedDecrement(&s_cServerLocks) ;
}
return S_OK ;
}
/*****************************************************************************/
// GetClassObject - Create a class factory based on a CLSID.
/*****************************************************************************/
HRESULT CFactory::GetClassObject(const CLSID& clsid,
const IID& iid,
void** ppv)
{
HRESULT hr = S_OK;
if ((iid != IID_IUnknown) && (iid != IID_IClassFactory))
{
hr = E_NOINTERFACE ;
}
if(SUCCEEDED(hr))
{
// Traverse the array of data looking for this class ID.
for (int i = 0; i < g_cFactoryDataEntries; i++)
{
if(g_FactoryDataArray[i].IsClassID(clsid))
{
// Found the ClassID in the array of components we can
// create. So create a class factory for this component.
// Pass the CFactoryData structure to the class factory
// so that it knows what kind of components to create.
const CFactoryData* pData = &g_FactoryDataArray[i] ;
CFactory* pFactory = new CFactory(pData);
if (pFactory == NULL)
{
hr = E_OUTOFMEMORY ;
}
else
{
// Get requested interface.
HRESULT hr = pFactory->QueryInterface(iid, ppv);
pFactory->Release();
}
break;
}
}
if(i == g_cFactoryDataEntries)
{
hr = CLASS_E_CLASSNOTAVAILABLE;
}
}
return hr;
}
/*****************************************************************************/
// Register all components.
/*****************************************************************************/
HRESULT CFactory::RegisterAll()
{
for(int i = 0 ; i < g_cFactoryDataEntries ; i++)
{
RegisterServer(s_hModule,
*(g_FactoryDataArray[i].m_pCLSID),
g_FactoryDataArray[i].m_RegistryName,
g_FactoryDataArray[i].m_szVerIndProgID,
g_FactoryDataArray[i].m_szProgID) ;
}
return S_OK ;
}
/*****************************************************************************/
// Un-register all components
/*****************************************************************************/
HRESULT CFactory::UnregisterAll()
{
for(int i = 0 ; i < g_cFactoryDataEntries ; i++)
{
UnregisterServer(*(g_FactoryDataArray[i].m_pCLSID),
g_FactoryDataArray[i].m_szVerIndProgID,
g_FactoryDataArray[i].m_szProgID) ;
}
return S_OK ;
}
/*****************************************************************************/
// Determine if the component can be unloaded.
/*****************************************************************************/
HRESULT CFactory::CanUnloadNow()
{
if (CUnknown::ActiveComponents() || IsLocked())
{
return S_FALSE ;
}
else
{
return S_OK ;
}
}
|
54bea3757a17fe09de80c8d5bc0e76a4fcf627d4 | e6d615cccd0153b15437301374ced513453a7b34 | /header_tupro.h | 7e29292dcbbd45c26adca0827c1d0a586db513bd | [] | no_license | hilaler/breadth-first-search | 03ee2fd14794f3a67ab2556f3631449ed3ccd67e | e2208a2cb14633b3f6c56c7f45c1644809380193 | refs/heads/master | 2022-11-13T12:02:57.773224 | 2020-07-02T15:05:00 | 2020-07-02T15:05:00 | 276,676,102 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,120 | h | header_tupro.h | #ifndef HEADER_TUPRO_H_INCLUDED
#define HEADER_TUPRO_H_INCLUDED
#include <iostream>
#define info_node(P) P->info_node
#define next_node(P) P->next_node
#define first_edge(P) P->first_edge
#define info_edge(P) P->info_edge
#define next_edge(P) P->next_edge
using namespace std;
typedef struct node *adr_node;
typedef struct edge *adr_edge;
typedef adr_node graph;
struct node{
char info_node;
adr_node next_node;
adr_edge first_edge;
};
struct edge{
char info_edge;
adr_edge next_edge;
};
struct Queue{
char info[100];
int tail;
};
struct Visited{
char info[100];
int n;
};
void createGraph(graph &G);
adr_node createNodeElmt(char X);
void insertLast(graph &G, adr_node &P);
adr_node searchNode(graph G, char findInfo);
void addNewNode(graph &G, char X);
adr_edge createEdgeElmt(char X);
void connectNodes(graph &G, char info1, char info2);
void printGraph(graph G);
void addQueue(Queue &Q, char X);
char deleteQueue(Queue &Q);
void addVisited(Visited &V, char X);
bool foundInVisited(Visited V, char X);
void printVisited(Visited V);
void apply_BFS(graph G, char startNode);
#endif |
e3d0b0d4c77075d4bb2e710c141aff7d2cb065a4 | fc0bd48ab30a93dfefa1eebfb17c2dd808a264c2 | /BOJ_2437_저울.cpp | 663c3ebba8d9bb34b490672e83f33d544c277743 | [] | no_license | IceStove/Algo | 403d12e22974d84480b6ceab3f72774f8983f885 | 6c66dc6c977493ca5b047bcacbbb4f8cd536c90a | refs/heads/master | 2022-12-02T01:44:29.112669 | 2022-11-23T05:46:02 | 2022-11-23T05:46:02 | 213,150,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 923 | cpp | BOJ_2437_저울.cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <stack>
#define MAX 1002
using namespace std;
int chu[MAX];
int N;
int Answer = -1;
void printChu() {
for (int i = 0; i < N; i++) {
printf("%d ", chu[i]);
}
printf("\n");
}
int main(void) {
scanf("%d", &N);
for (int i = 0; i < N; i++) {
scanf("%d", &chu[i]);
}
// 정렬
// 첫번째 인자는 시작지점 = 배열의 포인터
// 두번째 인자는 끝나는 지점 + 1 = chu(배열의 포인터) + 배열의 크기
sort(chu, chu+N);
/*
printf("\n");
printChu();
printf("\n");
*/
int sum = chu[0];
if (chu[0] != 1) {
Answer = 1;
}
else {
for (int i = 1; i < N; i++) {
if (sum+1 >= chu[i]) { // 가능한 것
sum += chu[i];
}
else {
Answer = sum + 1;
break;
}
}
}
if (Answer == -1) {
Answer = sum + 1;
}
printf("%d \n", Answer);
return 0;
} |
03e50dbf9d9273419f43e58c93d1811568a73712 | b3adba10b38f27086b856c45f59eefce7ee91c82 | /Demo008/src/AfRegionSelector.h | ac66e9bb253410c737f07ddca62e126c0bd7648b | [] | no_license | DLily0129/QtProjects | 927f750b573df0addee4a3d912004767688c89f9 | f29b86230f850ffede5b9273817302dae3a88080 | refs/heads/master | 2021-01-11T22:16:53.625465 | 2017-02-06T14:56:56 | 2017-02-06T14:56:56 | 78,942,293 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 946 | h | AfRegionSelector.h | #ifndef _REGION_SELECTOR_H
#define _REGION_SELECTOR_H
#include <QDialog>
#include <QtGui>
#include <QtGui/QPixmap>
/* AfRegionSelector
图像区域选择器。加载一个图像,选择一个区域。
作者:邵发
版本: 2016-03-14
官网: http://afanihao.cn
本代码为 C/C++学习指南(实战篇) 官方示例代码,最新版本请到官网下载
*/
class AfRegionSelector : public QDialog
{
Q_OBJECT
public:
AfRegionSelector(const QPixmap& screen, QWidget *parent = 0);
~AfRegionSelector();
private:
virtual void paintEvent(QPaintEvent *event);
virtual void mouseMoveEvent ( QMouseEvent * event );
virtual void mousePressEvent ( QMouseEvent * event );
virtual void mouseReleaseEvent ( QMouseEvent * event );
private:
QPixmap m_image;
QSound m_shutter; // 快门声
QPoint m_start, m_end;
QPoint m_pos;
bool m_dragging;
public:
QRect selectRegion; // 输出选中的区域
};
#endif // RegionSelector_H
|
57da6788a53359218f5ad99f27480601ab54e832 | d924cea389a79904e54c9f3fb77a93569c0b0342 | /lab11/Arduino-master/libraries/Radar/radar.h | 85ac60afb8226dbfc5089b3277b80c545e9211e8 | [
"MIT"
] | permissive | ianchen0119/IoTDevicesPlatforms | 7c33ff33baa889c31928f2092d5d37c8368e9c8c | 9f53f8685c0a27e99f5f7607dc0e8192b2abd2d4 | refs/heads/master | 2023-03-02T14:44:45.622695 | 2021-02-08T15:07:06 | 2021-02-08T15:07:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,069 | h | radar.h | #pragma once
//
// FILE: radar.h
// AUTHOR: Rob Tillaart
// VERSION: see RADAR_LIB_VERSION
// PURPOSE: Arduino library for a pan tilt radar.
// URL: https://github.com/RobTillaart/RADAR
#include "Arduino.h"
#define RADAR_LIB_VERSION "0.1.3"
#ifndef RADAR_POSITIONS
#define RADAR_POSITIONS 10
#endif
class RADAR
{
public:
RADAR(const uint8_t, const uint8_t);
// no valid range checking or negative value check.
void setPanPerSecond(float pps) { _panPerSecond = pps; };
float getPanPerSecond() { return _panPerSecond; };
void setTiltPerSecond(float tps) { _tiltPerSecond = tps; };
float getTiltPerSecond() { return _tiltPerSecond; };
// basic moves
void gotoPan(const int16_t pan);
int16_t getPan();
void gotoTilt(const int16_t tilt);
int16_t getTilt();
void gotoPanTilt(const int16_t pan, const int16_t tilt);
// memory positions - store / recall?
uint8_t getMaxPositions() { return RADAR_POSITIONS; };
bool setPosition(const uint8_t idx, const int16_t pan, const int16_t tilt);
bool getPosition(const uint8_t idx, int16_t & pan, int16_t & tilt);
bool gotoPosition(const uint8_t idx);
void setHomePosition(const int16_t pan, const int16_t tilt);
void gotoHomePosition();
// feedback on positions.
bool isMoving() { return isPanMoving() || isTiltMoving(); };
bool isPanMoving() { return getPan() != _pan; };
bool isTiltMoving() { return getTilt() != _tilt; };
uint32_t ping();
uint32_t ping(const int16_t pan, const int16_t tilt);
private:
int16_t _pinPan;
int16_t _pinTilt;
int16_t _prevPan;
int16_t _pan;
int16_t _homePan;
uint32_t _lastPanTime;
int16_t _prevTilt;
int16_t _tilt;
int16_t _homeTilt;
uint32_t _lastTiltTime;
int16_t _panArray[RADAR_POSITIONS];
int16_t _tiltArray[RADAR_POSITIONS];
float _panPerSecond = 15;
float _tiltPerSecond = 15;
};
// -- END OF FILE -- |
6032f3077cf63c442424f818662954d66429fd78 | 72852e07bb30adbee608275d6048b2121a5b9d82 | /algorithms/problem_1766/other3.cpp | c86d6f8cccc928959edcea2e26a2015582f40518 | [] | no_license | drlongle/leetcode | e172ae29ea63911ccc3afb815f6dbff041609939 | 8e61ddf06fb3a4fb4a4e3d8466f3367ee1f27e13 | refs/heads/master | 2023-01-08T16:26:12.370098 | 2023-01-03T09:08:24 | 2023-01-03T09:08:24 | 81,335,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,657 | cpp | other3.cpp | class Solution {
public:
int _gcd(int a, int b){
int temp;
while(b){
temp = a%b;
a = b;
b = temp;
}
return a;
}
void find(vector<vector<int>> &data, vector<int>& nums, vector<int>& ans,
vector<bool> &check, vector<vector<int>> &gcd, int index, vector<int> &val){
// update answer for all value after this node
vector<int> next(51, index);
for(int n : gcd[nums[index]]){
next[n] = val[n];
}
ans[index] = val[nums[index]];
// prevent repeat
check[index] = true;
// next node
for(int i=0 ; i<data[index].size() ; i++){
if(check[data[index][i]]== false){
find(data, nums, ans, check, gcd, data[index][i], next);
}
}
}
vector<int> getCoprimes(vector<int>& nums, vector<vector<int>>& edges) {
vector<int> ans(nums.size(), -1);
vector<int> val(51, -1);
vector<bool> check(nums.size(), false);
vector<vector<int>> data(nums.size(), vector<int>());
vector<vector<int>> gcd(51, vector<int>());
// pre compute gcd for all value
for(int i=1 ; i<51 ; i++){
for(int j=i ; j<51 ; j++){
if(_gcd(i, j) != 1){
gcd[i].push_back(j);
gcd[j].push_back(i);
}
}
}
// build graph
for(auto &e:edges){
data[e[0]].push_back(e[1]);
data[e[1]].push_back(e[0]);
}
find(data, nums, ans, check, gcd, 0, val);
return ans;
}
};
|
5232d2ca0642b40d4a83efafd7cce99ce12e94f9 | 69baadee0f95c51da12530e6db67a1fb993ebe0d | /Engine.cpp | 0d84e829f171e0d08868c719e5477962bd3c7aae | [] | no_license | Dule17/Chess | 9c451f2a0895949827614472b860d9898966c937 | 8eccf4a9c38b5c94b80f69904841a33bdec8fc0a | refs/heads/master | 2023-06-17T01:46:37.405970 | 2021-07-07T06:33:57 | 2021-07-07T06:33:57 | 383,698,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129,852 | cpp | Engine.cpp | #include<GL\glew.h>
#include "Engine.h"
Engine::Engine()
{
tabla_n=8;
igra_u_toku=0;
pocetna_pozicija_i=-1,pocetna_pozicija_j=-1;
tacka_x,tacka_z;
igrac_igra=1;
beli_sah=0;
crni_sah=0;
beli_broj_poteza=0;
crni_broj_poteza=0;
partija_broj=1;
}
void Engine::createFrameBufferObject(int WindowWidth,int WindowHeight )
{
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
// Create the texture object for the primitive information buffer
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, WindowWidth, WindowHeight,
0, GL_RGB, GL_FLOAT, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
texture, 0);
// Create the texture object for the depth buffer
glGenTextures(1, &depthTexture);
glBindTexture(GL_TEXTURE_2D, depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, WindowWidth, WindowHeight,
0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
depthTexture, 0);
// Disable reading to avoid problems with older GPUs
glReadBuffer(GL_NONE);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
// Restore the default framebuffer
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
Engine::~Engine(void)
{
}
void Engine::postaviFigure()
{
for(int i=0;i<tabla_n;i++)
for(int j=0;j<tabla_n;j++)
{
tabla[i][j].figura=NULL;
Vector3D d1((tabla[i][j].t1.m_x+tabla[i][j].t2.m_x)/2,0,(tabla[i][j].t1.m_z+tabla[i][j].t4.m_z)/2);
if(i==1)tabla[i][j].figura=new Pesak(20,0.5,0.3,0.1,0.2,0.3,0.6,d1,1);
if(i==6)tabla[i][j].figura=new Pesak(20,0.5,0.3,0.1,0.2,0.3,0.6,d1,0);
if((i==0&&j==0)||(i==0&&j==7))tabla[i][j].figura=new Top(20,0.5,0.3,0.2,0.4,0.3,0.3,0.6,0.1,0.2,d1,1);
if((i==7&&j==0)||(i==7&&j==7))tabla[i][j].figura=new Top(20,0.5,0.3,0.2,0.4,0.3,0.3,0.6,0.1,0.2,d1,0);
if((i==0&&j==2)||(i==0&&j==5))tabla[i][j].figura=new Lovac(20,0.5,0.3,0.2,0.15,0.3,0.6,d1,1);
if((i==7&&j==2)||(i==7&&j==5))tabla[i][j].figura=new Lovac(20,0.5,0.3,0.2,0.15,0.3,0.6,d1,0);
if(i==0&&j==3)tabla[i][j].figura=new Kraljica(20,0.5,0.4,0.3,0.2,0.3,0.6,d1,1);
if(i==7&&j==3)tabla[i][j].figura=new Kraljica(20,0.5,0.4,0.3,0.2,0.3,0.6,d1,0);
if(i==0&&j==4)tabla[i][j].figura=new Kralj(20,0.5,0.4,0.3,0.2,0.3,0.6,d1,1);
if(i==7&&j==4)tabla[i][j].figura=new Kralj(20,0.5,0.4,0.3,0.2,0.3,0.6,d1,0);
if((i==0&&j==1)||(i==0&&j==6))tabla[i][j].figura=new Konj(20,0.5,d1,1);
if((i==7&&j==1)||(i==7&&j==6))tabla[i][j].figura=new Konj(20,0.5,d1,0);
}
}
void Engine::createTabla()
{
glGenTextures(1,&tablaTexture);
int width, height;
unsigned char* image;
glBindTexture(GL_TEXTURE_2D, tablaTexture);
image = SOIL_load_image("tabla.jpg", &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,GL_UNSIGNED_BYTE, image);
SOIL_free_image_data(image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
tabla.resize(tabla_n);
for(int i=0;i<tabla_n;i++)tabla[i].resize(tabla_n);
int br;
for(int i=0;i<tabla_n;i++)
{
for(int j=0;j<tabla_n;j++)
{
tabla[i][j].t1.Set(j,0,-i);
tabla[i][j].t2.Set(j+1,0,-i);
tabla[i][j].t3.Set(j+1,0,-i-1);
tabla[i][j].t4.Set(j,0,-i-1);
br=10+i*10+j;
tabla[i][j].r=(br & 0x000000FF) >> 0;
tabla[i][j].g = (br & 0x0000FF00) >> 8;
tabla[i][j].b = (br & 0x00FF0000) >> 16;
}
}
Matrix4x4 mt;
mt.loadTranslate(-tabla_n/2,0,tabla_n/2);
for(int i=0;i<tabla_n;i++)
for(int j=0;j<tabla_n;j++)
{
tabla[i][j].t1=mt*tabla[i][j].t1;
tabla[i][j].t2=mt*tabla[i][j].t2;
tabla[i][j].t3=mt*tabla[i][j].t3;
tabla[i][j].t4=mt*tabla[i][j].t4;
}
postaviFigure();
}
void Engine::drawTabla(int ind)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
if(ind==1)
{
for(int i=0;i<tabla_n;i++)
for(int j=0;j<tabla_n;j++)
{
glColor3f(tabla[i][j].r/255.0f,tabla[i][j].g/255.0f, tabla[i][j].b/255.0f);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
}
}
else
{
glColor3f(1,1,1);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, tablaTexture);
float x=5.0;
float y=4.97;
glBegin(GL_QUADS);
glTexCoord2f(0,1);
glVertex3f(-x,-0.01,-y);
glTexCoord2f(1,1);
glVertex3f(-x,-0.01,y);
glTexCoord2f(1,0);
glVertex3f(x,-0.01,y);
glTexCoord2f(0,0);
glVertex3f(x,-0.01,-y);
glEnd();
glDisable(GL_TEXTURE_2D);
}
}
void Engine::drawFigure(int ind)
{
glColor3f(1,1,1);
for(int i=0;i<tabla_n;i++)
for(int j=0;j<tabla_n;j++)if(tabla[i][j].figura!=NULL)
{
if(ind==1)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(tabla[i][j].r/255.0f,tabla[i][j].g/255.0f, tabla[i][j].b/255.0f);
tabla[i][j].figura->DrawPicker();
}
else tabla[i][j].figura->Draw();
}
}
void Engine::drawMogucniPokreti()
{
if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Pesak")==0)
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind==0)
{
if(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_z);
glEnd();
if(pocetna_pozicija_i == 6&&tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].figura==NULL)
{
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j].t4.m_z);
glEnd();
}
}
if(pocetna_pozicija_j>0&&tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].figura!=NULL&&tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].figura->ind!=tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
if(pocetna_pozicija_j<tabla_n-1&&tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].figura!=NULL&&tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].figura->ind!=tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
}
else
{
if(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_z);
glEnd();
if(pocetna_pozicija_i == 1&&tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].figura==NULL)
{
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j].t4.m_z);
glEnd();
}
}
if(pocetna_pozicija_j>0&&tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].figura!=NULL&&tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].figura->ind!=tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
if(pocetna_pozicija_j<tabla_n-1&&tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].figura!=NULL&&tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].figura->ind!=tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
}
}
if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Top")==0)
{
for(int i=pocetna_pozicija_i+1;i<tabla_n;i++)
{
if(tabla[i][pocetna_pozicija_j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
}
if(tabla[i][pocetna_pozicija_j].figura!=NULL)
{
if(tabla[i][pocetna_pozicija_j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
break;
}
}
for(int i=pocetna_pozicija_i-1;i>-1;i--)
{
if(tabla[i][pocetna_pozicija_j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
}
if(tabla[i][pocetna_pozicija_j].figura!=NULL)
{
if(tabla[i][pocetna_pozicija_j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
break;
}
}
for(int j=pocetna_pozicija_j+1;j<tabla_n;j++)
{
if(tabla[pocetna_pozicija_i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
}
if(tabla[pocetna_pozicija_i][j].figura!=NULL)
{
if(tabla[pocetna_pozicija_i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
break;
}
}
for(int j=pocetna_pozicija_j-1;j>-1;j--)
{
if(tabla[pocetna_pozicija_i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
}
if(tabla[pocetna_pozicija_i][j].figura!=NULL)
{
if(tabla[pocetna_pozicija_i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
break;
}
}
}
if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Lovac")==0)
{
int i=pocetna_pozicija_i+1;
int j=pocetna_pozicija_j+1;
while(i<tabla_n&&j<tabla_n)
{
if(tabla[i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
}
if(tabla[i][j].figura!=NULL)
{
if(tabla[i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
break;
}
i++;
j++;
}
i=pocetna_pozicija_i-1;
j=pocetna_pozicija_j-1;
while(i>=0&&j>=0)
{
if(tabla[i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
}
if(tabla[i][j].figura!=NULL)
{
if(tabla[i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
break;
}
i--;
j--;
}
i=pocetna_pozicija_i+1;
j=pocetna_pozicija_j-1;
while(i<tabla_n&&j>=0)
{
if(tabla[i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
}
if(tabla[i][j].figura!=NULL)
{
if(tabla[i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
break;
}
i++;
j--;
}
i=pocetna_pozicija_i-1;
j=pocetna_pozicija_j+1;
while(i>=0&&j<tabla_n)
{
if(tabla[i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
}
if(tabla[i][j].figura!=NULL)
{
if(tabla[i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
break;
}
i--;
j++;
}
}
if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Kraljica")==0)
{
for(int i=pocetna_pozicija_i+1;i<tabla_n;i++)
{
if(tabla[i][pocetna_pozicija_j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
}
if(tabla[i][pocetna_pozicija_j].figura!=NULL)
{
if(tabla[i][pocetna_pozicija_j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
break;
}
}
for(int i=pocetna_pozicija_i-1;i>-1;i--)
{
if(tabla[i][pocetna_pozicija_j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
}
if(tabla[i][pocetna_pozicija_j].figura!=NULL)
{
if(tabla[i][pocetna_pozicija_j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][pocetna_pozicija_j].t1.m_x,tabla[i][pocetna_pozicija_j].t1.m_y,tabla[i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t2.m_x,tabla[i][pocetna_pozicija_j].t2.m_y,tabla[i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t3.m_x,tabla[i][pocetna_pozicija_j].t3.m_y,tabla[i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[i][pocetna_pozicija_j].t4.m_x,tabla[i][pocetna_pozicija_j].t4.m_y,tabla[i][pocetna_pozicija_j].t4.m_z);
glEnd();
break;
}
}
for(int j=pocetna_pozicija_j+1;j<tabla_n;j++)
{
if(tabla[pocetna_pozicija_i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
}
if(tabla[pocetna_pozicija_i][j].figura!=NULL)
{
if(tabla[pocetna_pozicija_i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
break;
}
}
for(int j=pocetna_pozicija_j-1;j>-1;j--)
{
if(tabla[pocetna_pozicija_i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
}
if(tabla[pocetna_pozicija_i][j].figura!=NULL)
{
if(tabla[pocetna_pozicija_i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][j].t1.m_x,tabla[pocetna_pozicija_i][j].t1.m_y,tabla[pocetna_pozicija_i][j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t2.m_x,tabla[pocetna_pozicija_i][j].t2.m_y,tabla[pocetna_pozicija_i][j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t3.m_x,tabla[pocetna_pozicija_i][j].t3.m_y,tabla[pocetna_pozicija_i][j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][j].t4.m_x,tabla[pocetna_pozicija_i][j].t4.m_y,tabla[pocetna_pozicija_i][j].t4.m_z);
glEnd();
break;
}
}
int i=pocetna_pozicija_i+1;
int j=pocetna_pozicija_j+1;
while(i<tabla_n&&j<tabla_n)
{
if(tabla[i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
}
if(tabla[i][j].figura!=NULL)
{
if(tabla[i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
break;
}
i++;
j++;
}
i=pocetna_pozicija_i-1;
j=pocetna_pozicija_j-1;
while(i>=0&&j>=0)
{
if(tabla[i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
}
if(tabla[i][j].figura!=NULL)
{
if(tabla[i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
break;
}
i--;
j--;
}
i=pocetna_pozicija_i+1;
j=pocetna_pozicija_j-1;
while(i<tabla_n&&j>=0)
{
if(tabla[i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
}
if(tabla[i][j].figura!=NULL)
{
if(tabla[i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
break;
}
i++;
j--;
}
i=pocetna_pozicija_i-1;
j=pocetna_pozicija_j+1;
while(i>=0&&j<tabla_n)
{
if(tabla[i][j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
}
if(tabla[i][j].figura!=NULL)
{
if(tabla[i][j].figura->ind==tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind)break;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[i][j].t1.m_x,tabla[i][j].t1.m_y,tabla[i][j].t1.m_z);
glVertex3f(tabla[i][j].t2.m_x,tabla[i][j].t2.m_y,tabla[i][j].t2.m_z);
glVertex3f(tabla[i][j].t3.m_x,tabla[i][j].t3.m_y,tabla[i][j].t3.m_z);
glVertex3f(tabla[i][j].t4.m_x,tabla[i][j].t4.m_y,tabla[i][j].t4.m_z);
glEnd();
break;
}
i--;
j++;
}
}
if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Kralj")==0)
{
if(pocetna_pozicija_i<tabla_n-1)
{
if(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_z);
glEnd();
}
else
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j].t4.m_z);
glEnd();
}
}
}
if(pocetna_pozicija_i<tabla_n-1&&pocetna_pozicija_j<tabla_n-1)
{
if(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
else
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
}
}
if(pocetna_pozicija_i<tabla_n-1&&pocetna_pozicija_j>0)
{
if(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
else
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
}
}
if(pocetna_pozicija_i>0)
{
if(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_z);
glEnd();
}
else
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j].t4.m_z);
glEnd();
}
}
}
if(pocetna_pozicija_i>0&&pocetna_pozicija_j<tabla_n-1)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
if(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
else
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
}
}
if(pocetna_pozicija_i>0&&pocetna_pozicija_j>0)
{
if(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
else
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
}
}
if(pocetna_pozicija_j<tabla_n-1)
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
else
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
}
}
if(pocetna_pozicija_j>0)
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].figura==NULL)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t4.m_z);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
else
{
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
}
}
if(pocetna_pozicija_j+3<tabla_n&&(pocetna_pozicija_i==0||pocetna_pozicija_i==7)&&tabla[pocetna_pozicija_i][pocetna_pozicija_j+1].figura==NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j+2].figura==NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].figura!=NULL)
{
if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].figura).name(),"class Top")==0)
{
glColor3f(0.3,0.3,0.9);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t1.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t1.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t2.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t2.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t3.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t3.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t4.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t4.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j+3].t4.m_z);
glEnd();
}
}
if(pocetna_pozicija_j-3>-1&&(pocetna_pozicija_i==0||pocetna_pozicija_i==7)&&tabla[pocetna_pozicija_i][pocetna_pozicija_j-1].figura==NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j-2].figura==NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].figura!=NULL)
{
if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].figura).name(),"class Top")==0)
{
glColor3f(0.3,0.3,0.9);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t1.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t1.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t2.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t2.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t3.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t3.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t4.m_x,tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t4.m_y,tabla[pocetna_pozicija_i][pocetna_pozicija_j-3].t4.m_z);
glEnd();
}
}
}
if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Konj")==0)
{
//--------------------------NAPRED
if((pocetna_pozicija_i+2<tabla_n&&pocetna_pozicija_j+1<tabla_n)&&tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].figura==NULL)
{
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i+2<tabla_n&&pocetna_pozicija_j+1<tabla_n)&&tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].figura!=NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i+2<tabla_n&&pocetna_pozicija_j-1>-1)&&tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].figura==NULL)
{
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i+2<tabla_n&&pocetna_pozicija_j-1>-1)&&tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].figura!=NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i+2][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
//-----------------------------------Nazad
if((pocetna_pozicija_i-2>-1&&pocetna_pozicija_j+1<tabla_n)&&tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].figura==NULL)
{
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i-2>-1&&pocetna_pozicija_j+1<tabla_n)&&tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].figura!=NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t1.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t1.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t2.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t2.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t3.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t3.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t4.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t4.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j+1].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i-2>-1&&pocetna_pozicija_j-1>-1)&&tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].figura==NULL)
{
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i-2>-1&&pocetna_pozicija_j-1>-1)&&tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].figura!=NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t1.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t1.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t2.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t2.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t3.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t3.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t4.m_x,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t4.m_y,tabla[pocetna_pozicija_i-2][pocetna_pozicija_j-1].t4.m_z);
glEnd();
}
//-----------------------------------------DESNO
if((pocetna_pozicija_i+1<tabla_n&&pocetna_pozicija_j+2<tabla_n)&&tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].figura==NULL)
{
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i+1<tabla_n&&pocetna_pozicija_j+2<tabla_n)&&tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].figura!=NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j+2].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i-1>-1&&pocetna_pozicija_j+2<tabla_n)&&tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].figura==NULL)
{
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i-1>-1&&pocetna_pozicija_j+2<tabla_n)&&tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].figura!=NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j+2].t4.m_z);
glEnd();
}
//-----------------------------------------------------LEVO
if((pocetna_pozicija_i+1<tabla_n&&pocetna_pozicija_j-2>-1)&&tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].figura==NULL)
{
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i+1<tabla_n&&pocetna_pozicija_j-2>-1)&&tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].figura!=NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t1.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t1.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t2.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t2.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t3.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t3.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t4.m_x,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t4.m_y,tabla[pocetna_pozicija_i+1][pocetna_pozicija_j-2].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i-1>-1&&pocetna_pozicija_j-2>-1)&&tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].figura==NULL)
{
glColor3f(0.6,0.9,0.6);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t4.m_z);
glEnd();
}
if((pocetna_pozicija_i-1>-1&&pocetna_pozicija_j-2>-1)&&tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].figura!=NULL&&tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura->ind!=tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].figura->ind)
{
glColor3f(0.9,0.5,0.5);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t1.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t1.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t2.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t2.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t3.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t3.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t4.m_x,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t4.m_y,tabla[pocetna_pozicija_i-1][pocetna_pozicija_j-2].t4.m_z);
glEnd();
}
}
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glColor3f(0, 1, 0);
glBegin(GL_POLYGON);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j].t1.m_x, tabla[pocetna_pozicija_i][pocetna_pozicija_j].t1.m_y, tabla[pocetna_pozicija_i][pocetna_pozicija_j].t1.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j].t2.m_x, tabla[pocetna_pozicija_i][pocetna_pozicija_j].t2.m_y, tabla[pocetna_pozicija_i][pocetna_pozicija_j].t2.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j].t3.m_x, tabla[pocetna_pozicija_i][pocetna_pozicija_j].t3.m_y, tabla[pocetna_pozicija_i][pocetna_pozicija_j].t3.m_z);
glVertex3f(tabla[pocetna_pozicija_i][pocetna_pozicija_j].t4.m_x, tabla[pocetna_pozicija_i][pocetna_pozicija_j].t4.m_y, tabla[pocetna_pozicija_i][pocetna_pozicija_j].t4.m_z);
glEnd();
}
void Engine::drawIspis()
{
/* glColor3f(0.7,0.7,0.7);
glBegin(GL_POLYGON);
glVertex3f(0.65,1,0);
glVertex3f(1,1,0);
glVertex3f(1,0,0);
glVertex3f(0.65,0,0);
glEnd();
glBegin(GL_POLYGON);
glVertex3f(-0.65,1,0);
glVertex3f(-1,1,0);
glVertex3f(-1,0,0);
glVertex3f(-0.65,0,0);
glEnd();
glColor3f(0,0,0);
char s[50];
if(igrac_igra==1)
{
sprintf_s(s,"Igrac 1\n\n\n Beli\n Igraj");
}else sprintf_s(s,"Igrac 1\n\n\n Beli\n Cekaj");
glRasterPos2f(-0.9,0.8);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(const unsigned char*) s);
if(igrac_igra==0)
{
sprintf_s(s,"Igrac 2\n\n\n Crni\n Igraj");
}else sprintf_s(s,"Igrac 2\n\n\n Crni\n Cekaj");
glRasterPos2f(0.75,0.8);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(const unsigned char*) s);
if(beli_sah>0)
{
glColor3f(1,0,0);
sprintf_s(s,"Sah");
glRasterPos2f(-0.9,0.1);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(const unsigned char*) s);
}
if(crni_sah>0)
{
glColor3f(1,0,0);
sprintf_s(s,"Sah");
glRasterPos2f(0.8,0.1);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(const unsigned char*) s);
}*/
glColor3f(0.7,0.7,0.7);
glBegin(GL_POLYGON);
glVertex3f(-1,-0.85,0);
glVertex3f(1,-0.85,0);
glVertex3f(1,-1,0);
glVertex3f(-1,-1,0);
glEnd();
glBegin(GL_POLYGON);
glVertex3f(-1,0.85,0);
glVertex3f(1,0.85,0);
glVertex3f(1,1,0);
glVertex3f(-1,1,0);
glEnd();
glColor3f(0,0,0);
char s[50];
if(igrac_igra==1)
{
sprintf_s(s," Igrac 1\t\t\t Beli\t Na potezu");
}else sprintf_s(s," Igrac 1\t\t\t Beli\t Cekaj");
glRasterPos2f(-0.9,-0.95);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(const unsigned char*) s);
if(igrac_igra==0)
{
sprintf_s(s," Igrac 2\t\t\t Crni\t Na potezu");
}else sprintf_s(s," Igrac 2\t\t\t Crni\t Cekaj");
glRasterPos2f(-0.9,0.9);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(const unsigned char*) s);
if(beli_sah>0)
{
glColor3f(1,0,0);
sprintf_s(s,"Sah");
glRasterPos2f(0.6,-0.95);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(const unsigned char*) s);
}
if(crni_sah>0)
{
glColor3f(1,0,0);
sprintf_s(s,"Sah");
glRasterPos2f(0.6,0.9);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(const unsigned char*) s);
}
}
void Engine::proveriSah()
{
glColor3f(1,0,0);
for(int i=0;i<tabla_n;i++)
for(int j=0;j<tabla_n;j++)
{
if(tabla[i][j].figura!=NULL&&strcmp(typeid(*tabla[i][j].figura).name(),"class Kralj")==0)
{
int sah=0;
//-GORE
for(int k=i+1;k<tabla_n;k++)
if(tabla[k][j].figura!=NULL)
{
if(tabla[k][j].figura->ind!=tabla[i][j].figura->ind)
{
if(strcmp(typeid(*tabla[k][j].figura).name(),"class Kralj")==0&&abs(k-i)==1)sah++;
if(strcmp(typeid(*tabla[k][j].figura).name(),"class Kraljica")==0)sah++;
if(strcmp(typeid(*tabla[k][j].figura).name(),"class Top")==0)sah++;
}
break;
}
//-DOLE
for(int k=i-1;k>-1;k--)
if(tabla[k][j].figura!=NULL)
{
if(tabla[k][j].figura->ind!=tabla[i][j].figura->ind)
{
if(strcmp(typeid(*tabla[k][j].figura).name(),"class Kralj")==0&&abs(k-i)==1)sah++;
if(strcmp(typeid(*tabla[k][j].figura).name(),"class Kraljica")==0)sah++;
if(strcmp(typeid(*tabla[k][j].figura).name(),"class Top")==0)sah++;
}
break;
}
//-DESNO
for(int k=j+1;k<tabla_n;k++)
if(tabla[i][k].figura!=NULL)
{
if(tabla[i][k].figura->ind!=tabla[i][j].figura->ind)
{
if(strcmp(typeid(*tabla[i][k].figura).name(),"class Kralj")==0&&abs(k-i)==1)sah++;
if(strcmp(typeid(*tabla[i][k].figura).name(),"class Kraljica")==0)sah++;
if(strcmp(typeid(*tabla[i][k].figura).name(),"class Top")==0)sah++;
}
break;
}
//-LEVO
for(int k=j-1;k>-1;k--)
if(tabla[i][k].figura!=NULL)
{
if(tabla[i][k].figura->ind!=tabla[i][j].figura->ind)
{
if(strcmp(typeid(*tabla[i][k].figura).name(),"class Kralj")==0&&abs(k-i)==1)sah++;
if(strcmp(typeid(*tabla[i][k].figura).name(),"class Kraljica")==0)sah++;
if(strcmp(typeid(*tabla[i][k].figura).name(),"class Top")==0)sah++;
}
break;
}
//GORE-DESNO
int k=i+1;
int l=j+1;
while(k<tabla_n&&l<tabla_n)
{
if(tabla[k][l].figura!=NULL)
{
if(tabla[k][l].figura->ind!=tabla[i][j].figura->ind)
{
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Pesak")==0&&abs(k-i)==1&&abs(l-j)==1&&tabla[k][l].figura->ind==0)sah++;
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Kraljica")==0)sah++;
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Lovac")==0)sah++;
}
break;
}
k++;
l++;
}
//GORE-Levo
k=i+1;
l=j-1;
while(k<tabla_n&&l>-1)
{
if(tabla[k][l].figura!=NULL)
{
if(tabla[k][l].figura->ind!=tabla[i][j].figura->ind)
{
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Pesak")==0&&abs(k-i)==1&&abs(l-j)==1&&tabla[k][l].figura->ind==0)sah++;
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Kraljica")==0)sah++;
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Lovac")==0)sah++;
}
break;
}
k++;
l--;
}
//DOLE-Levo
k=i-1;
l=j-1;
while(k>-1&&l>-1)
{
if(tabla[k][l].figura!=NULL)
{
if(tabla[k][l].figura->ind!=tabla[i][j].figura->ind)
{
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Pesak")==0&&abs(k-i)==1&&abs(l-j)==1&&tabla[k][l].figura->ind==1)sah++;
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Kraljica")==0)sah++;
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Lovac")==0)sah++;
}
break;
}
k--;
l--;
}
//Dole-Desno
k=i-1;
l=j+1;
while(k>-1&&l<tabla_n)
{
if(tabla[k][l].figura!=NULL)
{
if(tabla[k][l].figura->ind!=tabla[i][j].figura->ind)
{
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Pesak")==0&&abs(k-i)==1&&abs(l-j)==1&&tabla[k][l].figura->ind==1)sah++;
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Kraljica")==0)sah++;
if(strcmp(typeid(*tabla[k][l].figura).name(),"class Lovac")==0)sah++;
}
break;
}
k--;
l++;
}
//Konj-Gore-Dole
k=i+2;
l=j+1;
if(k<tabla_n&&l<tabla_n&&tabla[k][l].figura!=NULL&&tabla[k][l].figura->ind!=tabla[i][j].figura->ind&&strcmp(typeid(*tabla[k][l].figura).name(),"class Konj")==0)sah++;
k=i+2;
l=j-1;
if(k<tabla_n&&l>-1&&tabla[k][l].figura!=NULL&&tabla[k][l].figura->ind!=tabla[i][j].figura->ind&&strcmp(typeid(*tabla[k][l].figura).name(),"class Konj")==0)sah++;
k=i-2;
l=j-1;
if(k>-1&&l>-1&&tabla[k][l].figura!=NULL&&tabla[k][l].figura->ind!=tabla[i][j].figura->ind&&strcmp(typeid(*tabla[k][l].figura).name(),"class Konj")==0)sah++;
k=i-2;
l=j+1;
if(k>-1&&l<tabla_n&&tabla[k][l].figura!=NULL&&tabla[k][l].figura->ind!=tabla[i][j].figura->ind&&strcmp(typeid(*tabla[k][l].figura).name(),"class Konj")==0)sah++;
//Konj-Levo-Desno
k=i+1;
l=j+2;
if(k<tabla_n&&l<tabla_n&&tabla[k][l].figura!=NULL&&tabla[k][l].figura->ind!=tabla[i][j].figura->ind&&strcmp(typeid(*tabla[k][l].figura).name(),"class Konj")==0)sah++;
k=i-1;
l=j+2;
if(k>-1&&l<tabla_n&&tabla[k][l].figura!=NULL&&tabla[k][l].figura->ind!=tabla[i][j].figura->ind&&strcmp(typeid(*tabla[k][l].figura).name(),"class Konj")==0)sah++;
k=i+1;
l=j-2;
if(k<tabla_n&&l>-1&&tabla[k][l].figura!=NULL&&tabla[k][l].figura->ind!=tabla[i][j].figura->ind&&strcmp(typeid(*tabla[k][l].figura).name(),"class Konj")==0)sah++;
k=i-1;
l=j-2;
if(k>-1&&l>-1&&tabla[k][l].figura!=NULL&&tabla[k][l].figura->ind!=tabla[i][j].figura->ind&&strcmp(typeid(*tabla[k][l].figura).name(),"class Konj")==0)sah++;
if(sah>0)
{
if(tabla[i][j].figura->ind==1)beli_sah++;
else crni_sah++;
if(beli_sah==2)
{
igra_u_toku=1;
cout<<"Pobedio IGRAC 1-Crni\n"<<endl;
}
if(crni_sah==2)
{
igra_u_toku=1;
cout<<"Pobedio IGRAC 2-Beli\n"<<endl;
}
}else
{
if(tabla[i][j].figura->ind==1)beli_sah=0;
else crni_sah=0;
}
}
}
}
void Engine::PomeriPesak(int i, int j, int jedi_j, int k)
{
Vector3D pomeraj;
Figura *pom1;
Figura *pom2;
pom1 = tabla[i][j].figura;
pom2 = tabla[k][jedi_j].figura;
if (tabla[i][j].figura->ind == 0)
{
if (abs(k - i) == 1)
{
if (tabla[i - 1][j].figura == NULL && j == jedi_j && k < i)
{
pomeraj.Set(0, 0, 1);
tabla[i][j].figura->Move(pomeraj);
tabla[i - 1][j].figura = tabla[i][j].figura;
tabla[i][j].figura = NULL;
if (i - 1 == 0)
{
Vector3D d1((tabla[i - 1][jedi_j].t1.m_x + tabla[i - 1][jedi_j].t2.m_x) / 2, 0, (tabla[i - 1][jedi_j].t1.m_z + tabla[i - 1][j].t4.m_z) / 2);
tabla[i - 1][jedi_j].figura = new Kraljica(20, 0.5, 0.4, 0.3, 0.2, 0.3, 0.6, d1, 0);
}
}
if (j != jedi_j && tabla[i - 1][jedi_j].figura != NULL && k < i&&tabla[i - 1][jedi_j].figura->ind == 1)
{
if (jedi_j > j)pomeraj.Set(1, 0, 1);
else pomeraj.Set(-1, 0, 1);
tabla[i][j].figura->Move(pomeraj);
tabla[i - 1][jedi_j].figura = tabla[i][j].figura;
tabla[i][j].figura = NULL;
if (i - 1 == 0)
{
Vector3D d1((tabla[i - 1][jedi_j].t1.m_x + tabla[i - 1][jedi_j].t2.m_x) / 2, 0, (tabla[i - 1][jedi_j].t1.m_z + tabla[i - 1][j].t4.m_z) / 2);
tabla[i - 1][jedi_j].figura = new Kraljica(20, 0.5, 0.4, 0.3, 0.2, 0.3, 0.6, d1, 0);
}
}
}
else if (tabla[i - 1][j].figura == NULL && jedi_j == j && tabla[k][j].figura == NULL && k < i&&i == 6)
{
pomeraj.Set(0, 0, i - k);
tabla[i][j].figura->Move(pomeraj);
tabla[k][j].figura = tabla[i][j].figura;
tabla[i][j].figura = NULL;
}
}
else
{
if (abs(k - i) == 1)
{
if (tabla[i + 1][j].figura == NULL && j == jedi_j && k > i)
{
pomeraj.Set(0, 0, -1);
tabla[i][j].figura->Move(pomeraj);
tabla[i + 1][j].figura = tabla[i][j].figura;
tabla[i][j].figura = NULL;
if (i + 1 == tabla_n - 1)
{
Vector3D d1((tabla[i + 1][jedi_j].t1.m_x + tabla[i + 1][jedi_j].t2.m_x) / 2, 0, (tabla[i + 1][jedi_j].t1.m_z + tabla[i + 1][j].t4.m_z) / 2);
tabla[i + 1][jedi_j].figura = new Kraljica(20, 0.5, 0.4, 0.3, 0.2, 0.3, 0.6, d1, 1);
}
}
if (j != jedi_j && tabla[i + 1][jedi_j].figura != NULL && k > i&&tabla[i + 1][jedi_j].figura->ind == 0)
{
if (jedi_j > j)pomeraj.Set(1, 0, -1);
else pomeraj.Set(-1, 0, -1);
tabla[i][j].figura->Move(pomeraj);
tabla[i + 1][jedi_j].figura = tabla[i][j].figura;
tabla[i][j].figura = NULL;
if (i + 1 == tabla_n - 1)
{
Vector3D d1((tabla[i + 1][jedi_j].t1.m_x + tabla[i + 1][jedi_j].t2.m_x) / 2, 0, (tabla[i + 1][jedi_j].t1.m_z + tabla[i + 1][j].t4.m_z) / 2);
tabla[i + 1][jedi_j].figura = new Kraljica(20, 0.5, 0.4, 0.3, 0.2, 0.3, 0.6, d1, 1);
}
}
if (tabla[i + 1][j].figura == NULL && jedi_j == j && tabla[k][j].figura == NULL && beli_broj_poteza == 0)
{
pomeraj.Set(0, 0, k - j);
tabla[i][j].figura->Move(pomeraj);
tabla[k][j].figura = tabla[i][j].figura;
tabla[i][j].figura = NULL;
}
}
else if (tabla[i + 1][j].figura == NULL && jedi_j == j && tabla[k][j].figura == NULL && k > i&&i == 1)
{
pomeraj.Set(0, 0, i - k);
tabla[i][j].figura->Move(pomeraj);
tabla[k][j].figura = tabla[i][j].figura;
tabla[i][j].figura = NULL;
}
}
if (tabla[i][j].figura == NULL)
{
proveriSah();
if (pom1->ind == 0 && crni_sah == 1)
{
pomeraj = pomeraj * (-1);
tabla[k][jedi_j].figura->Move(pomeraj);
crni_sah = 0;
tabla[i][j].figura = pom1;
tabla[k][jedi_j].figura = pom2;
}
if (pom1->ind == 1 && beli_sah == 1)
{
pomeraj = pomeraj * (-1);
tabla[k][jedi_j].figura->Move(pomeraj);
beli_sah = 0;
tabla[i][j].figura = pom1;
tabla[k][jedi_j].figura = pom2;
}
}
}
void Engine::PomeriTop(int i,int j,int k_i,int k_j)
{
Vector3D pomeraj;
Figura *pom1;
Figura *pom2;
pom1=tabla[i][j].figura;
pom2=tabla[k_i][k_j].figura;
if(i==k_i)
{
int test=0;
if(k_j>j)for(int k=j+1;k<=k_j;k++)if(tabla[i][k].figura!=NULL){test++;}
if(k_j<j)for(int k=j-1;k>=k_j;k--)if(tabla[i][k].figura!=NULL){test++;}
if(tabla[k_i][k_j].figura!=NULL&&test==1&&tabla[i][j].figura->ind!=tabla[k_i][k_j].figura->ind)test=0;
if(test==0)
{
pomeraj.Set(k_j-j,0,0);
tabla[i][j].figura->Move(pomeraj);
tabla[i][k_j].figura=tabla[i][j].figura;
tabla[i][j].figura=NULL;
}
}
if(j==k_j)
{
int test=0;
if(k_i>i)for(int k=i+1;k<=k_i;k++)if(tabla[k][j].figura!=NULL){test++;}
if(k_i<i)for(int k=i-1;k>=k_i;k--)if(tabla[k][j].figura!=NULL){test++;}
if(tabla[k_i][k_j].figura!=NULL&&test==1&&tabla[i][j].figura->ind!=tabla[k_i][k_j].figura->ind)test=0;
if(test==0)
{
pomeraj.Set(0,0,-(k_i-i));
tabla[i][j].figura->Move(pomeraj);
tabla[k_i][j].figura=tabla[i][j].figura;
tabla[i][j].figura=NULL;
}
}
if (tabla[i][j].figura == NULL)
{
proveriSah();
if (pom1->ind == 0 && crni_sah == 1)
{
pomeraj = pomeraj * (-1);
tabla[k_i][k_j].figura->Move(pomeraj);
crni_sah = 0;
tabla[i][j].figura = pom1;
tabla[k_i][k_j].figura = pom2;
}
if (pom1->ind == 1 && beli_sah == 1)
{
pomeraj = pomeraj * (-1);
tabla[k_i][k_j].figura->Move(pomeraj);
beli_sah = 0;
tabla[i][j].figura = pom1;
tabla[k_i][k_j].figura = pom2;
}
}
}
void Engine::PomeriLovac(int i,int j, int k_i,int k_j)
{
Vector3D pomeraj;
Figura *pom1;
Figura *pom2;
pom1=tabla[i][j].figura;
pom2=tabla[k_i][k_j].figura;
int test=0;
int k,g;
k=i+1;
g=j+1;
if(i<k_i&&j<k_j) while(k<=k_i&&g<=k_j)
{
if(tabla[k][g].figura!=NULL){test++;}
k++;
g++;
}
k=i-1;
g=j+1;
if(i>k_i&&j<k_j) while(k>=k_i&&g<=k_j)
{
if(tabla[k][g].figura!=NULL){test++;}
k--;
g++;
}
k=i-1;
g=j-1;
if(i>k_i&&j>k_j) while(k>=k_i&&g>=k_j)
{
if(tabla[k][g].figura!=NULL){test++;}
k--;
g--;
}
k=i+1;
g=j-1;
if(i<k_i&&j>k_j) while(k<=k_i&&g>=k_j)
{
if(tabla[k][g].figura!=NULL){test++;}
k++;
g--;
}
if(tabla[k_i][k_j].figura!=NULL&&test==1&&tabla[i][j].figura->ind!=tabla[k_i][k_j].figura->ind)test=0;
if(test==0)
{
if((i<k_i&&j<k_j)||(i>k_i&&j>k_j))pomeraj.Set((k_i-i),0,-(k_j-j));
else pomeraj.Set(-(k_i-i),0,(k_j-j));
tabla[i][j].figura->Move(pomeraj);
tabla[k_i][k_j].figura=tabla[i][j].figura;
tabla[i][j].figura=NULL;
}
if (tabla[i][j].figura == NULL)
{
proveriSah();
if (pom1->ind == 0 && crni_sah == 1)
{
pomeraj = pomeraj * (-1);
tabla[k_i][k_j].figura->Move(pomeraj);
crni_sah = 0;
tabla[i][j].figura = pom1;
tabla[k_i][k_j].figura = pom2;
}
if (pom1->ind == 1 && beli_sah == 1)
{
pomeraj = pomeraj * (-1);
tabla[k_i][k_j].figura->Move(pomeraj);
beli_sah = 0;
tabla[i][j].figura = pom1;
tabla[k_i][k_j].figura = pom2;
}
}
}
void Engine::PomeriKralja_i_Kraljicu(int i,int j,int k_i,int k_j)
{
Vector3D pomeraj;
Figura *pom1;
Figura *pom2;
pom1=tabla[i][j].figura;
pom2=tabla[k_i][k_j].figura;
if(i!=k_i&&j!=k_j)
{
int test=0;
int k,g;
k=i+1;
g=j+1;
if(i<k_i&&j<k_j) while(k<=k_i&&g<=k_j)
{
if(tabla[k][g].figura!=NULL){test++;}
k++;
g++;
}
k=i-1;
g=j+1;
if(i>k_i&&j<k_j) while(k>=k_i&&g<=k_j)
{
if(tabla[k][g].figura!=NULL){test++;}
k--;
g++;
}
k=i-1;
g=j-1;
if(i>k_i&&j>k_j) while(k>=k_i&&g>=k_j)
{
if(tabla[k][g].figura!=NULL){test++;}
k--;
g--;
}
k=i+1;
g=j-1;
if(i<k_i&&j>k_j) while(k<=k_i&&g>=k_j)
{
if(tabla[k][g].figura!=NULL){test++;}
k++;
g--;
}
if(tabla[k_i][k_j].figura!=NULL&&test==1&&tabla[i][j].figura->ind!=tabla[k_i][k_j].figura->ind)test=0;
if(test==0)
{
if((i<k_i&&j<k_j)||(i>k_i&&j>k_j))pomeraj.Set((k_i-i),0,-(k_j-j));
else pomeraj.Set(-(k_i-i),0,(k_j-j));
tabla[i][j].figura->Move(pomeraj);
tabla[k_i][k_j].figura=tabla[i][j].figura;
tabla[i][j].figura=NULL;
}
}
else
{
if(i==k_i)
{
int test=0;
if(k_j>j)for(int k=j+1;k<=k_j;k++)if(tabla[i][k].figura!=NULL){test++;}
if(k_j<j)for(int k=j-1;k>=k_j;k--)if(tabla[i][k].figura!=NULL){test++;}
if(tabla[k_i][k_j].figura!=NULL&&test==1&&tabla[i][j].figura->ind!=tabla[k_i][k_j].figura->ind)test=0;
if(test==0)
{
pomeraj.Set(k_j-j,0,0);
tabla[i][j].figura->Move(pomeraj);
tabla[i][k_j].figura=tabla[i][j].figura;
tabla[i][j].figura=NULL;
}
}
if(j==k_j)
{
int test=0;
if(k_i>i)for(int k=i+1;k<=k_i;k++)if(tabla[k][j].figura!=NULL){test++;}
if(k_i<i)for(int k=i-1;k>=k_i;k--)if(tabla[k][j].figura!=NULL){test++;}
if(tabla[k_i][k_j].figura!=NULL&&test==1&&tabla[i][j].figura->ind!=tabla[k_i][k_j].figura->ind)test=0;
if(test==0)
{
pomeraj.Set(0,0,-(k_i-i));
tabla[i][j].figura->Move(pomeraj);
tabla[k_i][j].figura=tabla[i][j].figura;
tabla[i][j].figura=NULL;
}
}
}
if (tabla[i][j].figura == NULL)
{
proveriSah();
if (pom1->ind == 0 && crni_sah == 1)
{
pomeraj = pomeraj * (-1);
tabla[k_i][k_j].figura->Move(pomeraj);
crni_sah = 0;
tabla[i][j].figura = pom1;
tabla[k_i][k_j].figura = pom2;
}
if (pom1->ind == 1 && beli_sah == 1)
{
pomeraj = pomeraj * (-1);
tabla[k_i][k_j].figura->Move(pomeraj);
beli_sah = 0;
tabla[i][j].figura = pom1;
tabla[k_i][k_j].figura = pom2;
}
}
}
void Engine::PomeriKonja(int i,int j,int k_i,int k_j)
{
Figura *pom1;
Figura *pom2;
pom1=tabla[i][j].figura;
pom2=tabla[k_i][k_j].figura;
if(tabla[k_i][k_j].figura!=NULL&&tabla[k_i][k_j].figura->ind==tabla[i][j].figura->ind)return;
Vector3D pomeraj;
pomeraj.Set((k_j-j),0,-(k_i-i));
tabla[i][j].figura->Move(pomeraj);
tabla[k_i][k_j].figura=tabla[i][j].figura;
tabla[i][j].figura=NULL;
if (tabla[i][j].figura == NULL)
{
proveriSah();
if (pom1->ind == 0 && crni_sah == 1)
{
pomeraj = pomeraj * (-1);
tabla[k_i][k_j].figura->Move(pomeraj);
crni_sah = 0;
tabla[i][j].figura = pom1;
tabla[k_i][k_j].figura = pom2;
}
if (pom1->ind == 1 && beli_sah == 1)
{
pomeraj = pomeraj * (-1);
tabla[k_i][k_j].figura->Move(pomeraj);
beli_sah = 0;
tabla[i][j].figura = pom1;
tabla[k_i][k_j].figura = pom2;
}
}
}
void Engine::Zamena(int i,int j,int K_i,int k_j)
{
Figura *pom1;
Figura *pom2;
pom1 = tabla[i][j].figura;
pom2 = tabla[K_i][k_j].figura;
Vector3D pomeraj;
if(i==0||i==7)
{
if(k_j>j)
{
if(tabla[i][j+1].figura==NULL&&tabla[i][j+2].figura==NULL)
{
pomeraj.Set(2,0,0);
tabla[i][j].figura->Move(pomeraj);
pomeraj.Set(-2,0,0);
tabla[i][k_j].figura->Move(pomeraj);
tabla[i][j+1].figura=tabla[K_i][k_j].figura;
tabla[i][j+2].figura=tabla[i][j].figura;
tabla[i][j].figura=NULL;
tabla[i][k_j].figura=NULL;
}
}
else
{
if(tabla[i][j-1].figura==NULL&&tabla[i][j-2].figura==NULL)
{
pomeraj.Set(-2,0,0);
tabla[i][j].figura->Move(pomeraj);
pomeraj.Set(+2,0,0);
tabla[i][k_j].figura->Move(pomeraj);
tabla[i][j-1].figura=tabla[K_i][k_j].figura;
tabla[i][j-2].figura=tabla[i][j].figura;
tabla[i][j].figura=NULL;
tabla[i][k_j].figura=NULL;
}
}
}
if (tabla[i][j].figura == NULL)
{
proveriSah();
if (pom1->ind == 0 && crni_sah == 1)
{
if (k_j > j)
{
tabla[i][j + 2].figura->Move(pomeraj);
tabla[i][j + 2].figura = NULL;
pomeraj = pomeraj * (-1);
tabla[i][j + 1].figura->Move(pomeraj);
tabla[i][j + 1].figura = NULL;
}
else
{
tabla[i][j - 2].figura->Move(pomeraj);
tabla[i][j - 2].figura = NULL;
pomeraj = pomeraj * (-1);
tabla[i][j - 1].figura->Move(pomeraj);
tabla[i][j - 1].figura = NULL;
}
crni_sah = 0;
tabla[i][j].figura = pom1;
tabla[K_i][k_j].figura = pom2;
}
if (pom1->ind == 1 && beli_sah == 1)
{
if (k_j > j)
{
tabla[i][j + 2].figura->Move(pomeraj);
tabla[i][j + 2].figura = NULL;
pomeraj = pomeraj * (-1);
tabla[i][j + 1].figura->Move(pomeraj);
tabla[i][j + 1].figura = NULL;
}
else
{
tabla[i][j - 2].figura->Move(pomeraj);
tabla[i][j - 2].figura = NULL;
pomeraj = pomeraj * (-1);
tabla[i][j - 1].figura->Move(pomeraj);
tabla[i][j - 1].figura = NULL;
}
beli_sah = 0;
tabla[i][j].figura = pom1;
tabla[K_i][k_j].figura = pom2;
}
}
}
void Engine::ispisPobednika()
{
glColor3f(0.7,0.7,0.7);
glBegin(GL_POLYGON);
glVertex3f(-0.5,0.5,0);
glVertex3f(0.5,0.5,0);
glVertex3f(0.5,-0.5,0);
glVertex3f(-0.5,-0.5,0);
glEnd();
glColor3f(0.2,0.2,0.7);
if(crni_sah==2)
{
char s[200];
sprintf_s(s," Partija broj:%d\n Sah-mat u %d poteza\n Pobednik\n Igrac 1 - Beli\n\n Za novu igru pritisni R ",partija_broj,beli_broj_poteza);
glRasterPos2f(-0.4,0.3);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(const unsigned char*) s);
}
if(beli_sah==2)
{
char s[200];
sprintf_s(s," Partija broj:%d\n Sah-mat u %d poteza\n Pobednik\n Igrac 2 - Crni\n\n Za novu igru pritisni R ",partija_broj,crni_broj_poteza);
glRasterPos2f(-0.4,0.3);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(const unsigned char*) s);
}
}
void Engine::Proveri(int x,int y,int mode)
{
int i, j;
if (mode == 0)
{
unsigned char res[4];
GLint viewport[4];
glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo);
glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
glGetIntegerv(GL_VIEWPORT, viewport);
glReadPixels(x, viewport[3] - y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &res);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
i = res[0] / 10 - 1;
j = res[0] % 10;
if (res[0] == 0)
{
//pocetna_pozicija_i=-1;
//pocetna_pozicija_j=-1;
return;
}
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble posX, posY, posZ;
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
Vector4D proba;
winX = (float)x;
winY = (float)viewport[3] - (float)y;
glReadPixels(x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);
//if(posX>0.65&&posY>0)return;
//if(posX<-0.65&&posY>0)return;
if (posY >= 0.85 || posY <= -0.85)return;
}
else
{
i = x;
j = y;
}
if(tabla[i][j].figura!=NULL&&tabla[i][j].figura->ind==igrac_igra)
{
if (pocetna_pozicija_i!=-1&&tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura != NULL && strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(), "class Kralj") == 0 && abs(j - pocetna_pozicija_j) == 3 && pocetna_pozicija_i == i && strcmp(typeid(*tabla[i][j].figura).name(), "class Top") == 0)
{
Zamena(pocetna_pozicija_i, pocetna_pozicija_j, i, j);
if (tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura == NULL && igrac_igra == 1)
{
igrac_igra = 0;
beli_broj_poteza++;
pocetna_pozicija_i = -1;
pocetna_pozicija_j = -1;
}
else if (tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura == NULL && igrac_igra == 0)
{
igrac_igra = 1;
crni_broj_poteza++;
pocetna_pozicija_i = -1;
pocetna_pozicija_j = -1;
}
else
{
pocetna_pozicija_i = i;
pocetna_pozicija_j = j;
}
}
else
{
pocetna_pozicija_i = i;
pocetna_pozicija_j = j;
}
}
else if(pocetna_pozicija_i!=-1)
{
if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Pesak")==0)
{
if(abs(i-pocetna_pozicija_i)==1||abs(i-pocetna_pozicija_i)==2)
{
if(tabla[i][j].figura!=NULL&&strcmp(typeid(*tabla[i][j].figura).name(),"class Kralj")!=0)PomeriPesak(pocetna_pozicija_i,pocetna_pozicija_j,j,i);
if(tabla[i][j].figura==NULL)PomeriPesak(pocetna_pozicija_i,pocetna_pozicija_j,j,i);
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==1)
{
igrac_igra=0;
beli_broj_poteza++;
}
else if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==0)
{
igrac_igra=1;
crni_broj_poteza++;
}
}
}
else if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Top")==0)
{
if((pocetna_pozicija_i!=i&&pocetna_pozicija_j==j)||(pocetna_pozicija_j!=j&&pocetna_pozicija_i==i))
{
if(tabla[i][j].figura!=NULL&&strcmp(typeid(*tabla[i][j].figura).name(),"class Kralj")!=0)PomeriTop(pocetna_pozicija_i,pocetna_pozicija_j,i,j);
if(tabla[i][j].figura==NULL)PomeriTop(pocetna_pozicija_i,pocetna_pozicija_j,i,j);
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==1)
{
igrac_igra=0;
beli_broj_poteza++;
}
else if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==0)
{
igrac_igra=1;
crni_broj_poteza++;
}
}
}
else if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Lovac")==0)
{
if(pocetna_pozicija_i!=i&&pocetna_pozicija_j!=j&&(abs(pocetna_pozicija_i-i)==abs(pocetna_pozicija_j-j)))
{
if(tabla[i][j].figura!=NULL&&strcmp(typeid(*tabla[i][j].figura).name(),"class Kralj")!=0)PomeriLovac(pocetna_pozicija_i,pocetna_pozicija_j,i,j);
if(tabla[i][j].figura==NULL)PomeriLovac(pocetna_pozicija_i,pocetna_pozicija_j,i,j);
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==1)
{
igrac_igra=0;
beli_broj_poteza++;
}
else if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==0)
{
igrac_igra=1;
crni_broj_poteza++;
}
}
}
else if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Kraljica")==0)
{
if(((pocetna_pozicija_i!=i&&pocetna_pozicija_j==j)||(pocetna_pozicija_j!=j&&pocetna_pozicija_i==i))||(pocetna_pozicija_i!=i&&pocetna_pozicija_j!=j&&(abs(pocetna_pozicija_i-i)==abs(pocetna_pozicija_j-j))))
{
if(tabla[i][j].figura!=NULL&&strcmp(typeid(*tabla[i][j].figura).name(),"class Kralj")!=0)PomeriKralja_i_Kraljicu(pocetna_pozicija_i,pocetna_pozicija_j,i,j);
if(tabla[i][j].figura==NULL)PomeriKralja_i_Kraljicu(pocetna_pozicija_i,pocetna_pozicija_j,i,j);
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==1)
{
igrac_igra=0;
beli_broj_poteza++;
}
else if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==0)
{
igrac_igra=1;
crni_broj_poteza++;
}
}
}
else if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Kralj")==0)
{
if((((pocetna_pozicija_i!=i&&pocetna_pozicija_j==j)||(pocetna_pozicija_j!=j&&pocetna_pozicija_i==i))||(pocetna_pozicija_i!=i&&pocetna_pozicija_j!=j&&(abs(pocetna_pozicija_i-i)==abs(pocetna_pozicija_j-j))))&&(abs(i-pocetna_pozicija_i)<=1)&&(abs(j-pocetna_pozicija_j)<=1))
{
if(tabla[i][j].figura!=NULL&&strcmp(typeid(*tabla[i][j].figura).name(),"class Kralj")!=0)PomeriKralja_i_Kraljicu(pocetna_pozicija_i,pocetna_pozicija_j,i,j);
if(tabla[i][j].figura==NULL)PomeriKralja_i_Kraljicu(pocetna_pozicija_i,pocetna_pozicija_j,i,j);
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==1)
{
igrac_igra=0;
beli_broj_poteza++;
}
else if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==0)
{
igrac_igra=1;
crni_broj_poteza++;
}
}
}
else if(strcmp(typeid(*tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura).name(),"class Konj")==0)
{
if((abs(i-pocetna_pozicija_i)==2&&abs(pocetna_pozicija_j-j)==1)||(abs(i-pocetna_pozicija_i)==1&&abs(pocetna_pozicija_j-j)==2))
{
if(tabla[i][j].figura!=NULL&&strcmp(typeid(*tabla[i][j].figura).name(),"class Kralj")!=0)PomeriKonja(pocetna_pozicija_i,pocetna_pozicija_j,i,j);
if(tabla[i][j].figura==NULL)PomeriKonja(pocetna_pozicija_i,pocetna_pozicija_j,i,j);
if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==1)
{
igrac_igra=0;
beli_broj_poteza++;
}
else if(tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura==NULL&&igrac_igra==0)
{
igrac_igra=1;
crni_broj_poteza++;
}
}
}
if (tabla[pocetna_pozicija_i][pocetna_pozicija_j].figura == NULL)
{
pocetna_pozicija_i = -1;
pocetna_pozicija_j = -1;
}
}
glutPostRedisplay();
} |
3053bc59fecc24064475757e0f41a372fd52b074 | 232406e50d8de38ad18c68a05fba451712e6ed09 | /dp/扑克牌中的顺子.cpp | 2d653c9995402ddf3cd6673f0c50088a71bb2b95 | [] | no_license | fee1ng/Leetcode | 7dbac681d189b90a8c09fd4f191323eaa00529a5 | a90c860cd978909fad8a5a4a3a2533e9540144a1 | refs/heads/main | 2023-06-30T21:04:52.419038 | 2021-07-25T13:54:34 | 2021-07-25T13:54:34 | 362,314,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 879 | cpp | 扑克牌中的顺子.cpp | class Solution {
public:
bool isStraight(vector<int>& nums) {
int f1 = 0;
sort(nums.begin(), nums.end());
for (int i = 0;i < 4;i++)
{
if (nums[i] == 0)
{
f1++;
continue;
}
if (nums[i] == nums[i + 1])
return false;
if (nums[i] + 1 != nums[i + 1])
{
if (nums[i + 1] - nums[i] > 3)
return false;
if (f1)
{
if (f1 == 1 && nums[i] + 2 != nums[i + 1])
return false;
//else if(f1==2&&nums[i]+3!=nums[i+1])
//return false;
f1--;
}
else
return false;
}
}
return true;
}
}; |
b130180957b61c1cabf4568b8cea25bf6cb61765 | fca377708b3aada87d65e1358ec5305a069d48cd | /ConsoleApp_C++/ProjektCPP_PO/Serie.h | 1b8cdab36ea45d97bccfd01409a06613f1e2f5ba | [] | no_license | Simon13ws/Uni_Classes_Projects | d20ab2571e6cd10254609d721689fde609dd90c7 | ddbbe32868c9cb4332dcad1b9ba266f296ad8c86 | refs/heads/master | 2020-05-02T06:00:08.631577 | 2019-05-17T09:27:13 | 2019-05-17T09:27:13 | 177,784,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | h | Serie.h | #pragma once
#include "Video.h"
class Serie : public Video {
int episodes=0;
int seasons=0;
public:
int IMDB_rank = 0;
Serie(); //Konstruktor, w ktorym uzytkownik jest pytany po kolei o dane do kazdego pola w obiekcie (poza statusem watched, ktory mozna zmienic w edycji)
Serie(char); //Do tworzenia pustego obiektu
void save(ofstream&);
void load(ifstream&);
void showInfo(); //Wyswietlanie informacji o serialu
void edit();
string type();
};
|
3b9bdbb3f885423d4340cee5b3bb9d67d25b715d | 583b2b81e0e7ac3c910bc00204f877aa9c48bdae | /Analysis/TagAndProbe/test/TurnOnPlotMacro.cpp | 8316f5d2340c1482cee88fae8d1a56b54764bfc8 | [] | no_license | danielwinterbottom/ICHiggsTauTau | 8c88a3322c8e362114a53c559634a7ecceb266d2 | 69f6b580ec1faa4e5b6ef931be880f939f409979 | refs/heads/master | 2023-09-01T17:49:18.865198 | 2023-02-07T13:14:15 | 2023-02-07T13:14:15 | 10,723,688 | 4 | 12 | null | 2023-09-07T08:41:44 | 2013-06-16T18:08:22 | Python | UTF-8 | C++ | false | false | 3,802 | cpp | TurnOnPlotMacro.cpp | #include "TFile.h"
#include "TCanvas.h"
#include "TH1.h"
#include "TGraphErrors.h"
//#include "triggerEff_mine.C"
#include "TF1.h"
#include "TMath.h"
#include "TLegend.h"
#include "boost/lexical_cast.hpp"
#include <string>
#include "UserCode/ICHiggsTauTau/Analysis/Core/interface/Plot.h"
double efficiency(double m, double m0, double sigma, double alpha, double n, double norm)
{
const double sqrtPiOver2 = 1.2533141373;
const double sqrt2 = 1.4142135624;
double sig = fabs((double) sigma);
double t = (m - m0)/sig ;
if (alpha < 0)
t = -t;
double absAlpha = fabs(alpha / sig);
double a = TMath::Power(n/absAlpha,n)*exp(-0.5*absAlpha*absAlpha);
double b = absAlpha - n/absAlpha;
// if (a>=std::numeric_limits<double>::max()) return -1. ;
double ApproxErf ;
double arg = absAlpha / sqrt2 ;
if (arg > 5.) ApproxErf = 1 ;
else if (arg < -5.) ApproxErf = -1 ;
else ApproxErf = TMath::Erf(arg) ;
double leftArea = (1 + ApproxErf) * sqrtPiOver2 ;
double rightArea = ( a * 1/TMath::Power(absAlpha - b,n-1)) / (n - 1);
double area = leftArea + rightArea;
if ( t <= absAlpha ){
arg = t / sqrt2 ;
if (arg > 5.) ApproxErf = 1 ;
else if (arg < -5.) ApproxErf = -1 ;
else ApproxErf = TMath::Erf(arg) ;
return norm * (1 + ApproxErf) * sqrtPiOver2 / area ;
}
else{
return norm * (leftArea + a * (1/TMath::Power(t-b,n-1) - 1/TMath::Power(absAlpha - b,n-1)) / (1 - n)) / area ;
}
}
Double_t eff(Double_t *x, Double_t *par) {
Double_t xx = x[0];
Double_t m0 = par[0];
Double_t sigma = par[1];
Double_t alpha = par[2];
Double_t n = par[3];
Double_t norm = par[4];
return efficiency(xx,m0,sigma,alpha,n,norm);
}
int main(int argc, char* argv[]){
// Give argument info to user
std::cout << "Arguments passed to program: " << argc << std::endl;
for (int i = 0; i < argc; ++i){
std::cout << i << "\t" << argv[i] << std::endl;
}
if (argc != 8){
std::cerr << "Need 2 args: <filepath> <B/E/Eb> <par1> <par2> <par3> <par4> <par5>" << std::endl;
exit(1);
}
ic::Plot::SetTdrStyle();
std::string barrel=boost::lexical_cast<std::string>(argv[2]);
TFile* file2=new TFile(argv[1]);
TFile* output=new TFile("output.root", "RECREATE");
output->cd();
TF1 *myfit=NULL;
if(barrel=="B")
{
myfit= (TF1*)file2->Get("fitGraph1");
}
if(barrel=="E")
{
myfit= (TF1*)file2->Get("fitGraph2");
}
if(barrel=="Eb")
{
myfit= (TF1*)file2->Get("fitGraph3");
}
//myfit->SetLineColor(kBlue);
TF1* testfit;
testfit = new TF1("testfit", eff, 10., 80., 5);
double p1, p2, p3, p4, p5;
p1=boost::lexical_cast<double>(argv[3]);
p2=boost::lexical_cast<double>(argv[4]);
p3=boost::lexical_cast<double>(argv[5]);
p4=boost::lexical_cast<double>(argv[6]);
p5=boost::lexical_cast<double>(argv[7]);
testfit->SetParameters(p1, p2, p3, p4, p5);
TCanvas* canvas = new TCanvas("canvas", "canvas", 200,10, 700, 500);
TH1F* base = new TH1F("base", "base" , 100, 0 ,80);
TGraphErrors* gr = (TGraphErrors*)file2->Get("Graph");
base->GetXaxis()->SetTitle("p_{T} GeV");
base->GetYaxis()->SetTitle("Efficiency");
base->SetTitle(0);
base->SetStats(0);
base->Draw();
testfit->SetLineColor(kRed);
testfit->Draw("same");
gr->SetMarkerColor(1);
gr->Draw("Psame");
myfit->SetLineColor(kGreen+1);
myfit->Draw("same");
TLegend * legend = new TLegend(0.6, 0.45, 0.75, 0.60);
legend->AddEntry(testfit, "Test fit", "l");
legend->AddEntry(myfit, "My fit", "l");
legend->AddEntry(gr, "Data", "p");
legend->Draw();
canvas->Update();
canvas->Write();
output->Close();
return 0;
}
|
b4473be8b013425de51873c875d27d418ebaa5e3 | 01e21d29af961df02e516e729c26c381ce1d485d | /modules/squarepine_core/text/LanguageHandler.cpp | fa337169a200287d5880c32c2d2a629e9f9f2a68 | [
"ISC"
] | permissive | thinium/squarepine_core | 1f92848d668b9af48124e24891c2e1b85fe74532 | 9d73b0820b8b44129b62a643785e8a7d4a7035b0 | refs/heads/main | 2023-07-16T04:30:09.089866 | 2021-08-06T14:25:10 | 2021-08-06T14:25:10 | 383,528,340 | 0 | 0 | NOASSERTION | 2021-07-06T16:10:59 | 2021-07-06T16:10:58 | null | UTF-8 | C++ | false | false | 7,964 | cpp | LanguageHandler.cpp | namespace
{
const auto languageFileExtension = String (".language");
}
//==============================================================================
LanguageCode getLanguageCodeFromISO6391 (const String& s)
{
if (s.equalsIgnoreCase ("en")) return LanguageCode::eng;
if (s.equalsIgnoreCase ("fr")) return LanguageCode::fre;
if (s.equalsIgnoreCase ("es")) return LanguageCode::spa;
if (s.equalsIgnoreCase ("eo")) return LanguageCode::epo;
if (s.equalsIgnoreCase ("pt")) return LanguageCode::por;
if (s.equalsIgnoreCase ("de")) return LanguageCode::deu;
if (s.equalsIgnoreCase ("nl")) return LanguageCode::nld;
// "klingon", tlh // ISO 639-1 is not available.
return LanguageCode::unknown;
}
LanguageCode getLanguageCodeFromISO6392 (const String& s)
{
if (s.equalsIgnoreCase ("eng")) return LanguageCode::eng;
if (s.equalsIgnoreCase ("fre")) return LanguageCode::fre;
if (s.equalsIgnoreCase ("spa")) return LanguageCode::spa;
if (s.equalsIgnoreCase ("epo")) return LanguageCode::epo;
if (s.equalsIgnoreCase ("por")) return LanguageCode::por;
if (s.equalsIgnoreCase ("deu")) return LanguageCode::deu;
if (s.equalsIgnoreCase ("nld")) return LanguageCode::nld;
if (s.equalsIgnoreCase ("tlh")) return LanguageCode::tlh;
return LanguageCode::unknown;
}
LanguageCode getLanguageCode (const String& s)
{
const auto lc = getLanguageCodeFromISO6392 (s);
if (lc != LanguageCode::unknown)
return lc;
return getLanguageCodeFromISO6391 (s);
}
String toString (LanguageCode lc)
{
switch (lc)
{
case LanguageCode::eng: return "eng";
case LanguageCode::fre: return "fre";
case LanguageCode::spa: return "spa";
case LanguageCode::epo: return "epo";
case LanguageCode::por: return "por";
case LanguageCode::deu: return "deu";
case LanguageCode::nld: return "nld";
case LanguageCode::tlh: return "tlh";
default: break;
};
return {};
}
//==============================================================================
CountryCode getCountryCodeFromISO3166Alpha2 (const String& s)
{
if (s.equalsIgnoreCase ("us")) return CountryCode::us;
if (s.equalsIgnoreCase ("ca")) return CountryCode::ca;
if (s.equalsIgnoreCase ("gb")) return CountryCode::gb;
if (s.equalsIgnoreCase ("fr")) return CountryCode::fr;
if (s.equalsIgnoreCase ("de")) return CountryCode::de;
if (s.equalsIgnoreCase ("nl")) return CountryCode::nl;
return CountryCode::unknown;
}
CountryCode getCountryCodeFromISO3166Alpha3 (const String& s)
{
if (s.equalsIgnoreCase ("usa")) return CountryCode::us;
if (s.equalsIgnoreCase ("can")) return CountryCode::ca;
if (s.equalsIgnoreCase ("gbr")) return CountryCode::gb;
if (s.equalsIgnoreCase ("fra")) return CountryCode::fr;
if (s.equalsIgnoreCase ("deu")) return CountryCode::de;
if (s.equalsIgnoreCase ("nld")) return CountryCode::nl;
return CountryCode::unknown;
}
CountryCode getCountryCode (const String& s)
{
const auto lc = getCountryCodeFromISO3166Alpha3 (s);
if (lc != CountryCode::unknown)
return lc;
return getCountryCodeFromISO3166Alpha2 (s);
}
String toString (CountryCode cc)
{
switch (cc)
{
case CountryCode::us: return "us";
case CountryCode::ca: return "ca";
case CountryCode::gb: return "gb";
case CountryCode::fr: return "fr";
case CountryCode::de: return "de";
case CountryCode::nl: return "nl";
default: break;
};
return {};
}
//==============================================================================
void LanguageHandler::initialise (const File& langDir)
{
if (languageDirectory == langDir)
return;
languageDirectory = langDir;
if (! languageDirectory.isDirectory())
{
const auto r = languageDirectory.createDirectory();
if (! r.wasOk())
{
Logger::writeToLog ("Error! Failed to create language translations directory!\n");
if (r.getErrorMessage().isNotEmpty())
Logger::writeToLog ("Message: " + r.getErrorMessage());
jassertfalse;
languageDirectory = File();
return;
}
}
Array<File> languageFiles;
languageFiles.minimiseStorageOverheads();
languageDirectory.findChildFiles (languageFiles, File::findFiles, false, "*" + languageFileExtension);
IETFLanguageFile ietfDefaultLang;
const auto defaultLang = languageDirectory.getChildFile (ietfDefaultLang.tag.getDescription() + languageFileExtension);
if (languageFiles.isEmpty()
|| ! defaultLang.existsAsFile()
|| defaultLang.getSize() < 64
|| defaultLang.isSymbolicLink())
{
defaultLang.deleteRecursively (false);
auto fs = FileOutputStream (defaultLang);
if (fs.failedToOpen())
{
Logger::writeToLog ("Error! Unable to create default language file for some reason...\nSee path:\n\t" + defaultLang.getFullPathName());
jassertfalse;
return;
}
if (auto* ls = LocalisedStrings::getCurrentMappings())
{
const auto& mappings = ls->getMappings();
for (const auto& key : mappings.getAllKeys())
fs << key << " = " << mappings.getValue (key, {});
}
ietfDefaultLang.file = defaultLang;
addLanguageFile (ietfDefaultLang, true);
}
for (const auto& lf : languageFiles)
{
IETFLanguageFile f;
f.file = lf;
f.tag = IETFLanguageTag::fromString (f.file.getFileNameWithoutExtension());
if (f.tag.isValid())
{
addLanguageFile (f, false);
}
else
{
Logger::writeToLog ("Error! Unknown or broken language file...\nSee path:\n\t" + lf.getFullPathName());
jassertfalse;
}
}
}
bool LanguageHandler::isValid (const IETFLanguageFile& lf)
{
return lf.exists() && lf.isValid() && lf.file.getFileExtension() == languageFileExtension;
}
void LanguageHandler::addLanguageFile (const IETFLanguageFile& lf, bool makeActive)
{
if (! isValid (lf))
{
Logger::writeToLog ("Unknown or language file...\nSee path:\n\t" + lf.file.getFullPathName());
jassertfalse;
return;
}
if (languages.isEmpty())
makeActive = true;
// @TODO: for now, assume the language file is unique...
languages.add (new IETFLanguageFile (lf));
if (makeActive)
setCurrentLanguage (lf);
}
void LanguageHandler::setCurrentLanguage (const IETFLanguageTag& lt)
{
for (int i = languages.size(); --i >= 0;)
{
if (auto* lang = languages.getUnchecked (i))
{
if (*lang == lt)
{
if (activeLanguageIndex == i)
return; //Nothing to do...
activeLanguageIndex = i;
listeners.call ([&] (Listener& l) { l.languageChanged (*lang); });
return;
}
}
}
Logger::writeToLog (String ("Error! Tried to switch to an unknown language: ")
+ String ((int) lt.code) + "-" + String ((int) lt.country));
jassertfalse;
}
void LanguageHandler::setCurrentLanguage (const IETFLanguageFile& lf)
{
if (! isValid (lf))
{
Logger::writeToLog ("Invalid language file!\nSee path:\n\t" + lf.file.getFullPathName());
jassertfalse;
return;
}
for (int i = languages.size(); --i >= 0;)
{
if (auto* lang = languages.getUnchecked (i))
{
if (*lang == lf)
{
setCurrentLanguage (lf.tag);
return;
}
}
}
}
const IETFLanguageFile& LanguageHandler::getCurrentLanguage() const
{
jassert (! languages.isEmpty() && activeLanguageIndex >= 0);
return *languages.getFirst();
}
|
6f1606a12b2c478cec7865379646cb0a7f20d53e | 79fe90d5c8c3f6abe0c9f11731e729874f832022 | /141_Linked List Cycle/Solution_extraspace_success.cpp | 2b7f3baa1d97b89b4ca46f28cc60db665de6f1c7 | [] | no_license | ChiaYuLin/Leetcode | 59ee806729e32a5cbe09d68ccdb05761a79080cd | 3e36da877581aa5c25c27c87f5854c27ffcc1888 | refs/heads/master | 2021-01-20T05:31:59.064169 | 2018-03-25T04:56:06 | 2018-03-25T04:56:06 | 33,420,672 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,131 | cpp | Solution_extraspace_success.cpp | /*
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
*/
#include <iostream>
#include <cstdlib>
#include <set>
using namespace std;
/*
Put the node into a set.
Compare whether the node is existed in the set.
If it is existed in the set, there is a circle.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
set<ListNode *> nodeset;
if(head!=NULL)
{
while(head!=NULL)
{
if(nodeset.find(head)!=nodeset.end())
return true;
nodeset.insert(head);
head=head->next;
}
return false;
}
else
return false;
}
};
int main()
{
Solution solution;
bool result;
ListNode* input;
ListNode* head=new ListNode(1);
input=head;
for(int i=2;i<=5;i++)
{
head->next=new ListNode(i);
head=head->next;
}
head->next=input;
result=solution.hasCycle(input);
cout<<"result:"<<result<<endl;
} |
a48ab911add0f16e28b1b6729fc321b35ace6ac9 | ccc746be53b18d9284b60a99fb4f517e58cf4139 | /src/subsystems/chassis_profile_follower.cpp | 6cac19f93ebd443c88439ebb3d7501bf76d084e6 | [] | no_license | 77788J/77788J-TP-Mark-II | 0c4aaf6111dc7d324094534405871737cd1472d4 | 105bb25ef0e836021fae1b9bc6ecdd399c6a293b | refs/heads/master | 2021-10-21T08:39:30.232449 | 2019-03-03T20:43:28 | 2019-03-03T20:43:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,026 | cpp | chassis_profile_follower.cpp | // #include "../../include/subsystems/chassis_profile_follower.hpp"
// namespace chassis_profile_follower {
// // movement statistics
// float accel = 15; // acceleration of motors (mv/ms^2)
// float kp = 12.3; // proportional tuning parameter for feedback control
// float kp_turn = 40.0; // proportional tuning parameter for feedback control
// float kd = 10; // integral tuning parameter for feedback control
// float kd_turn = 14; // integral tuning parameter for feedback control
// // current motion statistics
// bool is_definite = true;
// float _dist = 0;
// float _max_voltage = 12000;
// float _start_voltage = 0;
// bool _rotating = false;
// // currently in motion?
// bool start_motion = false;
// bool in_motion = false;
// // controller for async movements
// pros::Task* async_controller;
// void async_controller_run(void* param) {
// while (true) {
// if (start_motion) {
// in_motion = true;
// start_motion = false;
// if (is_definite) move_definite(_dist, _max_voltage, _start_voltage, true);
// else move_indefinite(_max_voltage, _start_voltage, true);
// in_motion = false;
// }
// pros::delay(10);
// }
// }
// // move for specific distance
// void move_definite(float dist, float max_voltage, float start_voltage, bool syncronous) {
// // run in task if not syncronous
// if (!syncronous) {
// is_definite = true;
// _dist = dist;
// _max_voltage = max_voltage;
// _start_voltage = start_voltage;
// _rotating = false;
// start_motion = true;
// }
// else {
// // setup
// float start_pos = chassis::get_position(chassis::SIDE_BOTH);
// float dist_travelled = 0;
// float current_voltage = start_voltage;
// // do the thing
// if (dist > 0) {
// while (fabs(dist - dist_travelled) > 128 || fabs(chassis::get_velocity(chassis::SIDE_BOTH)) > 10) {
// if (dist_travelled < dist - dist_travelled) {
// current_voltage = clamp(current_voltage + accel * 10, 0, 12000);
// }
// else {
// current_voltage = clamp(kp * (dist - dist_travelled) - kd * chassis::get_velocity(chassis::SIDE_BOTH), 0, 12000);
// }
// chassis::move_voltage(current_voltage, current_voltage);
// pros::delay(10);
// dist_travelled = chassis::get_position(chassis::SIDE_BOTH) - start_pos;
// }
// }
// else {
// while (fabs(dist - dist_travelled) > 128 || fabs(chassis::get_velocity(chassis::SIDE_BOTH)) > 10) {
// if (dist_travelled > dist - dist_travelled) {
// current_voltage = clamp(current_voltage - accel * 10, -12000, 0);
// }
// else {
// current_voltage = clamp(kp * (dist - dist_travelled) - kd * chassis::get_velocity(chassis::SIDE_BOTH), -12000, 0);
// }
// chassis::move_voltage(current_voltage, current_voltage);
// pros::delay(10);
// dist_travelled = chassis::get_position(chassis::SIDE_BOTH) - start_pos;
// }
// }
// }
// }
// // move indefitely
// void move_indefinite(float max_voltage, float start_voltage, bool syncronous) {
// if (!syncronous) {
// is_definite = false;
// _max_voltage = max_voltage;
// _start_voltage = start_voltage;
// _rotating = false;
// start_motion = true;
// }
// else {
// // setup
// float dist_travelled = 0;
// float current_voltage = start_voltage;
// // ramp up
// while (fabs(current_voltage - max_voltage) > 100) {
// current_voltage = clamp(current_voltage + accel * sign(max_voltage), -12000, 12000);
// chassis::move_voltage(current_voltage, current_voltage);
// }
// }
// }
// // move for specific distance
// void rotate_by(float degrees, float max_voltage, float start_voltage, bool syncronous) {
// // run in task if not syncronous
// if (!syncronous) {
// is_definite = true;
// _dist = degrees;
// _max_voltage = max_voltage;
// _start_voltage = start_voltage;
// _rotating = true;
// start_motion = true;
// }
// else {
// // setup
// float start_pos = chassis::get_position(chassis::SIDE_BOTH_TURN);
// float dist = chassis::dist_to_angle(degrees * (PI / 180.f) * chassis::WHEEL_DIST / 2.f);
// float dist_travelled = 0;
// float current_voltage = start_voltage;
// printf("%f", dist);
// // do the thing
// if (dist > 0) {
// while (fabs(dist - dist_travelled) > 128 || fabs(chassis::get_velocity(chassis::SIDE_BOTH_TURN)) > 10) {
// if (dist_travelled < dist - dist_travelled) {
// current_voltage = clamp(current_voltage + accel * 10, 0, 12000);
// }
// else {
// current_voltage = clamp(kp_turn * (dist - dist_travelled) - kd_turn * chassis::get_velocity(chassis::SIDE_BOTH_TURN), 0, 12000);
// }
// chassis::move_voltage(-current_voltage, current_voltage);
// pros::delay(10);
// dist_travelled = chassis::get_position(chassis::SIDE_BOTH_TURN) - start_pos;
// }
// }
// else {
// while (fabs(dist - dist_travelled) > 128 || fabs(chassis::get_velocity(chassis::SIDE_BOTH_TURN)) > 10) {
// if (dist_travelled > dist - dist_travelled) {
// current_voltage = clamp(current_voltage - accel * 10, -12000, 0);
// }
// else {
// current_voltage = clamp(kp_turn * (dist - dist_travelled) - kd_turn * chassis::get_velocity(chassis::SIDE_BOTH_TURN), -12000, 0);
// }
// chassis::move_voltage(-current_voltage, current_voltage);
// pros::delay(10);
// dist_travelled = chassis::get_position(chassis::SIDE_BOTH_TURN) - start_pos;
// }
// }
// }
// }
// } |
9573beb26f12a29dc1660ff45ce559e5a151f457 | 82aed836e7a3f0e8db372d809a7eee221f16a0c4 | /src/stepper-test_arduino/stepper-test.ino | 1b945c6fa9cf9f4abb03639d84cc7c33791bdfdd | [
"MIT"
] | permissive | elomage/santa-test | 525a03058df2d8a73adba9262628dd85333f6e62 | 44e012dd6993f396a147ff59465ab6dbcf71fffd | refs/heads/master | 2020-05-21T14:57:12.380712 | 2017-02-13T13:43:46 | 2017-02-13T13:43:46 | 62,857,667 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,850 | ino | stepper-test.ino | /* LED Blink, Teensyduino Tutorial #1
http://www.pjrc.com/teensy/tutorial.html
This example code is in the public domain.
*/
//===== Prototypes =====
void myDelay();
//===== Data =====
// Comment below to enable the stepper controller all the time
#define LOWPOWER
#define BLINKRATE 200
#define DELAY_STEP 3
#define DELAY_START 10
#define DELAY_BRAKE 200
#define PINDIR 14
#define PINSTEP 15
#define PINM1 16
#define PINM2 17
#define PINM3 18
#define PINEN 19
// Teensy 3.0 has the LED on pin 13
const int ledPin = 13;
int cnt=0;
//-------------------------------------------
void stepperInit()
{
pinMode(PINDIR, OUTPUT);
pinMode(PINSTEP, OUTPUT);
pinMode(PINEN, OUTPUT);
pinMode(PINM1, OUTPUT);
pinMode(PINM2, OUTPUT);
pinMode(PINM3, OUTPUT);
// digitalWrite(PINM1, HIGH);
// digitalWrite(PINM2, HIGH);
// digitalWrite(PINM3, HIGH);
digitalWrite(PINM1, LOW);
digitalWrite(PINM2, LOW);
digitalWrite(PINM3, LOW);
digitalWrite(PINDIR, LOW);
digitalWrite(PINSTEP, LOW);
digitalWrite(PINEN, LOW);
}
//--------------------
void stepperBrake()
{
digitalWrite(PINEN, LOW);
delay(DELAY_START);
}
//--------------------
void stepperRelease()
{
delay(DELAY_BRAKE);
digitalWrite(PINEN, HIGH);
}
//--------------------
// Rotate the stepper N steps
//--------------------
void step(int steps)
{
// Enable
#ifdef LOWPOWER
stepperBrake();
#endif
for(int i=0; i<steps; i++){
digitalWrite(PINSTEP, HIGH);
delay(DELAY_STEP);
digitalWrite(PINSTEP, LOW);
delay(DELAY_STEP);
}
// Disable, to save power
#ifdef LOWPOWER
stepperRelease();
#endif
}
//===========================================
// the setup() method runs once, when the sketch starts
//===========================================
void setup() {
// initialize the digital pin as an output.
pinMode(ledPin, OUTPUT);
stepperInit();
stepperRelease();
Serial.begin(9600); // USB is always 12 Mbit/sec
}
//===========================================
// the loop() methor runs over and over again,
// as long as the board has power
//===========================================
void loop() {
int ch;
digitalWrite(ledPin, HIGH); // set the LED on
myDelay(); // wait
digitalWrite(ledPin, LOW); // set the LED off
myDelay(); // wait
// /*
// Serial.print("Hello World1...");
Serial.print(cnt);
//ch = Serial.read();
ch = Serial.parseInt();
Serial.print(" InByte=");
Serial.println(ch, DEC);
// Check the direction
if( ch<0 ){
digitalWrite(PINDIR, HIGH);
ch = -ch;
} else if( ch>0) {
digitalWrite(PINDIR, LOW);
}
// Rotate
if (ch>0){
step(ch);
}
/* === */
}
//--------------------
void myDelay()
{
delay(BLINKRATE); // wait for a second
cnt += BLINKRATE;
}
|
ba3d33b593303b37288d1c214bceae64c9f27102 | da7c499625123f5d1a28e3d75b037523df11ccb5 | /devel/coda/src/rc/runControl/Xui/src.s/rcHelpAboutDialog.cc | 805c7a5febc040472769604aad9adaf85265dea2 | [] | no_license | emuikernel/BDXDaq | 84d947b0a4c0c1799a855dbe6c59e9560a8fc4e2 | cf678d3b71bdfb95996e8b7e97ad3657ef98262f | refs/heads/master | 2021-01-18T07:26:38.855967 | 2015-06-08T15:45:58 | 2015-06-08T15:45:58 | 48,211,085 | 3 | 2 | null | 2015-12-18T02:56:53 | 2015-12-18T02:56:52 | null | UTF-8 | C++ | false | false | 5,384 | cc | rcHelpAboutDialog.cc | //-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// CEBAF Data Acquisition Group, 12000 Jefferson Ave., Newport News, VA 23606
// coda@cebaf.gov Tel: (804) 249-7030 Fax: (804) 249-5800
//-----------------------------------------------------------------------------
//
// Description:
// Implementation of rcHelpAboutDialog Class
//
// Author:
// Jie Chen
// CEBAF Data Acquisition Group
//
// Revision History:
// $Log: rcHelpAboutDialog.cc,v $
// Revision 1.1.1.1 1996/10/11 13:39:28 chen
// run control source
//
//
#include <Xm/Xm.h>
#include <Xm/Form.h>
#include <Xm/LabelG.h>
#include <Xm/PushBG.h>
#include <Xm/SeparatoG.h>
#include <XcodaXpmLabel.h>
#include <rcHelpAbout.h>
#include <codaConst.h>
#include <rcSvcProtocol.h>
#include "rcHelpAboutDialog.h"
#include <RCLogo.xpm>
rcHelpAboutDialog::rcHelpAboutDialog (rcHelpAbout* base,
char* name,
char* title)
:XcodaFormDialog (base->dialogBaseWidget (), name, title),
base_ (base), log_ (0)
{
#ifdef _TRACE_OBJECTS
printf (" Create rcHelpAboutDialog Class Object\n");
#endif
// empty
}
rcHelpAboutDialog::~rcHelpAboutDialog (void)
{
#ifdef _TRACE_OBJECTS
printf (" Create rcHelpAboutDialog Class Object\n");
#endif
// empty
}
void
rcHelpAboutDialog::createFormChildren (void)
{
Arg arg[20];
int ac = 0;
XtSetArg (arg[ac], XmNtopAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNtopOffset, 10); ac++;
XtSetArg (arg[ac], XmNleftAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNleftOffset, 10); ac++;
XtSetArg (arg[ac], XmNbottomAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNbottomOffset, 10); ac++;
Widget leftform = XtCreateWidget ("left_form", xmFormWidgetClass,
_w, arg, ac);
ac = 0;
log_ = new XcodaXpmLabel (leftform, " ", RCLogo_xpm);
log_->init ();
XtSetArg (arg[ac], XmNtopAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNtopOffset, 10); ac++;
XtSetArg (arg[ac], XmNleftAttachment, XmATTACH_FORM); ac++;
XtSetValues (log_->baseWidget (), arg, ac);
ac = 0;
XmString t = XmStringCreateSimple ("RunControl");
XtSetArg (arg[ac], XmNlabelString, t); ac++;
XtSetArg (arg[ac], XmNtopAttachment, XmATTACH_WIDGET); ac++;
XtSetArg (arg[ac], XmNtopWidget, log_->baseWidget ()); ac++;
XtSetArg (arg[ac], XmNbottomAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNbottomOffset, 10); ac++;
XtSetArg (arg[ac], XmNleftAttachment, XmATTACH_FORM); ac++;
Widget label = XtCreateManagedWidget ("label", xmLabelGadgetClass,
leftform, arg, ac);
ac = 0;
XmStringFree (t);
// create a separator
XtSetArg (arg[ac], XmNtopAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNtopOffset, 2); ac++;
XtSetArg (arg[ac], XmNbottomAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNbottomOffset, 2); ac++;
XtSetArg (arg[ac], XmNleftAttachment, XmATTACH_WIDGET); ac++;
XtSetArg (arg[ac], XmNleftWidget, leftform); ac++;
XtSetArg (arg[ac], XmNleftOffset, 10); ac++;
XtSetArg (arg[ac], XmNorientation, XmVERTICAL); ac++;
Widget sep = XtCreateManagedWidget ("sep", xmSeparatorGadgetClass,
_w, arg, ac);
ac = 0;
char msg[256], vstr[128];
::sprintf (msg, "Motif-based RunControl for Physics Experiments\n\n");
::sprintf (vstr, "RunControl Version %3.1f (CODA %s)\n\n",
(float)(CODA_RC_VERSION)/1000.0, CODA_VERSION);
::strcat (msg, vstr);
::sprintf (vstr, "Developed at TJNAF, by Data Acquisition Group");
::strcat (msg, vstr);
t = XmStringCreateLtoR (msg, XmSTRING_DEFAULT_CHARSET);
XtSetArg (arg[ac], XmNlabelString, t); ac++;
XtSetArg (arg[ac], XmNtopAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNtopOffset, 5); ac++;
XtSetArg (arg[ac], XmNbottomAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNbottomOffset, 5); ac++;
XtSetArg (arg[ac], XmNleftAttachment, XmATTACH_WIDGET); ac++;
XtSetArg (arg[ac], XmNleftWidget, sep) ;ac++;
XtSetArg (arg[ac], XmNleftOffset, 5); ac++;
Widget label1 = XtCreateManagedWidget ("label", xmLabelGadgetClass,
_w, arg, ac);
ac = 0;
XmStringFree (t);
t = XmStringCreateSimple ("ok");
XtSetArg (arg[ac], XmNlabelString, t); ac++;
XtSetArg (arg[ac], XmNtopAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNtopOffset, 5); ac++;
XtSetArg (arg[ac], XmNleftAttachment, XmATTACH_WIDGET); ac++;
XtSetArg (arg[ac], XmNleftWidget, label1); ac++;
XtSetArg (arg[ac], XmNleftOffset, 5); ac++;
XtSetArg (arg[ac], XmNrightAttachment, XmATTACH_FORM); ac++;
XtSetArg (arg[ac], XmNrightOffset, 5); ac++;
Widget ok = XtCreateManagedWidget ("ok", xmPushButtonGadgetClass,
_w, arg, ac);
ac = 0;
XmStringFree (t);
XtAddCallback (ok, XmNactivateCallback,
(XtCallbackProc)&(rcHelpAboutDialog::okCallback),
(XtPointer)this);
XtManageChild (leftform);
}
void
rcHelpAboutDialog::okCallback (Widget w,
XtPointer data,
XmAnyCallbackStruct* cbs)
{
rcHelpAboutDialog* dialog = (rcHelpAboutDialog *)data;
dialog->popdown ();
}
|
2f728f591e09f76f160579dbaed0b40a0c797024 | a9a69d75423576d42cdb995a8a320c1a423e0130 | /2015-CaroloCup/sources/OpenDaVINCI-msv/libopendavinci/include/core/wrapper/WIN32/WIN32UDPReceiver.h | 7ba1e5fd4e97c801c6a5770e39365d950e6959e4 | [
"AFL-3.0"
] | permissive | Pedram87/CaroloCup | df23bd4dd57ff5eab8f8232f0f7e4aa7500c3215 | d97dd565acd4f11412032a9cf5c174d82b2ae285 | refs/heads/master | 2021-03-15T04:19:23.393383 | 2016-03-10T22:49:16 | 2016-03-10T22:49:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,035 | h | WIN32UDPReceiver.h | /*
* OpenDaVINCI.
*
* This software is open source. Please see COPYING and AUTHORS for further information.
*/
#ifndef OPENDAVINCI_CORE_WRAPPER_WIN32IMPL_WIN32UDPRECEIVER_H_
#define OPENDAVINCI_CORE_WRAPPER_WIN32IMPL_WIN32UDPRECEIVER_H_
// core/platform.h must be included to setup platform-dependent header files and configurations.
#include "core/platform.h"
#include "core/wrapper/Runnable.h"
#include "core/wrapper/Thread.h"
#include "core/wrapper/UDPReceiver.h"
#include "core/wrapper/NetworkLibraryProducts.h"
#include "core/wrapper/UDPFactoryWorker.h"
namespace core {
namespace wrapper {
namespace WIN32Impl {
using namespace std;
/**
* This class implements a UDP receiver for receiving data using WIN32.
*
* @See UDPReceiver
*/
class WIN32UDPReceiver : public Runnable, public UDPReceiver {
private:
friend class UDPFactoryWorker<NetworkLibraryWin32>;
/**
* Constructor.
*
* @param address Address to bind on.
* @param port Port.
* @param isMulticast true, if this receiver is part of the UDP multicast group specified by address:port.
*/
WIN32UDPReceiver(const string &address, const uint32_t &port, const bool &isMulticast);
private:
enum {
BUFFER_SIZE = 65535
};
private:
/**
* "Forbidden" copy constructor. Goal: The compiler should warn
* already at compile time for unwanted bugs caused by any misuse
* of the copy constructor.
*/
WIN32UDPReceiver(const WIN32UDPReceiver &);
/**
* "Forbidden" assignment operator. Goal: The compiler should warn
* already at compile time for unwanted bugs caused by any misuse
* of the assignment operator.
*/
WIN32UDPReceiver& operator=(const WIN32UDPReceiver &);
public:
virtual ~WIN32UDPReceiver();
virtual void start();
virtual void stop();
private:
const char* inet_ntop(int af, const void* src, char* dst, int cnt);
private:
bool m_isMulticast;
struct sockaddr_in m_address;
struct ip_mreq m_mreq;
int32_t m_fd;
char *m_buffer;
Thread *m_thread;
virtual void run();
virtual bool isRunning();
};
}
}
} // core::wrapper::WIN32Impl
#endif /*OPENDAVINCI_CORE_WRAPPER_WIN32IMPL_WIN32UDPRECEIVER_H_*/
|
84f683ddfbef352a72adc98ea859c99afcbf2eb7 | fdc5b61ec9341c21086e17eb1497983caf2dc4d7 | /archive/Chapter 1/3N+1/a.cpp | f1585c75c6282c9a779c88454e1200b124071c27 | [] | no_license | madhav1928/ICPC-Programming-Challenges | 316dc0f3fc74a0df805c80b31486dbd2d69d2e0b | 3690d4d1dec4cfa6db3d8e795e5f648592dd2863 | refs/heads/master | 2021-05-29T11:06:14.490712 | 2015-06-18T18:45:12 | 2015-06-18T18:45:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | cpp | a.cpp | #include <iostream>
#include <vector>
#include <string>
using namespace std;
#define MAX 1000000
vector<long long> v(MAX);
unsigned long long hail(long long m) {
if(m < MAX && v.at(m) != 0) {
return v.at(m);
}
if(m == 1) {
v.at(m) = 1;
return 1;
}
int temp=0;
if(m%2 == 0) {
temp = 1+hail(m/2);
}else {
temp = 1+hail(m*3+1);
}
if(m < MAX) {
v.at(m) = temp;
}
return temp;
}
int main() {
for(int x = 0; x < MAX; x++) {
v.at(x) = 0;
}
int n, m;
for(int x = 1; x < MAX; x++) {
hail(x);
}
while(cin>>n>>m) {
cout << n << " " << m << " ";
if(m < n) {
int temp = n;
n = m;
m = temp;
}
int max = 0;
long long temp;
for(int x = n; x <= m; x++) {
temp = hail(x);
if(temp > max) {
max = temp;
}
}
cout << max << "\n";
}
return 0;
}
|
05bcfc62313b1ae26053aa9382c770e6fcf2be60 | 64cc2ec70569bd42e37b7e3dab730b29ea913d91 | /constants.hpp | 53a8db891ed370089e673738ded04b5373cbd7a0 | [] | no_license | coryknapp/fourfortyfour | 94340edbfb7f39c9357c1f713c28ab8e4983885a | 515a2a0a8b4e77b988d57038efb221580c574537 | refs/heads/master | 2021-01-12T06:39:13.693329 | 2016-12-26T20:21:37 | 2016-12-26T20:21:37 | 77,405,094 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,379 | hpp | constants.hpp | /*
* constants.hpp
* Copyright (C) 2016 cknapp <cknapp@mbp.local>
*
* Distributed under terms of the MIT license.
*/
#ifndef CONSTANTS_HPP
#define CONSTANTS_HPP
#include <string>
#include <set>
#include <vector>
const std::set<char> c_separators =
{ 9, //character tabulation
10, //line feed
11, //line tabulation
12, //form feed
13, //carriage return
32, //space
'(', ')', '{', '}', '*', '/', '+', '-',
'^', '[', ']', '&', '|', '=', '\'','\"',
';'};
const std::set<char> c_omit =
{ 9, //character tabulation
10, //line feed
11, //line tabulation
12, //form feed
13, //carriage return
32, //space
};
const std::set<std::string> c_multichar_operators =
{ "&&",
"==",
">=",
"<=",
"!=",
"||",
"++",
"--",
"/*", //comment start. Handled differently
};
const std::set<char> c_string_deliminators =
{ '\'',
'"',
};
const std::set<std::string> c_ops = {
"*", "+", "-", "/",
"&",
"(", ")", "[", "]", "{", "}"
};
const std::vector<std::string> c_op_priority_order =
{"=", "==", "<", ">", "*", "\\", "+", "-", "["};
const std::vector<std::string> c_binary_operators =
{"=", "==", "<", ">", "*", "\\", "+", "-"};
const std::vector<std::string> c_unary_operators =
{"!", "*", "&", "+", "-"};
const std::set<std::string> c_builtin_types =
{"int", "float", "char", "bool", "double"};
#endif /* !CONSTANTS_HPP */
|
0cc5f06fce0a92c46f3c21c8b944a19ee13f415a | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/agc007/B/3509757.cpp | 19d25f643eff3ece277e67d3e9dfc0ae68e258ca | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 853 | cpp | 3509757.cpp | #include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
#include <string>
#include <map>
#include <cmath>
using namespace std;
int main()
{
int N, p;
cin >> N;
int a[20005];
int b[20005];
for (int i = 0; i < N;i++)
{
int p;
cin >> p;
a[p - 1] = 20000 * p + 1 + i;
b[p - 1] = 4 * pow(10, 8) - 20000 * p + 1;
}
for (int i = 0; i < N;i++)
{
cout << a[i];
if(i == N-1)
{
cout << endl;
}
else
{
cout << ' ';
}
}
for (int i = 0; i < N; i++)
{
cout << b[i];
if (i == N-1)
{
cout << endl;
}
else
{
cout << ' ';
}
}
return 0;
} |
4df651235c23636d7a68f27040359a0874a5389d | 90e7b9cdf3a26be781cdb016dfd41467aabfe897 | /src/plugins/contrib/wxSmith/wxwidgets/defitems/wxsmenueditor.cpp | 534dc2bff9f48ad7f769b1295f7b1f810d2f12bb | [] | no_license | Akhireddy/test1 | 3d25f8caa90ae231a398e596646583c31f25b5ec | a978e43d9db772617cc871f65967a8a76e33f182 | refs/heads/master | 2021-05-07T14:12:01.554716 | 2017-11-08T14:51:50 | 2017-11-08T14:51:50 | 109,842,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,647 | cpp | wxsmenueditor.cpp | /*
* This file is part of wxSmith plugin for Code::Blocks Studio
* Copyright (C) 2007 Bartlomiej Swiecki
*
* wxSmith 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.
*
* wxSmith 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 wxSmith. If not, see <http://www.gnu.org/licenses/>.
*
* $Revision: 10272 $
* $Id: wxsmenueditor.cpp 10272 2015-05-15 10:57:25Z jenslody $
* $HeadURL: http://svn.code.sf.net/p/codeblocks/code/branches/release-16.xx/src/plugins/contrib/wxSmith/wxwidgets/defitems/wxsmenueditor.cpp $
*/
#include "wxsmenueditor.h"
#include "wxsmenu.h"
#include "wxsmenuitem.h"
#include "wxsmenubar.h"
#include "../wxsitemresdata.h"
#include <prep.h>
//(*InternalHeaders(wxsMenuEditor)
#include <wx/string.h>
#include <wx/intl.h>
//*)
//(*IdInit(wxsMenuEditor)
const long wxsMenuEditor::ID_TREECTRL1 = wxNewId();
const long wxsMenuEditor::ID_RADIOBUTTON1 = wxNewId();
const long wxsMenuEditor::ID_RADIOBUTTON4 = wxNewId();
const long wxsMenuEditor::ID_RADIOBUTTON2 = wxNewId();
const long wxsMenuEditor::ID_RADIOBUTTON5 = wxNewId();
const long wxsMenuEditor::ID_RADIOBUTTON3 = wxNewId();
const long wxsMenuEditor::ID_STATICLINE1 = wxNewId();
const long wxsMenuEditor::ID_STATICTEXT6 = wxNewId();
const long wxsMenuEditor::ID_TEXTCTRL4 = wxNewId();
const long wxsMenuEditor::ID_STATICTEXT1 = wxNewId();
const long wxsMenuEditor::ID_TEXTCTRL1 = wxNewId();
const long wxsMenuEditor::ID_STATICTEXT2 = wxNewId();
const long wxsMenuEditor::ID_TEXTCTRL2 = wxNewId();
const long wxsMenuEditor::ID_STATICTEXT3 = wxNewId();
const long wxsMenuEditor::ID_TEXTCTRL3 = wxNewId();
const long wxsMenuEditor::ID_STATICTEXT4 = wxNewId();
const long wxsMenuEditor::ID_CHECKBOX1 = wxNewId();
const long wxsMenuEditor::ID_STATICTEXT5 = wxNewId();
const long wxsMenuEditor::ID_CHECKBOX2 = wxNewId();
const long wxsMenuEditor::ID_STATICLINE2 = wxNewId();
const long wxsMenuEditor::ID_BUTTON1 = wxNewId();
const long wxsMenuEditor::ID_BUTTON2 = wxNewId();
const long wxsMenuEditor::ID_BUTTON3 = wxNewId();
const long wxsMenuEditor::ID_BUTTON4 = wxNewId();
const long wxsMenuEditor::ID_BUTTON5 = wxNewId();
const long wxsMenuEditor::ID_BUTTON6 = wxNewId();
//*)
wxsMenuEditor::wxsMenuEditor(wxWindow* parent,wxsMenuBar* MenuBar):
m_MenuBar(MenuBar),
m_Menu(0),
m_First(0),
m_Selected(0),
m_BlockSel(false),
m_BlockRead(false)
{
CreateDataCopy();
CreateContent(parent);
UpdateMenuContent();
}
wxsMenuEditor::wxsMenuEditor(wxWindow* parent,wxsMenu* Menu):
m_MenuBar(0),
m_Menu(Menu),
m_First(0),
m_Selected(0),
m_BlockSel(false),
m_BlockRead(false)
{
CreateDataCopy();
CreateContent(parent);
UpdateMenuContent();
}
void wxsMenuEditor::CreateContent(wxWindow* parent)
{
wxWindowID id = wxID_ANY;
//(*Initialize(wxsMenuEditor)
wxStaticBoxSizer* StaticBoxSizer2;
wxGridSizer* GridSizer1;
wxFlexGridSizer* FlexGridSizer1;
wxBoxSizer* BoxSizer3;
wxBoxSizer* BoxSizer2;
wxBoxSizer* BoxSizer1;
wxStaticBoxSizer* StaticBoxSizer1;
Create(parent, id, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("id"));
BoxSizer1 = new wxBoxSizer(wxHORIZONTAL);
StaticBoxSizer1 = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Content"));
m_Content = new wxTreeCtrl(this, ID_TREECTRL1, wxDefaultPosition, wxSize(200,295), wxTR_HIDE_ROOT|wxTR_DEFAULT_STYLE, wxDefaultValidator, _T("ID_TREECTRL1"));
StaticBoxSizer1->Add(m_Content, 1, wxEXPAND, 4);
BoxSizer1->Add(StaticBoxSizer1, 1, wxALL|wxEXPAND, 4);
StaticBoxSizer2 = new wxStaticBoxSizer(wxVERTICAL, this, _("Options"));
GridSizer1 = new wxGridSizer(0, 2, 0, 0);
m_TypeNormal = new wxRadioButton(this, ID_RADIOBUTTON1, _("Normal"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_RADIOBUTTON1"));
m_TypeNormal->SetValue(true);
m_TypeNormal->Disable();
GridSizer1->Add(m_TypeNormal, 1, wxLEFT|wxRIGHT|wxEXPAND, 4);
m_TypeSeparator = new wxRadioButton(this, ID_RADIOBUTTON4, _("Separator"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_RADIOBUTTON4"));
m_TypeSeparator->Disable();
GridSizer1->Add(m_TypeSeparator, 1, wxLEFT|wxRIGHT|wxEXPAND, 4);
m_TypeCheck = new wxRadioButton(this, ID_RADIOBUTTON2, _("Check"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_RADIOBUTTON2"));
m_TypeCheck->Disable();
GridSizer1->Add(m_TypeCheck, 1, wxLEFT|wxRIGHT|wxEXPAND, 4);
m_TypeBreak = new wxRadioButton(this, ID_RADIOBUTTON5, _("Break"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_RADIOBUTTON5"));
m_TypeBreak->Disable();
GridSizer1->Add(m_TypeBreak, 1, wxLEFT|wxRIGHT|wxEXPAND, 4);
m_TypeRadio = new wxRadioButton(this, ID_RADIOBUTTON3, _("Radio"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_RADIOBUTTON3"));
m_TypeRadio->Disable();
GridSizer1->Add(m_TypeRadio, 1, wxLEFT|wxRIGHT|wxEXPAND, 4);
StaticBoxSizer2->Add(GridSizer1, 0, wxEXPAND, 10);
StaticLine1 = new wxStaticLine(this, ID_STATICLINE1, wxDefaultPosition, wxSize(10,-1), wxLI_HORIZONTAL, _T("ID_STATICLINE1"));
StaticBoxSizer2->Add(StaticLine1, 0, wxALL|wxEXPAND, 4);
FlexGridSizer1 = new wxFlexGridSizer(0, 2, 0, 0);
StaticText6 = new wxStaticText(this, ID_STATICTEXT6, _("Id:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT6"));
FlexGridSizer1->Add(StaticText6, 1, wxTOP|wxALIGN_CENTER_VERTICAL, 4);
m_Id = new wxTextCtrl(this, ID_TEXTCTRL4, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL4"));
m_Id->Disable();
FlexGridSizer1->Add(m_Id, 1, wxTOP|wxLEFT|wxALIGN_CENTER_VERTICAL, 4);
StaticText1 = new wxStaticText(this, ID_STATICTEXT1, _("Label:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT1"));
FlexGridSizer1->Add(StaticText1, 1, wxTOP|wxALIGN_CENTER_VERTICAL, 4);
m_Label = new wxTextCtrl(this, ID_TEXTCTRL1, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL1"));
m_Label->Disable();
FlexGridSizer1->Add(m_Label, 1, wxTOP|wxLEFT|wxALIGN_CENTER_VERTICAL, 4);
StaticText2 = new wxStaticText(this, ID_STATICTEXT2, _("Accelerator:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT2"));
FlexGridSizer1->Add(StaticText2, 1, wxTOP|wxALIGN_CENTER_VERTICAL, 4);
m_Accelerator = new wxTextCtrl(this, ID_TEXTCTRL2, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL2"));
m_Accelerator->Disable();
FlexGridSizer1->Add(m_Accelerator, 1, wxTOP|wxLEFT|wxALIGN_CENTER_VERTICAL, 4);
StaticText3 = new wxStaticText(this, ID_STATICTEXT3, _("Help:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT3"));
FlexGridSizer1->Add(StaticText3, 1, wxTOP|wxALIGN_CENTER_VERTICAL, 4);
m_Help = new wxTextCtrl(this, ID_TEXTCTRL3, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL3"));
m_Help->Disable();
FlexGridSizer1->Add(m_Help, 1, wxTOP|wxLEFT|wxALIGN_CENTER_VERTICAL, 4);
StaticText4 = new wxStaticText(this, ID_STATICTEXT4, _("Checked:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT4"));
FlexGridSizer1->Add(StaticText4, 1, wxTOP|wxALIGN_CENTER_VERTICAL, 4);
m_Checked = new wxCheckBox(this, ID_CHECKBOX1, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX1"));
m_Checked->SetValue(false);
m_Checked->Disable();
FlexGridSizer1->Add(m_Checked, 1, wxTOP|wxLEFT|wxEXPAND, 4);
StaticText5 = new wxStaticText(this, ID_STATICTEXT5, _("Enabled:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT5"));
FlexGridSizer1->Add(StaticText5, 1, wxTOP|wxALIGN_CENTER_VERTICAL, 4);
m_Enabled = new wxCheckBox(this, ID_CHECKBOX2, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX2"));
m_Enabled->SetValue(false);
m_Enabled->Disable();
FlexGridSizer1->Add(m_Enabled, 1, wxTOP|wxLEFT|wxEXPAND, 4);
StaticBoxSizer2->Add(FlexGridSizer1, 0, wxEXPAND, 10);
StaticLine2 = new wxStaticLine(this, ID_STATICLINE2, wxDefaultPosition, wxSize(10,-1), wxLI_HORIZONTAL, _T("ID_STATICLINE2"));
StaticBoxSizer2->Add(StaticLine2, 0, wxALL|wxEXPAND, 4);
BoxSizer2 = new wxBoxSizer(wxHORIZONTAL);
Button1 = new wxButton(this, ID_BUTTON1, _("<"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT, wxDefaultValidator, _T("ID_BUTTON1"));
BoxSizer2->Add(Button1, 1, wxLEFT|wxRIGHT|wxEXPAND, 2);
Button2 = new wxButton(this, ID_BUTTON2, _(">"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT, wxDefaultValidator, _T("ID_BUTTON2"));
BoxSizer2->Add(Button2, 1, wxLEFT|wxRIGHT|wxEXPAND, 2);
Button3 = new wxButton(this, ID_BUTTON3, _("^"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT, wxDefaultValidator, _T("ID_BUTTON3"));
BoxSizer2->Add(Button3, 1, wxLEFT|wxRIGHT|wxEXPAND, 2);
Button4 = new wxButton(this, ID_BUTTON4, _("v"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT, wxDefaultValidator, _T("ID_BUTTON4"));
BoxSizer2->Add(Button4, 1, wxLEFT|wxRIGHT|wxEXPAND, 2);
StaticBoxSizer2->Add(BoxSizer2, 0, wxALIGN_CENTER_HORIZONTAL, 4);
StaticBoxSizer2->Add(-1,-1,1, wxEXPAND, 5);
BoxSizer3 = new wxBoxSizer(wxHORIZONTAL);
Button5 = new wxButton(this, ID_BUTTON5, _("New"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT, wxDefaultValidator, _T("ID_BUTTON5"));
BoxSizer3->Add(Button5, 1, wxRIGHT|wxEXPAND, 4);
Button6 = new wxButton(this, ID_BUTTON6, _("Delete"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT, wxDefaultValidator, _T("ID_BUTTON6"));
BoxSizer3->Add(Button6, 1, wxLEFT|wxEXPAND, 4);
StaticBoxSizer2->Add(BoxSizer3, 0, wxALIGN_CENTER_HORIZONTAL, 4);
BoxSizer1->Add(StaticBoxSizer2, 0, wxALL|wxEXPAND, 4);
SetSizer(BoxSizer1);
BoxSizer1->Fit(this);
BoxSizer1->SetSizeHints(this);
Connect(ID_TREECTRL1,wxEVT_COMMAND_TREE_SEL_CHANGED,(wxObjectEventFunction)&wxsMenuEditor::OnContentSelectionChanged);
Connect(ID_RADIOBUTTON1,wxEVT_COMMAND_RADIOBUTTON_SELECTED,(wxObjectEventFunction)&wxsMenuEditor::OnTypeChanged);
Connect(ID_RADIOBUTTON4,wxEVT_COMMAND_RADIOBUTTON_SELECTED,(wxObjectEventFunction)&wxsMenuEditor::OnTypeChanged);
Connect(ID_RADIOBUTTON2,wxEVT_COMMAND_RADIOBUTTON_SELECTED,(wxObjectEventFunction)&wxsMenuEditor::OnTypeChanged);
Connect(ID_RADIOBUTTON5,wxEVT_COMMAND_RADIOBUTTON_SELECTED,(wxObjectEventFunction)&wxsMenuEditor::OnTypeChanged);
Connect(ID_RADIOBUTTON3,wxEVT_COMMAND_RADIOBUTTON_SELECTED,(wxObjectEventFunction)&wxsMenuEditor::OnTypeChanged);
Connect(ID_TEXTCTRL1,wxEVT_COMMAND_TEXT_UPDATED,(wxObjectEventFunction)&wxsMenuEditor::OnLabelChanged);
Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsMenuEditor::OnButtonLeftClick);
Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsMenuEditor::OnButtonRightClick);
Connect(ID_BUTTON3,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsMenuEditor::OnButtonUpClick);
Connect(ID_BUTTON4,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsMenuEditor::OnButtonDownClick);
Connect(ID_BUTTON5,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsMenuEditor::OnButtonNewClick);
Connect(ID_BUTTON6,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsMenuEditor::OnButtonDelClick);
//*)
}
wxsMenuEditor::~wxsMenuEditor()
{
DeleteDataCopy();
//(*Destroy(wxsMenuEditor)
//*)
}
void wxsMenuEditor::CreateDataCopy()
{
if ( m_Menu )
{
CreateDataCopyReq(m_Menu,0);
}
else
{
CreateDataCopyReq(m_MenuBar,0);
}
}
void wxsMenuEditor::CreateDataCopyReq(wxsMenu* Menu,MenuItem* Parent)
{
MenuItem* LastChild = 0;
for ( int i=0; i<Menu->GetChildCount(); i++ )
{
wxsMenuItem* ChildMenu = (wxsMenuItem*)Menu->GetChild(i);
MenuItem* ChildItem = new MenuItem;
ChildItem->m_Next = 0;
ChildItem->m_Child = 0;
ChildItem->m_Parent = Parent;
if ( LastChild )
{
LastChild->m_Next = ChildItem;
}
else
{
(Parent ? Parent->m_Child : m_First) = ChildItem;
}
LastChild = ChildItem;
CreateDataCopyReq(ChildMenu,ChildItem);
}
}
void wxsMenuEditor::CreateDataCopyReq(wxsMenuBar* Menu,MenuItem* Parent)
{
MenuItem* LastChild = 0;
for ( int i=0; i<Menu->GetChildCount(); i++ )
{
wxsMenu* ChildMenu = (wxsMenu*)Menu->GetChild(i);
MenuItem* ChildItem = new MenuItem;
ChildItem->m_Type = wxsMenuItem::Normal;
ChildItem->m_Variable = ChildMenu->GetVarName();
ChildItem->m_IsMember = ChildMenu->GetIsMember();
if ( ChildMenu->GetBaseProps() ) ChildItem->m_ExtraCode = ChildMenu->GetBaseProps()->m_ExtraCode;
ChildItem->m_Label = ChildMenu->m_Label;
ChildItem->m_Enabled = true;
ChildItem->m_Checked = false;
ChildItem->m_Next = 0;
ChildItem->m_Child = 0;
ChildItem->m_Parent = Parent;
if ( LastChild )
{
LastChild->m_Next = ChildItem;
}
else
{
(Parent ? Parent->m_Child : m_First) = ChildItem;
}
LastChild = ChildItem;
CreateDataCopyReq(ChildMenu,ChildItem);
}
}
void wxsMenuEditor::CreateDataCopyReq(wxsMenuItem* Menu,MenuItem* Parent)
{
Parent->m_Type = Menu->m_Type;
Parent->m_Variable = Menu->GetVarName();
Parent->m_IsMember = Menu->GetIsMember();
if ( Menu->GetBaseProps() ) Parent->m_ExtraCode = Menu->GetBaseProps()->m_ExtraCode;
Parent->m_Id = Menu->GetIdName();
Parent->m_Label = Menu->m_Label;
Parent->m_Accelerator = Menu->m_Accelerator;
Parent->m_Help = Menu->m_Help;
Parent->m_Enabled = Menu->m_Enabled;
Parent->m_Checked = Menu->m_Checked;
Parent->m_Bitmap = Menu->m_Bitmap;
wxsEvents& Events = Menu->GetEvents();
if ( Events.GetCount()>0 )
{
Parent->m_HandlerFunction = Events.GetHandler(0);
}
MenuItem* LastChild = 0;
for ( int i=0; i<Menu->GetChildCount(); i++ )
{
wxsMenuItem* ChildMenu = (wxsMenuItem*)Menu->GetChild(i);
MenuItem* ChildItem = new MenuItem;
ChildItem->m_Next = 0;
ChildItem->m_Child = 0;
ChildItem->m_Parent = Parent;
if ( LastChild )
{
LastChild->m_Next = ChildItem;
}
else
{
(Parent ? Parent->m_Child : m_First) = ChildItem;
}
LastChild = ChildItem;
CreateDataCopyReq(ChildMenu,ChildItem);
}
}
void wxsMenuEditor::DeleteDataCopy()
{
DeleteDataCopyReq(m_First);
m_First = 0;
}
void wxsMenuEditor::DeleteDataCopyReq(MenuItem* Item)
{
while ( Item )
{
MenuItem* Next = Item->m_Next;
DeleteDataCopyReq(Item->m_Child);
delete Item;
Item = Next;
}
}
void wxsMenuEditor::UpdateMenuContent()
{
CheckConsistency();
m_Content->Freeze();
m_BlockSel = true; // wxTreeCtrl changes selection during delete
m_Content->DeleteAllItems();
m_BlockSel = false;
wxTreeItemId RootId = m_Content->AddRoot(_T("Menu"));
UpdateMenuContentReq(RootId,m_First);
m_Content->Thaw();
if ( m_Selected )
{
m_Content->SelectItem(m_Selected->m_TreeId);
}
}
void wxsMenuEditor::UpdateMenuContentReq(wxTreeItemId Id,MenuItem* Item)
{
for ( ; Item; Item = Item->m_Next )
{
wxTreeItemId ItemId = m_Content->AppendItem(Id,GetItemTreeName(Item),-1,-1,new MenuItemHolder(Item));
Item->m_TreeId = ItemId;
UpdateMenuContentReq(ItemId,Item->m_Child);
m_Content->Expand(ItemId);
}
}
wxString wxsMenuEditor::GetItemTreeName(MenuItem* Item)
{
switch ( Item->m_Type )
{
case wxsMenuItem::Separator: return _T("--------");
case wxsMenuItem::Break: return _("** BREAK **");
default: return Item->m_Label;
}
}
void wxsMenuEditor::OnContentSelectionChanged(wxTreeEvent& event)
{
if ( m_BlockSel ) return;
wxTreeItemId Id = event.GetItem();
if ( !Id.IsOk() ) return;
MenuItem* Selected = ((MenuItemHolder*)m_Content->GetItemData(Id))->m_Item;
SelectItem(Selected);
}
void wxsMenuEditor::SelectItem(MenuItem* NewSelection)
{
if ( m_Selected )
{
// Storing current data to item
if ( m_TypeNormal->GetValue() ) m_Selected->m_Type = wxsMenuItem::Normal;
if ( m_TypeCheck->GetValue() ) m_Selected->m_Type = wxsMenuItem::Check;
if ( m_TypeRadio->GetValue() ) m_Selected->m_Type = wxsMenuItem::Radio;
if ( m_TypeBreak->GetValue() ) m_Selected->m_Type = wxsMenuItem::Break;
if ( m_TypeSeparator->GetValue() ) m_Selected->m_Type = wxsMenuItem::Separator;
m_Selected->m_Id = m_Id->GetValue();
m_Selected->m_Label = m_Label->GetValue();
m_Selected->m_Accelerator = m_Accelerator->GetValue();
m_Selected->m_Help = m_Help->GetValue();
m_Selected->m_Enabled = m_Enabled->GetValue();
m_Selected->m_Checked = m_Checked->GetValue();
}
if ( m_Selected == NewSelection ) return;
m_Selected = NewSelection;
if ( m_Selected )
{
m_BlockRead = true;
m_TypeNormal->Enable();
m_TypeCheck->Enable();
m_TypeRadio->Enable();
m_TypeBreak->Enable();
m_TypeSeparator->Enable();
bool UseId = false;
bool UseLabel = false;
bool UseAccelerator = false;
bool UseHelp = false;
bool UseEnabled = false;
bool UseChecked = false;
switch ( CorrectType(m_Selected,UseId,UseLabel,UseAccelerator,UseHelp,UseEnabled,UseChecked) )
{
case wxsMenuItem::Normal:
m_TypeNormal->SetValue(true);
// If item has children, can not change type to anything else
// Same goes for children of wxMenuBar
if ( m_Selected->m_Child || (!m_Selected->m_Parent && m_MenuBar) )
{
m_TypeCheck->Disable();
m_TypeRadio->Disable();
m_TypeBreak->Disable();
m_TypeSeparator->Disable();
}
break;
case wxsMenuItem::Radio:
m_TypeRadio->SetValue(true);
break;
case wxsMenuItem::Check:
m_TypeCheck->SetValue(true);
break;
case wxsMenuItem::Separator:
m_TypeSeparator->SetValue(true);
break;
case wxsMenuItem::Break:
m_TypeBreak->SetValue(true);
break;
default:
break;
}
m_Id->Enable(UseId);
m_Id->SetValue(m_Selected->m_Id);
m_Label->Enable(UseLabel);
m_Label->SetValue(m_Selected->m_Label);
m_Accelerator->Enable(UseAccelerator);
m_Accelerator->SetValue(m_Selected->m_Accelerator);
m_Help->Enable(UseHelp);
m_Help->SetValue(m_Selected->m_Help);
m_Enabled->Enable(UseEnabled);
m_Enabled->SetValue(m_Selected->m_Enabled);
m_Checked->Enable(UseChecked);
m_Checked->SetValue(m_Selected->m_Checked);
m_BlockRead = false;
}
else
{
m_Id->Clear();
m_Label->Clear();
m_Accelerator->Clear();
m_Help->Clear();
m_Enabled->SetValue(true);
m_Checked->SetValue(false);
m_Id->Disable();
m_Label->Disable();
m_Accelerator->Disable();
m_Help->Disable();
m_Enabled->Disable();
m_Checked->Disable();
m_TypeNormal->Disable();
m_TypeCheck->Disable();
m_TypeRadio->Disable();
m_TypeBreak->Disable();
m_TypeSeparator->Disable();
}
}
void wxsMenuEditor::ApplyChanges()
{
// Re-selecting item to write data from window to ItemData object
SelectItem(m_Selected);
// Now storing everything into original structure
StoreDataCopy();
}
void wxsMenuEditor::StoreDataCopy()
{
wxsParent* Parent = m_MenuBar ? ((wxsItem*)m_MenuBar)->ConvertToParent() : ((wxsItem*)m_Menu)->ConvertToParent();
if ( Parent )
{
// First notifying that structure is going to change
Parent->GetResourceData()->BeginChange();
// Have to delete all children of menu
for ( int Count = Parent->GetChildCount(); Count-->0; )
{
wxsItem* Child = Parent->GetChild(Count);
Parent->UnbindChild(Count);
delete Child;
}
if ( m_Menu )
{
// If it is menu, we store items directly into wxMenu class
StoreDataCopyReq(Parent,m_First);
}
else
{
// If it is wxMenuBar, we have to create separate wxMenu for
// each root entry
for ( MenuItem* Item = m_First; Item; Item = Item->m_Next )
{
wxsMenu* NewMenu = new wxsMenu(m_MenuBar->GetResourceData());
NewMenu->m_Label = Item->m_Label;
NewMenu->SetVarName(Item->m_Variable);
NewMenu->SetIsMember(Item->m_IsMember);
if ( NewMenu->GetBaseProps() ) NewMenu->GetBaseProps()->m_ExtraCode = Item->m_ExtraCode;
m_MenuBar->AddChild(NewMenu);
StoreDataCopyReq(NewMenu,Item->m_Child);
}
}
// Notifying about finished change
Parent->GetResourceData()->EndChange();
}
}
void wxsMenuEditor::StoreDataCopyReq(wxsParent* Parent,MenuItem* Item)
{
// First need to copy data from Item to Menu, not all data will
// be copied, only things proper to item type
for ( ; Item; Item = Item->m_Next )
{
bool UseId = false;
bool UseLabel = false;
bool UseAccelerator = false;
bool UseHelp = false;
bool UseEnabled = false;
bool UseChecked = false;
Type ItemType = CorrectType(Item,UseId,UseLabel,UseAccelerator,UseHelp,UseEnabled,UseChecked);
bool BreakOrSeparator = (ItemType==wxsMenuItem::Break) || (ItemType==wxsMenuItem::Separator);
wxsMenuItem* Menu = new wxsMenuItem(Parent->GetResourceData(),BreakOrSeparator);
if ( !Parent->AddChild(Menu) )
{
delete Menu;
continue;
}
Menu->SetVarName(Item->m_Variable);
Menu->SetIsMember(Item->m_IsMember);
if ( Menu->GetBaseProps() ) Menu->GetBaseProps()->m_ExtraCode = Item->m_ExtraCode;
Menu->SetIdName(_T(""));
Menu->m_Label.Clear();
Menu->m_Accelerator.Clear();
Menu->m_Help.Clear();
Menu->m_Enabled = true;
Menu->m_Checked = false;
Menu->m_Type = ItemType;
if ( UseId ) Menu->SetIdName(Item->m_Id);
if ( UseLabel ) Menu->m_Label = Item->m_Label;
if ( UseAccelerator ) Menu->m_Accelerator = Item->m_Accelerator;
if ( UseHelp ) Menu->m_Help = Item->m_Help;
if ( UseEnabled ) Menu->m_Enabled = Item->m_Enabled;
if ( UseChecked ) Menu->m_Checked = Item->m_Checked;
Menu->m_Bitmap = Item->m_Bitmap;
wxsEvents& Events = Menu->GetEvents();
if ( Events.GetCount()>0 )
{
Events.SetHandler(0,Item->m_HandlerFunction);
}
StoreDataCopyReq(Menu,Item->m_Child);
}
}
wxsMenuEditor::Type wxsMenuEditor::CorrectType(MenuItem* Item,bool& UseId,bool& UseLabel,bool& UseAccelerator,bool& UseHelp,bool& UseEnabled,bool& UseChecked)
{
UseId = false;
UseLabel = false;
UseAccelerator = false;
UseHelp = false;
UseEnabled = false;
UseChecked = false;
if ( !Item->m_Parent && m_MenuBar )
{
// Children of wxMenuBar must be menus
UseId = true;
UseLabel = true;
return wxsMenuItem::Normal;
}
if ( Item->m_Child )
{
// There's child item, so it must be wxMenu too
if ( m_MenuBar && !Item->m_Parent )
{
// Only label (title) is used when child of wxMenuBar
UseLabel = true;
}
else
{
UseId = true;
UseLabel = true;
UseHelp = true;
UseEnabled = true;
}
return wxsMenuItem::Normal;
}
switch ( Item->m_Type )
{
case wxsMenuItem::Separator:
return wxsMenuItem::Separator;
case wxsMenuItem::Break:
return wxsMenuItem::Break;
case wxsMenuItem::Check:
UseChecked = true;
// Fall through
case wxsMenuItem::Radio:
case wxsMenuItem::Normal:
UseId = true;
UseLabel = true;
UseAccelerator = true;
UseHelp = true;
UseEnabled = true;
return Item->m_Type;
default:;
}
return wxsMenuItem::Normal;
}
void wxsMenuEditor::OnTypeChanged(cb_unused wxCommandEvent& event)
{
MenuItem* Selected = m_Selected;
SelectItem(Selected);
m_Selected = 0;
SelectItem(Selected);
m_Content->SetItemText(m_Selected->m_TreeId,GetItemTreeName(m_Selected));
}
void wxsMenuEditor::OnButtonUpClick(cb_unused wxCommandEvent& event)
{
if ( !m_Selected ) return;
MenuItem* Parent = m_Selected->m_Parent;
MenuItem* Previous = GetPrevious(m_Selected);
if ( Previous )
{
Previous->m_Next = m_Selected->m_Next;
m_Selected->m_Next = Previous;
MenuItem* Previous2 = GetPrevious(Previous);
if ( Previous2 )
{
Previous2->m_Next = m_Selected;
}
else
{
// Moving to first position in parent
if ( Parent )
{
Parent->m_Child = m_Selected;
}
else
{
m_First = m_Selected;
}
}
}
else
{
// Have to put outside current parent
if ( !Parent ) return;
Parent->m_Child = m_Selected->m_Next;
m_Selected->m_Next = Parent;
Parent = m_Selected->m_Parent = Parent->m_Parent;
MenuItem* Previous2 = GetPrevious(Parent);
if ( Previous2 )
{
Previous2->m_Next = m_Selected;
}
else if ( Parent )
{
Parent->m_Child = m_Selected;
}
else
{
m_First = m_Selected;
}
}
// Rebuilding tree
UpdateMenuContent();
}
void wxsMenuEditor::OnButtonDownClick(cb_unused wxCommandEvent& event)
{
if ( !m_Selected ) return;
MenuItem* Previous = GetPrevious(m_Selected);
MenuItem* Next = m_Selected->m_Next;
MenuItem* Parent = m_Selected->m_Parent;
if ( Next )
{
if ( Previous )
{
Previous->m_Next = Next;
}
else if ( Parent )
{
Parent->m_Child = Next;
}
else
{
m_First = Next;
}
m_Selected->m_Next = Next->m_Next;
Next->m_Next = m_Selected;
}
else
{
// Last item of parent, need to jump out of menu
if ( !Parent ) return;
if ( Previous )
{
Previous->m_Next = 0;
}
else
{
Parent->m_Child = 0;
}
m_Selected->m_Next = Parent->m_Next;
m_Selected->m_Parent = Parent->m_Parent;
Parent->m_Next = m_Selected;
}
// Rebuilding tree
UpdateMenuContent();
}
wxsMenuEditor::MenuItem* wxsMenuEditor::GetPrevious(MenuItem* Item)
{
MenuItem* Parent = Item->m_Parent;
if ( !Parent && Item == m_First ) return 0;
if ( Parent && Item == Parent->m_Child ) return 0;
for ( MenuItem* Prev = Parent ? Parent->m_Child : m_First ; Prev; Prev = Prev->m_Next )
{
if ( Prev->m_Next == Item ) return Prev;
}
return 0;
}
void wxsMenuEditor::OnButtonNewClick(cb_unused wxCommandEvent& event)
{
MenuItem* NewItem = new MenuItem;
NewItem->m_Type = wxsMenuItem::Normal;
NewItem->m_Label = _("New Menu");
NewItem->m_IsMember = true;
NewItem->m_Enabled = true;
NewItem->m_Checked = false;
NewItem->m_Child = 0;
if ( !m_Selected )
{
// Just adding new item into m_Data
NewItem->m_Parent = 0;
NewItem->m_Next = m_First;
m_First = NewItem;
}
else
{
NewItem->m_Parent = m_Selected->m_Parent;
NewItem->m_Next = m_Selected->m_Next;
m_Selected->m_Next = NewItem;
}
SelectItem(NewItem);
UpdateMenuContent();
}
void wxsMenuEditor::OnButtonDelClick(cb_unused wxCommandEvent& event)
{
if ( !m_Selected ) return;
if ( cbMessageBox(
_("Are you sure to delete this menu item ?\n"
"(It will delete all sub menus too)"),
_("Delete menu"),
wxYES_NO) != wxID_YES ) return;
MenuItem* Previous = GetPrevious(m_Selected);
MenuItem* Parent = m_Selected->m_Parent;
if ( Previous )
{
Previous->m_Next = m_Selected->m_Next;
m_Selected->m_Next = 0;
DeleteDataCopyReq(m_Selected);
m_Selected = 0;
if ( Previous->m_Next )
{
SelectItem(Previous->m_Next);
}
else
{
SelectItem(Previous);
}
}
else
{
if ( Parent )
{
Parent->m_Child = m_Selected->m_Next;
}
else
{
m_First = m_Selected->m_Next;
}
MenuItem* NewSelected = m_Selected;
if ( m_Selected->m_Next )
{
NewSelected = m_Selected->m_Next;
}
else
{
NewSelected = m_Selected->m_Parent;
}
m_Selected->m_Next = 0;
DeleteDataCopyReq(m_Selected);
m_Selected = 0;
SelectItem(NewSelected);
}
UpdateMenuContent();
}
void wxsMenuEditor::OnButtonLeftClick(cb_unused wxCommandEvent& event)
{
if ( !m_Selected ) return;
if ( !m_Selected->m_Parent ) return;
MenuItem* Previous = GetPrevious(m_Selected);
MenuItem* Parent = m_Selected->m_Parent;
if ( Previous )
{
Previous->m_Next = m_Selected->m_Next;
}
else
{
Parent->m_Child = m_Selected->m_Next;
}
m_Selected->m_Parent = Parent->m_Parent;
m_Selected->m_Next = Parent->m_Next;
Parent->m_Next = m_Selected;
UpdateMenuContent();
}
void wxsMenuEditor::OnButtonRightClick(cb_unused wxCommandEvent& event)
{
if ( !m_Selected ) return;
MenuItem* Previous = GetPrevious(m_Selected);
if ( !Previous ) return;
if ( Previous->m_Type == wxsMenuItem::Separator ) return;
if ( Previous->m_Type == wxsMenuItem::Break ) return;
Previous->m_Type = wxsMenuItem::Normal;
Previous->m_Next = m_Selected->m_Next;
m_Selected->m_Parent = Previous;
m_Selected->m_Next = 0;
if ( !Previous->m_Child )
{
Previous->m_Child = m_Selected;
}
else
{
Previous = Previous->m_Child;
while ( Previous->m_Next )
{
Previous = Previous->m_Next;
}
Previous->m_Next = m_Selected;
}
UpdateMenuContent();
}
void wxsMenuEditor::OnLabelChanged(cb_unused wxCommandEvent& event)
{
if ( m_BlockRead ) return;
SelectItem(m_Selected);
if ( m_Selected && m_Selected->m_TreeId.IsOk() )
{
m_Content->SetItemText(m_Selected->m_TreeId,GetItemTreeName(m_Selected));
}
}
void wxsMenuEditor::CheckConsistency()
{
//CheckConsistencyReq(m_First);
}
void wxsMenuEditor::CheckConsistencyReq(MenuItem* Item)
{
if ( !Item ) return;
MenuItem* Parent = Item->m_Parent;
for ( MenuItem* Scan = Item; Scan; Scan = Scan->m_Next )
{
for ( MenuItem* LoopScan = Scan->m_Next; LoopScan; LoopScan = LoopScan->m_Next )
{
if ( LoopScan == Scan )
{
// We've got looping sequence
wxMessageBox(_T("wxSmith: Loop"));
return;
}
}
if ( Scan->m_Parent != Parent )
{
wxMessageBox(_T("wxSmith: Parent"));
return;
}
CheckConsistencyReq(Scan->m_Child);
}
}
|
b3aa71443c60c02cb1dcb95dcc0ac8b01aae4d8b | c9e05d02afbb3360a498876a0bc9d68b1394b074 | /EduClient/subteacher/entergradeform.cpp | 4fa2d87a5acdd7d4e67ff688e501682218768d54 | [] | no_license | duier2018/EduMSForNetBase | 971cdb96ae8293f16685620aaa2a537a82b43327 | 7e908b75522e06cf25103c1f855e982ff5094d76 | refs/heads/master | 2020-07-06T08:45:36.584843 | 2019-08-18T04:31:03 | 2019-08-18T04:31:03 | 202,959,860 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | cpp | entergradeform.cpp | #include "entergradeform.h"
#include "ui_entergradeform.h"
#include <QMessageBox>
#include <QDebug>
EnterGradeForm::EnterGradeForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::EnterGradeForm)
{
ui->setupUi(this);
}
EnterGradeForm::~EnterGradeForm()
{
delete ui;
}
void EnterGradeForm::on_pb_sure_clicked()
{
if(ui->le_stuid->text().isEmpty())
{
QMessageBox::warning(this, "警告", "学号不能为空!",
QMessageBox::Retry|QMessageBox::Close);
}
else if(ui->le_classid->text().isEmpty())
{
QMessageBox::warning(this,"警告","班号不能为空",
QMessageBox::Retry|QMessageBox::Close);
}
else if(ui->le_courseid->text().isEmpty())
{
QMessageBox::warning(this,"警告","课号不能为空",
QMessageBox::Retry|QMessageBox::Close);
}
else if(ui->le_grade->text().isEmpty())
{
QMessageBox::warning(this,"警告","成绩不能为空",
QMessageBox::Retry|QMessageBox::Close);
}
else
{
emit signalEnterGrade(ui->le_stuid->text(),ui->le_classid->text(),
ui->le_courseid->text(),ui->le_grade->text());
qDebug() << "录入成绩";
}
}
|
3bb2d3a914aa735e7655a66b7de9b584936daf18 | 3135407540dd3a8a795a77494492868511edf7ee | /461. 汉明距离 .cpp | b20b7fe309350e57ded62f288af16d9b4a5606bd | [] | no_license | hrz123/algorithm | 93013154720a34aad82fedd88b6ff85340e9c7f1 | 56fc72f895cb16cc619b99b945f055a08422ec83 | refs/heads/master | 2023-02-26T12:45:48.641750 | 2021-02-07T03:42:36 | 2021-02-07T03:42:36 | 296,176,971 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202 | cpp | 461. 汉明距离 .cpp | //
// Created by Ruizhe Hou on 2020/10/7.
//
#include <bitset>
using namespace std;
class Solution {
public:
int hammingDistance(int x, int y) {
return bitset<32>(x ^ y).count();
}
};
|
3f5fa55d4d601f8ff324fd9381911c793b5ecac5 | 43b13b4717baa5b858ed973a86f0665db56ff237 | /RiseOfDarkness/Classes/SelectScene.cpp | 6697934076facae11feaa03f0eb907d35656081b | [] | no_license | hvduc97/RiseOfDarkness | 2f79fcc918642209ebd10ae2d2ca9f11ffc997b6 | cb1eb6a6c828d527108f42817aa07bf14e43bcd0 | refs/heads/master | 2020-11-30T03:56:08.337512 | 2019-12-26T16:38:19 | 2019-12-26T16:38:19 | 230,294,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,067 | cpp | SelectScene.cpp | #include "SelectScene.h"
#include "ui/CocosGUI.h"
#include "ResourceManager.h"
#include "InputNameScene.h"
USING_NS_CC;
using namespace ui;
Scene* SelectScene::CreateScene()
{
return SelectScene::create();
}
bool SelectScene::init()
{
if (!Scene::init())
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto bg = ResourceManager::GetInstance()->GetSpriteById(7);//Sprite::create("/res/sprites/selectbg.jpg");
bg->removeFromParent();
bg->setScale(visibleSize.width / bg->getContentSize().width, visibleSize.height / bg->getContentSize().height);
bg->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
this->addChild(bg, -1);
//===============
auto button = ResourceManager::GetInstance()->GetButtonById(3)->clone();//Button::create("/res/buttons/chose.png");
button->setPosition(Vec2(visibleSize.width / 4 + origin.x, visibleSize.height / 1.5 + origin.y));
button->setScale(0.75);
this->addChild(button,0);
auto buttonnewgame = ResourceManager::GetInstance()->GetButtonById(6)->clone();//Button::create("/res/buttons/newgame .png");
buttonnewgame->setPosition(Vec2(visibleSize.width / 4 + origin.x, visibleSize.height / 1.3 + origin.y));
buttonnewgame->setScale(0.65);
buttonnewgame->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type)
{
if (type == ui::Widget::TouchEventType::ENDED)
{
auto gotoNext = CallFunc::create([]() {
Director::getInstance()->replaceScene(InputNameScene::create());
});
runAction(gotoNext);
}
});
this->addChild(buttonnewgame,1);
auto btcont = ResourceManager::GetInstance()->GetButtonById(4)->clone();//Button::create("/res/buttons/continue.png");
btcont->setPosition(Vec2(visibleSize.width / 4 + origin.x, visibleSize.height / 1.6 + origin.y));
btcont->setScale(0.65);
this->addChild(btcont, 1);
btcont->setEnabled(false);
//===================
auto button2 = ResourceManager::GetInstance()->GetButtonById(3)->clone(); //Button::create("/res/buttons/chose.png");
button2->setPosition(Vec2(visibleSize.width / 4.35+button2->getContentSize().width + origin.x, visibleSize.height / 1.5 + origin.y));
button2->setScale(0.75);
this->addChild(button2);
auto buttonnewgame2 = ResourceManager::GetInstance()->GetButtonById(6)->clone(); //Button::create("/res/buttons/newgame .png");
buttonnewgame2->setPosition(Vec2(visibleSize.width / 4.35 + button2->getContentSize().width + origin.x, visibleSize.height / 1.3 + origin.y));
buttonnewgame2->setScale(0.65);
buttonnewgame2->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type)
{
if (type == ui::Widget::TouchEventType::ENDED)
{
auto gotoNext = CallFunc::create([]() {
Director::getInstance()->replaceScene(InputNameScene::create());
});
runAction(gotoNext);
}
});
this->addChild(buttonnewgame2, 1);
auto btcont2 = ResourceManager::GetInstance()->GetButtonById(4)->clone(); //Button::create("/res/buttons/continue.png");
btcont2->setPosition(Vec2(visibleSize.width / 4.35 + button2->getContentSize().width + origin.x, visibleSize.height / 1.6 + origin.y));
btcont2->setScale(0.65);
this->addChild(btcont2, 1);
btcont2->setEnabled(false);
//========================
auto button3 = ResourceManager::GetInstance()->GetButtonById(3)->clone(); //Button::create("/res/buttons/chose.png");
button3->setPosition(Vec2(visibleSize.width / 5 + button2->getContentSize().width*2 + origin.x, visibleSize.height / 1.5 + origin.y));
button3->setScale(0.75);
this->addChild(button3);
auto buttonnewgame3 = ResourceManager::GetInstance()->GetButtonById(6)->clone(); //Button::create("/res/buttons/newgame .png");
buttonnewgame3->setPosition(Vec2(visibleSize.width / 5 + button2->getContentSize().width * 2 + origin.x, visibleSize.height / 1.3 + origin.y));
buttonnewgame3->setScale(0.65);
buttonnewgame3->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type)
{
if (type == ui::Widget::TouchEventType::ENDED)
{
auto gotoNext = CallFunc::create([]() {
Director::getInstance()->replaceScene(InputNameScene::create());
});
runAction(gotoNext);
}
});
this->addChild(buttonnewgame3, 1);
auto btcont3 = ResourceManager::GetInstance()->GetButtonById(4)->clone(); //Button::create("/res/buttons/continue.png");
btcont3->setPosition(Vec2(visibleSize.width / 5 + button2->getContentSize().width * 2, visibleSize.height / 1.6 + origin.y));
btcont3->setScale(0.65);
this->addChild(btcont3, 1);
btcont3->setEnabled(false);
//========================
auto buttondelete = ResourceManager::GetInstance()->GetButtonById(5)->clone(); //Button::create("/res/buttons/delete.png");
buttondelete->setPosition(Vec2(visibleSize.width / 4+ origin.x, visibleSize.height / 2.75 + origin.y));
buttondelete->setScale(0.75);
this->addChild(buttondelete);
buttondelete->setEnabled(false);
auto buttondelete2 = ResourceManager::GetInstance()->GetButtonById(5)->clone(); //Button::create("/res/buttons/delete.png");
buttondelete2->setPosition(Vec2(visibleSize.width / 4.35 + button2->getContentSize().width + origin.x, visibleSize.height / 2.75 + origin.y));
buttondelete2->setScale(0.75);
this->addChild(buttondelete2);
buttondelete2->setEnabled(false);
auto buttondelete3 = ResourceManager::GetInstance()->GetButtonById(5)->clone(); //Button::create("/res/buttons/delete.png");
buttondelete3->setPosition(Vec2(visibleSize.width / 5 + button2->getContentSize().width*2 + origin.x, visibleSize.height / 2.75 + origin.y));
buttondelete3->setScale(0.75);
this->addChild(buttondelete3);
buttondelete3->setEnabled(false);
//=============
//auto text = ResourceManager::GetInstance()->DuplicateSprite(ResourceManager::GetInstance()->GetSpriteById(4));//Sprite::create("/res/sprites/h.png");
//text->setAnchorPoint(Vec2(0, 0));
//text->setPosition(Vec2(visibleSize.width / 8 + origin.x, visibleSize.height / 30+ origin.y));
//text->setScaleX(1.5);
//text->setScaleY(0.4);
//this->addChild(text);
return true;
}
|
bb0a4092643cdb312b55c851d0ee0c2b9a7a0bee | 3af29124223df5d6a023f6896fd297b537943e9c | /forward_list().cpp | 0f6c86f64885c566957e7c3663845c07e3b1247b | [] | no_license | bashar404/STL | bebf23d5428c027b4e65898c498d93f55497a645 | c1d901338a6782be3a62f7e4effc4b112fcb9639 | refs/heads/master | 2022-12-15T21:26:37.069473 | 2020-09-17T22:19:12 | 2020-09-17T22:19:12 | 276,786,324 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,521 | cpp | forward_list().cpp | //Topic: forward list in STL
//forward list is a single LL, Introduced from C++11
//It differs from list by the fact that forward list keeps track of location of only next element while list keeps track to both next and previous elements,
#include<iostream>
#include<forward_list>
using namespace std;
int main()
{
forward_list<int>list1={5,4,6,2};
forward_list<int>list2;
//assigning value using assign
list2.assign({7,6,1,9});
// insert_after() This function gives us a choice to insert elements at any position in forward list.
list1.insert_after(list1.begin(),8); //58462 //// starts insertion from second position
list1.insert_after(list1.begin(),{7,8,9}); //57898462
list1.push_front(1); //157898462 // push_front() :- This function is used to insert the element at the first position on forward list.
list1.emplace_front(0); //0157898462 //. emplace_front() :- This function is similar to the previous function but in this no copying operation occurs, the element is created directly at the memory before the first element of the forward list
list1.pop_front();//15789...//pop_front() :- This function is used to delete the first element of list.
auto ptr=list2.begin();
list2.emplace_after(++ptr,8); //76819
list2.erase_after(++ptr); //7689
list2.remove(7); //689 remove() :- This function removes the particular element from the forward list mentioned in its argument.
list2.remove_if( [] (int x) { return x>6; }); //6 remove_if() :- This function removes according to the condition in its argument.
list2.splice_after(list2.begin(),list1); //6157898562 splice_after() :- This function transfers elements from one forward list to other.
list2.reverse(); //2648987516
list2.sort(); //1245667889
forward_list<int>list3={1,5,2};
forward_list<int>list4={3,4,2};
//list3.merge(list4); //134252 ??? what?
//***Before merging two lists we must ensure the lists are in sorted order.***
list3.sort();
list4.sort();
list3.merge(list4); //122345
forward_list<int>list5={3,4,2,2,5,1,3};
list5.unique(); //342513 <<remove the all **ADJACENT** duplicate elements from forward list.>>
list5.resize(9);//342513000
list5.resize(2);//34
// If the given size is greater than the current size then new elements are inserted at the end of the forward_list. If the given size is smaller than current size then extra elements are destroyed.
for(auto i:list5)
cout<<i;
} |
c745450a2aec3327e0bd6da01a853b2f5078f74c | 70edeaa90b1e3cef4c1e64307f9e897918244a30 | /models/CpbStoryModel.cpp | fa51ef8cc30fc5bac658a27e145778a87c49a10b | [] | no_license | dmitrylis/CriticalPathBuilder | e42cee6406bf5e7da937028f3911dc1b4950e73c | 821571cb4850b2368706a961f5aff7f66b344e22 | refs/heads/master | 2022-11-06T07:22:17.019843 | 2022-10-28T12:01:06 | 2022-10-28T12:01:06 | 153,790,583 | 0 | 0 | null | 2022-10-28T12:01:07 | 2018-10-19T13:53:26 | C++ | UTF-8 | C++ | false | false | 1,801 | cpp | CpbStoryModel.cpp | #include "CpbStoryModel.h"
using namespace CPB;
StoryModel::StoryModel(QObject *parent)
: EntityModel<Story> (parent)
{
}
StoryModel::~StoryModel()
{
}
QVariant StoryModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
{
return QVariant();
}
Story* const story = m_entityList[index.row()];
switch(role) {
case StoryRoles::StoryRole:
return QVariant::fromValue(story);
case StoryRoles::TitleRole:
return story->title();
case StoryRoles::OwnerRole:
return story->owner();
case StoryRoles::RowCountRole:
return story->rowCount();
case StoryRoles::ColumnCountRole:
return story->columnCount();
case StoryRoles::TaskModelRole:
return QVariant::fromValue(story->taskModel());
default:
break;
}
return QVariant();
}
bool StoryModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
{
return false;
}
Story* const story = m_entityList[index.row()];
switch(role) {
case StoryRoles::OwnerRole:
story->setOwner(value.toString());
break;
case StoryRoles::RowCountRole:
story->setRowCount(value.toInt());
break;
default:
QAbstractListModel::setData(index, value, role);
break;
}
return true;
}
QHash<int, QByteArray> StoryModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[StoryRoles::StoryRole] = "storyRole";
roles[StoryRoles::TitleRole] = "titleRole";
roles[StoryRoles::OwnerRole] = "ownerRole";
roles[StoryRoles::RowCountRole] = "rowCountRole";
roles[StoryRoles::ColumnCountRole] = "columnCountRole";
roles[StoryRoles::TaskModelRole] = "taskModelRole";
return roles;
}
|
c61dfa90dbd25e82469c28eb63f0e15b71e7ffdf | 1d08b447a53cf225b23a27fd778bba75ed77fd53 | /NetIO.cpp | 9ed9a2232bbdd6dc344234e2b84c6c142eb37154 | [] | no_license | CyanideTD/ProxyServer | 5d501a42c74b46ac61a1d7e3c65442dbdb307ada | f41651038f178bedb1788523f0fd5c910e479ddf | refs/heads/master | 2020-03-12T19:09:35.363131 | 2018-05-04T02:44:28 | 2018-05-04T02:44:28 | 130,778,490 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,974 | cpp | NetIO.cpp | #include "NetIO.h"
extern CTaskQueue g_lNodeMgr;
NetIO::NetIO()
{
}
NetIO::~NetIO()
{
if (m_poLongConn != NULL)
{
m_poLongConn->UninitLongConn();
m_poLongConn->Release();
m_poLongConn = NULL;
}
m_poPack->Uninit();
m_poUnpack->Uninit();
}
int NetIO::Init(TCHAR* pszIp, TUINT16 uwPort, CTaskQueue* poWorkQueue, CTaskQueue* poRecvQue, bool bIsHttpListen, bool bIsConnToServ)
{
m_bIsHttpListen = bIsHttpListen;
m_poWorkQueue = poWorkQueue;
m_ReceQue = poRecvQue;
m_bIsConnToServ = bIsConnToServ;
m_uwPort = htons(uwPort);
TUINT32 ip = inet_addr(pszIp);
memcpy(m_szIp, &ip, sizeof(TUINT32));
m_poLongConn = CreateLongConnObj();
if (m_poLongConn == NULL)
{
return -1;
}
m_hListenSock = CreateListenSocket(pszIp, uwPort);
if (m_hListenSock < 0)
{
return -1;
}
if (m_poLongConn->InitLongConn(this, 1024, m_hListenSock, 100U, 0, 0, bIsHttpListen) == FALSE)
{
return -1;
}
if (bIsConnToServ)
{
m_uLockServer = m_poLongConn->CreateLongConnSession("127.0.0.1", 16060);
}
m_poPack = new CBaseProtocolPack;
m_poPack->Init();
m_poUnpack = new CBaseProtocolUnpack;
m_poUnpack->Init();
return 1;
}
TVOID* NetIO::RoutineNetIO(TVOID* pParam)
{
NetIO* netProcess = 0;
netProcess = (NetIO*) pParam;
while (1)
{
netProcess->m_poLongConn->RoutineLongConn(1000);
}
return 0;
}
SOCKET NetIO::CreateListenSocket(TCHAR* pszListenHost, TUINT16 udwPort)
{
int flag = 1;
int sock = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(int));
if (sock < 0)
{
return -1;
}
struct sockaddr_in host;
host.sin_port = htons(udwPort);
inet_aton(pszListenHost, &host.sin_addr);
host.sin_family = AF_INET;
flag = bind(sock, (struct sockaddr*)&host, sizeof(host));
if (flag < 0)
{
return -1;
}
flag = listen(sock, 1024);
if (flag < 0)
{
return -1;
}
return sock;
}
int NetIO::CloseListenSocket()
{
if (m_hListenSock >= 0)
{
close(m_hListenSock);
}
return 1;
}
TVOID NetIO::OnUserRequest(LongConnHandle stHandle, const TUCHAR* pszData, TUINT32 udwDataLen, TINT32 &dwWillResponse)
{
dwWillResponse = true;
SessionWrapper* session = 0;
g_lNodeMgr.WaitTillPop(session);
memcpy(session->m_szData, pszData, udwDataLen);
std::string s((char*)session->m_szData, session->m_udwBufLen);
if (s.find("favicon") != std::string::npos)
{
session->Reset();
g_lNodeMgr.WaitTillPush(session);
return;
}
session->m_stHandle = stHandle;
session->m_udwBufLen = udwDataLen;
session->m_bIsBinaryData = !m_bIsHttpListen;
m_poUnpack->UntachPackage();
m_poUnpack->AttachPackage(session->m_szData, session->m_udwBufLen);
m_poUnpack->Unpack();
int service = m_poUnpack->GetServiceType();
if (service == EN_SERVICE_TYPE_RESOURCE_GET || EN_SERVICE_TYPE_RESOURCE_COST)
{
session->m_sState = GET_REQ;
m_poWorkQueue->WaitTillPush(session);
}
else
{
}
}
TVOID NetIO::OnTasksFinishedCallBack(LTasksGroup* pstTasksGrp)
{
SessionWrapper* session = 0;
session = (SessionWrapper*) pstTasksGrp->m_UserData1.ptr;
memcpy(session->m_szData, pstTasksGrp->m_Tasks[0]._pReceivedData, pstTasksGrp->m_Tasks[0]._uReceivedDataLen);
session->m_udwBufLen = pstTasksGrp->m_Tasks[0]._uReceivedDataLen;
m_poUnpack->UntachPackage();
m_poUnpack->AttachPackage(session->m_szData, session->m_udwBufLen);
m_poUnpack->Unpack();
int service = m_poUnpack->GetServiceType();
if (session->m_sState == SEND_BACK || service == EN_SERVICE_TYPE_LOCK2HU__GET_RSP || service == EN_SERVICE_TYPE_LOCK2HU__RELEASE_RSP)
{
m_poWorkQueue->WaitTillPush(session);
}
else
{
}
}
|
afc3a254e0620e807f9746c923214088048f2e70 | 400857d7bf2a490b253777c5815260025803a728 | /ifopt_core/src/composite.cc | 831aeba7e8b67672e62ec84fa1e06ebc6e6aa411 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ethz-adrl/ifopt | e7565adb52a47c34fb538612ed3d05f9e3588259 | 1082d9d5ab61d2734fc318d61dcfefce6fb19bd3 | refs/heads/master | 2023-08-08T04:34:07.657345 | 2023-08-04T13:38:44 | 2023-08-04T13:39:22 | 114,131,004 | 661 | 157 | BSD-3-Clause | 2023-09-14T13:58:46 | 2017-12-13T14:30:12 | C++ | UTF-8 | C++ | false | false | 5,834 | cc | composite.cc | /******************************************************************************
Copyright (c) 2017, Alexander W Winkler. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include <ifopt/composite.h>
#include <iomanip>
#include <iostream>
namespace ifopt {
Component::Component(int num_rows, const std::string& name)
{
num_rows_ = num_rows;
name_ = name;
}
int Component::GetRows() const
{
return num_rows_;
}
void Component::SetRows(int num_rows)
{
num_rows_ = num_rows;
}
std::string Component::GetName() const
{
return name_;
}
void Component::Print(double tol, int& index) const
{
// calculate squared bound violation
VectorXd x = GetValues();
VecBound bounds = GetBounds();
std::vector<int> viol_idx;
for (std::size_t i = 0; i < bounds.size(); ++i) {
double lower = bounds.at(i).lower_;
double upper = bounds.at(i).upper_;
double val = x(i);
if (val < lower - tol || upper + tol < val)
viol_idx.push_back(i); // constraint out of bounds
}
std::string black = "\033[0m";
std::string red = "\033[31m";
std::string color = viol_idx.empty() ? black : red;
std::cout.precision(2);
std::cout << std::fixed << std::left << std::setw(30) << name_ << std::right
<< std::setw(4) << num_rows_ << std::setw(9) << index
<< std::setfill('.') << std::setw(7) << index + num_rows_ - 1
<< std::setfill(' ') << color << std::setw(12) << viol_idx.size()
<< black << std::endl;
index += num_rows_;
}
Composite::Composite(const std::string& name, bool is_cost) : Component(0, name)
{
is_cost_ = is_cost;
}
void Composite::AddComponent(const Component::Ptr& c)
{
// at this point the number of rows must be specified.
assert(c->GetRows() != kSpecifyLater);
components_.push_back(c);
if (is_cost_)
SetRows(1);
else
SetRows(GetRows() + c->GetRows());
}
void Composite::ClearComponents()
{
components_.clear();
SetRows(0);
}
const Component::Ptr Composite::GetComponent(std::string name) const
{
for (const auto& c : components_)
if (c->GetName() == name)
return c;
assert(false); // component with name doesn't exist, abort program
return Component::Ptr();
}
Composite::VectorXd Composite::GetValues() const
{
VectorXd g_all = VectorXd::Zero(GetRows());
int row = 0;
for (const auto& c : components_) {
int n_rows = c->GetRows();
VectorXd g = c->GetValues();
g_all.middleRows(row, n_rows) += g;
if (!is_cost_)
row += n_rows;
}
return g_all;
}
void Composite::SetVariables(const VectorXd& x)
{
int row = 0;
for (auto& c : components_) {
int n_rows = c->GetRows();
c->SetVariables(x.middleRows(row, n_rows));
row += n_rows;
}
}
Composite::Jacobian Composite::GetJacobian() const
{ // set number of variables only the first time this function is called,
// since number doesn't change during the optimization. Improves efficiency.
if (n_var == -1)
n_var = components_.empty() ? 0 : components_.front()->GetJacobian().cols();
Jacobian jacobian(GetRows(), n_var);
if (n_var == 0)
return jacobian;
int row = 0;
std::vector<Eigen::Triplet<double>> triplet_list;
for (const auto& c : components_) {
const Jacobian& jac = c->GetJacobian();
triplet_list.reserve(triplet_list.size() + jac.nonZeros());
for (int k = 0; k < jac.outerSize(); ++k)
for (Jacobian::InnerIterator it(jac, k); it; ++it)
triplet_list.push_back(
Eigen::Triplet<double>(row + it.row(), it.col(), it.value()));
if (!is_cost_)
row += c->GetRows();
}
jacobian.setFromTriplets(triplet_list.begin(), triplet_list.end());
return jacobian;
}
Composite::VecBound Composite::GetBounds() const
{
VecBound bounds_;
for (const auto& c : components_) {
VecBound b = c->GetBounds();
bounds_.insert(bounds_.end(), b.begin(), b.end());
}
return bounds_;
}
const Composite::ComponentVec Composite::GetComponents() const
{
return components_;
}
void Composite::PrintAll() const
{
int index = 0;
double tol =
0.001; ///< tolerance when printing out constraint/bound violation.
std::cout << GetName() << ":\n";
for (auto c : components_) {
std::cout << " "; // indent components
c->Print(tol, index);
}
std::cout << std::endl;
}
} // namespace ifopt
|
aa85c148acacd2cd7f6e13a855785edbe1b3ffe1 | 54b6f6a641dc6aa82791335d5ee0bd451861e451 | /qmtp/identifiable/qmtpalbum.cpp | d1e7a5d650aee75b92f1235a14afedec91afdbfe | [] | no_license | ssharunas/qmtp | ffd7af6bee693012cc25dee797383de333a54a61 | 098ae2ab4fe56f22a2c0de81307cdb81b2640353 | refs/heads/master | 2016-08-04T02:43:11.834241 | 2010-02-12T14:32:45 | 2010-02-12T14:32:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51 | cpp | qmtpalbum.cpp | #include "qmtpalbum.h"
QMtpAlbum::QMtpAlbum()
{
}
|
ac26e80e5bbfb86160df3ceb9c0bc5e7f7f79f8c | e26a898f8399693f3c2e85828b8fd4969985a84c | /ChanukahChallenge/chanukahChallenge.cpp | 7d4753073bf8e2959c03a596e9afe34c43eca405 | [] | no_license | SKajiwara/Jan2.2021.OneKattisADayChallenge | d3ab6124d527f6716c85a2be289a2637de79dd74 | 8d0cd2f92be0a89f7ad3e319e750040a78e4bef2 | refs/heads/main | 2023-02-22T13:02:35.715815 | 2021-01-25T22:49:58 | 2021-01-25T22:49:58 | 326,895,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 356 | cpp | chanukahChallenge.cpp | #include <iostream>
using namespace std;
int main()
{
int num, index, days, candles;
cin >> num;
for (int i = 1; i <= num; i++)
{
candles = 0;
cin >> index >> days;
for (int j = 2; j < (days + 2); j++)
{
candles += j;
}
cout << i << ' ' << candles << endl;
}
return 0;
} |
f3d378b5efdc582857ec2c45ef663c34ac4ac288 | 0c436f330bb6fa217593da614c451d32ecef0a3f | /La_Rochelle/IUT/iOS/Learn_iOS/VariousSequenceMatchingTechniques/VariousSequenceMatchingTechniques/commandlineapplication.h | f7c218548180a6e31cb978bb014354f92350b643 | [
"MIT",
"BSL-1.0"
] | permissive | tanmayGIT/Teaching | 8dc4c8633f1f259fd0b479684a99804b7d9a9fe5 | bd8775090f9e000a1ae2a8045cccf7fb3bff0654 | refs/heads/master | 2021-09-22T16:28:04.040274 | 2021-09-14T09:13:24 | 2021-09-14T09:13:24 | 228,865,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | commandlineapplication.h | /*!
\author Abdourahman Aden Hassan
Bastien Meunier
\date 05/01/2014
20/01/2015
\package commandline
\class CommandeLineApplication
\implements CommandeLine
\brief Class for the basic execution type
*/
#ifndef COMMANDLINEAPPLICATION_H
#define COMMANDLINEAPPLICATION_H
#include "CommandLine.h"
namespace commandline{
class CommandLineApplication : public CommandLine
{
public:
CommandLineApplication(int argc, char *argv[]) : CommandLine(argc,argv){};
void run();
};
}
#endif // COMMANDLINEAPPLICATION_H
|
a23c3bf229a178f966ce05112f72df0d9845b256 | b830c214c44439b9ab877cd079e094ead0375127 | /Banker's Algorithm.cpp | 90789154bca39b6c2eff368df9833abc51765018 | [] | no_license | SamarNegm/acm | 15251c27edb73031bf71d576602414a38a3cdccc | 0e25172073e178d593d8eb3ca484a868714aefcc | refs/heads/master | 2022-08-21T16:37:23.687751 | 2020-05-30T00:51:25 | 2020-05-30T00:51:25 | 267,983,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,830 | cpp | Banker's Algorithm.cpp | #include<bits/stdc++.h>
using namespace std;
int alloc[10000][10000];
int mat[10000][10000];
int need[10000][10000];
int finsh[100000];
int av[100000];
int n,m;
int main()
{
cout<<"Enter n & m\n";
cin>>n>>m;
cout<<"Enter the matrix\n";
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
cin>>mat[i][j];
}
cout<<"Enter allocation matrix\n";
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
cin>>alloc[i][j];
}
cout<<"The needed matrix\n";
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++){
need[i][j]=mat[i][j]-alloc[i][j];
cout<<need[i][j]<<" ";
}
cout<<"\n";
}
cout<<"Enter avilable\n";
for(int i=0; i<n; i++)
cin>>av[i];
int k=0;
while(k<n)
{
bool flg=0;
int j;
for(int i=0; i<n; i++)
{
if(finsh[i])
continue;
for( j=0; j<m; j++)
{
cout<<av[j]<<" "<<need[i][j]<<"\n";
if(av[j]<need[i][j])
{
break;
}
}
cout<<" \nend of iterration\n\n";
if(j==m)
{
finsh[i]=1;
k++;
flg=1;
//update av
cout<<"THE UPDATED AVILABLE\n";
for(int j=0; j<m; j++)
{
av[j]+=alloc[i][j];
cout<<av[j]<<" ";
}
cout<<"\n\n";
}
}
if(flg==0)
{
cout<<"Not save\n";
break;
}
}
if(n==k)
cout<<"Save\n";
return 0;
}/*
7 5 3
3 2 2
9 0 2
0 1 0
2 0 0
3 0 2
1 0 3
0 1 2
1 2 0
1 0 3
0 1 2
1 2 0
*/
|
c39a01f87ee24db88be1290f209694c5135de759 | b8376621d63394958a7e9535fc7741ac8b5c3bdc | /lib/lib_mech/src/base/base/m_FrameRate.h | 7ee4d708f7989c36fdd1b325782d70e2b6e81a1d | [] | no_license | 15831944/job_mobile | 4f1b9dad21cb7866a35a86d2d86e79b080fb8102 | ebdf33d006025a682e9f2dbb670b23d5e3acb285 | refs/heads/master | 2021-12-02T10:58:20.932641 | 2013-01-09T05:20:33 | 2013-01-09T05:20:33 | null | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 1,938 | h | m_FrameRate.h | /*
filename: m_FrameRate.h
coder : Cho Wook Rea (mech12@hanmail.net)
compiler: vc++ 6.0
date : 1999 /
title :
*/
#if !defined(AFX_M_FRAMERATE_H__E47B14E7_E6E0_11D2_8FBA_00A02486A654__INCLUDED_)
#define AFX_M_FRAMERATE_H__E47B14E7_E6E0_11D2_8FBA_00A02486A654__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define M_USING_FRAMERATE
#define MOVEPIXEL_PER_SEC_BY_KEY 180
#include "header/jRDTSC.h"
namespace nMech
{
namespace nTIME
{
extern uint32 e,s;
class JBASE_API CFrameRate
{
unsigned int m_FrameTime; // Time of the last frame.
unsigned int m_Frames; // The frame rate (frames/second).
unsigned int m_Count; // Frames displayed.
unsigned int time ;
public:
CFrameRate(){Init();}
void Init();
void Update();
operator int(){return m_Frames;}
int GetFramePerSec(){return m_Frames;}
unsigned int GetClock(){return time;}
//////////////////////////////////////////////
// RDTSC┐Ű.
//////////////////////////////////////////////
void Start(){ RDTSC(s); }
unsigned int End(){RDTSC(e);return e-s;}
// virtual ~CFrameRate(){;};
};
}//nTIME
}
#if 0
#ifndef __CClock__
#define __CClock__
#include <time.h>
#if !defined( CLOCKS_PER_SEC )
#define CLOCKS_PER_SEC CLK_TCK
#endif
class CFps{
private:
clock_t m_Begin,m_End;
clock_t m_Max , m_Min, m_Curr;
public:
void Init(){m_Max = m_Begin =0; m_Min = 9999;}
void Begin(){m_Begin=clock(); }
void End(){ m_Curr = clock()-m_Begin; }
float GetTimePerFrame(){ return (float)(m_Curr)/(float)(CLOCKS_PER_SEC);}
const long& GetClockPerFrame() const { return m_Curr;}
const long& GetMaxClock() const {return m_Max;}
const long& GetMinClock() const {return m_Min;}
};
#endif //__CClock__
#endif
#endif // !defined(AFX_M_FRAMERATE_H__E47B14E7_E6E0_11D2_8FBA_00A02486A654__INCLUDED_)
|
c3741a30e1bb0d278633703a40feb76c6693a653 | e87c19d6694143df66f05bd06b010043a63bfe2f | /stl/string.cc | c61a4b6ad2a14459b3d09a40c348de7f07343a88 | [
"MIT"
] | permissive | Becavalier/playground-cpp | 2c38d016dc66c4293bc17d8945b3fec8983a635b | 0fce453f769111698f813852238f933e326ed441 | refs/heads/master | 2021-04-18T20:27:27.965096 | 2018-10-27T01:29:46 | 2018-10-27T01:29:46 | 94,588,693 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,822 | cc | string.cc | #include <string>
#include <cctype>
#include <locale>
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
string s1;
string s2 = s1;
// Copy initilization;
string s3 = "hiya";
// Directly initilization;
string s4(10, 'c');
string s5 = string(10, 'c');
/*
* string temp(10, 'c');
* string s5 = temp;
*/
string s6;
cin >> s6;
cout << s6 << endl;
string line;
// Type of string::size_type;
string::size_type lineLength;
while(getline(cin, line)) {
lineLength = line.size();
cout << lineLength << ": " << line << endl;
if (lineLength == 2)
break;
}
// "+"
cout << s3 + s4 << endl;
// Standard string dealing procedures <cctype>
cout << isalnum(s3[0]) << endl;
// Use "for" to iterate string
for (auto c : (s3 + s4)) {
cout << "char: " << c << endl;
}
string s("Hello World!!");
decltype(s3.size()) punct_cnt = 0;
for (auto c : s) {
if (ispunct(c))
++punct_cnt;
}
cout << "The punct count is: " << punct_cnt << endl;
for (auto &c : s) {
c = toupper(c);
}
cout << s << endl;
const string hexdigits = "0123456789ABCDEF";
cout << "Input numbers: " << endl;
string result;
string::size_type n;
while (cin >> n) {
if (n == 0)
break;
if (n < hexdigits.size())
result += hexdigits[n];
}
cout << "Result: " << result << endl;
// Readable and writable (!!only read or edit with iterator!!);
for (string::iterator it = s3.begin(); it != s3.end(); it++) {
*it = 'j';
cout << *it << endl;
// cout << (*it).empty() << endl;
}
// Read only;
for (string::const_iterator it = s3.begin(); it != s3.end(); it++) {
cout << *it << endl;
}
for (auto it = s3.cbegin(); it != s3.cend(); it++) {
cout << *it << endl;
}
return 0;
}
|
f28a010a326c1bc8980abf457025f6fb66c6394e | 1ff855f95822a9c0bf8ec296f2219407ee826276 | /src/t_socket.cpp | 869dab868b6d14d88f091277868e246c3357355b | [
"MIT"
] | permissive | Forsteholdet/TinyClient | ab4ec0d4f45a9b24bdceb36712b6d3843814586c | f606f89b6965c15537e17971b70ef768090ded3b | refs/heads/main | 2023-04-07T20:10:57.420979 | 2021-04-13T07:41:49 | 2021-04-13T07:41:49 | 339,339,457 | 0 | 0 | MIT | 2021-07-30T08:05:22 | 2021-02-16T09:02:33 | C++ | UTF-8 | C++ | false | false | 62 | cpp | t_socket.cpp | //
// Created by anders on 2/25/21.
//
#include "t_socket.h"
|
e3e02635a89ac4cdbe64838f9d59b09d3ece79de | 49e20f71157f05c4c895f941ec64db7e286324b1 | /dsp/L2/tests/aie/widget_api_cast/test.cpp | 366dd7da51c5bc4d3ebd08785e6295643b4b6d4b | [
"Apache-2.0",
"OFL-1.1",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"BSD-2-Clause",
"MIT"
] | permissive | mahinlma/Vitis_Libraries | 06095f1e72b4d3eba0980e89852cf188aaec7b07 | af74a0c74377fc3126f1ba846063ed4bf6bd8bb0 | refs/heads/master | 2021-12-02T19:20:42.806076 | 2021-08-17T05:54:45 | 2021-08-17T05:54:45 | 232,494,142 | 0 | 0 | Apache-2.0 | 2020-04-13T04:52:53 | 2020-01-08T06:26:29 | null | UTF-8 | C++ | false | false | 3,869 | cpp | test.cpp | /*
* Copyright 2021 Xilinx, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
This file holds the body of the test harness for the widger api cast
reference model graph
*/
#include <stdio.h>
#include "test.hpp"
#if (NUM_INPUTS == 1)
#if (NUM_OUTPUT_CLONES == 1)
simulation::platform<1, 1> platform(QUOTE(INPUT_FILE), QUOTE(OUTPUT_FILE));
#elif (NUM_OUTPUT_CLONES == 2)
simulation::platform<1, 2> platform(QUOTE(INPUT_FILE), QUOTE(OUTPUT_FILE), QUOTE(OUTPUT_FILE2));
#elif (NUM_OUTPUT_CLONES == 3)
simulation::platform<1, 3> platform(QUOTE(INPUT_FILE), QUOTE(OUTPUT_FILE), QUOTE(OUTPUT_FILE2), QUOTE(OUTPUT_FILE3));
#elif (NUM_OUTPUT_CLONES == 4)
simulation::platform<1, 4> platform(
QUOTE(INPUT_FILE), QUOTE(OUTPUT_FILE), QUOTE(OUTPUT_FILE2), QUOTE(OUTPUT_FILE3), QUOTE(OUTPUT_FILE4));
#endif
#elif (NUM_INPUTS == 2)
#if (NUM_OUTPUT_CLONES == 1)
simulation::platform<2, 1> platform(QUOTE(INPUT_FILE), QUOTE(INPUT_FILE2), QUOTE(OUTPUT_FILE));
#elif (NUM_OUTPUT_CLONES == 2)
simulation::platform<2, 2> platform(QUOTE(INPUT_FILE), QUOTE(INPUT_FILE2), QUOTE(OUTPUT_FILE), QUOTE(OUTPUT_FILE2));
#elif (NUM_OUTPUT_CLONES == 3)
simulation::platform<2, 3> platform(
QUOTE(INPUT_FILE), QUOTE(INPUT_FILE2), QUOTE(OUTPUT_FILE), QUOTE(OUTPUT_FILE2), QUOTE(OUTPUT_FILE3));
#elif (NUM_OUTPUT_CLONES == 4)
simulation::platform<2, 4> platform(QUOTE(INPUT_FILE),
QUOTE(INPUT_FILE2),
QUOTE(OUTPUT_FILE),
QUOTE(OUTPUT_FILE2),
QUOTE(OUTPUT_FILE3),
QUOTE(OUTPUT_FILE4));
#endif
#endif
xf::dsp::aie::testcase::test_graph widgetTestHarness;
// Connect platform to uut
connect<> net_in0(platform.src[0], widgetTestHarness.in[0]);
#if (NUM_INPUTS > 1)
connect<> net_in1(platform.src[1], widgetTestHarness.in[1]);
#endif
connect<> net_out0(widgetTestHarness.out[0], platform.sink[0]);
#if (NUM_OUTPUT_CLONES > 1)
connect<> net_out2(widgetTestHarness.out[1], platform.sink[1]);
#endif
#if (NUM_OUTPUT_CLONES > 2)
connect<> net_out3(widgetTestHarness.out[2], platform.sink[2]);
#endif
#if (NUM_OUTPUT_CLONES > 3)
connect<> net_out4(widgetTestHarness.out[3], platform.sink[3]);
#endif
int main(void) {
printf("\n");
printf("========================\n");
printf("UUT: ");
printf(QUOTE(UUT_GRAPH));
printf("\n");
printf("========================\n");
printf("Number of samples = %d \n", WINDOW_VSIZE);
switch (IN_API) {
case 0:
printf("Input API = window\n");
break;
case 1:
printf("Input API = stream\n");
break;
default:
printf("Input API unrecognised = %d\n", IN_API);
break;
};
switch (OUT_API) {
case 0:
printf("Output API = window\n");
break;
case 1:
printf("Output API = stream\n");
break;
default:
printf("Output API unrecognised = %d\n", OUT_API);
break;
};
printf("Data type = ");
printf(QUOTE(DATA_TYPE));
printf("\n");
printf("NUM_OUTPUT_CLONES = %d \n", NUM_OUTPUT_CLONES);
printf("\n");
widgetTestHarness.init();
widgetTestHarness.run(NITER);
widgetTestHarness.end();
return 0;
}
|
25740c86800f375c33ead2c61add31889512cfee | 2b8fb66ed7fe286420b409a09d9cea55e20430da | /qt/cursoQt/apostila/03_gui/03_05_mdi/ui_form2.h | 6078025071fa690fd80b5847d1e2baf0650d9ce7 | [] | no_license | marvinfy/Trainings | 3826c9097210c669cf1298d2bccc86fcfa8ef3a5 | d1caaf8ac972bb2a695c07af4f722fdcb7ef293f | refs/heads/master | 2021-01-01T15:15:55.450954 | 2012-12-15T20:12:23 | 2012-12-15T20:12:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,447 | h | ui_form2.h | /********************************************************************************
** Form generated from reading ui file 'form2.ui'
**
** Created: Fri 30. Oct 21:13:46 2009
** by: Qt User Interface Compiler version 4.5.3
**
** WARNING! All changes made in this file will be lost when recompiling ui file!
********************************************************************************/
#ifndef UI_FORM2_H
#define UI_FORM2_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QComboBox>
#include <QtGui/QHeaderView>
#include <QtGui/QSpacerItem>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Form2
{
public:
QVBoxLayout *verticalLayout;
QSpacerItem *verticalSpacer;
QComboBox *comboBox;
QSpacerItem *verticalSpacer_2;
void setupUi(QWidget *Form2)
{
if (Form2->objectName().isEmpty())
Form2->setObjectName(QString::fromUtf8("Form2"));
Form2->resize(422, 213);
Form2->setMinimumSize(QSize(422, 213));
verticalLayout = new QVBoxLayout(Form2);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Fixed);
verticalLayout->addItem(verticalSpacer);
comboBox = new QComboBox(Form2);
comboBox->setObjectName(QString::fromUtf8("comboBox"));
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(comboBox->sizePolicy().hasHeightForWidth());
comboBox->setSizePolicy(sizePolicy);
verticalLayout->addWidget(comboBox);
verticalSpacer_2 = new QSpacerItem(20, 204, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer_2);
retranslateUi(Form2);
QMetaObject::connectSlotsByName(Form2);
} // setupUi
void retranslateUi(QWidget *Form2)
{
Form2->setWindowTitle(QApplication::translate("Form2", "Formul\303\241rio - 2", 0, QApplication::UnicodeUTF8));
Q_UNUSED(Form2);
} // retranslateUi
};
namespace Ui {
class Form2: public Ui_Form2 {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_FORM2_H
|
2f9510ac66bfc31fceda7d090d06e896d7ead6e3 | 31f9ebed3a88dbbf21a5d62f32b82da0c4823398 | /ProjectSourceCode/player/ui_win3.h | 80577d19fc10a46a95ae7fe8c7dd7d464cc0ace1 | [] | no_license | LuoShen0/-Qt-Multimedia-player | 7ac6b91cac4898270c1d6c1260dc72dabbfd1020 | 8a2b177d70b2cda54b9124cc2d950601db8ad757 | refs/heads/master | 2022-04-22T02:26:20.883637 | 2020-04-21T05:36:49 | 2020-04-21T05:36:49 | 257,489,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,661 | h | ui_win3.h | /********************************************************************************
** Form generated from reading UI file 'win3.ui'
**
** Created by: Qt User Interface Compiler version 5.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_WIN3_H
#define UI_WIN3_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QListWidget>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSlider>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_win3
{
public:
QWidget *centralwidget;
QLabel *label;
QListWidget *listWidget;
QPushButton *pushButton;
QPushButton *pushButton_2;
QPushButton *pushButton_3;
QPushButton *pushButton_4;
QPushButton *pushButton_5;
QPushButton *pushButton_6;
QPushButton *pushButton_7;
QPushButton *pushButton_8;
QLabel *label_2;
QLabel *label_3;
QLabel *label_4;
QSlider *horizontalSlider;
QPushButton *pushButton_10;
void setupUi(QMainWindow *win3)
{
if (win3->objectName().isEmpty())
win3->setObjectName(QStringLiteral("win3"));
win3->resize(800, 480);
QFont font;
font.setPointSize(11);
win3->setFont(font);
win3->setStyleSheet(QStringLiteral("background-color: rgb(41, 0, 0);"));
centralwidget = new QWidget(win3);
centralwidget->setObjectName(QStringLiteral("centralwidget"));
label = new QLabel(centralwidget);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(70, 290, 521, 71));
QFont font1;
font1.setPointSize(15);
label->setFont(font1);
label->setStyleSheet(QStringLiteral("color: rgb(114, 159, 207);"));
listWidget = new QListWidget(centralwidget);
listWidget->setObjectName(QStringLiteral("listWidget"));
listWidget->setGeometry(QRect(610, 50, 191, 351));
listWidget->setStyleSheet(QStringLiteral("color: rgb(238, 238, 236);"));
pushButton = new QPushButton(centralwidget);
pushButton->setObjectName(QStringLiteral("pushButton"));
pushButton->setGeometry(QRect(680, 430, 111, 41));
QFont font2;
font2.setPointSize(10);
pushButton->setFont(font2);
pushButton->setStyleSheet(QLatin1String("color: rgb(238, 238, 236);\n"
"border:2px groove gray;\n"
"border-radius:7px;\n"
"padding:2px 4px;"));
pushButton_2 = new QPushButton(centralwidget);
pushButton_2->setObjectName(QStringLiteral("pushButton_2"));
pushButton_2->setGeometry(QRect(80, 420, 51, 41));
QFont font3;
font3.setPointSize(8);
pushButton_2->setFont(font3);
pushButton_2->setStyleSheet(QLatin1String("color: rgb(238, 238, 236);\n"
"border:2px groove gray;\n"
"border-radius:20px;\n"
"padding:2px 4px;"));
pushButton_3 = new QPushButton(centralwidget);
pushButton_3->setObjectName(QStringLiteral("pushButton_3"));
pushButton_3->setGeometry(QRect(150, 420, 51, 41));
pushButton_3->setFont(font3);
pushButton_3->setStyleSheet(QLatin1String("color: rgb(238, 238, 236);\n"
"border:2px groove gray;\n"
"border-radius:20px;\n"
"padding:2px 4px;"));
pushButton_4 = new QPushButton(centralwidget);
pushButton_4->setObjectName(QStringLiteral("pushButton_4"));
pushButton_4->setGeometry(QRect(220, 420, 51, 41));
pushButton_4->setFont(font3);
pushButton_4->setStyleSheet(QLatin1String("color: rgb(238, 238, 236);\n"
"border:2px groove gray;\n"
"border-radius:20px;\n"
"padding:2px 4px;"));
pushButton_5 = new QPushButton(centralwidget);
pushButton_5->setObjectName(QStringLiteral("pushButton_5"));
pushButton_5->setGeometry(QRect(280, 400, 71, 71));
pushButton_5->setStyleSheet(QLatin1String("color: rgb(238, 238, 236);\n"
"border:2px groove gray;\n"
"border-radius:28px;\n"
"padding:2px 4px;"));
pushButton_6 = new QPushButton(centralwidget);
pushButton_6->setObjectName(QStringLiteral("pushButton_6"));
pushButton_6->setGeometry(QRect(370, 420, 51, 41));
pushButton_6->setFont(font3);
pushButton_6->setStyleSheet(QLatin1String("color: rgb(238, 238, 236);\n"
"border:2px groove gray;\n"
"border-radius:20px;\n"
"padding:2px 4px;"));
pushButton_7 = new QPushButton(centralwidget);
pushButton_7->setObjectName(QStringLiteral("pushButton_7"));
pushButton_7->setGeometry(QRect(440, 420, 51, 41));
pushButton_7->setFont(font3);
pushButton_7->setStyleSheet(QLatin1String("color: rgb(238, 238, 236);\n"
"border:2px groove gray;\n"
"border-radius:20px;\n"
"padding:2px 4px;"));
pushButton_8 = new QPushButton(centralwidget);
pushButton_8->setObjectName(QStringLiteral("pushButton_8"));
pushButton_8->setGeometry(QRect(0, 430, 61, 41));
pushButton_8->setStyleSheet(QLatin1String("color: rgb(238, 238, 236);\n"
"border-image: url(:/r1.jpg);\n"
"border:2px groove gray;\n"
"border-radius:7px;\n"
"padding:2px 4px;"));
label_2 = new QLabel(centralwidget);
label_2->setObjectName(QStringLiteral("label_2"));
label_2->setGeometry(QRect(10, 240, 531, 31));
label_2->setStyleSheet(QLatin1String("\n"
"color: rgb(238, 238, 236);"));
label_3 = new QLabel(centralwidget);
label_3->setObjectName(QStringLiteral("label_3"));
label_3->setGeometry(QRect(610, 10, 181, 21));
label_3->setStyleSheet(QStringLiteral("color: rgb(238, 238, 236);"));
label_4 = new QLabel(centralwidget);
label_4->setObjectName(QStringLiteral("label_4"));
label_4->setGeometry(QRect(0, 0, 400, 225));
label_4->setStyleSheet(QStringLiteral("background-color: rgb(41, 0, 0);"));
horizontalSlider = new QSlider(centralwidget);
horizontalSlider->setObjectName(QStringLiteral("horizontalSlider"));
horizontalSlider->setGeometry(QRect(10, 370, 531, 16));
horizontalSlider->setStyleSheet(QStringLiteral(""));
horizontalSlider->setOrientation(Qt::Horizontal);
pushButton_10 = new QPushButton(centralwidget);
pushButton_10->setObjectName(QStringLiteral("pushButton_10"));
pushButton_10->setGeometry(QRect(570, 430, 91, 41));
pushButton_10->setFont(font3);
pushButton_10->setStyleSheet(QLatin1String("border:2px groove gray;\n"
"color: rgb(238, 238, 236);\n"
"border-radius:10px;\n"
"padding:2px 4px;"));
win3->setCentralWidget(centralwidget);
retranslateUi(win3);
QMetaObject::connectSlotsByName(win3);
} // setupUi
void retranslateUi(QMainWindow *win3)
{
win3->setWindowTitle(QApplication::translate("win3", "MainWindow", 0));
label->setText(QApplication::translate("win3", " \345\215\225\345\207\273\351\237\263\344\271\220\345\220\215\347\247\260\345\217\257\346\222\255\346\224\276\351\237\263\344\271\220", 0));
pushButton->setText(QApplication::translate("win3", "\346\267\273\345\212\240\351\237\263\344\271\220", 0));
pushButton_2->setText(QApplication::translate("win3", "\345\277\253\350\277\233 ", 0));
pushButton_3->setText(QApplication::translate("win3", "\345\277\253\351\200\200", 0));
pushButton_4->setText(QApplication::translate("win3", "\346\232\202\345\201\234", 0));
pushButton_5->setText(QApplication::translate("win3", "\346\222\255\346\224\276", 0));
pushButton_6->setText(QApplication::translate("win3", "\351\237\263\351\207\217+", 0));
pushButton_7->setText(QApplication::translate("win3", "\351\237\263\351\207\217-", 0));
pushButton_8->setText(QString());
label_2->setText(QApplication::translate("win3", "\346\255\214\350\257\215\345\244\247\346\204\217 \357\274\232(\346\217\220\347\244\272\357\274\232\345\217\257\350\207\252\345\212\250\350\267\263\350\275\254\345\210\260\344\270\213\351\246\226\344\270\200\351\237\263\344\271\220)", 0));
label_3->setText(QApplication::translate("win3", "\351\237\263\344\271\220\345\210\227\350\241\250\357\274\232", 0));
label_4->setText(QApplication::translate("win3", "TextLabel", 0));
pushButton_10->setText(QApplication::translate("win3", "ON/OFF\345\210\227\350\241\250", 0));
} // retranslateUi
};
namespace Ui {
class win3: public Ui_win3 {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_WIN3_H
|
81dbc3f7dd91d64963c4571b231da391f9b84ef6 | fef8ff5b42eeb6b562824a87608bb87fb4b638e5 | /usb/usb.cpp | 2e86ad7ba34f231c280ef613052b8dd967cedffb | [] | no_license | Sync1983/avr_common | 52ae0002644404c135e62e5ced6efa6a0d5586ee | f068e76faf8d148bdcee104a84899f0440bd1fa3 | refs/heads/master | 2021-04-28T21:53:57.295364 | 2017-01-01T01:36:05 | 2017-01-01T01:36:05 | 77,761,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,805 | cpp | usb.cpp | /*
* usb.cpp
*
* Created: 23.12.2016 22:42:26
* Author: Sync
*/
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "usb.h"
#include "../common/common.h"
#include <string.h>
USB::USB(uint16_t vid, uint16_t pid, float usbVer, bool useString){
this->useStr = useString;
uint8_t hiVer = (uint8_t)usbVer;
uint8_t loVer = (uint8_t)((usbVer - (float)hiVer)*10)<<4;
this->device.len = sizeof(device);
this->device.dtype = 0x01;
this->device.usbVersion = 0x0110,//(hiVer<<8) | loVer;
this->device.deviceClass = 0x00;
this->device.deviceSubClass = 0x00;
this->device.deviceProtocol = 0x00;
this->device.packetSize0 = 64;
this->device.idVendor = vid;
this->device.idProduct = pid;
this->device.deviceVersion = 0x0101;
this->device.iManufacturer = this->getStrId();
this->device.iProduct = this->getStrId();
this->device.iSerialNumber = this->getStrId();
this->device.bNumConfigurations = 1;
}
void USB::initPLL(){
PLLFRQ = 0b01001010; //Set PLL freq 96MHz and PLL USB divider 2
PLLCSR |= (1<<PINDIV); //Set PLL div for 16MHz
PLLCSR |= (1<<PLLE);
while( (PLLCSR & 0x01) == 0)
;
}
void USB::init(){
cli();
this->isEnum = false;
this->initPLL();
UHWCON = 0b00000001;
USBCON |= (1<<OTGPADE) | (1<<USBE) | (1<<FRZCLK);
USBCON &= ~(1<<FRZCLK); // UNFREEZE;
_delay_ms(1);
UDCON &= ~(1<<DETACH); // ATTACH;
UDIEN = (1<<EORSTE);
sei();
}
bool USB::isEnumerate(){
return this->isEnum;
}
uint8_t USB::getStrId(){
return (this->useStr?++this->stringCounter:0);
}
inline void USB::sof(void){
}
inline void USB::eorst(void){
this->initControl();
UDIEN &= ~(1<<EORSTE);
}
void USB::waitIn(void){
while (!(UEINTX & (1<<TXINI)))
;
}
void USB::clearIn(void){
UEINTX &= ~((1<<FIFOCON)|(1<<TXINI));
this->sendBufPos = 0;
}
inline void USB::stall(void){
UECONX |= (1<<STALLRQ);
}
inline void USB::readBuf(uint8_t *buffer, uint8_t size){
while(size--){
*(buffer++) = UEDATX;
}
}
void USB::writeBuf(volatile const uint8_t *buffer, uint8_t bufSize, uint8_t maxSize){
volatile uint8_t buf[50],pos = 0;
this->selectEndPoint(0);
memcpy((void*)&buf,(void*)buffer,bufSize);
//if( (this->sendBufPos + bufSize) > maxSize ) {
// return;
//}
volatile uint8_t b;
//this->clearIn();
while(bufSize--){
b = buf[pos++];//*buffer++;
UEDATX = b;
this->sendBufPos++;
}
}
void USB::initControl(void){
this->initInternalEndpoint(0, CONTROL,OUT,SIZE64,ONE);
UEIENX = (1 << RXSTPE);
}
void USB::selectEndPoint(uint8_t num){
UENUM = ((num) & 0x0F);
}
bool USB::initInternalEndpoint(uint8_t num, upType type, upDirection dir,upSize size, upBank bank){
this->selectEndPoint(0);
UECONX |= (1<<EPEN);
UECFG1X = 0;
UECFG0X = (type << EPTYPE0) | (dir);
UECFG1X = (1<<ALLOC) | (size << 4) | ((bank==TWO)?0b100:0);
return (UESTA0X & (1<<CFGOK))?true:false;
}
void USB::ControlRequest(){
this->selectEndPoint(0);
volatile uint8_t intStatus = UEINTX;
USB_Request_Header head;
if( !IS_SET(intStatus,RXSTPI) ){
return;
}
UEIENX &= ~(1<<RXSTPE);
this->readBuf((uint8_t*)&head,sizeof(USB_Request_Header));
UEINTX = ~( (1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI) );
if( (head.bmRequestType & 0x80) == 0x80 ) { this->waitIn(); } else { this->clearIn(); };
bool accepted = true;
switch(head.bRequest){
case GET_STATUS:
accepted = this->getStatus();
nop();
break;
case CLEAR_FEATURE:
accepted = this->clearFeature();
break;
case SET_FEATURE:
accepted = this->setFeature();
break;
case SET_ADDRESS:
accepted = this->setAddres();
break;
case GET_DESCRIPTOR:
accepted = this->getDescriptor(&head);
break;
case SET_DESCRIPTOR:
accepted = this->setDescriptor();
nop();
break;
case GET_CONFIGURATION:
accepted = this->getConfiguration();
nop();
break;
case SET_CONFIGURATION:
accepted = this->setConfiguration();
nop();
break;
case GET_INTERFACE:
accepted = this->getInterface();
break;
case SET_INTERFACE:
accepted = this->setInterface();
break;
default:
accepted = false;
nop();
}
//if( accepted ){
// this->clearIn();
//} else {
this->stall();
//}
UEIENX |= (1 << RXSTPE);
}
void USB::onGenEvent(){
uint8_t state = UDINT;
UDINT = 0;
if( IS_SET(state,EORSTI) ){
this->eorst();
}
if( IS_SET(state, SOFE) ){
this->sof();
}
sei();
}
void USB::onComEvent(){
uint8_t pos, mask;
//this->currentEndpoins = UENUM;
this->selectEndPoint(0);
if( IS_SET(UEINTX,RXSTPI) ){
this->ControlRequest();
sei();
return;
}
this->clearIn();
return;
for(pos = 0;pos<7;pos++){
mask = (1<<pos);
if( ((UENUM & mask) == mask) && (this->epEvents[pos]!= 0)) {
this->epEvents[pos]();
}
}
this->selectEndPoint(this->currentEndpoins);
}
bool USB::getStatus(){
return false;
}
bool USB::clearFeature(){
return false;
}
bool USB::setFeature(){
return false;
}
bool USB::setAddres(){
return false;
}
bool USB::getDescriptor(USB_Request_Header *request){
switch( request->wValueH ){
case GET_DESCRIPTOR_DEVICE:
writeBuf((const uint8_t*)&this->device,sizeof(USB_Device_Descriptor),this->controlHeader.wLengthL);
UEINTX &= ~((1<<TXINI));
nop();
//this->clearIn();
break;
//case GET_DESCRIPTOR_CONFIG:
//sendControl((const uint8_t*)&config, sizeof(config), head.wLengthL);
//sendControl((const uint8_t*)&iface0, sizeof(iface0), head.wLengthL);
//sendControl((const uint8_t*)&ep1, sizeof(ep1), head.wLengthL);
//sendControl((const uint8_t*)&ep2, sizeof(ep2), head.wLengthL);
//sendControl((const uint8_t*)&ep3, sizeof(ep3), head.wLengthL);
//break;
//case GET_DESCRIPTOR_STRING:
//switch(head.wValueL){
// case 0:
// sendControl((const uint8_t*)&lang0,4,head.wLengthL);
// break;
// default:
// getString();
//}
//break;
//case GET_DESCRIPTOR_QUALIFER:
//sendControl((const uint8_t*)&qal,qal.bLength,head.wLengthL);
//break;
default:
return false;
}
return true;
}
bool USB::setDescriptor(){
return false;
}
bool USB::getConfiguration(){
return false;
}
bool USB::setConfiguration(){
return false;
}
bool USB::getInterface(){
return false;
}
bool USB::setInterface(){
return false;
}
|
f01e173ba0f6a351fc148e30168a2d0954fabdab | 005c33655b6260cc5e0ff2087471e6e0a2226a01 | /CAssembler/include/tools.h | 2c69429efa64771002b53f3f843160a6b8ec8ad6 | [
"MIT"
] | permissive | zeFresk/CASM | 11c76af18b782961a92dc4d5e313594f5fee9cef | 38cb88ca51799894c5c3e46a26f821b971a40850 | refs/heads/master | 2020-03-30T05:00:47.934265 | 2018-11-03T21:23:54 | 2018-11-03T21:29:31 | 150,774,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 908 | h | tools.h | /*
Collection of usefull standalone functions
*/
#ifndef tools_h
#define tools_h
#include <vector>
#include <string>
#include <iostream>
// Retrieve filename without extension
// If no extension return as it is
// Undefined behaviour if str is empty
std::string get_filename(std::string const& str);
// Extract data from a file efficiently
// Return and array of lines
// Throw if unable to open file
std::vector<std::string> load_from_file(std::string const& filename);
template <typename T>
void unused(T const&) {}
// Print everything concatened if verbose is true
// At least one argument beside the first one must be passed
template <typename... Args>
void v_log(bool verbose, Args&& ...args)
{
if (verbose)
{
int dummy[sizeof...(args)] = { (std::cout << args, 0)... };
unused(dummy); // dummy var is necessary but we don't want any warning
}
}
#endif
|
32685398d8bf8f092bded1aa080455409f426768 | 0a5645154953b0a09d3f78753a1711aaa76928ff | /common/c/build/corelib/ncdb/yocto/intel_nuc_64/2.45.1.1000/output/include/AutoPtr.h | 418e0bf1f835a05bfff546c05a3f39a8805eff8c | [] | no_license | GENIVI/navigation-next | 3a6f26063350ac8862b4d0e2e9d3522f6f249328 | cb8f7ec5ec4c78ef57aa573315b75960b2a5dd36 | refs/heads/master | 2023-08-04T17:44:45.239062 | 2023-07-25T19:22:19 | 2023-07-25T19:22:19 | 116,230,587 | 17 | 11 | null | 2018-05-18T20:00:38 | 2018-01-04T07:43:22 | C++ | UTF-8 | C++ | false | false | 6,939 | h | AutoPtr.h | /*
Copyright (c) 2018, TeleCommunication Systems, 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 the TeleCommunication Systems, 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 TELECOMMUNICATION SYSTEMS, INC.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 AutoPtr.h
@date 02/15/2009
@defgroup MOBIUS_UTILS Mobius utility classes
Simple non-counting smart pointer templates.
These simple non-counting smart pointer templates are intended to be used
only as automatic variables or a class data member.
Passing them as parameters or returning from functions is forbidden.
You can use AutoArrayPtr template to automatically delete arrays, although
the usage of dynamically allocated arrays is not recommended.
It's better to use STL 'vector' class or other containers.
*/
/*
(C) Copyright 2014 by TeleCommunication Systems, Inc.
The information contained herein is confidential, proprietary
to TeleCommunication Systems, Inc., and considered a trade secret as
defined in section 499C of the penal code of the State of
California. Use of this information by anyone other than
authorized employees of TeleCommunication Systems is granted only
under a written non-disclosure agreement, expressly
prescribing the scope and manner of such use.
---------------------------------------------------------------------------*/
/*! @{ */
#ifndef AUTOPTR_H_IS_INCLUDED
#define AUTOPTR_H_IS_INCLUDED
#include "NcdbTypes.h"
namespace Ncdb {
/*! AutoPtr - Automaticly deleted non-counting pointer.
Can be used only as automatic variable or as a class data memeber.
@note 1. When copying the original pointer becomes NULL.
@note 2. Only explicit copying is allowed, so it can not be passed
as a parameter or returned from functions.
*/
template<class T>
class AutoPtr
{
public:
//! Default Constructor prepares a NULL pointer.
AutoPtr() : m_ptr(0)
{}
//! Constructor keeps the pointer parameter.
AutoPtr(T* ptr) : m_ptr(ptr)
{}
//! destructor deletes an object.
~AutoPtr()
{ delete m_ptr; }
//! Convert AutoPtr to non-const pointer.
operator T* () const
{ return m_ptr; }
//! Non-const member access operator.
T* operator->() const
{ return m_ptr; }
//! Convert AutoPtr to non-const reference.
operator T & ()
{ return * m_ptr; }
//! Derefernce operator to non-const reference.
T & operator * () const
{ return * m_ptr;}
////! Derefernce operator to const reference.
//const T & operator * () const
// { return * m_ptr; }
//! Copy pointer to AutoPtr.
// It deletes the previous contents of destination object.
T * operator = (T* ptr)
{
delete m_ptr;
m_ptr = ptr;
return *this;
}
//! Copy AutoPtr to another AutoPtr.
// It deletes the previous contents of destination object and empties the source object.
AutoPtr<T>& operator =( AutoPtr<T> & ptr )
{
delete m_ptr;
m_ptr = ptr.m_ptr;
ptr.m_ptr = 0;
return *this;
}
private:
//! copy constructor is forbidden to prevent returning it from function or passing as a parameter.
AutoPtr( AutoPtr<T> & ptr )
{ }
T* m_ptr; // stored pointer to object
};
/*! AutoArrayPtr - Automaticly deleted non-counting pointer to array.
Can be used only as automatic variable or as a class data memeber.
Use it instead AutoPtr when array elements has to be normally destructed by operator 'delete []'.
@note 1. When copying the original pointer becomes NULL.
@note 2. Only explicit copying is allowed, so it can not be passed
as a parameter or returned from functions.
*/
template<class T>
class AutoArrayPtr
{
public:
//! Default Constructor prepares a NULL pointer.
AutoArrayPtr() : m_ptr(0)
{}
//! Constructor keeps the pointer parameter.
AutoArrayPtr(T * arr) : m_ptr(arr)
{}
//! destructor deletes an object.
~AutoArrayPtr()
{ delete [] m_ptr; }
//! Convert AutoArrayPtr to simple non-const pointer.
operator T* () const
{ return m_ptr; }
//! Copy array to AutoArrayPtr.
//! @note It deletes the previous contents of destination object.
T * operator =(T* arr)
{
delete[] m_ptr;
m_ptr = arr;
return m_ptr;
}
//! Copy AutoArrayPtr to another AutoArrayPtr.
//! @note It deletes the previous contents of destination object and empties the source object.
AutoArrayPtr <T> & operator =( AutoArrayPtr <T> & ptr )
{
delete [] m_ptr;
m_ptr = ptr.m_ptr;
ptr.m_ptr = 0;
return *this;
}
//! Index non-const operator.
T & operator [] ( int i )
{
return m_ptr[i];
}
private:
//! copy constructor is forbidden to prevent returning it from function or passing as a parameter.
AutoArrayPtr( AutoArrayPtr<T> & ptr )
{ }
T* m_ptr; // stored pointer to array
};
};
#endif // AUTOPTR_H_IS_INCLUDED
/*! @} */
|
b5da4ac5c9e0a9ce83544f9a6f773f9820fc89b0 | 5f7e901cb2785835c8048d2a2bba44caedefe568 | /大程/Final/Final/Equation.h | 6dbce5ec7b9b6a0146b734c776995ef0fe37b7cd | [] | no_license | Wholanz/OOP | 2a8d0ae33d29c37b251724cacc34a4dfaac6a855 | efdc04194472df8a0b0d2e4939b4fdc1f05cca25 | refs/heads/master | 2016-08-12T09:53:24.577439 | 2015-11-01T03:36:24 | 2015-11-01T03:36:24 | 45,327,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | h | Equation.h | #pragma once
#ifndef _Equation_h_
#define _Equation_h_
#include "Function.h"
class Equation : public Function
{
public :
Equation(){};
virtual ~Equation(){};
virtual void getCoeff() = 0;
virtual double* solve() = 0;
void function(){
this->getCoeff();
this->solve();
}
;
};
#endif //_Equation_h_ |
6f069e53c2305a528870c14d37bc75fbd8901fe8 | 5205378bf9fd382cbb070d9170610a8d5e4b0f7a | /src/HomeAssistant/Components/WaterHeater.hpp | 8052345bbb69ea092c7347f04e8ba38c7e7f7686 | [
"MIT"
] | permissive | RobinSinghNanda/Home-assistant-display | 65d02124f59bb078945271489152eeeba6aa7e41 | 6f59104012c0956b54d4b55e190aa89941c2c1af | refs/heads/main | 2023-01-20T00:00:43.051506 | 2020-11-24T10:39:11 | 2020-11-24T10:39:11 | 306,589,564 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,477 | hpp | WaterHeater.hpp | #ifndef __WATERHEATER_H__
#define __WATERHEATER_H__
#include "Entity.hpp"
namespace HomeAssistant {
class WaterHeater : public Entity {
public:
WaterHeater(const char * entity);
virtual ~WaterHeater();
static constexpr const char * ENTITY_DOMAIN = "water_heater";
//Features
static constexpr Feature SUPPORT_TARGET_TEMPERATURE = 1;
static constexpr Feature SUPPORT_OPERATION_MODE = 2;
static constexpr Feature SUPPORT_AWAY_MODE = 4;
//States
static constexpr State STATE_ECO = "eco";
static constexpr State STATE_ELECTRIC = "electric";
static constexpr State STATE_PERFORMANCE = "performance";
static constexpr State STATE_HIGH_DEMAND = "high_demand";
static constexpr State STATE_HEAT_PUMP = "heat_pump";
static constexpr State STATE_GAS = "gas";
//Services
static constexpr ServiceName SERVICE_SET_AWAY_MODE = "set_away_mode";
static constexpr ServiceName SERVICE_SET_TEMPERATURE = "set_temperature";
static constexpr ServiceName SERVICE_SET_OPERATION_MODE = "set_operation_mode";
//Attributes
static constexpr AttributeName ATTR_TEMPERATURE = "temperature";
static constexpr AttributeName ATTR_MAX_TEMP = "max_temp";
static constexpr AttributeName ATTR_MIN_TEMP = "min_temp";
static constexpr AttributeName ATTR_AWAY_MODE = "away_mode";
static constexpr AttributeName ATTR_OPERATION_MODE = "operation_mode";
static constexpr AttributeName ATTR_OPERATION_LIST = "operation_list";
static constexpr AttributeName ATTR_TARGET_TEMP_HIGH = "target_temp_high";
static constexpr AttributeName ATTR_TARGET_TEMP_LOW = "target_temp_low";
static constexpr AttributeName ATTR_CURRENT_TEMPERATURE = "current_temperature";
//API
virtual void updateAttributes(JsonObject stateAttributesObject);
virtual void callService(HomeAssistantClient * client, const char * service);
protected:
float currentTemperature = 0;
float temperature = 0;
float maxTemperature = 0;
float minTemperature = 0;
string awayMode = "";
string operationMode = "";
vector<string> operationModes;
};
};
#endif // __WATERHEATER_H__ |
7e9c22179a3ad2bb354fc659585bc48bdcde6b97 | 4966b3b6600596681af0d7506a2c0914b296abae | /RenderCore/GeoProc/NascentCommandStream.h | 6351641e5396561ace8b4176ac1deb276855cbc0 | [
"MIT"
] | permissive | djewsbury/XLE | 4200c797e823e683cebb516958ebee5f45a02bf0 | f7f63de2c620ed5d0b1292486eb894016932b74b | refs/heads/master | 2023-07-03T14:26:38.517034 | 2023-06-30T03:22:03 | 2023-06-30T03:22:03 | 32,975,591 | 13 | 6 | null | 2015-03-27T08:35:02 | 2015-03-27T08:35:02 | null | UTF-8 | C++ | false | false | 6,631 | h | NascentCommandStream.h | // Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#pragma once
#include "NascentSkeletonHelper.h"
#include "../Assets/AnimationScaffoldInternal.h"
#include "../Assets/ModelCompilationConfiguration.h" // for ModelCompilationConfiguration::SkeletonRules
#include "../../Math/Transformations.h"
#include <vector>
#include <string>
namespace Assets { class BlockSerializer; }
namespace RenderCore { namespace Assets { class RawAnimationCurve; }}
namespace RenderCore { enum class Format : int; }
namespace Utility { class OutputStream; }
namespace RenderCore { namespace Assets { namespace GeoProc
{
//
// "NascentAnimationSet" is a set of animations
// and some information to bind these animations to
// a skeleton
//
class NascentAnimationSet
{
public:
using AnimationDriver = RenderCore::Assets::AnimationSet::AnimationDriver;
using ConstantDriver = RenderCore::Assets::AnimationSet::ConstantDriver;
using AnimationBlock = RenderCore::Assets::AnimationSet::AnimationBlock;
using Animation = RenderCore::Assets::AnimationSet::Animation;
struct StringOrHash
{
std::optional<std::string> _stringForm;
uint64_t _hashForm = ~0ull;
StringOrHash() = default;
StringOrHash(const std::string&);
StringOrHash(uint64_t);
friend bool operator==(const StringOrHash& lhs, const StringOrHash& rhs);
};
struct BlockSpan { unsigned _beginFrame, _endFrame; };
class NascentBlock;
std::vector<NascentBlock> AddAnimation(const std::string& name, IteratorRange<const BlockSpan*>, float framesPerSecond);
class NascentBlock
{
public:
unsigned AddCurve(RenderCore::Assets::RawAnimationCurve&& curve);
void AddAnimationDriver(
StringOrHash parameterName,
AnimSamplerComponent parameterComponent,
AnimSamplerType samplerType,
unsigned curveIndex,
CurveInterpolationType interpolationType);
void AddConstantDriver(
StringOrHash parameterName,
AnimSamplerComponent parameterComponent,
AnimSamplerType samplerType,
const void* constantValue,
size_t constantValueSize,
Format format);
NascentBlock() = default;
private:
NascentAnimationSet* _animSet = nullptr;
unsigned _blockIdx = 0;
NascentBlock(NascentAnimationSet& animSet, unsigned blockIdx) : _animSet(&animSet), _blockIdx(blockIdx) {}
friend class NascentAnimationSet;
};
unsigned AddParameter(StringOrHash parameterName, AnimSamplerComponent parameterComponent, AnimSamplerType samplerType);
bool HasAnimationDriver(StringOrHash parameterName) const;
void MergeInAsManyAnimations(const NascentAnimationSet& copyFrom, const std::string& namePrefix = {});
void MakeIndividualAnimation(const std::string& name, float framesPerSecond);
unsigned AddCurve(RenderCore::Assets::RawAnimationCurve&& curve);
IteratorRange<const AnimationDriver*> GetAnimationDrivers() const { return MakeIteratorRange(_animationDrivers); }
IteratorRange<const ConstantDriver*> GetConstantDrivers() const { return MakeIteratorRange(_constantDrivers); }
IteratorRange<const RenderCore::Assets::RawAnimationCurve*> GetCurves() const { return MakeIteratorRange(_curves); }
unsigned GetParameterIndex(const std::string& parameterName, AnimSamplerComponent parameterComponent) const;
friend std::ostream& SerializationOperator(std::ostream&, const NascentAnimationSet&);
friend void SerializationOperator(::Assets::BlockSerializer&, const NascentAnimationSet&);
private:
std::vector<AnimationDriver> _animationDrivers;
std::vector<ConstantDriver> _constantDrivers;
std::vector<AnimationBlock> _animationBlocks;
std::vector<std::pair<std::string, Animation>> _animations;
struct Param { StringOrHash _name; AnimSamplerComponent _component; AnimSamplerType _samplerType; };
std::vector<Param> _parameterInterfaceDefinition;
std::vector<uint8_t> _constantData;
std::vector<RenderCore::Assets::RawAnimationCurve> _curves;
void AppendAnimationDriverToBlock(unsigned blockIdx, unsigned driverIdx);
void AppendConstantDriverToBlock(unsigned blockIdx, unsigned driverIdx);
};
//
// "NascentSkeleton" represents the skeleton information for an
// object. Usually this is mostly just the transformation machine.
// But we also need some binding information for binding the output
// matrices of the transformation machine to joints.
//
class NascentSkeleton
{
public:
struct Transform
{
std::optional<Float4x4> _fullTransform;
std::optional<Float3> _translation;
std::optional<Quaternion> _rotationAsQuaternion;
std::optional<ArbitraryRotation> _rotationAsAxisAngle;
std::optional<Float3> _arbitraryScale;
std::optional<float> _uniformScale;
Transform() = default;
Transform(const Float4x4&);
Transform(const Float3& translation, const Quaternion& rotation, float scale);
};
void WriteStaticTransform(const Transform& transform);
void WriteParameterizedTransform(StringSection<> parameterName, const Transform& transform);
void WriteOutputMarker(StringSection<> skeletonName, StringSection<> jointName);
void WritePushLocalToWorld();
void WritePopLocalToWorld(unsigned popCount=1);
friend void SerializationOperator(::Assets::BlockSerializer&, const NascentSkeleton&);
Internal::NascentSkeletonHelper& GetSkeletonMachine() { return _skeletonMachine; }
const Internal::NascentSkeletonHelper& GetSkeletonMachine() const { return _skeletonMachine; }
private:
Internal::NascentSkeletonHelper _skeletonMachine;
std::vector<uint32_t> TransformToCmds(const Transform& transform, unsigned& cmdCount);
};
void OptimizeSkeleton(NascentSkeleton& embeddedSkeleton, const RenderCore::Assets::ModelCompilationConfiguration::SkeletonRules&);
}}}
|
c4ef70af9fa0d575d4aa85835a12e9395a43c59b | ca4f6a8c5fa697a30efae3ae0c0a2d16f02c2921 | /serialStringBlueTooth/serialStringBlueTooth.ino | c2f5cb52acac6de0da7c6ac781288f220c8cf490 | [] | no_license | JunguGuo/SkyLight | 90211788e18b5c856e50463899e39f88e224e038 | 0f4b67d8d7f6ac94e31c52af1c30d817f4e21260 | refs/heads/master | 2020-04-02T10:43:08.618986 | 2018-10-23T15:26:01 | 2018-10-23T15:26:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,988 | ino | serialStringBlueTooth.ino | #include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6
Adafruit_NeoPixel strip = Adafruit_NeoPixel(12, PIN, NEO_GRB + NEO_KHZ800);
//-----bluetooth----
#include<SoftwareSerial.h>
#define TxD 3
#define RxD 2
//#define LED_PIN 13
SoftwareSerial bluetoothSerial(TxD, RxD);
//--------
String inString = ""; // string to hold input
String test = "12:44:123:34:66:78:123:222:9:1:2:4:12:44:123:34:66:78:123:222:9:1:2:4:12:44:123:34:66:78:123:222:9:1:2:4:";//must end with ':'
void setup() {
// Open serial communications and wait for port to open:
bluetoothSerial.begin(9600);
//Serial.begin(9600);
strip.begin();
strip.show(); // Initialize all pixels to 'off'
//parseCommand(test);
}
void loop() {
// Read serial input:
while (bluetoothSerial.available() > 0) {//bluetoothSerial.available()
int inChar = bluetoothSerial.read();//bluetoothSerial.read();
if (inChar!= '\n') {
//Serial.print(inChar);
// convert the incoming byte to a char and add it to the string:
inString += (char)inChar;
}
// if you get a newline, print the string, then the string's value:
if (inChar == '\n') {
//echo the command back
// Serial.print("String: ");
// Serial.println(inString);
bluetoothSerial.println("x"); //indicate processing to send the next command//bluetoothSerial.println("x");bbbbbbbbbb
parseCommand(inString);
// String xval = getValue(inString, ':', 0);
// String yval = getValue(inString, ':', 2);
// String zval = getValue(inString, ':', 4);
//
// Serial.print("X:" + xval);
// Serial.print("Y:" + yval);
// Serial.println("Z:" + zval);
// clear the string for new input:
inString = "";
}
}
//parseCommand(test);
}
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = { 0, -1 };
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
void parseCommand(String com){
// String part1 = com.substring(0,com.indexOf(" "));
// String part2 = com.substring(com.indexOf(" ")+1);
int i = 0;
int id = 0;
while(i!= com.length()){
int index = com.indexOf(":",i+1);
String R = com.substring(i,index);
int index2 = com.indexOf(":",index+1);
String G = com.substring(index+1,index2);
index = com.indexOf(":",index2+1);
String B = com.substring(index2+1,index);
i = index+1;
strip.setPixelColor(id, strip.Color(R.toInt(), G.toInt(), B.toInt()));
// Serial.print("id: ");Serial.print(id);
// Serial.println(" | R: "+R + " | G: "+G + " | B: "+B);
id++;
//Serial.println(i);
}
strip.show();
delay(20);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.