text
stringlengths 8
6.88M
|
|---|
/*In this program we will be seeing about LOOPS in C++ Program*/
/*In C++ while, do while and for are different loop Statements , which is used to execute certain number of codes for certain number of times. That is the code inside the loop will be execute certain number of times till the condition fails and loop comes out of the scope.*/
/*In this Example lets see how DO WHILE LOOP works in a program.*/
/*Do While loop is kind of LOOP , which is used to execute the code for certain number of times, till the condition fails. Do While loop is also know as 'EXIT CHECK LOOP',that is loop will execute atleast once even though the condition fails.*/
/*When the condition becomes false, then the program control passes to the line which is next to the loop end.*/
/*Syntax of do while loop
do
{
Statement(S) / block of code;//Any number of statements can present inside the loop
Increment;
}while(condition)
*/
/*including preprocessor / header file in the program*/
#include <iostream>
/*using namespace*/
using namespace std ;
/*creating a main() function of the program*/
int main()
{
/* local variable definition */
int a = 0 ;
/*Do while loop*/
do
{
cout<<"\nValue of a = " << a << endl ;
cout<<"\nThe DO WHILE LOOP is executed for " << a << endl ;
a++; /*Increment the value of variable a */
}while ( a < 0 ) ; /*End of while loop */
/*do While loop condition,Where condition will be checked.*/
/*when this line is printed it print a = 1 , since 1 time the do while condition has been checked and only at 1th time the condition has failed and for loop comes out the scope*/
cout<<"\nThe DO WHILE LOOP is checked for "<< a << " number of times." << endl ;
}
|
//
// linear.cpp
// Homework 3
//
// Created by Shashank Khanna on 2/10/15.
// Copyright (c) 2015 CS 32. All rights reserved.
//
// Return true if the somePredicate function returns true for at
// least one of the array elements, false otherwise.
bool anyTrue(const double a[], int n)
{
if (n < 1)
return false;
if (somePredicate(a[n-1]))
return true;
if(anyTrue(a, n-1))
return true;
return false;
}
// Return the number of elements in the array for which the
// somePredicate function returns true.
int countTrue(const double a[], int n)
{
if (n <= 0)
return false;
int count = somePredicate(a[0]);
count += countTrue(a+1, n-1);
return count;
}
// Return the subscript of the first element in the array for which
// the somePredicate function returns true. If there is no such
// element, return -1.
int firstTrue(const double a[], int n)
{
if (n <= 0)
return -1;
if (somePredicate(a[n-1]))
return n-1;
return firstTrue(a, n-1);
}
// Return the subscript of the smallest element in the array (i.e.,
// the one whose value is <= the value of all elements). If more
// than one element has the same smallest value, return the smallest
// subscript of such an element. If the array has no elements to
// examine, return -1.
int indexOfMin(const double a[], int n)
{
if (n <= 0)
return -1;
if (n == 1)
return n;
if (n==2)
{
if (a[n-2] < a[n-1])
return n-2;
else
return n-1;
} // location of the lower value
int compare = 1+indexOfMin(a+1, n-1);
if ( a[0] <= a[compare])
return 0;
else
return compare;
}
// If all n2 elements of a2 appear in the n1 element array a1, in
// the same order (though not necessarily consecutively), then
// return true; otherwise (i.e., if the array a1 does not include
// a2 as a not-necessarily-contiguous subsequence), return false.
// (Of course, if a2 is empty (i.e., n2 is 0), return true.)
// For example, if a1 is the 7 element array
// 10 50 40 20 50 40 30
// then the function should return true if a2 is
// 50 20 30
// or
// 50 40 40
// and it should return false if a2 is
// 50 30 20
// or
// 10 20 20
bool includes(const double a1[], int n1, const double a2[], int n2)
{
if (n2 == 0)
return true;
if (n1 ==0)
return false;
//bool isTrue; // int i,j = 0;
if ((a1[0] == a2[0]))
{ if ( includes(a1+1 , n1-1, a2+1, n2-1))
return true;}
else
if(includes(a1+1, n1-1, a2, n2))
return true;
// if first one exists and if first's next comes after first in array 1 then we're good
return false;
// return true;
}
|
#pragma once
namespace EActiveOperation
{
enum
{
True = 0,
False = 1
};
}
namespace EEntityType
{
enum
{
RenderTarget = 0,
HUD = 1,
StaticObject = 2,
MovableObject = 3,
PlayerCharacter = 4,
NonePlayerCharacter = 5,
EnemyCharacter = 6,
Item = 7,
Buliding = 8,
VisualEffect = 9,
DamageObject = 10,
Level = 11
};
}
namespace EComponentSystemIndex
{
enum
{
Job = 0,
Entity = 1,
Input = 2,
Movement = 3,
Network = 4,
Render2D = 5,
Timer = 6,
UnitController = 7,
World = 8,
GameMode = 9,
Collision = 10,
UnitStatus = 11
};
}
namespace EGameState
{
enum
{
TITLE,
GAME_READY,
GAME_START,
GAME_MAIN,//실제 게임 화면 스테이지 1 ,2,3,4, ...
STAGE_CLEAR,
GAME_OVER
};
}
|
#include <door_passing/door_passing.h>
#include <ros/ros.h>
DoorPassing::DoorPassing():laser_robot_center_offset_x_(0.3)
{
reset();
}
DoorPassing::~DoorPassing()
{
}
bool DoorPassing::setGoal(int goal, double distance_inside, Gateways detected_gateways)
{
goal_ = goal;
distance_inside_ = distance_inside;
if( goal_ == 2 && detected_gateways.left_door.range_x > 0)
{
turn_range_ = detected_gateways.left_door.range_x;
turn_angle_ = detected_gateways.left_door.angle;
}
else if (goal_ == 1 && detected_gateways.front_door.range_x > 0)
{
turn_range_ = detected_gateways.front_door.range_x;
turn_angle_ = detected_gateways.front_door.angle;
}
else if (goal_ == 0 && detected_gateways.right_door.range_x > 0)
{
turn_range_ = detected_gateways.right_door.range_x;
turn_angle_ = detected_gateways.right_door.angle;
}
else
{
return false;
}
return true;
}
void DoorPassing::setParams(double laser_robot_center_offset_x)
{
laser_robot_center_offset_x_ = laser_robot_center_offset_x;
}
double DoorPassing::getInitialOrientation()
{
return intial_orientation_;
}
double DoorPassing::getTurnAngle()
{
return turn_angle_;
}
double DoorPassing::getPassingOrientation()
{
return passing_orientation_;
}
double DoorPassing::getInsideOrientation()
{
return orientation_inside_;
}
bool DoorPassing::isStateChanged(double monitored_distance, double monitored_heading, Gateways detected_gateways)
{
if (state_ == -1 && fabs(monitored_heading - intial_orientation_) < 0.02)
{
if (goal_ == 1)
{
state_ = 2;
computePassingOrientation(detected_gateways);
computeDistanceToDoor(detected_gateways);
}
else
state_ = 0;
return true;
}
else if (state_ == 0 && (monitored_distance) > turn_range_)
{
state_ = 1;
return true;
}
else if (state_ == 1 && fabs(monitored_heading - turn_angle_) < 0.02)
{
state_ = 2;
computePassingOrientation(detected_gateways);
computeDistanceToDoor(detected_gateways);
return true;
}
else if (state_ == 2 && (monitored_distance > distance_to_door_))
{
state_ = 3;
return true;
}
else if (state_ == 3 && (monitored_distance > distance_inside_))
{
state_ = 4;
return true;
}
return false;
}
int DoorPassing::getState()
{
return state_;
}
bool DoorPassing::computeInitialOrientation(int goal, Gateways detected_gateways)
{
if( goal == 0 && detected_gateways.left_door.range_x > 0)
{
intial_orientation_ = detected_gateways.left_door.angle - (M_PI/2);
return true;
}
else if (goal == 1 && detected_gateways.front_door.range_x > 0)
{
intial_orientation_ = detected_gateways.front_door.angle;
return true;
}
else if( goal == 2 && detected_gateways.right_door.range_x > 0)
{
intial_orientation_ = detected_gateways.right_door.angle + (M_PI/2);
return true;
}
return false;
}
bool DoorPassing::computePassingOrientation(Gateways detected_gateways)
{
if( detected_gateways.front_door.range_x > 0)
{
double new_passing_orientation_ = atan2(detected_gateways.front_door.range_y, detected_gateways.front_door.range_x);
// update angle only if its within intiial range
if (fabs(passing_orientation_ - new_passing_orientation_) < 0.3)
{
passing_orientation_ = new_passing_orientation_;
return true;
}
}
return false;
}
bool DoorPassing::computeDistanceToDoor(Gateways detected_gateways)
{
if( detected_gateways.front_door.range_x > 0)
{
distance_to_door_ = pow(pow(detected_gateways.front_door.range_x, 2) + pow(detected_gateways.front_door.range_y, 2), 0.5);
return true;
}
return false;
}
bool DoorPassing::computeInsideOrientation(Gateways detected_gateways)
{
if( detected_gateways.hallway.left_range > 0 && detected_gateways.hallway.right_range > 0)
{
orientation_inside_ = (detected_gateways.hallway.left_angle + detected_gateways.hallway.right_angle)/2.0;
return true;
}
else if (detected_gateways.hallway.left_range > 0)
{
orientation_inside_ = detected_gateways.hallway.left_angle;
return true;
}
else if (detected_gateways.hallway.right_range > 0)
{
orientation_inside_ = detected_gateways.hallway.right_angle;
return true;
}
return false;
}
void DoorPassing::reset()
{
goal_ = -1;
state_ = -1;
intial_orientation_ = 0;
turn_range_ = 0;
turn_angle_ = 0;
distance_to_door_ = 0;
passing_orientation_ = 0;
distance_inside_ = 0;
orientation_inside_ = 0;
}
|
/*
* the implementation of the Class String
*/
#include <iostream>
#include "string.h"
using std::cout;
using std::endl;
//构造函数
String::String()
{
InitString();
}
//析构函数
String::~Srting()
{
DestoryString();
}
//返回主串的长度
int String::StrLength()
{
return str.length;
}
//用T生成主串
bool String::StrAssign(char *T)
{
int i;
char *c;
if(str.ch)
free(str.ch);
for(i=0,c=T ; c ; ++i, ++c);
if(!i)
{
str.ch = NULL;
str.length = 0;
}
else
{
if(!(str.ch = (char *)malloc(i*sizeof(char))))
{
std::cout<<"malloc fail, Assign fail"<<std::endl;
return ERROR;
}
for(int j=0 ; j<i ; j++)
str.ch[i] = T[i];
str.length = i;
}
return OK;
}
//将T复制为主串
bool String::StrCopy(String &T)
{
StrAssign(T.str.ch);
}
//判断主串是否为空
bool String::StrEmpty()
{
if(0 == str.length)
return OK;
else
return ERROR;
}
//将主串和T作对比
int String::StrCompare(String &T)
{
for(int i=0 ; i<str.length && i<T.str.length ; ++i)
if(str.ch[i] != T.str.ch[i])
return str.ch[i] - T.str.ch[i];
return str.length - T.str.length;
}
//清空主串
bool String::ClearString()
{
if(str.ch)
{
free(str.ch);
str.ch = NULL;
}
str.length = 0;
return OK;
}
//将主串由S1和S2连接而成
bool String::Concat(String &S1, String &S2)
{
int i;
if(str.ch)
free(str.ch);
if(!(str.ch = (char *)malloc((S1.str.length+S2.str.length)*sizeof(char))))
{
std::cout<<"malloc fail, Concat fail"<<std::endl;
return ERROR;
}
for(i=0 ; i<S1.str.length ; ++i)
str.ch[i] = S1.str.ch[i];
str.length = S1.str.length + S2.str.length;
for(int j=0 ; i<str.length ; ++i,++j)
str.ch[i] = S2.str.ch[j];
return OK;
}
//用Sub返回主串的第pos个字符起长度为len的子串
bool String::SubString(String &Sub, int pos, int len)
{
if(pos<1 || pos>str.length || len<0 || len>str.length-pos+1)
return ERROR;
if(Sub.str.ch)
free(Sub.str.ch);
if(!len)
{
Sub.str.ch = NULL;
Sub.str.length = 0;
}
else
{
Sub.str.ch = (char *)malloc(len*sizeof(char));
int i=0, j=pos-1;
for( ; i<len ; ++i,++j)
Sub.str[i] = str.ch[j];
}
return OK;
}
//返回主串中第pos个字符之后第一次出现子串T的位置,否则返回0
int String::Index(String &T, int pos)
{
if(pos > 0)
{
int n = StrLength();
int m = T.StrLength();
int i = pos;
String Sub;
while(i <= n-m+1)
{
SubString(Sub, i, m);
if(Sub.StrCompare(T) != 0)
++i;
else
return i;
}
}
return 0;
}
//用V替换主串中出现的所有与T相等的不重叠的子串,返回num替换个数
bool String::Replace(String &T, String &V, int &num)
{
int i = 0;
int n = StrLength();
int m = T.StrLength();
String Sub;
num = 0;
while(i <= n-m+1)
{
SubString(Sub, i, m);
if(Sub.StrCompare(T) != 0)
++i;
else
{
StrDelete(i+1, m);
StrInsert(i+1, V);
i += V.StrLength();
num++;
}
}
return num;
}
//在字符串的第pos个字符之前插入串T
bool String::StrInsert(int pos, String &T)
{
if(pos<1 || pos>str.length+1)
return ERROR;
if(T.length)
{
if(!(str.ch = (char *)realloc(str.ch, (str.length+T.str.length)*sizeof(char))))
{
std::cout<<"malloc fail, StrInsert fail"<<std::endl;
return ERROR;
}
int i = str.length-1;
int j = i+T.str.length;
for( ; i>pos-1 ; --i,--j)
str.ch[j] = str.ch[i];
for(i=T.str.length-1 ; i>=0 ; --i,--j)
str.ch[j] = T.str.ch[i];
str.length += T.str.length;
}
return OK;
}
//将字符串中第pos个字符起长度为len的子串删除
bool String::StrDelete(int pos, int len)
{
if(pos<1 || pos>str.length-1 || len<0 || pos+len>str.length+1)
return ERROR;
int i = 0;
for( ; i<len-1 ; ++i,++pos)
str.ch[pos-1] = str.ch[pos-1+i];
return OK;
}
//字符串初始化函数,被构造函数所调用
bool String::InitString()
{
str.ch = (char *)malloc(sizeof(char));
if(!str.ch)
{
std::cout<<"malloc fail, init fail"<<std::endl;
return ERROR;
}
str.length = 0;
return OK;
}
//销毁字符串,被析构函数所调用
bool String::DestoryString()
{
free(str.ch);
str.ch = NULL;
str.length = 0;
return OK;
}
|
#ifndef BASEWINDOW_H
#define BASEWINDOW_H
#include <windows.h>
#include <string>
#include "..\Menu\Menu.h"
/* The callback for all the window classes */
LRESULT CALLBACK windowCallback(HWND, UINT, WPARAM, LPARAM);
class BaseWindow
{
friend LRESULT CALLBACK windowCallback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
public:
BaseWindow(std::string title, int width, int height, DWORD style = 0, BaseWindow* parent = 0);
bool takeMenu(Menu*);
Menu* giveMenu(void);
bool takePopupMenu(Menu* toAdd);
Menu* givePopupMenu();
protected:
virtual ~BaseWindow();
virtual LRESULT handleMessage(UINT, WPARAM, LPARAM);
HWND handle;
Menu* popupMenu;
private:
BaseWindow();
bool initWinClass();
Menu* mainMenu;
static bool classCreated;
};
#endif // BASEWINDOW_H
|
#include <iostream>
#include <fstream>
#include <vector>
#include <boost/random.hpp>
#include <cppmc/cppmc.hpp>
using namespace CppMC;
using std::vector;
using std::ofstream;
using std::cout;
using std::endl;
class TauY : public MCMCDeterministic<double,Mat> {
private:
Bernoulli<Col>& state_;
Normal<Col>& sd0_;
Normal<Col>& sd1_;
public:
TauY(Bernoulli<Col>& state, Normal<Col>& sd0, Normal<Col>& sd1):
MCMCDeterministic<double,Mat>(mat(state.size(),1)), state_(state), sd0_(sd0), sd1_(sd1)
{
for(uint i = 0; i < state_.size(); i++) {
MCMCDeterministic<double,Mat>::value_[i] = state_[i] ? pow(sd1_[0],-2.0) : pow(sd0_[0],-2.0);
}
}
void getParents(std::vector<MCMCObject*>& parents) const {
parents.push_back(&state_);
parents.push_back(&sd0_);
parents.push_back(&sd1_);
}
Mat<double> eval() const {
mat ans(state_.size(),1);
for(uint i = 0; i < state_.size(); i++) {
ans[i] = state_[i] ? pow(sd1_[0],-2) : pow(sd0_[0],-2);
}
return ans;
}
};
class EstimatedY : public MCMCDeterministic<double,Mat> {
private:
mat& X_;
MCMCStochastic<double,Mat>& B_;
mutable mat B_full_rank_;
mutable mat permutation_matrix_;
Bernoulli<Col>& state_;
public:
EstimatedY(Mat<double>& X, MCMCStochastic<double,Mat>& B, Bernoulli<Col>& state):
MCMCDeterministic<double,Mat>(mat(X.n_rows,1)), X_(X), B_(B), B_full_rank_(X_.n_rows,X.n_cols),
permutation_matrix_(X_.n_rows,B.nrow()), state_(state) {
permutation_matrix_.fill(0.0);
MCMCDeterministic<double,Mat>::value_ = eval();
}
void update_perm_mat() const {
for(uint i = 0; i < state_.nrow(); i++) {
permutation_matrix_(i,state_[i]) = 1.0;
}
}
void getParents(std::vector<MCMCObject*>& parents) const {
parents.push_back(&B_);
parents.push_back(&state_);
}
Mat<double> eval() const {
const mat& B = B_();
update_perm_mat();
B_full_rank_ = permutation_matrix_ * B;
return sum(X_ % B_full_rank_,1);
}
};
// global rng generators
CppMCGeneratorT MCMCObject::generator_;
int main() {
const int NR = 20;
const int NC = 2;
const int Nstates = 2;
double true_sd0 = 1.0;
double true_sd1 = 3.0;
double state1p = 0.05;
// create state probability vector, and establish true state variable based on it
vec statetest = randu<vec>(NR);
ivec true_state(NR);
for(int i = 0; i < NR; i++) { true_state[i] = statetest[i] > (1-state1p) ? 1 : 0; }
mat X = randn<mat>(NR,NC);
mat y = randn<mat>(NR,1);
// scale y based on true state vector
for(int i = 0; i < NR; i++) { y[i] *= (true_state[i] > 0) ? true_sd1 : true_sd0; }
cout << "y sd:" << stddev(y,0) << endl;
// make X col 0 const
for(int i = 0; i < NR; i++) { X(i,0) = 1; }
Normal<Mat> B(0.0, 0.0001, randn<mat>(Nstates,NC)); B.print();
Normal<Col> sd0(1.0,0.0001,randu<vec>(1)); sd0.print();
Normal<Col> sd1(2.0,0.0001,randu<vec>(1)); sd1.print();
Uniform<Col> high_vol_statep(0,0.10, randu<vec>(1)); high_vol_statep.print();
Bernoulli<Col> state(high_vol_statep,(randu<vec>(NR) > .5)); state.print();
EstimatedY obs_fcst(X, B, state); obs_fcst.print();
TauY tau_y(state,sd0,sd1); tau_y.print();
NormalLikelihood<Mat> likelihood(y, obs_fcst, tau_y);
int iterations = 1e6;
likelihood.sample(iterations, 1e5, 100);
cout << "iterations: " << iterations << endl;
cout << "collected " << B.getHistory().size() << " samples." << endl;
//cout << "lm coefs" << endl << coefs << endl;
cout << "avg_coefs" << endl << B.mean() << endl;
cout << "state" << endl << state.mean() << endl;
// cout << "tau: " << tau_y.mean() << endl;
return 1;
}
|
#pragma once
//======================================================================
#if defined(_MSC_VER)
#define _CRT_SECURE_NO_WARNINGS
#endif
//======================================================================
/* Everybody needs these: */
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
//======================================================================
#if defined(_MSC_VER)
#define UPL_NOEXCEPT throw()
#define UPL_UNREACHABLE __assume(0)
#define vsnprintf _vsnprintf
#else
#define UPL_NOEXCEPT nothrow
#define UPL_UNREACHABLE __builtin_unreachable()
#endif
//======================================================================
#define UPL_STRINGIZE_IMPL(s) #s
#define UPL_STRINGIZE(s) UPL_STRINGIZE_IMPL(s)
#define UPL_MAX(a, b) (((a) < (b)) ? (b) : (a))
#define UPL_MIN(a, b) (((a) < (b)) ? (a) : (b))
//======================================================================
namespace UPL {
//======================================================================
typedef wchar_t Char;
typedef std::wstring String;
typedef int64_t Int;
typedef double Real;
typedef bool Bool;
typedef std::string Path;
//======================================================================
/* Character Classification: */
Char InvalidChar ();
bool IsInvalid (Char c);
bool IsNewline (Char c);
bool IsWhitespace (Char c);
bool IsDigit (Char c);
bool IsLetter (Char c);
bool IsLower (Char c);
bool IsUpper (Char c);
bool IsAlphanum (Char c);
bool IsIdentStarter (Char c);
bool IsIdentContinuer (Char c);
//======================================================================
class Location
{
public:
Location (int line_no_ = 1, int column_no_ = 0, int char_no_ = 0)
: m_line_no (line_no_), m_column_no (column_no_), m_char_no (char_no_)
{}
int line () const {return m_line_no;}
int column () const {return m_column_no;}
int totalChars () const {return m_char_no;}
void feed (Char c)
{
m_char_no += 1;
if (IsNewline(c))
m_line_no += 1, m_column_no = 0;
else
m_column_no += 1;
}
private:
int m_line_no;
int m_column_no;
int m_char_no;
};
//======================================================================
/* String utilities: */
//----------------------------------------------------------------------
template <typename T>
String ToString (T v);
//----------------------------------------------------------------------
template <typename T>
T FromString (String const & str);
//----------------------------------------------------------------------
template <typename C>
bool HasChar (C const * str, C c);
//----------------------------------------------------------------------
//======================================================================
} // namespace UPL
//======================================================================
|
#pragma once
class preview
{
private:
field f;
console* Console;
int x;
int y;
int r;
int s;
public:
preview(console*);
void drawShip(int, int, int, int, field);
//void moveShip(int);
};
|
#ifndef BLUEDIALOG_H
#define BLUEDIALOG_H
#include <QDialog>
class BlueDialog : public QDialog
{
Q_OBJECT
public:
explicit BlueDialog(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event) override;
};
#endif // BLUEDIALOG_H
|
#ifndef VERTEX_H
#define VERTEX_H
#include <QGLWidget>
#include <QGLFunctions>
#include <QOpenGLVertexArrayObject>
#include <QTimer>
#include "camera.h"
#include "halfedge.h"
#include "face.h"
#include <QListWidgetItem>
class Vertex : public QListWidgetItem
{
private:
glm::vec4 coordinates;
int id;
public:
Vertex();
Vertex(glm::vec4);
void assignID(int);
void assignCoordinates(glm::vec4);
glm::vec4 getCoordinates();
GLfloat* getPoint();
int getID();
};
#endif // VERTEX_H
|
class ItemTinBar
{
weight = 0.01;
};
class ItemTinBar10oz
{
weight = 0.1;
};
|
#ifndef _WORLD_AERO_H_
#define _WORLD_AERO_H_
#include "../Toolbox/Toolbox.h"
#include "../Graphics/Color/Color.h"
#include "../Physics/Simulator/PhysicsSimulator.h"
#include "../Toolbox/PoolUniqueID/PoolUniqueID.h"
#include <limits>
#include <array>
#include <unordered_map>
////////////////////////////////////////////////////////////
/// \defgroup scene Scene Management
///
/// Objects hierarchy management in the world.
///
////////////////////////////////////////////////////////////
namespace ae
{
class WorldObject;
class Light;
class PhysicObject;
class AeroCore;
/// \ingroup scene
/// <summary>
/// World class that represent the scene. <para/>
/// Hold the objects hierarchy.
/// </summary>
class AERO_CORE_EXPORT World
{
friend class WorldObject;
friend class Light;
friend class PhysicObject;
friend class AeroCore;
public:
/// <summary>Type used to identify object in the world.</summary>
using ObjectID = Uint16;
/// <summary>Value that represent an invalid object ID.</summary>
static constexpr ObjectID InvalidObjectID = PoolUniqueID::InvalidID;
/// <summary>Represents the maximum amount of objects that the world can have at the same time.</summary>
static constexpr ObjectID MaxObjectID = PoolUniqueID::MaxID;
public:
/// <summary>Initialiaze an empty world.</summary>
World();
/// <summary>Retrieve all the lights that are active in the world.</summary>
/// <returns>World's lights.</returns>
const std::unordered_map<ObjectID, Light*>& GetLights() const;
/// <summary>Retrieve all the objects in the world.</summary>
/// <returns>World's objects.</returns>
const std::unordered_map<ObjectID, WorldObject*>& GetObjects() const;
/// <summary>Retrieve all the objects in the world.</summary>
/// <returns>World's objects.</returns>
std::unordered_map<ObjectID, WorldObject*>& GetObjects();
/// <summary>Get the object with the <paramref name="_ID"/> in the world.</summary>
/// <param name="_ID">The ID of the object to retrieve from the world.</param>
/// <returns>Object in the world with the corresponding ID.</returns>
const WorldObject* GetObject( ObjectID _ID ) const;
/// <summary>Get the object with the <paramref name="_ID"/> in the world.</summary>
/// <param name="_ID">The ID of the object to retrieve from the world.</param>
/// <returns>Object in the world with the corresponding ID.</returns>
WorldObject* GetObject( ObjectID _ID );
/// <summary>Retrieve the world physics settings.</summary>
/// <returns>The world physics settings.</returns>
const PhysicsSettings& GetPhysicsSettings() const;
/// <summary>Retrieve the world physics settings.</summary>
/// <returns>The world physics settings.</returns>
PhysicsSettings& GetPhysicsSettings();
/// <summary>
/// Function called by the editor.
/// It allows the class to expose some attributes for user editing.
/// Think to call all inherited class function too when overloading.
/// </summary>
void ToEditor();
private:
/// <summary>Update the world objects.</summary>
void Update();
/// <summary>Take a new object ID from the pool.</summary>
/// <returns>The new ID taken from the pool (can be InvalidObjectID).</returns>
ObjectID GenerateObjectID();
/// <summary>Make available again an ID in the pool.</summary>
/// <param name="_ID">ID to make available in the pool.</param>
void FreeObjectID( ObjectID _ID );
/// <summary>
/// Add a new object in the world. <para/>
/// If the object is invalid or if there is not available ID
/// <paramref name="_ObjectToAdd"/> will not be added to the world. <para/>
/// If an object with the same ID already exists, <paramref name="_ObjectToAdd"/>
/// will not be added to the world.
/// </summary>
/// <returns>The ID of the object added (can be InvalidObjectID).</returns>
ObjectID AddObjectToWorld( WorldObject* _ObjectToAdd );
/// <summary>
/// Remove an object from the world. <para/>
/// Its ID will be available again in the pool ID.
/// </summary>
void RemoveObjectFromWorld( WorldObject* _ObjectToRemove );
/// <summary>
/// Add a light (must be valid) to the lights list
/// to improve lights access while rendering.
/// </summary>
void AddLightToList( Light* _LightToAdd );
/// <summary>
/// Remove a light from the lights list.
/// </summary>
void RemoveLightFromList( Light* _LightToRemove );
/// <summary>
/// Add a physic object (must be valid) to the physic object list
/// to improve physic object access while doing the simumation.
/// </summary>
/// <returns>The ID of the object added (can be InvalidObjectID).</returns>
void AddPhysicObjectToList( PhysicObject* _PhysicObjectToAdd );
/// <summary>
/// Remove a physic object from the physic object list.
/// </summary>
void RemoveLightFromList( PhysicObject* _PhysicObjectToRemove );
private:
/// <summary>Object ID generator.</summary>
PoolUniqueID m_IDPool;
/// <summary>World objects.</summary>
std::unordered_map<ObjectID, WorldObject*> m_Objects;
/// <summary>World lights, for quicker access in render.</summary>
std::unordered_map<ObjectID, Light*> m_Lights;
/// <summary>World physic objects, for quicker access for simulation.</summary>
std::unordered_map<ObjectID, PhysicObject*> m_PhysicObjects;
/// <summary>Physics simulator to update physic objects.</summary>
priv::PhysicsSimulator m_PhysicsSimulator;
};
} //ae
#endif // _WORLD_AERO_H_
|
int LED=11;
int BUTTON=7;
void setup() {
for(;LED>8;LED--){
pinMode(LED,OUTPUT);
}
pinMode(LED,OUTPUT);
pinMode(BUTTON,INPUT);
}
void loop() {
LED=11;
digitalWrite(11,HIGH);
delay(2000);
digitalWrite(11,LOW);
for(int i=0;i<3;i++)
{
digitalWrite(11,HIGH);
delay(300);
digitalWrite(11,LOW);
delay(300);
}
digitalWrite(9,HIGH);
delay(1000);
digitalWrite(9,LOW);
digitalWrite(10,HIGH);
delay(1000);
digitalWrite(10,LOW);
}
|
#ifndef ANALYZERMAINFORM_H
#define ANALYZERMAINFORM_H
#include <QMainWindow>
namespace Ui {
class AnalyzerMainForm;
}
class AnalyzerMainForm : public QMainWindow
{
Q_OBJECT
public:
explicit AnalyzerMainForm(QWidget *parent = 0);
~AnalyzerMainForm();
private:
Ui::AnalyzerMainForm *ui;
};
#endif // ANALYZERMAINFORM_H
|
void WriteStringToEEPROM(int beginaddress, String string){
char charBuf[string.length() + 1];
string.toCharArray(charBuf, string.length() + 1);
for (int t = 0; t < sizeof(charBuf); t++)
{
EEPROM.write(beginaddress + t, charBuf[t]);
}
EEPROM.commit();
}
String ReadStringFromEEPROM(int beginaddress){
volatile byte counter = 0;
char rChar;
String retString = "";
while (1)
{
rChar = EEPROM.read(beginaddress + counter);
if (rChar == 0) break;
if (counter > 31) break;
counter++;
retString.concat(rChar);
}
return retString;
}
void EEPROMWritelong(int address, long value){
byte four = (value & 0xFF);
byte three = ((value >> 8) & 0xFF);
byte two = ((value >> 16) & 0xFF);
byte one = ((value >> 24) & 0xFF);
//Write the 4 bytes into the eeprom memory.
EEPROM.write(address, four);
EEPROM.write(address + 1, three);
EEPROM.write(address + 2, two);
EEPROM.write(address + 3, one);
EEPROM.commit();
}
long EEPROMReadlong(long address){
//Read the 4 bytes from the eeprom memory.
long four = EEPROM.read(address);
long three = EEPROM.read(address + 1);
long two = EEPROM.read(address + 2);
long one = EEPROM.read(address + 3);
//Return the recomposed long by using bitshift.
return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);
}
|
#pragma once
#include "ToDoAreaWidgets/todoareawidget.h"
#include "PriorityWidget/prioritywidget.h"
#include "ToDoWidgets/TaskWidget/taskwidget.h"
class TaskAreaWidget : public ToDoAreaWidget
{
Q_OBJECT
public:
TaskAreaWidget();
~TaskAreaWidget() override;
void readToDoFromfile() override;
private slots:
void on_addToDoButton_clicked() override;
void addTaskFromOtherArea(TaskWidget movedTask);
protected:
PriorityWidget * priorityWidget;
};
|
//: C16:StackTemplate.h
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Prosty szablon stosu
#ifndef STACKTEMPLATE_H
#define STACKTEMPLATE_H
#include "../require.h"
template<class T>
class StackTemplate {
enum { ssize = 100 };
T stack[ssize];
int top;
public:
StackTemplate() : top(0) {}
void push(const T& i) {
require(top < ssize, "Zbyt wiele wywolan funkcji push()");
stack[top++] = i;
}
T pop() {
require(top > 0, "Zbyt wiele wywolan funkcji pop()");
return stack[--top];
}
int size() { return top; }
};
#endif // STACKTEMPLATE_H ///:~
|
//
// C++ Interface: ShareFile
//
// Description:
// 添加或删除共享文件,即管理共享文件
//
// Author: Jally <jallyx@163.com>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef SHAREFILE_H
#define SHAREFILE_H
#include "mess.h"
class ShareFile {
public:
ShareFile();
~ShareFile();
static void ShareEntry(GtkWidget *parent);
private:
void InitSublayer();
void ClearSublayer();
GtkWidget *CreateMainDialog(GtkWidget *parent);
GtkWidget *CreateAllArea();
GtkTreeModel *CreateFileModel();
void FillFileModel(GtkTreeModel *model);
GtkWidget *CreateFileTree(GtkTreeModel *model);
void ApplySharedData();
void AttachSharedFiles(GSList *list);
GSList *PickSharedFile(uint32_t fileattr);
GData *widset;
GData *mdlset;
//回调处理部分
private:
static void AddRegular(ShareFile *sfile);
static void AddFolder(ShareFile *sfile);
static void DeleteFiles(GData **widset);
static void SetPassword(GData **widset);
static void ClearPassword(GData **widset);
static void DragDataReceived(ShareFile *sfile, GdkDragContext *context,
gint x, gint y, GtkSelectionData *data,
guint info, guint time);
static gint FileTreeCompareFunc(GtkTreeModel *model, GtkTreeIter *a,
GtkTreeIter *b);
};
#endif
|
/***********************************************************************
class£ºHash Table for vertex clustering
***********************************************************************/
#include "Noise3D.h"
using namespace Noise3D;
|
#include <iostream>
#include <vector>
#include <list>
#include <deque>
#include <set>
#include <algorithm>
using namespace std;
template<typename T>
void print_sequence(const T &t)
{
typename T::const_iterator pos;
for (pos = t.begin(); pos != t.end(); ++pos) {
cout << *pos << " ";
}
cout << endl;
}
int main(int argc, char *argv[])
{
list<int> col1;
for (int i=1 ; i < 9; ++i)
col1.push_back(i);
print_sequence(col1);
vector<int> col2;
copy(col1.begin(), col1.end(), back_inserter(col2));
print_sequence(col2);
deque<int> col3;
copy(col2.begin(), col2.end(), front_inserter(col3));
print_sequence(col3);
set<int> col4;
copy(col1.begin(), col1.end(), inserter(col4, col4.begin()));
print_sequence(col4);
return 0;
}
|
#include "concretRA.h"
concretRA::concretRA()
{
}
concretRA::~concretRA()
{
}
void concretRA::ChangeData(int tag)
{
for (int i = 0; i < 128; i++)
{
float v = float(i*i % 31);
this->x.push_back ( v);
}
for (std::vector<float>::const_iterator k = x.begin(); k != x.end(); ++k)
{
float v = *k;
y.push_back(1.05 - 0.5*v);
}
this->Notify(tag, this->x, this->y);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2002 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Petter Nilsen (pettern) / Alexander Remen (alexr)
*/
#ifndef DESKTOPFILELOGGER_H
#define DESKTOPFILELOGGER_H
#include "modules/pi/system/OpLowLevelFile.h"
#include "modules/pi/OpLocale.h"
#include "modules/util/adt/oplisteners.h"
#include "adjunct/quick/managers/CommandLineManager.h"
#include "modules/pi/OpTimeInfo.h"
#include "modules/util/OpHashTable.h"
#include "modules/windowcommander/OpWindowCommander.h"
#include <time.h>
#define OP_PROFILE_METHOD(x) OpAutoPtr<MethodProfiler> profiler (g_profile_logger ? OP_NEW(MethodProfiler, (0, x)) : 0)
#define OP_PROFILE_MSG(x) DesktopFileLogger::Msg(x)
#define OP_PROFILE_INIT() DesktopFileLogger::Init()
#define OP_PROFILE_EXIT() DesktopFileLogger::Exit()
#define OP_PROFILE_CHECKPOINT_START(id, text) DesktopFileLogger::CheckpointStart(id, text)
#define OP_PROFILE_CHECKPOINT_END(id) DesktopFileLogger::CheckpointEnd(id)
class OpFile;
class FileLogTarget
{
public:
FileLogTarget() : m_file(NULL) {}
~FileLogTarget() { OP_DELETE(m_file); }
OP_STATUS Init(const OpStringC & filename);
OP_STATUS OutputEntry(const OpStringC8& entry)
{ return IsLogging() ? OutputEntryInternal(entry) : OpStatus::OK; }
BOOL IsLogging() { return m_file && m_file->IsOpen(); }
void StartLogging();
void EndLogging();
private:
OP_STATUS OutputEntryInternal(const OpStringC8& entry);
OpLowLevelFile *m_file; // we will not use OpFile as it is in a module not initialized yet and might or might not have dependencies
static const OpStringC8 s_log_header;
static const OpStringC8 s_log_footer;
};
namespace DesktopFileLogger
{
OP_STATUS Log(OpFile*& file, const OpStringC8& heading, const OpStringC8& text);
void Msg(const char *x);
void CheckpointStart(const OpWindowCommander* commander, const char *text);
void CheckpointEnd(const OpWindowCommander* commander);
void Init();
void Exit();
class CheckpointEntry
{
private:
CheckpointEntry() {}
public:
CheckpointEntry(const OpWindowCommander* commander, const char *text);
const char* m_text; // message to print at the end of the checkpoint
const OpWindowCommander* m_commander; // WindowCommander for this check point
double m_startticks; // start time
};
};
struct ProfileLogger
{
ProfileLogger() : log_level(0), filelog_target(NULL), logger_time_info(NULL) { }
~ProfileLogger() { OP_DELETE(filelog_target); OP_DELETE(logger_time_info); }
UINT32 log_level; // nested level, 1 is top level
FileLogTarget *filelog_target;
OpTimeInfo *logger_time_info; // pi is not initialized when we need this
OpPointerHashTable<OpWindowCommander, DesktopFileLogger::CheckpointEntry> checkpoints; // Hash table used for the check points
};
extern struct ProfileLogger* g_profile_logger;
// Will profile the time taken from the constructor to the destructor
class MethodProfiler
{
public:
MethodProfiler(int not_used, const char *method)
{
g_profile_logger->log_level++;
m_method = method;
m_startticks = g_profile_logger->logger_time_info->GetRuntimeMS();
}
virtual ~MethodProfiler()
{
double endticks = g_profile_logger->logger_time_info->GetRuntimeMS();
double ms_used = endticks - m_startticks;
OpString8 tmp, date_str, out;
double time_utc = g_profile_logger->logger_time_info->GetTimeUTC();
time_t time_s = time_utc / 1000;
int time_ms = (INT64)time_utc % 1000;
struct tm* date = op_gmtime(&time_s);
OpStatus::Ignore(tmp.Set(m_method));
if(date)
{
if (date_str.Reserve(128))
{
strftime(date_str.CStr(), date_str.Capacity(), "%Y-%m-%d %H:%M:%S", date);
out.AppendFormat("%s.%03d %3.0f ms - ", date_str.CStr(), time_ms, ms_used);
UINT32 tmp_level = g_profile_logger->log_level - 1;
while(tmp_level)
{
out.Append("+");
tmp_level--;
}
if(g_profile_logger->log_level > 1)
{
out.Append(" ");
}
out.Append(tmp.CStr());
if(g_profile_logger->filelog_target)
{
g_profile_logger->filelog_target->OutputEntry(out);
}
}
}
g_profile_logger->log_level--;
}
private:
const char *m_method;
double m_startticks;
};
#endif // DESKTOPFILELOGGER_H
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <quic/logging/BaseQLogger.h>
namespace {
void addQuicSimpleFrameToEvent(
quic::QLogPacketEvent* event,
const quic::QuicSimpleFrame& simpleFrame) {
switch (simpleFrame.type()) {
case quic::QuicSimpleFrame::Type::StopSendingFrame: {
const quic::StopSendingFrame& frame = *simpleFrame.asStopSendingFrame();
event->frames.push_back(std::make_unique<quic::StopSendingFrameLog>(
frame.streamId, frame.errorCode));
break;
}
case quic::QuicSimpleFrame::Type::PathChallengeFrame: {
const quic::PathChallengeFrame& frame =
*simpleFrame.asPathChallengeFrame();
event->frames.push_back(
std::make_unique<quic::PathChallengeFrameLog>(frame.pathData));
break;
}
case quic::QuicSimpleFrame::Type::PathResponseFrame: {
const quic::PathResponseFrame& frame = *simpleFrame.asPathResponseFrame();
event->frames.push_back(
std::make_unique<quic::PathResponseFrameLog>(frame.pathData));
break;
}
case quic::QuicSimpleFrame::Type::NewConnectionIdFrame: {
const quic::NewConnectionIdFrame& frame =
*simpleFrame.asNewConnectionIdFrame();
event->frames.push_back(std::make_unique<quic::NewConnectionIdFrameLog>(
frame.sequenceNumber, frame.token));
break;
}
case quic::QuicSimpleFrame::Type::MaxStreamsFrame: {
const quic::MaxStreamsFrame& frame = *simpleFrame.asMaxStreamsFrame();
event->frames.push_back(std::make_unique<quic::MaxStreamsFrameLog>(
frame.maxStreams, frame.isForBidirectional));
break;
}
case quic::QuicSimpleFrame::Type::RetireConnectionIdFrame: {
const quic::RetireConnectionIdFrame& frame =
*simpleFrame.asRetireConnectionIdFrame();
event->frames.push_back(
std::make_unique<quic::RetireConnectionIdFrameLog>(
frame.sequenceNumber));
break;
}
case quic::QuicSimpleFrame::Type::HandshakeDoneFrame: {
event->frames.push_back(std::make_unique<quic::HandshakeDoneFrameLog>());
break;
}
case quic::QuicSimpleFrame::Type::KnobFrame: {
const quic::KnobFrame& frame = *simpleFrame.asKnobFrame();
event->frames.push_back(std::make_unique<quic::KnobFrameLog>(
frame.knobSpace, frame.id, frame.blob->length()));
break;
}
case quic::QuicSimpleFrame::Type::AckFrequencyFrame: {
const quic::AckFrequencyFrame& frame = *simpleFrame.asAckFrequencyFrame();
event->frames.push_back(std::make_unique<quic::AckFrequencyFrameLog>(
frame.sequenceNumber,
frame.packetTolerance,
frame.updateMaxAckDelay,
frame.reorderThreshold));
break;
}
case quic::QuicSimpleFrame::Type::NewTokenFrame: {
const quic::NewTokenFrame& frame = *simpleFrame.asNewTokenFrame();
auto tokenHexStr = folly::hexlify(frame.token->coalesce());
event->frames.push_back(
std::make_unique<quic::NewTokenFrameLog>(tokenHexStr));
break;
}
}
}
} // namespace
namespace quic {
std::unique_ptr<QLogPacketEvent> BaseQLogger::createPacketEvent(
const RegularQuicPacket& regularPacket,
uint64_t packetSize) {
auto event = std::make_unique<QLogPacketEvent>();
event->refTime = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now().time_since_epoch());
event->packetSize = packetSize;
event->eventType = QLogEventType::PacketReceived;
const ShortHeader* shortHeader = regularPacket.header.asShort();
if (shortHeader) {
event->packetType = kShortHeaderPacketType.toString();
} else {
event->packetType =
toQlogString(regularPacket.header.asLong()->getHeaderType()).str();
}
if (event->packetType != toString(LongHeader::Types::Retry)) {
// A Retry packet does not include a packet number.
event->packetNum = regularPacket.header.getPacketSequenceNum();
}
uint64_t numPaddingFrames = 0;
// looping through the packet to store logs created from frames in the packet
for (const auto& quicFrame : regularPacket.frames) {
switch (quicFrame.type()) {
case QuicFrame::Type::PaddingFrame: {
numPaddingFrames += quicFrame.asPaddingFrame()->numFrames;
break;
}
case QuicFrame::Type::RstStreamFrame: {
const auto& frame = *quicFrame.asRstStreamFrame();
event->frames.push_back(std::make_unique<RstStreamFrameLog>(
frame.streamId, frame.errorCode, frame.offset));
break;
}
case QuicFrame::Type::ConnectionCloseFrame: {
const auto& frame = *quicFrame.asConnectionCloseFrame();
event->frames.push_back(std::make_unique<ConnectionCloseFrameLog>(
frame.errorCode, frame.reasonPhrase, frame.closingFrameType));
break;
}
case QuicFrame::Type::MaxDataFrame: {
const auto& frame = *quicFrame.asMaxDataFrame();
event->frames.push_back(
std::make_unique<MaxDataFrameLog>(frame.maximumData));
break;
}
case QuicFrame::Type::MaxStreamDataFrame: {
const auto& frame = *quicFrame.asMaxStreamDataFrame();
event->frames.push_back(std::make_unique<MaxStreamDataFrameLog>(
frame.streamId, frame.maximumData));
break;
}
case QuicFrame::Type::DataBlockedFrame: {
const auto& frame = *quicFrame.asDataBlockedFrame();
event->frames.push_back(
std::make_unique<DataBlockedFrameLog>(frame.dataLimit));
break;
}
case QuicFrame::Type::StreamDataBlockedFrame: {
const auto& frame = *quicFrame.asStreamDataBlockedFrame();
event->frames.push_back(std::make_unique<StreamDataBlockedFrameLog>(
frame.streamId, frame.dataLimit));
break;
}
case QuicFrame::Type::StreamsBlockedFrame: {
const auto& frame = *quicFrame.asStreamsBlockedFrame();
event->frames.push_back(std::make_unique<StreamsBlockedFrameLog>(
frame.streamLimit, frame.isForBidirectional));
break;
}
case QuicFrame::Type::ReadAckFrame: {
const auto& frame = *quicFrame.asReadAckFrame();
event->frames.push_back(std::make_unique<ReadAckFrameLog>(
frame.ackBlocks,
frame.ackDelay,
frame.frameType,
frame.maybeLatestRecvdPacketTime,
frame.maybeLatestRecvdPacketNum,
frame.recvdPacketsTimestampRanges));
break;
}
case QuicFrame::Type::ReadStreamFrame: {
const auto& frame = *quicFrame.asReadStreamFrame();
event->frames.push_back(std::make_unique<StreamFrameLog>(
frame.streamId, frame.offset, frame.data->length(), frame.fin));
break;
}
case QuicFrame::Type::ReadCryptoFrame: {
const auto& frame = *quicFrame.asReadCryptoFrame();
event->frames.push_back(std::make_unique<CryptoFrameLog>(
frame.offset, frame.data->length()));
break;
}
case QuicFrame::Type::ReadNewTokenFrame: {
event->frames.push_back(std::make_unique<ReadNewTokenFrameLog>());
break;
}
case QuicFrame::Type::PingFrame: {
event->frames.push_back(std::make_unique<quic::PingFrameLog>());
break;
}
case QuicFrame::Type::QuicSimpleFrame: {
const auto& simpleFrame = *quicFrame.asQuicSimpleFrame();
addQuicSimpleFrameToEvent(event.get(), simpleFrame);
break;
}
case QuicFrame::Type::NoopFrame: {
break;
}
case QuicFrame::Type::DatagramFrame: {
const auto& frame = *quicFrame.asDatagramFrame();
event->frames.push_back(
std::make_unique<quic::DatagramFrameLog>(frame.length));
break;
}
case QuicFrame::Type::ImmediateAckFrame: {
event->frames.push_back(std::make_unique<quic::ImmediateAckFrameLog>());
break;
}
}
}
if (numPaddingFrames > 0) {
event->frames.push_back(
std::make_unique<PaddingFrameLog>(numPaddingFrames));
}
return event;
}
std::unique_ptr<QLogPacketEvent> BaseQLogger::createPacketEvent(
const RegularQuicWritePacket& writePacket,
uint64_t packetSize) {
auto event = std::make_unique<QLogPacketEvent>();
event->refTime = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now().time_since_epoch());
event->packetNum = writePacket.header.getPacketSequenceNum();
event->packetSize = packetSize;
event->eventType = QLogEventType::PacketSent;
const ShortHeader* shortHeader = writePacket.header.asShort();
if (shortHeader) {
event->packetType = kShortHeaderPacketType.toString();
} else {
event->packetType =
toQlogString(writePacket.header.asLong()->getHeaderType()).str();
}
uint64_t numPaddingFrames = 0;
// looping through the packet to store logs created from frames in the packet
for (const auto& quicFrame : writePacket.frames) {
switch (quicFrame.type()) {
case QuicWriteFrame::Type::PaddingFrame:
numPaddingFrames += quicFrame.asPaddingFrame()->numFrames;
break;
case QuicWriteFrame::Type::RstStreamFrame: {
const RstStreamFrame& frame = *quicFrame.asRstStreamFrame();
event->frames.push_back(std::make_unique<RstStreamFrameLog>(
frame.streamId, frame.errorCode, frame.offset));
break;
}
case QuicWriteFrame::Type::ConnectionCloseFrame: {
const ConnectionCloseFrame& frame = *quicFrame.asConnectionCloseFrame();
event->frames.push_back(std::make_unique<ConnectionCloseFrameLog>(
frame.errorCode, frame.reasonPhrase, frame.closingFrameType));
break;
}
case QuicWriteFrame::Type::MaxDataFrame: {
const MaxDataFrame& frame = *quicFrame.asMaxDataFrame();
event->frames.push_back(
std::make_unique<MaxDataFrameLog>(frame.maximumData));
break;
}
case QuicWriteFrame::Type::MaxStreamDataFrame: {
const MaxStreamDataFrame& frame = *quicFrame.asMaxStreamDataFrame();
event->frames.push_back(std::make_unique<MaxStreamDataFrameLog>(
frame.streamId, frame.maximumData));
break;
}
case QuicWriteFrame::Type::StreamsBlockedFrame: {
const StreamsBlockedFrame& frame = *quicFrame.asStreamsBlockedFrame();
event->frames.push_back(std::make_unique<StreamsBlockedFrameLog>(
frame.streamLimit, frame.isForBidirectional));
break;
}
case QuicWriteFrame::Type::DataBlockedFrame: {
const DataBlockedFrame& frame = *quicFrame.asDataBlockedFrame();
event->frames.push_back(
std::make_unique<DataBlockedFrameLog>(frame.dataLimit));
break;
}
case QuicWriteFrame::Type::StreamDataBlockedFrame: {
const StreamDataBlockedFrame& frame =
*quicFrame.asStreamDataBlockedFrame();
event->frames.push_back(std::make_unique<StreamDataBlockedFrameLog>(
frame.streamId, frame.dataLimit));
break;
}
case QuicWriteFrame::Type::WriteAckFrame: {
const WriteAckFrame& frame = *quicFrame.asWriteAckFrame();
event->frames.push_back(std::make_unique<WriteAckFrameLog>(
frame.ackBlocks,
frame.ackDelay,
frame.frameType,
frame.maybeLatestRecvdPacketTime,
frame.maybeLatestRecvdPacketNum,
frame.recvdPacketsTimestampRanges));
break;
}
case QuicWriteFrame::Type::WriteStreamFrame: {
const WriteStreamFrame& frame = *quicFrame.asWriteStreamFrame();
event->frames.push_back(std::make_unique<StreamFrameLog>(
frame.streamId, frame.offset, frame.len, frame.fin));
break;
}
case QuicWriteFrame::Type::WriteCryptoFrame: {
const WriteCryptoFrame& frame = *quicFrame.asWriteCryptoFrame();
event->frames.push_back(
std::make_unique<CryptoFrameLog>(frame.offset, frame.len));
break;
}
case QuicWriteFrame::Type::QuicSimpleFrame: {
const QuicSimpleFrame& simpleFrame = *quicFrame.asQuicSimpleFrame();
addQuicSimpleFrameToEvent(event.get(), simpleFrame);
break;
}
case QuicWriteFrame::Type::NoopFrame: {
break;
}
case QuicWriteFrame::Type::DatagramFrame: {
// TODO
break;
}
case QuicWriteFrame::Type::ImmediateAckFrame: {
event->frames.push_back(std::make_unique<quic::ImmediateAckFrameLog>());
break;
}
case QuicWriteFrame::Type::PingFrame: {
event->frames.push_back(std::make_unique<quic::PingFrameLog>());
break;
}
}
}
if (numPaddingFrames > 0) {
event->frames.push_back(
std::make_unique<PaddingFrameLog>(numPaddingFrames));
}
return event;
}
std::unique_ptr<QLogVersionNegotiationEvent> BaseQLogger::createPacketEvent(
const VersionNegotiationPacket& versionPacket,
uint64_t packetSize,
bool isPacketRecvd) {
auto event = std::make_unique<QLogVersionNegotiationEvent>();
event->refTime = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now().time_since_epoch());
event->packetSize = packetSize;
event->eventType =
isPacketRecvd ? QLogEventType::PacketReceived : QLogEventType::PacketSent;
event->packetType = kVersionNegotiationPacketType;
event->versionLog = std::make_unique<VersionNegotiationLog>(
VersionNegotiationLog(versionPacket.versions));
return event;
}
std::unique_ptr<QLogRetryEvent> BaseQLogger::createPacketEvent(
const RetryPacket& retryPacket,
uint64_t packetSize,
bool isPacketRecvd) {
auto event = std::make_unique<QLogRetryEvent>();
event->refTime = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now().time_since_epoch());
event->packetSize = packetSize;
event->tokenSize = retryPacket.header.getToken().size();
event->eventType =
isPacketRecvd ? QLogEventType::PacketReceived : QLogEventType::PacketSent;
event->packetType = toQlogString(retryPacket.header.getHeaderType()).str();
return event;
}
} // namespace quic
|
// Sharna Hossain
// CSC 111
// Lab 21 | binary_search.cpp
#include <iostream>
// In order for binary search to work, the array
// needs to already be in ascending order.
// For this exercise, I will use the algorithm's library
// to sort so that I can focus on implementing binary search.
#include <algorithm>
#include <iomanip>
using namespace std;
void output(int, int);
int binary_search(int arr[], int size, int query)
{
int first = 0,
last = size - 1,
middle, result = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (arr[middle] == query)
{
found = true;
result = middle;
}
else if (arr[middle] > query)
{
last = middle - 1;
}
else
first = middle + 1;
}
return result;
}
int main()
{
// Initialize values
int size, query;
cout << "Enter the size of the array of numbers: ";
cin >> size;
int arr[size];
for (int i = 0; i < size; i++)
{
cout << "Enter number #" << i + 1 << ": ";
cin >> arr[i];
}
// Sorting array in ascending order
sort(arr, arr + size);
cout << "Sorted list of numbers: ";
for(int i = 0; i < size; i++)
{
cout << setw(4) << arr[i];
}
cout << "\nEnter the number you're searching for: ";
cin >> query;
// Output Values
output(query, binary_search(arr, size, query));
return 0;
}
void output(int query, int index)
{
if (index == -1)
{
cout << query << " does not exist in array";
}
else
{
cout << query << " is the #" << index + 1;
cout << " element and is located at ";
cout << "array[" << index << "]\n";
}
}
|
#pragma once
/*
Vector2i is a wrapper for the sf::Vector2i
*/
class Vector2i
{
public:
Vector2i();
Vector2i(int aX, int aY);
Vector2i(sf::Vector2i aVector);
int X() const { return m_vec.x; }
int Y() const { return m_vec.y; }
friend Vector2i operator+(const Vector2i& aVec1, const Vector2i& aVec2);
const sf::Vector2i& GetVector() const { return m_vec; }
private:
sf::Vector2i m_vec;
};
|
//
// rvHeapArena.cpp - Heap arena object that manages a set of heaps
// Date: 12/13/04
// Created by: Dwight Luetscher
//
#include "../idlib/precompiled.h"
#pragma hdrstop
#ifdef _RV_MEM_SYS_SUPPORT
// rvHeapArena
//
// constructor
rvHeapArena::rvHeapArena()
{
// ResetValues(); do this in the Init() call instead (due to the fact that other constructors could call rvHeapArena::Init() before this constructor is called)
}
// ~rvHeapArena
//
// destructor
rvHeapArena::~rvHeapArena()
{
Shutdown();
}
// Init
//
// initializes this heap arena for use
void rvHeapArena::Init( )
{
if ( m_isInitialized )
{
return;
}
ResetValues();
m_isInitialized = true;
// create the critical section used by this heap arena
InitializeCriticalSection( &m_criticalSection );
}
// Shutdown
//
// releases this heap arena from use (shutting down all associated heaps)
void rvHeapArena::Shutdown( )
{
// shutdown each heap from this arena's list
rvHeap *curHeap = m_heapList, *nextHeap;
while ( curHeap != NULL )
{
nextHeap = curHeap->GetNext();
curHeap->Shutdown();
curHeap = nextHeap;
}
DeleteCriticalSection( &m_criticalSection );
ResetValues();
}
// ResetValues
//
// resets the data members to their pre-initialized state
void rvHeapArena::ResetValues( )
{
memset( m_heapStack, 0, sizeof(m_heapStack) );
memset( &m_criticalSection, 0, sizeof(m_criticalSection) );
m_tos = -1;
m_heapList = NULL;
m_isInitialized = false;
}
// Push
//
// pushes the given heap onto the top of the stack making it the active one for this arena
void rvHeapArena::Push( rvHeap &newActiveHeap )
{
EnterArenaCriticalSection();
assert( newActiveHeap.GetArena() == this );
assert(m_tos+1 < maxHeapStackDepth); // stack overflow?
if (m_tos+1 < maxHeapStackDepth)
{
m_heapStack[++m_tos] = &newActiveHeap;
}
ExitArenaCriticalSection();
}
// Pop
//
// pops the top of the stack, restoring the previous heap as the active heap for this arena
void rvHeapArena::Pop( )
{
EnterArenaCriticalSection();
assert(m_tos > -1); // stack underflow?
if (m_tos > -1)
{
m_tos--;
}
ExitArenaCriticalSection();
}
// GetHeap
//
// returns: the heap that the given allocation was made from, NULL for none
rvHeap *rvHeapArena::GetHeap( void *p )
{
EnterArenaCriticalSection();
if ( !m_isInitialized )
{
ExitArenaCriticalSection();
return NULL;
}
rvHeap *curHeap = m_heapList;
while ( curHeap != NULL && !curHeap->DoesAllocBelong(p) )
{
curHeap = curHeap->GetNext();
}
ExitArenaCriticalSection();
return curHeap;
}
// Allocate
//
// allocates the given amount of memory from this arena.
void *rvHeapArena::Allocate( unsigned int sizeBytes, int debugTag )
{
rvHeap *curHeap;
EnterArenaCriticalSection();
assert( m_tos >= 0 && m_tos < maxHeapStackDepth );
if ( m_tos < 0 )
{
ExitArenaCriticalSection();
return NULL;
}
curHeap = m_heapStack[ m_tos ];
ExitArenaCriticalSection();
return curHeap->Allocate( sizeBytes, debugTag );
}
// Allocate16
//
// allocates the given amount of memory from this arena,
// aligned on a 16-byte boundary.
void *rvHeapArena::Allocate16( unsigned int sizeBytes, int debugTag )
{
rvHeap *curHeap;
EnterArenaCriticalSection();
assert( m_tos >= 0 && m_tos < maxHeapStackDepth );
if ( m_tos < 0 )
{
ExitArenaCriticalSection();
return NULL;
}
curHeap = m_heapStack[ m_tos ];
ExitArenaCriticalSection();
return curHeap->Allocate16( sizeBytes, debugTag );
}
// Free
//
// free memory back to this arena
void rvHeapArena::Free( void *p )
{
rvHeap *heap = GetHeap( p ); // arena critical section protection is in GetHeap()
if (heap != NULL)
{
heap->Free( p );
}
}
// Msize
//
// returns: the size, in bytes, of the allocation at the given address (including header, alignment bytes, etc).
int rvHeapArena::Msize( void *p )
{
rvHeap *heap = GetHeap( p ); // arena critical section protection is in GetHeap()
if (heap != NULL)
{
return heap->Msize( p );
}
return 0;
}
// InitHeap
//
// initializes the given heap to be under the care of this arena
void rvHeapArena::InitHeap( rvHeap &newActiveHeap )
{
assert( newActiveHeap.GetArena() == NULL );
newActiveHeap.SetArena( this );
newActiveHeap.SetNext( m_heapList );
m_heapList = &newActiveHeap;
}
// ShutdownHeap
//
// releases the given heap from the care of this arena
void rvHeapArena::ShutdownHeap( rvHeap &activeHeap )
{
int stackPos, copyPos;
assert( activeHeap.GetArena() == this );
activeHeap.SetArena( NULL );
// make sure that the heap is removed from the stack
for ( stackPos = 0; stackPos <= m_tos; stackPos++ )
{
if ( m_heapStack[stackPos] == &activeHeap )
{
for ( copyPos = stackPos; copyPos < m_tos; copyPos++ )
{
m_heapStack[copyPos] = m_heapStack[copyPos+1];
}
m_tos--;
}
}
// remove the heap from this arena's list
rvHeap *curHeap = m_heapList, * prevHeap = NULL;
while ( curHeap != NULL )
{
if ( curHeap == &activeHeap )
{
if ( NULL == prevHeap )
{
m_heapList = m_heapList->GetNext();
}
else
{
prevHeap->SetNext( curHeap->GetNext() );
}
break;
}
prevHeap = curHeap;
curHeap = curHeap->GetNext();
}
}
// GetNextHeap
//
// returns: that follows the given one (associated with this arena), NULL for none
rvHeap *rvHeapArena::GetNextHeap( rvHeap &rfPrevHeap )
{
rvHeap *nextHeap;
EnterArenaCriticalSection();
if ( rfPrevHeap.GetArena() != this )
{
nextHeap = NULL;
}
else
{
nextHeap = rfPrevHeap.GetNext();
}
ExitArenaCriticalSection();
return nextHeap;
}
// GetTagStats
//
// returns: the total stats for a particular tag type (across all heaps managed by this arena)
void rvHeapArena::GetTagStats(int tag, int &num, int &size, int &peak)
{
int curPeak;
assert( tag < MA_MAX );
EnterArenaCriticalSection();
num = size = peak = 0;
rvHeap *curHeap = m_heapList;
while ( curHeap != NULL )
{
num += curHeap->GetNumAllocationsByTag( (Mem_Alloc_Types_t) tag );
size += curHeap->GetBytesAllocatedByTag( (Mem_Alloc_Types_t) tag );
curPeak = curHeap->GetPeekBytesAllocatedByTag( (Mem_Alloc_Types_t) tag );
if ( curPeak > peak )
{
peak = curPeak;
}
curHeap = curHeap->GetNext();
}
ExitArenaCriticalSection();
}
#endif // #ifdef _RV_MEM_SYS_SUPPORT
|
//implemenetation
#include <iostream>
#include <string>
#include "time.h"
using namespace std;
//operator overloading
ostream& operator <<(ostream& osObject, const time& time1)
{
osObject << time1.Hour << ":" << time1.Min;
return osObject;
}
istream& operator >>(istream& isObject, time& time1)
{
isObject >> time1.Hour >> time1.Min;
return isObject;
}
//comparison operator overloading
bool time::operator < (time& rhs)const {
if (this->getHour() < rhs.getHour()) {
return true;
}
else if (this->getHour() == rhs.getHour()) {
if (this->getMin() < rhs.getMin()) {
return true;
}
else { return false; }
}
else { return false; }
}
bool time::operator == (time& rhs)const {
if (this->getHour() == rhs.getHour()) {
if (this->getMin() == rhs.getMin()) {
return true;
}
else { return false; }
}
else { return false; }
}
time& time::operator = (const int rhs) // copy assignment
{
if (rhs == 0) {
this->setHour(00);
this->setMin(00);
}
return *this;
}
//default contructor
time::time() // hearer file name ::header file location
{
Hour = 0; Min = 0;
}
//destructor
time::~time() {
}
//specific constructor
time::time(int hr, int mm) {
Hour = hr;
Min = mm;
}
//setter
void time::setHour(int hr) {
Hour = hr;
}
void time::setMin(int mm) {
Min = mm;
}
void time::setTime(int hr, int mm) {
Hour = hr;
Min = mm;
}
//getter
void time::print() {
cout << "hour: " << Hour << " min: " << Min;
}
int time::getHour() const {
return Hour;
}
int time::getMin() const {
return Min;
}
|
//42. Trapping Rain Water
class Solution {
public:
int trap(vector<int>& arr) {
int n = arr.size();
int trapAmount = 0;
if(n < 3) return 0;
vector<int> leftMax(n, 0), rightMax(n, 0);
leftMax[0] = arr[0];
rightMax[n-1] = arr[n-1];
for(int i = 1; i < n-1; i++) {
leftMax[i] = max(leftMax[i-1], arr[i]);
rightMax[n-i-1] = max(rightMax[n-i], arr[n-i-1]);
}
for(int i = 1; i < n-1; i++) {
trapAmount += min(leftMax[i], rightMax[i]) - arr[i];
}
return trapAmount;
}
};
|
// Created on: 1993-03-24
// Created by: JCV
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Geom2d_Conic_HeaderFile
#define _Geom2d_Conic_HeaderFile
#include <gp_Ax22d.hxx>
#include <Geom2d_Curve.hxx>
class Geom2d_Conic;
DEFINE_STANDARD_HANDLE(Geom2d_Conic, Geom2d_Curve)
//! The abstract class Conic describes the common
//! behavior of conic curves in 2D space and, in
//! particular, their general characteristics. The Geom2d
//! package provides four specific classes of conics:
//! Geom2d_Circle, Geom2d_Ellipse,
//! Geom2d_Hyperbola and Geom2d_Parabola.
//! A conic is positioned in the plane with a coordinate
//! system (gp_Ax22d object), where the origin is the
//! center of the conic (or the apex in case of a parabola).
//! This coordinate system is the local coordinate
//! system of the conic. It gives the conic an explicit
//! orientation, determining the direction in which the
//! parameter increases along the conic. The "X Axis" of
//! the local coordinate system also defines the origin of
//! the parameter of the conic.
class Geom2d_Conic : public Geom2d_Curve
{
public:
//! Modifies this conic, redefining its local coordinate system
//! partially, by assigning theA as its axis
void SetAxis (const gp_Ax22d& theA) { pos.SetAxis(theA); }
//! Assigns the origin and unit vector of axis theA to the
//! origin of the local coordinate system of this conic and X Direction.
//! The other unit vector of the local coordinate system
//! of this conic is recomputed normal to theA, without
//! changing the orientation of the local coordinate
//! system (right-handed or left-handed).
void SetXAxis (const gp_Ax2d& theAX) { pos.SetXAxis(theAX); }
//! Assigns the origin and unit vector of axis theA to the
//! origin of the local coordinate system of this conic and Y Direction.
//! The other unit vector of the local coordinate system
//! of this conic is recomputed normal to theA, without
//! changing the orientation of the local coordinate
//! system (right-handed or left-handed).
void SetYAxis (const gp_Ax2d& theAY) { pos.SetYAxis(theAY); }
//! Modifies this conic, redefining its local coordinate
//! system partially, by assigning theP as its origin.
void SetLocation (const gp_Pnt2d& theP) { pos.SetLocation(theP); }
//! Returns the "XAxis" of the conic.
//! This axis defines the origin of parametrization of the conic.
//! This axis and the "Yaxis" define the local coordinate system
//! of the conic.
//! -C++: return const&
Standard_EXPORT gp_Ax2d XAxis() const;
//! Returns the "YAxis" of the conic.
//! The "YAxis" is perpendicular to the "Xaxis".
Standard_EXPORT gp_Ax2d YAxis() const;
//! returns the eccentricity value of the conic e.
//! e = 0 for a circle
//! 0 < e < 1 for an ellipse (e = 0 if MajorRadius = MinorRadius)
//! e > 1 for a hyperbola
//! e = 1 for a parabola
Standard_EXPORT virtual Standard_Real Eccentricity() const = 0;
//! Returns the location point of the conic.
//! For the circle, the ellipse and the hyperbola it is the center of
//! the conic. For the parabola it is the vertex of the parabola.
const gp_Pnt2d& Location() const { return pos.Location(); }
//! Returns the local coordinates system of the conic.
const gp_Ax22d& Position() const { return pos; }
//! Reverses the direction of parameterization of <me>.
//! The local coordinate system of the conic is modified.
Standard_EXPORT void Reverse() Standard_OVERRIDE;
//! Returns the parameter on the reversed curve for
//! the point of parameter U on <me>.
Standard_EXPORT virtual Standard_Real ReversedParameter (const Standard_Real U) const Standard_OVERRIDE = 0;
//! Returns GeomAbs_CN which is the global continuity of any conic.
Standard_EXPORT GeomAbs_Shape Continuity() const Standard_OVERRIDE;
//! Returns True, the order of continuity of a conic is infinite.
Standard_EXPORT Standard_Boolean IsCN (const Standard_Integer N) const Standard_OVERRIDE;
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(Geom2d_Conic,Geom2d_Curve)
protected:
gp_Ax22d pos;
};
#endif // _Geom2d_Conic_HeaderFile
|
#include "Sock.h"
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "PrintLog.h"
#ifdef _WIN32
#include <WinSock2.h>
#else //_WIN32
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#endif //_WIN32
CSock::CSock()
{
m_fd = INVALID_SOCK_FD;
}
CSock::~CSock()
{
Close();
}
int CSock::GetFd() const
{
return m_fd;
}
int CSock::AttachFd( int fd )
{
if( m_fd != INVALID_SOCK_FD )
return -1;
else
m_fd = fd;
if( m_fd > 0 ){
if( set_block_opt( false ) < 0 ){
m_fd = INVALID_SOCK_FD;
return -1;
}
}
return 0;
}
int CSock::DetachFd()
{
int tmp = m_fd;
m_fd = INVALID_SOCK_FD;
return tmp;
}
int CSock::open( int sock_type )
{
Close();
m_fd = ::socket( AF_INET, sock_type, 0 );
if( m_fd == -1 ){
LogError( "create socket failed, err info:%d %s\n", ERROR_NO, ERROR_STR );
return -1;
}
if( set_block_opt( false ) < 0 ){
Close();
return -1;
}
return m_fd;
}
void CSock::Close()
{
if( m_fd != INVALID_SOCK_FD ){
#ifdef _WIN32
::closesocket( m_fd );
#else
::close( m_fd );
#endif
m_fd = INVALID_SOCK_FD;
}
}
int CSock::bind( const char* ip, int port )
{
struct sockaddr_in local_addr;
if( get_addr( ip, port, local_addr ) < 0 )
return -1;
if( ::bind( m_fd, (struct sockaddr *)&local_addr, sizeof(local_addr) ) == -1 ){
LogError( "bind failed, err info:%d %s\n", ERROR_NO, ERROR_STR );
return -1;
}
return 0;
}
int CSock::get_addr( const char* ip, int port, sockaddr_in& addr )
{
int ip_n = 0;
if( ip == NULL || ip[0] == '\0' )
ip_n = 0;
else if( inet_addr(ip) == INADDR_NONE ){
struct hostent* hent = NULL;
if( (hent = gethostbyname( ip )) == NULL ){
LogError( "get host by name failed, name:%s\n", ip );
return -1;
}
memcpy( &ip_n, *(hent->h_addr_list), sizeof(ip_n) );
}else
ip_n = inet_addr(ip);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = ip_n;
addr.sin_port = htons( port );
return 0;
}
int CSock::set_addr_reuse()
{
int opt = 1;
if( ::setsockopt( m_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt) ) < 0 ){
LogError( "set reuseaddr failed, err info:%d %s\n", ERROR_NO, ERROR_STR );
return -1;
}
return 0;
}
int CSock::set_block_opt( bool is_block )
{
if( m_fd == INVALID_SOCK_FD )
return 0;
#ifdef _WIN32
u_long block = 1;
if( is_block )
block = 0;
if( SOCKET_ERROR == ::ioctlsocket( m_fd, FIONBIO, &block ) ){
LogError( "set socket block failed!\n" );
return -1;
}
#else
int flags = ::fcntl( m_fd, F_GETFL );
if( flags < 0 ) {
LogError( "set socket block failed! %s\n", ERROR_STR );
return -1;
}
if( is_block )
flags &= ~O_NONBLOCK;
else
flags |= O_NONBLOCK;
int retval = ::fcntl( m_fd, F_SETFL, flags );
if( retval < 0 ){
LogError( "set socket block failed! %s\n", ERROR_STR );
return -1;
}
#endif
return 0;
}
|
//
// Created by msagebaum on 3/31/18.
//
#ifndef GPSANALYSER_UTIL_H
#define GPSANALYSER_UTIL_H
#include <ctime>
#include <iomanip>
#include <rapidxml.hpp>
inline std::string formatDateTime(long value, bool dateOut, bool timeOut, bool milliOut) {
long milli = value % 1000;
std::time_t time = value / 1000;
std::tm* r;
r = gmtime(&time);
std::stringstream s;
if(dateOut) {s << std::put_time(r, "%Y-%m-%d");}
if(dateOut && timeOut) {s << "T";}
if(timeOut) {s << std::put_time(r, "%H:%M:%S");}
if(milliOut) {s << "." << std::setfill('0') << std::setw(3) << milli;}
return s.str();
}
inline std::string formatDouble(double value, int precission, int width) {
std::stringstream s;
s.setf(std::stringstream::fixed);
s.precision(precission);
s << std::setw(width) << value;
return s.str();
}
inline std::string formatInt(int value, int width) {
std::stringstream s;
s.width(width);
s << value;
return s.str();
}
inline double parseDouble(const char* value) {
const std::string s(value);
return std::stod(s, nullptr);
}
inline double parseDouble(rapidxml::xml_node<>* node, const double def) {
if(nullptr == node) {
return def;
} else {
return parseDouble(node->value());
}
}
inline double parseDouble(rapidxml::xml_attribute<>* node, const double def) {
if(nullptr == node) {
return def;
} else {
return parseDouble(node->value());
}
}
inline long parseDateTime(rapidxml::xml_node<>* node, const long def) {
if(nullptr == node) {
return def;
} else {
const char* value = node->value();
std::istringstream s(value);
std::tm r = {};
long ms;
s >> std::get_time(&r, "%Y-%m-%dT%H:%M:%S.");
s >> ms;
ms += mktime(&r) * 1000;
return ms;
}
}
inline const char* toString(rapidxml::xml_document<>& doc, double value) {
std::string s = formatDouble(value, 14, 0);
return doc.allocate_string(s.c_str(), s.size() + 1);
}
inline const char* toString(rapidxml::xml_document<>& doc, long value) {
std::string s = formatDateTime(value, true, true, true) + "Z";
return doc.allocate_string(s.c_str(), s.size() + 1);
}
inline const char* toString(rapidxml::xml_document<>& doc, const std::string& value) {
return doc.allocate_string(value.c_str(), value.size() + 1);
}
inline std::string extractFileName(const std::string& input) {// TODO: Improved splitting of file name
std::string::size_type pos = input.find_last_of('/');
if(pos == std::string::npos) {
// local file name
pos = 0;
} else {
pos += 1;
}
return input.substr(pos);
}
inline double deg2Rad(const double deg) {
return deg * 3.14159265359 / 180.0;
}
#endif //GPSANALYSER_UTIL_H
|
#include <iostream>
using namespace std;
string s1,s2;
bool flag=true;
int ind[10005][30];
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>s1>>s2;
int sz1=s1.size();
int sz2=s2.size();
for(int j=0;j<26;j++){
ind[sz1][j]=-1;
}
for(int i=sz1-1;i>=0;i--){
for(int j=0;j<26;j++){
ind[i][j]=ind[i+1][j];
}
ind[i][s1[i]-'a']=i;
}
ind[0][s1[0]-'a']=0;
int pos=0;
int ans=0;
for(int i=0;i<sz2;i++){
int t=s2[i]-'a';
// cout<<pos<<endl;
if(ind[0][t]==-1){
flag=false;
break;
}
if(ind[pos][t]==-1){
// cout<<pos<<endl;
ans++;
pos=0;
}
pos=ind[pos][t]+1;
}
cout << (!flag ? -1 : ans+1) << '\n';
return 0;
}
|
//By SCJ
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define maxn 1000002
int n,m,ans=0,tp,d[maxn],a[maxn];
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n>>m;
string A,B;cin>>A>>B;
for(int i=0;i<n;++i) if(A[i]!=B[i]) a[i+1]=1;
for(int i=1;i<=n-m+1;++i)
{
tp+=d[i];
if((tp&1)^a[i]) d[i+m]--,ans++,tp++;
}
bool flag=0;
for(int i=n-m+2;i<=n;++i)
{
tp+=d[i];
if((tp&1)^a[i]){flag=1;break;}
}
if(flag) cout<<"No Way!!"<<endl;
else cout<<ans<<endl;
}
|
#include "ChessBoardWidget.h"
#include <qpainter.h>
#include <qmessagebox.h>
#include <utility>
#include <random>
#include <ctime>
ChessBoardWidget::ChessBoardWidget(QWidget *parent)
: QWidget(parent)
{
setMouseTracking(true);
brushBlack = QBrush(QColor(0, 0, 0, 200), Qt::SolidPattern);
brushWhite = QBrush(QColor(0, 0, 0, 100), Qt::SolidPattern);
brushHighlight = QBrush(QColor(0, 255, 0, 150), Qt::SolidPattern);
//brushGreen = QBrush(QColor(0, 255, 0, 100), Qt::SolidPattern);
brushRed = QBrush(QColor(255, 0, 0, 150), Qt::SolidPattern);
QImage sheet("./Resources/chess_pieces.png");
Q_ASSERT(!sheet.isNull());
int pieceWidth = 333;
int pieceHeight = 333;
pieceImages["W_K"] = sheet.copy(pieceWidth * 0, 0, pieceWidth, pieceHeight);
pieceImages["W_Q"] = sheet.copy(pieceWidth * 1, 0, pieceWidth, pieceHeight);
pieceImages["W_B"] = sheet.copy(pieceWidth * 2, 0, pieceWidth, pieceHeight);
pieceImages["W_H"] = sheet.copy(pieceWidth * 3, 0, pieceWidth, pieceHeight);
pieceImages["W_C"] = sheet.copy(pieceWidth * 4, 0, pieceWidth, pieceHeight);
pieceImages["W_P"] = sheet.copy(pieceWidth * 5, 0, pieceWidth, pieceHeight);
pieceImages["B_K"] = sheet.copy(pieceWidth * 0, pieceHeight, pieceWidth, pieceHeight);
pieceImages["B_Q"] = sheet.copy(pieceWidth * 1, pieceHeight, pieceWidth, pieceHeight);
pieceImages["B_B"] = sheet.copy(pieceWidth * 2, pieceHeight, pieceWidth, pieceHeight);
pieceImages["B_H"] = sheet.copy(pieceWidth * 3, pieceHeight, pieceWidth, pieceHeight);
pieceImages["B_C"] = sheet.copy(pieceWidth * 4, pieceHeight, pieceWidth, pieceHeight);
pieceImages["B_P"] = sheet.copy(pieceWidth * 5, pieceHeight, pieceWidth, pieceHeight);
restart();
}
void ChessBoardWidget::restart()
{
gameEnd = false;
selectedPiece = nullptr;
board.restart();
QMessageBox choseType(this);
choseType.setText("Select game type");
QPushButton* PvP = choseType.addButton(tr("PvP"), QMessageBox::NoRole);
QPushButton* PvE = choseType.addButton(tr("PvE"), QMessageBox::NoRole);
QPushButton* EvE = choseType.addButton(tr("EvE"), QMessageBox::NoRole);
gameType = choseType.exec();
if (gameType == 1)
{
QMessageBox whoFirst(this);
whoFirst.setText("Choose who goes first");
QPushButton* me = whoFirst.addButton(tr("Me"), QMessageBox::NoRole);
QPushButton* bot = whoFirst.addButton(tr("Bot"), QMessageBox::NoRole);
QPushButton* rng = whoFirst.addButton(tr("HOLY RANDOM!!!"), QMessageBox::NoRole);
int reply = whoFirst.exec();
if (reply == 0)
{
botColor = false;
}
else if (reply == 1)
{
botColor = true;
}
else
{
srand(time(0));
botColor = rand() % 2;
}
}
whatPlayerTurn = true;
lastTurn = 0;
gameEnd = true;
}
pair<pair<int, int>, pair<int, int> > ChessBoardWidget::getBotTurn()
{
vector <pair<pair<int, int>, pair<int, int> > > allMoves;
vector <pair<pair<int, int>, pair<int, int> > > eatPeaceMoves;
vector <Figures*> peaceInDanger;
for (auto i : board.getFigures(whatPlayerTurn))
{
for (int x = 0; x < 8; ++x)
for (int y = 0; y < 8; ++y)
if (i->checkMove(x, y) && !i->willBeOnCheck(x, y))
allMoves.push_back(make_pair(make_pair(
i->getPos().first, i->getPos().second), make_pair(x, y)
));
if (i->isInDanger())
peaceInDanger.push_back(i);
}
for (auto i : allMoves)
{
if (board[i.first.first][i.first.second]->willBeCheckmate(i.second.first, i.second.second))
return i;
if (board[i.second.first][i.second.second] != nullptr)
eatPeaceMoves.push_back(i);
else if (board[i.first.first][i.first.second]->getName() == "W_P" &&
board[i.first.first][i.first.second]->getPos().second == 4
||
board[i.first.first][i.first.second]->getName() == "B_P" &&
board[i.first.first][i.first.second]->getPos().second == 3)
{
Figures* peace = board[i.first.first][i.first.second];
if (peace->getColor() &&
board[i.second.first][4] != nullptr &&
board[i.second.first][4]->getName() == "B_P" &&
board[i.second.first][4]->getMovesCounter() == 1)
eatPeaceMoves.push_back(i);
if (!peace->getColor() &&
board[i.second.first][3] != nullptr &&
board[i.second.first][3]->getName() == "W_P" &&
board[i.second.first][3]->getMovesCounter() == 1)
eatPeaceMoves.push_back(i);
}
}
pair<pair<int, int>, pair<int, int> > bestMove;
int maxValue = -100;
for (auto i : eatPeaceMoves)
{
if (board[i.first.first][i.first.second]->getName() == "W_P" &&
board[i.first.first][i.first.second]->getPos().second == 4
||
board[i.first.first][i.first.second]->getName() == "B_P" &&
board[i.first.first][i.first.second]->getPos().second == 3)
{
Figures* peace = board[i.first.first][i.first.second];
if ((peace->getColor() &&
board[i.second.first][4] != nullptr &&
board[i.second.first][4]->getName() == "B_P" &&
board[i.second.first][4]->getMovesCounter() == 1)
||
(!peace->getColor() &&
board[i.second.first][3] != nullptr &&
board[i.second.first][3]->getName() == "W_P" &&
board[i.second.first][3]->getMovesCounter() == 1))
if (board[i.first.first][i.first.second]->isInDanger(i.second.first, i.second.second))
{
if (maxValue < 0)
{
maxValue = 0;
bestMove = i;
}
}
else if (board[i.first.first][i.first.second]->getPriority() > maxValue)
{
maxValue = board[i.first.first][i.first.second]->getPriority();
bestMove = i;
}
}
else
if (board[i.first.first][i.first.second]->isInDanger(i.second.first, i.second.second))
{
if (board[i.second.first][i.second.second]->getPriority() - board[i.first.first][i.first.second]->getPriority() > maxValue)
{
maxValue = board[i.second.first][i.second.second]->getPriority() - board[i.first.first][i.first.second]->getPriority();
bestMove = i;
}
}
else if (board[i.second.first][i.second.second]->getPriority() > maxValue)
{
maxValue = board[i.second.first][i.second.second]->getPriority();
bestMove = i;
}
}
if (maxValue != -100)
return bestMove;
Figures* king;
if (whatPlayerTurn)
king = board.getWhiteKing();
else
king = board.getBlackKing();
if (king->isInDanger())
{
srand(time(0));
return allMoves[rand() % allMoves.size()];
}
maxValue = 100;
for (auto i : allMoves)
{
if (board[i.first.first][i.first.second]->isInDanger(i.second.first, i.second.second))
{
if (board[i.first.first][i.first.second]->getPriority() < maxValue)
{
maxValue = board[i.first.first][i.first.second]->getPriority();
bestMove = i;
}
}
else
{
maxValue = 0;
bestMove = i;
}
}
vector <pair<pair<int, int>, pair<int, int> > > useless;
for (auto i : allMoves)
{
if (maxValue == 0)
{
if (!board[i.first.first][i.first.second]->isInDanger(i.second.first, i.second.second))
useless.push_back(i);
}
else if (board[i.first.first][i.first.second]->getPriority() == maxValue)
{
useless.push_back(i);
}
}
float bestPos = -6.0;
vector <pair<pair<int, int>, pair<int, int> > > random;
for (auto i : useless)
{
if (board[i.first.first][i.first.second]->getPosPriority(i.second.first, i.second.second) > bestPos)
{
bestPos = board[i.first.first][i.first.second]->getPosPriority(i.second.first, i.second.second);
}
}
while (random.size() == 0)
{
for (auto i : useless)
{
srand(time(0));
float noize = (float)((rand() % 6000) + 9000) / 1000;
if (board[i.first.first][i.first.second]->getPosPriority(i.second.first, i.second.second) * noize >= bestPos)
{
random.push_back(i);
}
}
}
srand(time(0));
return random[rand() % random.size()];
}
void ChessBoardWidget::paintEvent(QPaintEvent*)
{
if(gameEnd)
if ((lastTurn != board.getTurn() && (whatPlayerTurn && !board.getWhiteKing()->havePossibleMoves() || !whatPlayerTurn && !board.getBlackKing()->havePossibleMoves())))
{
gameEnd = false;
if (whatPlayerTurn && board.getWhiteKing()->isInDanger())
QMessageBox::about(this, "End", "Black win!!!");
else if (!whatPlayerTurn && board.getBlackKing()->isInDanger())
QMessageBox::about(this, "End", "White win!!!");
else
QMessageBox::about(this, "End", "Draw!!!");
restart();
}
else
{
lastTurn = board.getTurn();
}
if (gameEnd && board.getFigures().size() == 2)
{
gameEnd = false;
QMessageBox::about(this, "End", "Draw!!!");
}
QPainter painter(this);
currentSize = width() < (height() - 30) ? width() : (height() - 30);
currentTileSize = currentSize / 8;
horisontalOffsets = (width() - currentSize) / 2;
verticalOffsets = (height() - 30 - currentSize) / 2 + 30;
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
if ((x + y) % 2 == 1)
painter.setBrush(brushBlack);
else
painter.setBrush(brushWhite);
//painter.setBrush((x + y) % 2 == 1 ? brushBlack : brushWhite);
int _X = x * currentTileSize + horisontalOffsets;
int _Y = y * currentTileSize + verticalOffsets;
//painter.drawRect(x * currentTileSize + horisontalOffsets, y * currentTileSize + verticalOffsets, currentTileSize, currentTileSize);
painter.drawRect(_X, _Y, currentTileSize, currentTileSize);
if (board[x][y] == board.getBlackKing() && board.getBlackKing()->isInDanger())
{
painter.setBrush(brushRed);
painter.drawRect(board.getBlackKing()->getPos().first * currentTileSize + horisontalOffsets, (7 - board.getBlackKing()->getPos().second) * currentTileSize + verticalOffsets, currentTileSize, currentTileSize);
}
if (board[x][y] == board.getWhiteKing() && board.getWhiteKing()->isInDanger())
{
painter.setBrush(brushRed);
painter.drawRect(board.getWhiteKing()->getPos().first * currentTileSize + horisontalOffsets, (7 - board.getWhiteKing()->getPos().second) * currentTileSize + verticalOffsets, currentTileSize, currentTileSize);
}
if (board[x][7 - y] != nullptr && board[x][7 - y] != selectedPiece)
{
painter.drawImage(QRect(x * currentTileSize + horisontalOffsets, y * currentTileSize + verticalOffsets, currentTileSize, currentTileSize), pieceImages[board[x][7 - y]->getName()]);
}
}
}
if (selectedPiece != nullptr)
{
painter.setBrush(brushHighlight);
for (auto i : selectedPiece->getPosibleMoves())
if (!selectedPiece->willBeOnCheck(i.first, i.second))
painter.drawRect(i.first * currentTileSize + horisontalOffsets, (7 - i.second) * currentTileSize + verticalOffsets, currentTileSize, currentTileSize);
painter.setOpacity(0.2);
painter.drawImage(QRect(selectedPiece->getPos().first * currentTileSize + horisontalOffsets, (7 - selectedPiece->getPos().second) * currentTileSize + verticalOffsets, currentTileSize, currentTileSize), pieceImages[selectedPiece->getName()]);
painter.setOpacity(1);
}
painter.drawText(width() / 2, 15, "Turn number: " + QString::number(board.getTurn()));
if (gameEnd && gameType == 1 && botColor == whatPlayerTurn)
{
auto i = getBotTurn();
board[i.first.first][i.first.second]->move(i.second.first, i.second.second);
whatPlayerTurn = !whatPlayerTurn;
update();
}
}
void ChessBoardWidget::mousePressEvent(QMouseEvent* _e)
{
if (_e->button() == Qt::LeftButton)
{
if (gameType != 2)
{
int x = (_e->x() - horisontalOffsets) / currentTileSize;
int y = (_e->y() - verticalOffsets) / currentTileSize;
if (selectedPiece == nullptr)
{
if (board[x][7 - y] != nullptr
&& board[x][7 - y]->getColor() == whatPlayerTurn
&& board[x][7 - y]->havePossibleMoves())
selectedPiece = board[x][7 - y];
}
else
{
if (selectedPiece->move(x, 7 - y))
{
whatPlayerTurn = !whatPlayerTurn;
}
selectedPiece = nullptr;
}
update();
}
else
{
auto i = getBotTurn();
board[i.first.first][i.first.second]->move(i.second.first, i.second.second);
whatPlayerTurn = !whatPlayerTurn;
update();
}
}
}
|
/*
* File: inversedynamics.cpp
* Author: azamat
*
* Created on December 21, 2011, 11:46 AM
*/
//#define VERBOSE_CHECK //switches on console output in kdl related methods
//#define VERBOSE_CHECK_MAIN // switches on console output in main
#include <kdl_extensions/functionalcomputation_kdl.hpp>
using namespace std;
using namespace KDL;
void createMyTree(KDL::Tree& twoBranchTree)
{
Joint joint1 = Joint("j1", Joint::RotZ, 1, 0, 0.01);
Joint joint2 = Joint("j2", Joint::RotZ, 1, 0, 0.01);
Joint joint3 = Joint("j3", Joint::RotZ, 1, 0, 0.01);
Joint joint4 = Joint("j4", Joint::RotZ, 1, 0, 0.01);
Joint joint5 = Joint("j5", Joint::RotZ, 1, 0, 0.01);
Joint joint6 = Joint("j6", Joint::RotZ, 1, 0, 0.01);
Joint joint7 = Joint("j7", Joint::RotZ, 1, 0, 0.01);
Joint joint8 = Joint("j8", Joint::RotZ, 1, 0, 0.01);
Joint joint9 = Joint("j9", Joint::RotZ, 1, 0, 0.01);
Joint joint10 = Joint("j10", Joint::RotZ, 1, 0, 0.01);
Frame frame1(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
Frame frame2(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
Frame frame3(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
Frame frame4(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
Frame frame5(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
Frame frame6(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
Frame frame7(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
Frame frame8(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
Frame frame9(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
Frame frame10(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
//Segment (const Joint &joint=Joint(Joint::None), const Frame &f_tip=Frame::Identity(), const RigidBodyInertia &I=RigidBodyInertia::Zero())
Segment segment1 = Segment("L1", joint1, frame1);
Segment segment2 = Segment("L2", joint2, frame2);
Segment segment3 = Segment("L3", joint3, frame3);
Segment segment4 = Segment("L4", joint4, frame4);
Segment segment5 = Segment("L5", joint5, frame5);
Segment segment6 = Segment("L6", joint6, frame6);
Segment segment7 = Segment("L7", joint7, frame7);
Segment segment8 = Segment("L8", joint8, frame8);
Segment segment9 = Segment("L9", joint9, frame9);
Segment segment10 = Segment("M0", joint10, frame10);
// RotationalInertia (double Ixx=0, double Iyy=0, double Izz=0, double Ixy=0, double Ixz=0, double Iyz=0)
RotationalInertia rotInerSeg1(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); //around symmetry axis of rotation
double pointMass = 0.25; //in kg
//RigidBodyInertia (double m=0, const Vector &oc=Vector::Zero(), const RotationalInertia &Ic=RotationalInertia::Zero())
RigidBodyInertia inerSegment1(pointMass, Vector(0.0, -0.4, 0.0), rotInerSeg1);
RigidBodyInertia inerSegment2(pointMass, Vector(0.0, -0.4, 0.0), rotInerSeg1);
RigidBodyInertia inerSegment3(pointMass, Vector(0.0, -0.4, 0.0), rotInerSeg1);
RigidBodyInertia inerSegment4(pointMass, Vector(0.0, -0.4, 0.0), rotInerSeg1);
RigidBodyInertia inerSegment5(pointMass, Vector(0.0, -0.4, 0.0), rotInerSeg1);
RigidBodyInertia inerSegment6(pointMass, Vector(0.0, -0.4, 0.0), rotInerSeg1);
RigidBodyInertia inerSegment7(pointMass, Vector(0.0, -0.4, 0.0), rotInerSeg1);
RigidBodyInertia inerSegment8(pointMass, Vector(0.0, -0.4, 0.0), rotInerSeg1);
RigidBodyInertia inerSegment9(pointMass, Vector(0.0, -0.4, 0.0), rotInerSeg1);
RigidBodyInertia inerSegment10(pointMass, Vector(0.0, -0.4, 0.0), rotInerSeg1);
segment1.setInertia(inerSegment1);
segment2.setInertia(inerSegment2);
segment3.setInertia(inerSegment3);
segment4.setInertia(inerSegment4);
segment5.setInertia(inerSegment5);
segment6.setInertia(inerSegment6);
segment7.setInertia(inerSegment7);
segment8.setInertia(inerSegment8);
segment9.setInertia(inerSegment9);
segment10.setInertia(inerSegment10);
//Tree twoBranchTree("L0");
twoBranchTree.addSegment(segment1, "L0");
twoBranchTree.addSegment(segment2, "L1");
twoBranchTree.addSegment(segment3, "L2");
twoBranchTree.addSegment(segment4, "L3");
twoBranchTree.addSegment(segment10, "L4");
// twoBranchTree.addSegment(segment5, "L2"); //branches connect at joint 3 and j5 is co-located with j3
// twoBranchTree.addSegment(segment6, "L5");
// twoBranchTree.addSegment(segment7, "L6");
// twoBranchTree.addSegment(segment8, "L7");
// twoBranchTree.addSegment(segment9, "L8");
}
int main(int argc, char** argv)
{
std::cout << "Computing inverse dynamics for a tree" << std::endl;
Tree twoBranchTree("L0");
createMyTree(twoBranchTree);
//arm root acceleration
Vector linearAcc(0.0, 0.0, -9.8); //gravitational acceleration along Z
Vector angularAcc(0.0, 0.0, 0.0);
Twist rootAcc(linearAcc, angularAcc);
std::vector<kdle::JointState> jstate, jstateOut;
jstate.resize(twoBranchTree.getNrOfSegments() + 1);
jstateOut.resize(twoBranchTree.getNrOfSegments() + 1);
jstate[0].q = PI / 3.0;
jstate[0].qdot = 0.2;
jstate[1].q = -PI / 3.0;
jstate[1].qdot = 0.4;
jstate[2].q = PI / 4.0;
jstate[2].qdot = -0.2;
std::vector<kdle::SegmentState> lstate;
lstate.resize(twoBranchTree.getNrOfSegments() + 1);
printf("Number of Joints %d\n", twoBranchTree.getNrOfJoints());
printf("Number of Segments %d\n", twoBranchTree.getNrOfSegments());
std::vector<kdle::SegmentState> lstate2;
lstate2.resize(twoBranchTree.getNrOfSegments() + 1);
lstate[0].Xdotdot = rootAcc; //gravitational acceleration along Z
//================================Definition of an algorithm=========================//
printf("Templated inverse dynamics for Tree \n");
kdle::transform<kdle::kdl_tree_iterator, kdle::pose> _comp1;
kdle::transform<kdle::kdl_tree_iterator, kdle::twist> _comp2;
kdle::transform<kdle::kdl_tree_iterator, kdle::accTwist> _comp3;
kdle::balance<kdle::kdl_tree_iterator, kdle::force> _comp4;
kdle::project<kdle::kdl_tree_iterator, kdle::wrench> _comp5;
//typedef Composite<kdle::func_ptr(myTestComputation), kdle::func_ptr(myTestComputation) > compositeType0;
typedef kdle::Composite< kdle::transform<kdle::kdl_tree_iterator, kdle::twist>, kdle::transform<kdle::kdl_tree_iterator, kdle::pose> > compositeType1;
typedef kdle::Composite< kdle::balance<kdle::kdl_tree_iterator, kdle::force>, kdle::transform<kdle::kdl_tree_iterator, kdle::accTwist> > compositeType2;
typedef kdle::Composite<compositeType2, compositeType1> compositeType3;
compositeType1 composite1 = kdle::compose(_comp2, _comp1);
compositeType3 composite2 = kdle::compose(kdle::compose(_comp4, _comp3), kdle::compose(_comp2, _comp1));
//kdle::DFSPolicy<KDL::Tree> mypolicy;
kdle::DFSPolicy<KDL::Tree, kdle::inward> mypolicy1;
kdle::DFSPolicy<KDL::Tree, kdle::outward> mypolicy2;
std::cout << std::endl << std::endl << "FORWARD TRAVERSAL" << std::endl << std::endl;
kdle::traverseGraph(twoBranchTree, composite2, mypolicy2)(jstate, lstate, lstate2); // 3 argument walk takes opers with 4 args
#ifdef VERBOSE_CHECK_MAIN
std::cout << std::endl << std::endl << "LSTATE1" << std::endl << std::endl;
for (unsigned int i = 0; i < twoBranchTree.getNrOfSegments(); i++)
{
std::cout << lstate[i].segmentName << std::endl;
std::cout << std::endl << lstate[i].X << std::endl;
std::cout << lstate[i].Xdot << std::endl;
std::cout << lstate[i].Xdotdot << std::endl;
std::cout << lstate[i].F << std::endl;
std::cout << lstate[i].Fext << std::endl;
}
std::cout << std::endl << std::endl << "LSTATE2" << std::endl << std::endl;
for (unsigned int i = 0; i < twoBranchTree.getNrOfSegments(); i++)
{
std::cout << lstate2[i].segmentName << std::endl;
std::cout << std::endl << lstate2[i].X << std::endl;
std::cout << lstate2[i].Xdot << std::endl;
std::cout << lstate2[i].Xdotdot << std::endl;
std::cout << lstate2[i].F << std::endl;
std::cout << lstate[i].Fext << std::endl;
}
#endif
std::vector<kdle::SegmentState> lstate3;
lstate3.resize(twoBranchTree.getNrOfSegments() + 1);
std::cout << std::endl << std::endl << "REVERSE TRAVERSAL" << std::endl << std::endl;
kdle::traverseGraph(twoBranchTree, _comp5, mypolicy1)(jstate, jstateOut, lstate2, lstate3);
//================================end of the definition===========================//
#ifdef VERBOSE_CHECK_MAIN
std::cout << std::endl << std::endl << "LSTATE3" << std::endl << std::endl;
for (KDL::SegmentMap::const_reverse_iterator iter = twoBranchTree.getSegments().rbegin(); iter != twoBranchTree.getSegments().rend(); ++iter)
{
std::cout << std::endl << iter->first << std::endl;
std::cout << lstate3[iter->second.q_nr].X << std::endl;
std::cout << lstate3[iter->second.q_nr].Xdot << std::endl;
std::cout << lstate3[iter->second.q_nr].Xdotdot << std::endl;
std::cout << lstate3[iter->second.q_nr].F << std::endl;
std::cout << lstate3[iter->second.q_nr].Fext << std::endl;
std::cout << "Joint index and torque " << iter->second.q_nr << " " << jstateOut[iter->second.q_nr].torque << std::endl;
}
#endif
return 0;
}
|
#ifndef HW_TECHNIQUE_H
#define HW_TECHNIQUE_H
#include<string>
#include "Pass.h"
namespace HW
{
class Technique
{
public:
string mName;
std::vector<Pass *> mPasses;
void addPass(Pass * pass)
{
mPasses.push_back(pass);
}
Pass * getPass(unsigned int id)
{
if(id >= mPasses.size())
return NULL;
return mPasses[id];
}
unsigned int numPass() const
{
return mPasses.size();
}
~Technique()
{
for(unsigned int i = 0 ; i < mPasses.size();i++)
{
delete mPasses[i];
}
mPasses.clear();
}
};
}
#endif
|
//Using MST. Time-0.190s
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define vll vector<ll>
class UnionFind {
private:
vll p, rank, setSize;
ll numSets;
public:
UnionFind(ll N) {
setSize.assign(N, 1); numSets = N; rank.assign(N, 0);
p.assign(N, 0); for (ll i = 0; i < N; i++) p[i] = i; }
ll findSet(ll i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); }
bool isSameSet(ll i, ll j) { return findSet(i) == findSet(j); }
void unionSet(ll i, ll j) {
if (!isSameSet(i, j)) { numSets--;
ll x = findSet(i), y = findSet(j);
// rank is used to keep the tree short
if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; }
else { p[x] = y; setSize[y] += setSize[x];
if (rank[x] == rank[y]) rank[y]++; } } }
ll numDisjointSets() { return numSets; }
ll sizeOfSet(ll i) { return setSize[findSet(i)]; }
};
int main()
{
long double t,n,r,a,b,states;
cin>>t;
for(int i=0;i<t;i++)
{
cout<<"Case #"<<i+1<<": ";
cin>>n>>r;
vector<pair<long double, pair<ll,ll> > > EdgeList;
vector<pair<ll,ll> > c;
for(int i=0;i<n;i++)
{
cin>>a>>b;
c.push_back(make_pair(a,b));
}
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
long double dist=sqrt( pow(c[i].first-c[j].first,2) + pow(c[i].second-c[j].second,2) );
EdgeList.push_back(make_pair(dist,make_pair(i,j)));
}
}
sort(EdgeList.begin(), EdgeList.end()); // sort by edge weight O(E log E)
long double scost = 0,bcost=0;
states=1;
UnionFind UF(n); // all V are disjoint sets initially
for (int i = 0; i < EdgeList.size() ; i++) { // for each edge, O(E)
pair<long double, pair<ll,ll> > front = EdgeList[i];
if (!UF.isSameSet(front.second.first, front.second.second)) { // check
if(front.first<=r) scost+=front.first;
else {bcost+=front.first; states++;}
UF.unionSet(front.second.first, front.second.second); // link them
} }
cout<<states<<" "<<(ll)(scost+0.5)<<" "<<(ll)(bcost+0.5)<<"\n";
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright 2010 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
/** @file security_docman.cpp
* Cross-module security manager: docman model.
*
* See document/xxx.txt
*/
#ifndef SECURITY_DOCMAN_H
#define SECURITY_DOCMAN_H
class OpSecurityCheckCallback;
class OpSecurityContext;
class OpSecurityState;
class OpSecurityContext_Docman
{
public:
OpSecurityContext_Docman() : document_manager(NULL) {}
BOOL IsTopDocument() const;
DocumentManager *GetDocumentManager() const { return document_manager; };
protected:
DocumentManager* document_manager;
};
class OpSecurityManager_Docman
{
protected:
OP_STATUS CheckDocManUrlLoadingSecurity(const OpSecurityContext& source, const OpSecurityContext& target, OpSecurityCheckCallback* callback);
};
#endif // SECURITY_DOCMAN_H
|
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int* m[2];
m[0] = new int[n + 1]; // minimal costs for 1...n
m[1] = new int[n + 1]; // operations
m[0][1] = 0;
// Minimal cost search
for (int i = 2; i <= n; i++)
{
// Adding 1
m[0][i] = m[0][i - 1] + i; // count current cost
m[1][i] = 1; // put an operation
// Division by 2
if (i % 2 == 0 && m[0][i / 2] + i < m[0][i])
{
m[0][i] = m[0][i / 2] + i; // changing current cost if nessesary
m[1][i] = 2; // put an operation
}
// Division by 3
if (i % 3 == 0 && m[0][i / 3] + i < m[0][i])
{
m[0][i] = m[0][i / 3] + i; // changing current cost if nessesary
m[1][i] = 3; // put an operation
}
}
cout << m[0][n] << endl; // print the lowest cost
// Searching for a transformation
for (int j = n; j > 1;)
{
if (m[1][j] == 1)
{
cout << "-1";
j--;
}
else if (m[1][j] == 2)
{
cout << "/2";
j /= 2;
}
else if (m[1][j] == 3)
{
cout << "/3";
j /= 3;
}
if (j > 1) cout << " "; // divide by space characters
}
cout << endl;
return 0;
}
|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "mpi.h"
#include <string>
static void showArrReverse(uint32_t* arr, uint32_t N) {
for (int i = 0; i < N; i++) {
std::cout << " " << arr[N-i-1];
}
printf("\n");
}
int main(int argc, char* argv[])
{
//#proc num N:: N = C / 2 + 1, where C - nums size (count)
//such as^
// Nums | procs
// 2 | 2
// 4 | 3
// 8 | 5
// 16 | 9
MPI_Init(&argc, &argv);
MPI_Datatype LongInt;
uint32_t LongIntSize = 10;
MPI_Type_contiguous(LongIntSize, MPI_UINT32_T, &LongInt);
MPI_Type_commit(&LongInt);
int ProcNum, ProcRank;
MPI_Status Status;
MPI_Comm_size(MPI_COMM_WORLD, &ProcNum);
MPI_Comm_rank(MPI_COMM_WORLD, &ProcRank);
uint32_t** Nums;
uint32_t NumsSize;
NumsSize = 16;
if (ProcRank == 0) {
//Nums = new uint32_t[NumsSize] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 1, 1, 1, 1, 1 };
Nums = new uint32_t * [NumsSize]
{
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
new uint32_t[LongIntSize]{ 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
}
else {
Nums = new uint32_t*[1]{new uint32_t[0]};
}
uint32_t Step;
uint32_t MaxStep;
uint32_t MaxNums;
Step = 1;
MaxNums = ProcNum - 1;
MaxStep = log2(2 * MaxNums);
uint32_t* num1 = new uint32_t[LongIntSize];
uint32_t* num2 = new uint32_t[LongIntSize];
while (Step <= MaxStep) {
/*if (ProcRank == 0) {
showArr(Nums[0], LongIntSize);
}*/
if (ProcRank == 0) {
for (int i = 0; i < MaxNums / Step; i++) {
uint32_t* sendNum = Nums[2*i];
MPI_Send(sendNum, 1, LongInt, i+1, 1, MPI_COMM_WORLD);
sendNum = Nums[2 * i + 1];
MPI_Send(sendNum, 1, LongInt, i+1, 2, MPI_COMM_WORLD);
}
}
if (ProcRank < MaxNums / Step + 1 && ProcRank != 0)
{
MPI_Recv(num1, 1, LongInt, 0, 1, MPI_COMM_WORLD, &Status);
MPI_Recv(num2, 1, LongInt, 0, 2, MPI_COMM_WORLD, &Status);
//---multiplying---start---
uint32_t* multiply = new uint32_t[LongIntSize] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < LongIntSize; i++) {
for (int j = 0; j < LongIntSize; j++) {
uint64_t mltpl = (uint64_t)num1[i] * (uint64_t)num2[j];
uint32_t n1 = (uint32_t) mltpl;
uint32_t n2 = (uint32_t)(mltpl >> 32);
if (i + j < LongIntSize) {
multiply[i + j] += n1;
}
if (i + j + 1 < LongIntSize) {
multiply[i + j + 1] += n2;
}
}
}
//---multiplying---end---
MPI_Send(multiply, 1, LongInt, 0, 3, MPI_COMM_WORLD);
}
if (ProcRank == 0) {
for (int i = 0; i < MaxNums / Step; i++) {
uint32_t* recvNum = new uint32_t[LongIntSize];
MPI_Recv(recvNum, 1, LongInt, i+1, 3, MPI_COMM_WORLD, &Status);
Nums[i] = recvNum;
}
}
Step++;
}
if (ProcRank == 0) {
showArrReverse(Nums[0], LongIntSize);
}
MPI_Finalize();
return 0;
}
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef XPUNIONEXPR_H
#define XPUNIONEXPR_H
#include "modules/xpath/src/xpexpr.h"
class XPath_UnionExpression
: public XPath_Expression
{
private:
XPath_UnionExpression (XPath_Parser *parser)
: XPath_Expression (parser)
{
}
OpVector<XPath_Producer> *producers;
public:
static XPath_Expression *MakeL (XPath_Parser *parser, XPath_Expression *lhs, XPath_Expression *rhs);
virtual ~XPath_UnionExpression ();
virtual unsigned GetResultType ();
virtual unsigned GetExpressionFlags ();
virtual XPath_Producer *GetProducerInternalL (XPath_Parser *parser);
};
class XPath_UnionProducer
: public XPath_Producer
{
protected:
OpVector<XPath_Producer> *producers;
unsigned producer_index_index, localci_index;
public:
XPath_UnionProducer (XPath_Parser *parser, OpVector<XPath_Producer> *producers);
virtual ~XPath_UnionProducer ();
virtual unsigned GetProducerFlags ();
virtual BOOL Reset (XPath_Context *context, BOOL local_context_only);
virtual XPath_Node *GetNextNodeL (XPath_Context *context);
};
#endif // XPUNIONEXPR_H
|
#include "ItemSlot.h"
#include "Single/GameInstance/RPGGameInst.h"
#include "Components/Image.h"
UItemSlot::UItemSlot(const FObjectInitializer& objectInitializer) :
Super(objectInitializer)
{
static ConstructorHelpers::FObjectFinder<UDataTable> DT_ITEM_INFO(
TEXT("DataTable'/Game/Resources/DataTables/DT_ItemInfo.DT_ItemInfo'"));
if (DT_ITEM_INFO.Succeeded()) DT_ItemInfo = DT_ITEM_INFO.Object;
}
void UItemSlot::InitializeSlot(ESlotType slotType, FName inCode)
{
Super::InitializeSlot(slotType, inCode);
// 아이템 정보 설정
SetItemInfo(inCode);
// 아이템 이미지 갱신
UpdateItemImage();
}
void UItemSlot::UpdateItemImage()
{
UTexture2D* itemImage = nullptr;
// 아이템 정보가 비어있다면 투명한 이미지를 사용합니다.
if (ItemInfo.IsEmpty()) itemImage = T_Null;
// 아이템 정보가 비어있지 않을 경우
else
{
// 아이템 이미지 경로가 비어있다면 투명한 이미지 사용
if (ItemInfo.ItemImagePath.IsNull())
itemImage = T_Null;
// 아이템 이미지 경로가 비어있지 않다면 아이템 이미지를 로드하여 사용합니다.
else itemImage = Cast<UTexture2D>(
GetManager(FStreamableManager)->LoadSynchronous(ItemInfo.ItemImagePath));
//FStreamableDelegate onLoadFin;
//onLoadFin.BindLambda([]() {
// GetSlotImage()->SetBrushFromTexture(itemImage);
// });
//GetManager(FStreamableManager)->RequestAsyncLoad(ItemInfo.ItemImagePath, onLoadFin);
}
// 아이템 이미지 적용
GetSlotImage()->SetBrushFromTexture(itemImage);
}
void UItemSlot::SetItemInfo(FName itemCode)
{
// 아이템 코드가 비어있다면
if (itemCode.IsNone())
{
// 아이템 정보를 비웁니다.
ItemInfo = FItemInfo();
return;
}
// 아이템 정보 찾기
FString contextString;
FItemInfo* findedItemInfo = DT_ItemInfo->FindRow<FItemInfo>(itemCode, contextString);
// 아이템 정보를 찾지 못했다면 아이템 정보를 비웁니다.
if (findedItemInfo == nullptr) ItemInfo = FItemInfo();
else ItemInfo = *findedItemInfo;
}
|
#include "gtest/gtest.h"
#include "Source.hpp"
namespace
{
const uint32_t DATA_SIZE(10);
}
class TestSource : public testing::Test
{
public:
TestSource();
virtual ~TestSource();
virtual void SetUp();
virtual void TearDown();
protected:
LibMpegTS::Source source_;
uint8_t* pData_;
};
TestSource::TestSource()
{
pData_ = new uint8_t[DATA_SIZE];
}
TestSource::~TestSource()
{
delete[] pData_;
pData_ = nullptr;
}
void TestSource::SetUp() {}
void TestSource::TearDown() {}
TEST_F(TestSource, test_writeTo_from_empty_Source)
{
// act
const uint32_t sizeWritten = source_.writeTo(pData_, DATA_SIZE);
// assert
EXPECT_EQ(0, sizeWritten);
}
TEST_F(TestSource, test_writeTo_from_Source_having_data_more_than_DATA_SIZE_once)
{
// arrange
const std::string data = "abcdefghijklmnopqrstuvwxyz"; // length = 26
source_.load<LibMpegTS::Source::Source::STRING>(data);
// act
const uint32_t sizeWritten = source_.writeTo(pData_, DATA_SIZE);
// assert
EXPECT_EQ(DATA_SIZE, sizeWritten);
EXPECT_EQ(97/*a*/, pData_[0]);
}
TEST_F(TestSource, test_writeTo_from_Source_having_less_data_than_DATA_SIZE_once)
{
// arrange
const std::string data = "abcde"; // length = 5
source_.load<LibMpegTS::Source::Source::STRING>(data);
// act
const uint32_t sizeWritten = source_.writeTo(pData_, DATA_SIZE);
// assert
EXPECT_EQ(data.size(), sizeWritten);
EXPECT_EQ(97/*a*/, pData_[0]);
}
TEST_F(TestSource, test_writeTo_from_Source_having_data_more_than_double_DATA_SIZE_until_readout)
{
// arrange
const std::string data = "abcdefghijklmnopqrstuvwxyz"; // length = 26
source_.load<LibMpegTS::Source::Source::STRING>(data);
// act
uint32_t sizeWritten = source_.writeTo(pData_, DATA_SIZE);
EXPECT_EQ(DATA_SIZE, sizeWritten);
EXPECT_EQ(97/*a*/, pData_[0]);
sizeWritten = source_.writeTo(pData_, DATA_SIZE);
EXPECT_EQ(DATA_SIZE, sizeWritten);
EXPECT_EQ(107/*a*/, pData_[0]);
sizeWritten = source_.writeTo(pData_, DATA_SIZE);
EXPECT_EQ(data.size() - 2 * DATA_SIZE, sizeWritten);
EXPECT_EQ(117/*a*/, pData_[0]);
}
TEST_F(TestSource, test_reset_read_once)
{
// arrange
const std::string data = "abcdefghijklmnopqrstuvwxyz"; // length = 26
source_.load<LibMpegTS::Source::Source::STRING>(data);
// act
source_.writeTo(pData_, DATA_SIZE);
source_.reset();
const uint32_t sizeWritten = source_.writeTo(pData_, DATA_SIZE);
// assert
EXPECT_EQ(DATA_SIZE, sizeWritten);
EXPECT_EQ(97/*a*/, pData_[0]);
}
TEST_F(TestSource, test_reset_read_twice)
{
// arrange
const std::string data = "abcdefghijklmnopqrstuvwxyz"; // length = 26
source_.load<LibMpegTS::Source::Source::STRING>(data);
// act
source_.writeTo(pData_, DATA_SIZE);
source_.writeTo(pData_, DATA_SIZE);
source_.reset();
const uint32_t sizeWritten = source_.writeTo(pData_, DATA_SIZE);
// assert
EXPECT_EQ(DATA_SIZE, sizeWritten);
EXPECT_EQ(97/*a*/, pData_[0]);
}
TEST_F(TestSource, test_size)
{
// arrange
const std::string data = "abcdefghijklmnopqrstuvwxyz"; // length = 26
// act
source_.load<LibMpegTS::Source::Source::STRING>(data);
// assert
EXPECT_EQ(data.size(), source_.size());
}
|
//
// baza.cpp
// serialowabaza
//
// Created by Julia on 06.11.2018.
// Copyright © 2018 Julia. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <fstream>
#include "baza.h"
#include "film.h"
#include "zakonczony.h"
#include "trwajacy.h"
#include "memory"
#include "event.h"
#include <vector>
void baza::wczytajwszystko(){
try{
std::fstream plik;
char pom;
int licznosc;
plik.open("seriale.txt",std::ios::in);
if (plik.fail()){
blad<std::string> bl;
bl.setmessage("Nie udało się otworzyć pliku.\n");
throw bl;
}
plik>>licznosc;
for (int i=0;i<licznosc;i++){
plik>>pom;
switch (pom) {
case 'F':{
std::shared_ptr<film> ptrf(new(film));
ptrf->load(plik);
PulaStalych.push_back(ptrf);
break;}
case 'E':{
std::shared_ptr<event> ptre(new(event));
ptre->load(plik);
Wydarzenia.push_back(ptre);
break;}
case 'T':{
std::shared_ptr<trwajacy> ptrt(new(trwajacy));
ptrt->load(plik);
PulaStalych.push_back(ptrt);
break;}
case 'Z':{
std::shared_ptr<zakonczony> ptrz (new(zakonczony));
ptrz->load(plik);
PulaStalych.push_back(ptrz);
break;}
default:{
std::cerr<<"Znaleziono niezidntyfikowany typ.\n";
break;}
}
}
}
catch(blad<std::string> bl){
bl.showyourself();
}
catch(...){
std::cerr<<"Problem wystąpił, jednak nie wpłynął on na pracę programu. \n";
}
}
void baza::zapiszwszystko(){
std::fstream plik;
plik.open("seriale.txt",std::ios::out);
plik<<(Wydarzenia.size()+PulaStalych.size())<<"\n";
std::vector<std::shared_ptr<ogladadlo>>::iterator iter;
for (iter=PulaStalych.begin();iter!=PulaStalych.end();++iter)
(*iter)->save(plik);
std::vector<std::shared_ptr<event>>::iterator itek;
for(itek=Wydarzenia.begin();itek!=Wydarzenia.end();++itek)
(*itek)->save(plik);
}
void baza::gatunek(std::string gat){
std::vector<std::shared_ptr<ogladadlo>>::iterator iter;
for (iter=PulaStalych.begin();iter!=PulaStalych.end();++iter)
if ((*iter)->getspiese()==gat)
(*iter)->prezentujsie();
}
void baza::powyzej(double ocena){
std::vector<std::shared_ptr<ogladadlo>>::iterator iter;
for (iter=PulaStalych.begin();iter!=PulaStalych.end();++iter)
if ((*iter)->getnote()>=ocena)
(*iter)->prezentujsie();
}
void baza::wszystkieogladadla(){
std::vector<std::shared_ptr<ogladadlo>>::iterator iter;
for (iter=PulaStalych.begin();iter!=PulaStalych.end();++iter)
(*iter)->prezentujsie();
}
void baza::wszystkieeventy(){
std::cout<<"W bazie znajdują się następujące wydarzenia:\n";
std::vector<std::shared_ptr<event>>::iterator iter;
for (iter=Wydarzenia.begin();iter!=Wydarzenia.end();++iter)
(*iter)->prezentujsie();
}
void baza::statystyki(){
std::cout<<"W bazie jest:\n";
std::cout<<Wydarzenia.size()<<" wydarzeń,\n";
int filmy=0,trwajace=0,zakonczone=0;
std::vector<std::shared_ptr<ogladadlo>>::iterator iter;
for (iter=PulaStalych.begin();iter!=PulaStalych.end();++iter){
if (((*iter)->gettype())=='F')
filmy++;
else {
if (((*iter)->gettype())=='T')
trwajace++;
else zakonczone++;
}
}
std::cout<<filmy<<" filmów,\n"<<(trwajace+zakonczone)<<" seriali, w tym: "<<zakonczone<<" zakończonych i "<<trwajace<<" emitowanych.\n";
}
void baza::dodajwydarzenie(){
std::shared_ptr<event> wskaznik (new (event));
std::string nazwa,typ;
int data[2];
double cena, czas;
std::cout<<"Podaj nazwę oraz rodzaj wydarzenia. Następnie wprowadź datę [dzień i miesiąc],szacowany czas trwania a także cenę biletu normalnego.\n";
std::cin>>nazwa>>typ>>data[0]>>data[1]>>czas>>cena;
wskaznik->setinfo(nazwa, typ, czas, data[0], data[1], cena);
Wydarzenia.push_back(wskaznik);
}
void baza::dodajogladadlo(){
char pom;
std::cout<<"Czy chcesz dodać film, czy serial? [F/S]\n";
std::cin>>pom;
std::string nazwa,gatunek;
double Czas, ocena;
int cyfry;
std::cout<<"Wprowadź nazwę, gatunek, czas trwania oraz ocenę [0-10]\n";
std::cin>>nazwa>>gatunek>>Czas>>ocena;
if (pom=='F'){
std::cout<<"Wprowadź ograniczenie wiekowe [minimalny wiek]\n";
std::cin>>cyfry;
std::shared_ptr<film> wskaznik (new(film));
wskaznik->setinfo(nazwa, gatunek, Czas, cyfry);
wskaznik->setnote(ocena);
PulaStalych.push_back(wskaznik);}
else {
std::cout<<"Czy serial się zakończył? [T/N]\n";
std::cin>>pom;
if (pom=='T'){
std::cout<<"Podaj ilość wyemitowanych odcinków.\n";
std::cin>>cyfry;
std::shared_ptr<zakonczony> wskaznik (new(zakonczony));
wskaznik->setinfo(nazwa, gatunek, Czas);
wskaznik->setepisodes(cyfry);
wskaznik->setnote(ocena);
PulaStalych.push_back(wskaznik);
}
else {
std::cout<<"Ile razy tygodniowo jest emitowany?\n";
std::cin>>cyfry;
int *tab= new int[cyfry];
std::cout<<"Wprowadź dni emisji. [0-poniedziałek]\n";
for (int i=0;i<cyfry;i++)
std::cin>>tab[i];
std::shared_ptr<trwajacy> wskaznik (new(trwajacy));
wskaznik->setinfo(nazwa, gatunek, Czas);
wskaznik->setemission(cyfry, tab);
wskaznik->setnote(ocena);
PulaStalych.push_back(wskaznik);
}
}
}
|
#ifndef PhysVol_SegmentedCrystal_Box_h
#define PhysVol_SegmentedCrystal_Box_h 1
/*! @file PhysVol_SegmentedCrystal_Box.hh
@brief Defines mandatory user class PhysVol_SegmentedCrystal_Box.
@date September, 2015
@author Flechas (D. C. Flechas dcflechasg@unal.edu.co)
@version 2.0
In this header file, the 'physical' setup is defined: materials, geometries and positions.
This class defines the experimental hall used in the toolkit.
*/
#include "globals.hh"
#include "G4VSolid.hh"
#include "G4Box.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4NistManager.hh"
/* units and constants */
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
class G4Material;
/*! @brief This mandatory user class defines the geometry.
It is responsible for
@li Construction of geometry
\sa Construct()
*/
class PhysVol_SegmentedCrystal_Box : public G4PVPlacement
{
public:
//! Constructor
PhysVol_SegmentedCrystal_Box(G4String fname="SegmentedCrystal_Box_phys",
G4RotationMatrix* pRot= new G4RotationMatrix(),
const G4ThreeVector& tlate = G4ThreeVector(),
G4LogicalVolume* pMotherLogical =
new G4LogicalVolume(new G4Box("SCB_sol",
66.48*mm * std::sin(pi/4.),
66.48*mm * std::sin(pi/4.),
0.7*cm),
(G4NistManager::Instance())->FindOrBuildMaterial("G4_AIR"),
"SCB_log",0,0,0),
G4double flen=6.40*cm*std::sin(pi/4.),
G4double fheight=0.7*cm,
G4int fNpixelX=64, G4int fNpixelY=64 ,
G4Material* fMaterial=(G4NistManager::Instance())->FindOrBuildMaterial("G4_CESIUM_IODIDE"));
//! Destructor
~PhysVol_SegmentedCrystal_Box();
public:
inline void SetLength(G4double val) {Length = val;};
inline void SetHeight(G4double val) {Height = val;};
inline void SetXPixels(G4int val) {XPixelNum = val;};
inline void SetYPixels(G4int val) {YPixelNum = val;};
//inline void SetID(G4int pID) {ID = pID;};
inline void SetName(G4String pname) {Name = pname;};
inline G4LogicalVolume* GetSegmentedCrystal_Box(void) {return SegmentedCrystal_Box_LogVol;};
private:
void ConstructPhysVol_SegmentedCrystal_Box(void);
private:
// General solid volume
G4LogicalVolume* SegmentedCrystal_Box_LogVol;
//! Material
G4Material* Material;
//! Name
G4String Name;
// Dimensions
G4double Length;
G4double Height;
G4int XPixelNum;
G4int YPixelNum;
// G4int ID;
};
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#endif
|
/*
* Copyright 2019 LogMeIn
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <mutex>
#include "asyncly/executor/IExecutor.h"
#include "asyncly/scheduler/IScheduler.h"
#include "asyncly/scheduler/detail/BaseScheduler.h"
#include "asyncly/task/Task.h"
namespace asyncly {
namespace test {
class FakeClockScheduler : public IScheduler {
public:
FakeClockScheduler();
bool advanceClockToNextEvent(clock_type::time_point limit);
clock_type::time_point getLastExpiredTime() const;
void clear();
// IScheduler
clock_type::time_point now() const override;
std::shared_ptr<Cancelable> execute_at(
const IExecutorWPtr& executor, const clock_type::time_point& absTime, Task&&) override;
std::shared_ptr<Cancelable> execute_after(
const IExecutorWPtr& executor, const clock_type::duration& relTime, Task&&) override;
private:
BaseScheduler m_baseScheduler;
clock_type::time_point m_mockedNow;
mutable std::mutex m_scheduledMutex;
mutable std::mutex m_elapsedMutex;
};
inline FakeClockScheduler::FakeClockScheduler()
: m_baseScheduler([this]() { return m_mockedNow; })
{
}
inline bool FakeClockScheduler::advanceClockToNextEvent(clock_type::time_point limit)
{
// NOTE: Always take m_elapsedMutex before m_scheduledMutex
std::unique_lock<std::mutex> lockE(m_elapsedMutex);
{
std::unique_lock<std::mutex> lockS(m_scheduledMutex);
auto next = m_baseScheduler.getNextExpiredTime(limit);
m_mockedNow = next;
m_baseScheduler.prepareElapse();
}
m_baseScheduler.elapse();
return (m_mockedNow >= limit);
}
inline clock_type::time_point FakeClockScheduler::getLastExpiredTime() const
{
return m_baseScheduler.getLastExpiredTime();
}
inline void FakeClockScheduler::clear()
{
// NOTE: Always take m_elapsedMutex before m_scheduledMutex
std::unique_lock<std::mutex> lockE(m_elapsedMutex);
std::unique_lock<std::mutex> lock(m_scheduledMutex);
m_baseScheduler.clear();
}
inline asyncly::clock_type::time_point FakeClockScheduler::now() const
{
std::unique_lock<std::mutex> lock(m_scheduledMutex);
return m_mockedNow;
}
inline std::shared_ptr<Cancelable> FakeClockScheduler::execute_at(
const IExecutorWPtr& executor, const clock_type::time_point& absTime, Task&& task)
{
std::unique_lock<std::mutex> lock(m_scheduledMutex);
return m_baseScheduler.execute_at(executor, absTime, std::move(task));
}
inline std::shared_ptr<Cancelable> FakeClockScheduler::execute_after(
const IExecutorWPtr& executor, const clock_type::duration& relTime, Task&& task)
{
std::unique_lock<std::mutex> lock(m_scheduledMutex);
return m_baseScheduler.execute_after(executor, relTime, std::move(task));
}
}
}
|
#include <Wire.h>
#include "font8x16.h"
//#include "fatty7x16.h"
#include <FastLED.h>
#include <colorutils.h>
#include <SPI.h>
#include "RTClib.h"
#include "kandy_commands.h"
RTC_DS3231 rtc;
const bool USE_12_HOUR_FORMAT = true;
const int DS3231_ADDR = 104;
const int DS3231_ALARM1_OFFSET = 0x7;
const int DS3231_ALARM2_OFFSET = 0xB;
const byte N_8x8_ROW = 2;
const byte N_8x8_COL = 7;
const byte N_CLOCK = 2;
const byte N_ROW = N_8x8_ROW * 8;
const byte N_COL = N_8x8_COL * 8;
const byte BUFFER_SIZE = N_ROW * 8;
const unsigned long long SECOND = 1;
const unsigned long long MINUTE = 60 * SECOND;
const unsigned long long HOUR = 60 * MINUTE;
TimeSpan countdown_duration(0);
const uint16_t N_PIXEL_PER_CLOCK = N_ROW * N_COL;
const uint16_t N_PIXEL = N_PIXEL_PER_CLOCK * N_CLOCK;
CRGB leds[N_PIXEL];
const byte digits4x7[4 * 10] = {
62, 65, 65, 62, // 0
0, 66, 127, 64, // 1
98, 81, 73, 70, // 2
34, 73, 73, 54, // 3
30, 16, 16, 127, // 4
39, 69, 69, 57, // 5
62, 73, 73, 50, // 6
97, 17, 9, 7, // 7
54, 73, 73, 54, // 8
38, 73, 73, 62 // 9
};
const byte digits8x16[10 * 16] = {
0x3c,0x7e,0xe7,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xe7,0x7e,0x3c, // 0
0x18,0x1c,0x1e,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x7e,0x7e, // 1
0x3c,0x7e,0xe7,0xc3,0xc0,0xc0,0xe0,0x70,0x38,0x1c,0x0e,0x07,0x03,0x03,0xff,0xff, // 2
0x3c,0x7e,0xe7,0xc3,0xc0,0xc0,0xe0,0x78,0x78,0xe0,0xc0,0xc0,0xc3,0xe7,0x7e,0x3c, // 3
0x60,0x63,0x63,0x63,0x63,0x63,0x63,0xff,0xff,0x60,0x60,0x60,0x60,0x60,0x60,0x60, // 4
0xff,0xff,0x03,0x03,0x03,0x03,0x3f,0x7f,0xe0,0xc0,0xc0,0xc0,0xc3,0xe7,0x7e,0x3c, // 5
0x3c,0x7e,0xe7,0xc3,0x03,0x03,0x03,0x3f,0x7f,0xe3,0xc3,0xc3,0xc3,0xe7,0x7e,0x3c, // 6
0xff,0xff,0xc0,0xc0,0xe0,0x70,0x38,0x1c,0x0e,0x06,0x06,0x06,0x06,0x06,0x06,0x06, // 7
0x3c,0x7e,0xe7,0xc3,0xc3,0xc3,0xe7,0x7e,0x7e,0xe7,0xc3,0xc3,0xc3,0xe7,0x7e,0x3c, // 8
0x3c,0x7e,0xe7,0xc3,0xc3,0xc3,0xc7,0xfe,0xfc,0xc0,0xc0,0xc0,0xc3,0xe7,0x7e,0x3c, // 9
};
const byte digits4x8[10 * 8] = {
0x06,0x09,0x09,0x09,0x09,0x09,0x09,0x06, // 0
0x04,0x06,0x04,0x04,0x04,0x04,0x04,0x0e, // 1
0x06,0x09,0x08,0x08,0x04,0x02,0x01,0x0f, // 2
0x06,0x09,0x08,0x04,0x08,0x08,0x09,0x06, // 3
0x04,0x05,0x05,0x05,0x0f,0x04,0x04,0x04, // 4
0x0f,0x01,0x01,0x07,0x08,0x08,0x09,0x06, // 5
0x06,0x09,0x01,0x01,0x07,0x09,0x09,0x06, // 6
0x0f,0x08,0x08,0x04,0x02,0x01,0x01,0x01, // 7
0x06,0x09,0x09,0x06,0x09,0x09,0x09,0x06, // 8
0x06,0x09,0x09,0x0e,0x08,0x08,0x09,0x06, // 9
};
//uint8_t brightness = 1;
const uint8_t MAX_BRIGHTNESS = 40;
const uint8_t N_MODE = 4;
const uint8_t CLOCK_MODE = 1;
const uint8_t STANDBY_MODE = 2;
const uint8_t RACE_MODE = 3;
const uint8_t WAVE_MODE = 4;
const uint16_t MIN_WAVE_SEP = 30;
DateTime now;
uint32_t stopwatch_start_time = 0;
uint8_t brightness = 1;
uint8_t mode = CLOCK_MODE;
uint8_t n_wave = 1;
uint16_t wave_sep = 60;
bool racing = false;
const struct CRGB & Wheel(byte WheelPos) {
WheelPos = 255 - WheelPos;
if(WheelPos < 85) {
return CRGB(255 - WheelPos * 3, 0, WheelPos * 3);
}
if(WheelPos < 170) {
WheelPos -= 85;
return CRGB(0, WheelPos * 3, 255 - WheelPos * 3);
}
WheelPos -= 170;
return CRGB(WheelPos * 3, 255 - WheelPos * 3, 0);
}
int32_t snake(byte row, byte col){
// 1. find the board
uint32_t out = 0;
uint8_t board;
if (row / 8 % 2 == 0){
board = col / 8; // # assume 2 rows of boards
if(col % 2 == 0){
out = 7 - row + col * 8;
}
else{
out = col * 8 + row;
}
}
else{
board = 7 - (col - 8 * N_8x8_COL) / 8 - 1; //# assume 2 rows of boards
//col = 47 - col;
col = N_8x8_COL * 8 - 1 - col;
row -= 8;
if(col % 2 == 0){
out = 64 * N_8x8_COL + row + col * 8;
}
else{
out = 64 * N_8x8_COL + (7 - row) + col * 8;
}
}
if(out > N_PIXEL){
out = -1;
}
/*
Serial.print(row);
Serial.print(" ");
Serial.print(col);
Serial.print(" ");
Serial.print(board);
Serial.print(" ");
Serial.println(out);
*/
return out;
}
void setPixel(byte row, byte col, const struct CRGB & color){
if(false){// flip display?
row = 8 * N_8x8_ROW - 1 - row;
col = 8 * N_8x8_COL - 1 - col;
}
uint16_t pos = snake(row, col);
if(0 <= pos && pos < N_PIXEL_PER_CLOCK){
leds[pos] = color; // get front side
if(N_CLOCK > 1 && (pos + N_PIXEL_PER_CLOCK < N_PIXEL)){
leds[pos + N_PIXEL_PER_CLOCK] = color; // get flip side
}
}
}
void draw_colen(uint8_t col, const struct CRGB & color){
setPixel( 4, col, color);
setPixel( 5, col, color);
setPixel(10, col, color);
setPixel(11, col, color);
}
void draw_colens(const struct CRGB & color){
draw_colen(17, color);
draw_colen(17 + 20, color);
}
void draw_dash(int16_t col, const struct CRGB & color){
for(int16_t c = col; c < col + 8; c++){
setPixel(7, c, color);
setPixel(8, c, color);
}
}
void draw_dashes(const struct CRGB & color){
draw_dash(-1, color);
draw_dash(8, color);
draw_dash(19, color);
draw_dash(28, color);
draw_dash(39, color);
draw_dash(48, color);
}
const struct CRGB & getPixel(int16_t row, int16_t col){
uint32_t out = 0;
int32_t pos;
if(col < N_COL){
pos = snake(row, col);
if(0 <= pos && pos < N_PIXEL){
out = leds[pos];
}
}
return out;
}
void displayChar(uint16_t row, uint16_t col, byte ascii, const struct CRGB & color){
byte *data = font8x16 + ascii * FONT8x16_N_ROW;
for(uint8_t r=0; r<FONT8x16_N_ROW; r++){
for(uint8_t c=0; c<FONT8x16_N_COL; c++){
if((data[r] >> (FONT8x16_N_COL - 1 - c)) & 1){
setPixel(row + r, col + c, color);
}
else{
setPixel(row + r, col + c, CRGB::Black);
}
}
}
}
void shiftLeft(uint32_t *col){
for(uint16_t col=0; col < N_COL - 1; col++){
for(uint16_t row=0; row < N_ROW; row++){
setPixel(row, col, getPixel(row, col+1));
}
}
for(uint16_t row=0; row < N_ROW - 1; row++){
setPixel(row, N_COL - 1, col[row]);
}
}
void fill(const struct CRGB & color) {
for(uint16_t i = 0;i < N_PIXEL; i++){
leds[i] = color;
}
}
void write_stopwatch_start_time(uint32_t start_time);
void interact();
void setup() {
Serial.begin(115200);
delay(100);
Serial1.begin(57600);
FastLED.addLeds<APA102, SCK, MOSI, BGR, DATA_RATE_MHZ(25)>(leds, N_PIXEL);
FastLED.setMaxPowerInVoltsAndMilliamps(5, 20000);
fill(CRGB::Black);
FastLED.setBrightness(brightness);
fill(CRGB::Green);
FastLED.show();
FastLED.show();
delay(100);
fill(CRGB::Black);
FastLED.show();
FastLED.show();
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1){
for(int i=0; i<3; i++){
digitalWrite(13, HIGH);
delay(250);
digitalWrite(13, LOW);
delay(250);
}
for(int i=0; i<3; i++){
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}
for(int i=0; i<3; i++){
digitalWrite(13, HIGH);
delay(250);
digitalWrite(13, LOW);
delay(250);
}
}
}
else{
}
now = rtc.now();
/* // rainbow test
for(int ii=0; ii<N_PIXEL; ii++){
leds[ii] = Wheel(ii % 256);
}
FastLED.show();
while(1);
*/
//stopwatch_start_time = now.unixtime();
stopwatch_start_time = read_stopwatch_start_time();
if(racing){
mode = RACE_MODE;
}
#ifdef NOTDEF // ## test small font
// test 4x8 font
for(int i=0; i<11; i++){
digit_4x8(i * 5, 0, i % 9, CRGB::White);
}
digits_4x8(0, 8, 1234567890L, 11, CRGB::Green);
FastLED.show();
uint32_t count = 0;
while(1){
digits_4x8(0, 8, count++, 11, CRGB::Green);
FastLED.show();
}
#endif
/*
n_wave = 3; //default
wave_sep = 120; // default
rtc_raw_write(DS3231_ALARM2_OFFSET + 1, 1, false, ((uint8_t*)&n_wave)); // n waves?
rtc_raw_write(DS3231_ALARM2_OFFSET + 2, 2, false, ((uint8_t*)&wave_sep)); // wave separation?
*/
}
void littleDigit(byte d, const struct CRGB & color){
byte row, col;
for(col = 0; col < 4; col++){
for(row = 0; row < 7; row++){
if((digits4x7[d * 4 + col] >> row) & 1){
setPixel(row, col, color);
}
else{
setPixel(row, col, 0);
}
}
}
}
void digit_4x8(byte x, byte y, byte d, const struct CRGB & color){
byte row, col;
if(d < 10){
for(col = 0; col < 4; col++){
for(row = 0; row < 8; row++){
if((digits4x8[d * 8 + row] >> col) & 1){
setPixel(row + y, col + x, color);
}
else{
setPixel(row + y, col + x, 0);
}
}
}
}
}
void digits_4x8(byte x, byte y, uint32_t v, byte n_digit, const struct CRGB & color){
byte digit;
for(byte i = 0; i < n_digit; i++){
digit = v / int(pow(10, i)) % 10;
digit_4x8(x + (5 * (n_digit - 1)) - i * 5, y, digit, color);
}
}
void bigDigit(byte start, byte d, const struct CRGB & color){
byte row, col;
if(d < 10){
for(col = 0; col < 8; col++){
for(row = 0; row < 16; row++){
if((digits8x16[d * 16 + row] >> col) & 1){
setPixel(row, col + start, color);
}
else{
setPixel(row, col + start, 0);
}
}
}
}
}
void bigDigits(byte start, uint32_t v, const byte n_digit, const struct CRGB & color){
byte digit;
for(byte i = 0; i < n_digit; i++){
digit = v / int(pow(10, i)) % 10;
bigDigit(start + (9 * (n_digit - 1)) - i * 9, digit, color);
}
}
void littleOne(const struct CRGB & color){
uint8_t ii;
for(ii=2; ii<12; ii++){
setPixel(ii, 1, color);
setPixel(ii, 2, color);
}
//setPixel(2, 2, color);
setPixel(3, 0, color);
setPixel(11, 0, color);
setPixel(11, 3, color);
}
void littleTwo(const struct CRGB & color){
setPixel(1, 0, color);
setPixel(0, 1, color);
setPixel(0, 2, color);
setPixel(1, 3, color);
setPixel(2, 3, color);
setPixel(3, 2, color);
setPixel(4, 1, color);
setPixel(5, 0, color);
setPixel(6, 0, color);
setPixel(6, 1, color);
setPixel(6, 2, color);
setPixel(6, 3, color);
}
void displayTime(uint8_t hh, uint8_t mm, uint8_t ss, const struct CRGB & color, bool colen){
char time[7];
uint8_t ii;
time[0] = '0' + hh / 10;
time[1] = '0' + hh % 10;
time[2] = '0' + mm / 10;
time[3] = '0' + mm % 10;
time[4] = '0' + ss / 10;
time[5] = '0' + ss % 10;
time[6] = 0;
if(hh / 10 > 0){
bigDigit( 0 - 1 + 0, hh / 10, color);
}
bigDigit( 9 - 1 + 0, hh % 10, color);
bigDigit(18 + 1, mm / 10, color);
bigDigit(27 + 1, mm % 10, color);
bigDigit(37 + 2, ss / 10, color);
bigDigit(46 + 2, ss % 10, color);
if(colen){
draw_colens(color);
}
}
int count = 0;
char *msg = "2x6 ULTIM8x8 array!!! ";
void display_count(unsigned int v, const struct CRGB & color){
bigDigit( 0, (int)(v / 1e6) % 10, color);
bigDigit( 8, (int)(v / 1e5) % 10, color);
bigDigit(16, (int)(v / 1e4) % 10, color);
bigDigit(24, (int)(v / 1e3) % 10, color);
bigDigit(32, (int)(v / 1e2) % 10, color);
bigDigit(40, (int)(v / 1e1) % 10, color);
bigDigit(48, (int)(v / 1e0) % 10, color);
FastLED.show();
}
void loop(){
count++;
//display_count(count, CRGB::Red);return;
//displayTime(0, 0, count%10, CRGB::Red, true); FastLED.show(); return;
//bigDigits(0, 9999, 4, CRGB::Red); FastLED.show(); return;
//Serial.println(count);
now = rtc.now();
//now = count;
updateDisplay();
interact();
//Serial.println(count);
}
void updateDisplay(){
uint32_t empty[16];
uint16_t ii, row, col;
byte hh, mm, ss;
bool pending_start = false;
TimeSpan race_time;
long long race_seconds;
uint8_t race_hh, race_mm, race_ss;
fill(CRGB::Black);
if(now.unixtime() > stopwatch_start_time){
race_time = TimeSpan(now.unixtime() - stopwatch_start_time);
}
else if(mode == RACE_MODE){
race_time = TimeSpan(stopwatch_start_time - now.unixtime());
pending_start = true;
}
// wall clock time
hh = now.hour();
if(USE_12_HOUR_FORMAT){ // use 12 hour clock
hh = hh % 12;
if(hh == 0){
hh = 12;
}
}
mm = now.minute();
ss = now.second();
// displayTime(hh % 100, mm, ss, CRGB::White, true); FastLED.show(); return;
if(mode == STANDBY_MODE){
// race time
race_hh = countdown_duration.hours();
race_mm = countdown_duration.minutes();
race_ss = countdown_duration.seconds();
displayTime(race_hh % 100, race_mm, race_ss, CRGB::Yellow, true);
for(int row=0; row < 16; row++){
for(int col=0; col < 8; col++){
setPixel(row, col, CRGB::Black);
}
}
}
else if(mode == RACE_MODE){
if(racing){
// race time
race_hh = race_time.hours(); //+ race_time.days() * 24;
race_mm = race_time.minutes();
race_ss = race_time.seconds();
race_seconds = race_hh * HOUR + race_mm * MINUTE + race_ss * SECOND;
displayTime(race_hh % 100, race_mm, race_ss, CRGB::White, race_ss % 2);
if(pending_start){
if(0 <= race_seconds && race_seconds < 10){
//if(race_hh == 0 && race_mm == 0 && race_ss < 10){
if(race_ss > 0){
fill(CRGB::Red);
}
else{
fill(CRGB::Green);
}
for(int col=0; col<10; col++){
for(int row=0; row<16; row++){
setPixel(row, col+23, CRGB::Black);
}
}
bigDigit(24, race_ss, CRGB::White);
}
}
else{
for(uint8_t i = 0; i < n_wave; i++){
// see if we are about to start a new wave
int wave_seconds = race_seconds - i * wave_sep;
if(-10 < wave_seconds && wave_seconds < 0){
if(race_ss > 0){
fill(CRGB::Red);
}
else{
fill(CRGB::Green);
}
for(int col=0; col<10; col++){
for(int row=0; row<16; row++){
setPixel(row, col+23, CRGB::Black);
}
}
bigDigit(24, abs(wave_seconds), CRGB::White);
}
// see if a new wave just started
if(0 <= race_seconds - i * wave_sep && race_seconds - i * wave_sep < 10){
fill(CRGB::Black);
for(int col=0; col<20; col++){
for(int row=0; row<16; row++){
setPixel(row, col+(race_ss%2) * 36, CRGB::Green);
}
}
bigDigit(24, race_seconds - i * wave_sep, CRGB::White);
}
}
}
}
else{ // put dashes
draw_dashes(CRGB::White);
draw_colens(CRGB::White);
}
}
else if (mode == CLOCK_MODE){
displayTime(hh % 100, mm, ss, CRGB::White, true);
}
else if (mode == WAVE_MODE){
bigDigits(0, n_wave, 2, CRGB::Purple);
if(n_wave > 1){
bigDigits(56 - 4 * 9, wave_sep % 10000, 4, CRGB::SeaGreen);
}
}
//displayTime(0, 0, count%10, CRGB::Green, true); FastLED.show(); return;
FastLED.show();
return;
}
void interact(){
uint8_t command;
bool update = false;
while(Serial.available()){
update = true;
command = Serial.read();
Serial.print((char)command);
if(command > 0 && command <= KANDY_MAX_COMMAND){
do_command(command);
}
}
while(Serial1.available()){
update = true;
command = Serial1.read();
Serial.write((char)command);
if(command > 0 && command <= KANDY_MAX_COMMAND){
do_command(command);
}
}
if(update){
updateDisplay();
}
}
void do_command(uint8_t command){
uint8_t hh = now.hour();
uint8_t mm = now.minute();
uint8_t ss = now.second();
switch(command){
case KANDY_START: // start / resume
if(mode == STANDBY_MODE){
racing = true;
stopwatch_start_time = (now + countdown_duration).unixtime();
write_stopwatch_start_time(stopwatch_start_time);
increment_mode();
}
break;
case KANDY_STOP: // stop / pause
break;
case KANDY_INC_HOUR:
if(mode == CLOCK_MODE){
now = rtc.now() + HOUR;
racing = false;
rtc.adjust(now);
}
break;
case KANDY_DEC_HOUR:
if(mode == CLOCK_MODE){
now = rtc.now() - HOUR;
racing = false;
rtc.adjust(now);
}
break;
case KANDY_INC_MIN:
if(mode == CLOCK_MODE){
now = rtc.now() + MINUTE;
racing = false;
rtc.adjust(now);
}
break;
case KANDY_DEC_MIN:
if(mode == CLOCK_MODE){
now = rtc.now() - MINUTE;
racing = false;
rtc.adjust(now);
}
break;
case KANDY_INC_SEC:
if(mode == CLOCK_MODE){
now = rtc.now() + SECOND;
racing = false;
rtc.adjust(now);
}
break;
case KANDY_DEC_SEC:
if(mode == CLOCK_MODE){
now = rtc.now() - SECOND;
racing = false;
rtc.adjust(now);
}
break;
case KANDY_ZERO_SEC:
if(mode == CLOCK_MODE){
now = rtc.now() - ss;
racing = false;
rtc.adjust(now);
}
break;
case KANDY_INC_CD_HOUR:
if(mode == STANDBY_MODE){
countdown_duration = countdown_duration + HOUR;
}
break;
case KANDY_DEC_CD_HOUR:
if(mode == STANDBY_MODE){
if(countdown_duration.totalseconds() > 3600){
countdown_duration = countdown_duration - HOUR;
}
}
break;
case KANDY_INC_CD_MIN:
if(mode == STANDBY_MODE){
countdown_duration = countdown_duration + MINUTE;
}
break;
case KANDY_DEC_CD_MIN:
if(mode == STANDBY_MODE){
if(countdown_duration.totalseconds() > 60){
countdown_duration = countdown_duration - MINUTE;
}
}
break;
case KANDY_INC_CD_SEC:
if(mode == STANDBY_MODE){
countdown_duration = countdown_duration + SECOND;
}
break;
case KANDY_DEC_CD_SEC:
if(mode == STANDBY_MODE){
if(countdown_duration.totalseconds() > 0){
countdown_duration = countdown_duration - SECOND;
}
}
break;
case KANDY_INC_BRIGHTNESS:
increment_brightness();
break;
case KANDY_DEC_BRIGHTNESS:
decrement_brightness();
break;
case KANDY_INC_MODE:
increment_mode();
break;
case KANDY_DEC_MODE:
decrement_mode();
break;
case KANDY_INC_RACE_HOUR:
if(mode == RACE_MODE){
if(stopwatch_start_time > 3600){
stopwatch_start_time -= 3600;
}
else{
fill(CRGB::Red);
delay(500);
}
}
break;
case KANDY_DEC_RACE_HOUR:
if(mode == RACE_MODE){
stopwatch_start_time += 3600;
}
break;
case KANDY_INC_RACE_MIN:
if(mode == RACE_MODE){
if(stopwatch_start_time > 60){
stopwatch_start_time -= 60;
}
else{
fill(CRGB::Red);
delay(500);
}
}
break;
case KANDY_DEC_RACE_MIN:
if(mode == RACE_MODE){
stopwatch_start_time += 60;
}
break;
case KANDY_INC_RACE_SEC:
if(mode == RACE_MODE){
if(stopwatch_start_time > 1){
stopwatch_start_time -= 1;
}
else{
fill(CRGB::Red);
delay(500);
}
}
break;
case KANDY_DEC_RACE_SEC:
if(mode == RACE_MODE){
stopwatch_start_time += 1;
}
break;
case KANDY_SET_TO_MIDNIGHT:
if(mode == CLOCK_MODE){
now = rtc.now() - (hh * HOUR + mm * MINUTE + ss * SECOND);
racing = false;
rtc.adjust(now);
}
break;
case KANDY_INC_N_WAVE:
if(mode == WAVE_MODE){
if(n_wave < 99){
n_wave++;
}
}
break;
case KANDY_DEC_N_WAVE:
if(mode == WAVE_MODE){
if(n_wave > 1){
n_wave--;
}
}
break;
case KANDY_INC_WAVE_SEP:
if(mode == WAVE_MODE){
if(wave_sep < MAX_WAVE_SEP){
wave_sep+=10;
}
}
break;
case KANDY_DEC_WAVE_SEP:
if(mode == WAVE_MODE){
if(wave_sep > MIN_WAVE_SEP){
wave_sep-=10;
}
}
break;
case KANDY_RACE_STOP:
if(mode == RACE_MODE){
racing = false;
write_stopwatch_start_time(stopwatch_start_time); // save race state (fact that race is stopped)
}
default:
break;
}
}
void increment_brightness(){
if(brightness < MAX_BRIGHTNESS){
brightness++;
FastLED.setBrightness(brightness);
}
}
void decrement_brightness(){
if(brightness > 1){
brightness--;
FastLED.setBrightness(brightness);
}
}
void increment_mode(){
if(mode < N_MODE){
mode++;
}
}
void decrement_mode(){
if(mode > 1){
mode--;
}
}
uint8_t dec2bcd(int dec){
uint8_t t = dec / 10;
uint8_t o = dec - t * 10;
return (t << 4) + o;
}
void write_stopwatch_start_time(uint32_t start_time){
uint8_t *time_bytes_p;
/*
set to:
0 in clock mode
start time in race mode
*/
time_bytes_p = (uint8_t*)(&start_time);
uint16_t countdown = countdown_duration.totalseconds();
rtc_raw_write(DS3231_ALARM1_OFFSET, 4, false, time_bytes_p);
rtc_raw_write(DS3231_ALARM2_OFFSET, 1, false, ((uint8_t*)&racing)); // race on?
rtc_raw_write(DS3231_ALARM2_OFFSET + 1, 1, false, ((uint8_t*)&n_wave)); // n waves?
rtc_raw_write(DS3231_ALARM2_OFFSET + 2, 2, false, ((uint8_t*)&wave_sep)); // wave separation?
//rtc_raw_write(DS3231_ALARM2_OFFSET + 4, 2, false, ((uint8_t*)&countdown));
}
uint32_t read_stopwatch_start_time(){
uint8_t *time_bytes_p;
uint32_t out;
uint16_t countdown;
/*
set to:
0 in clock mode
start time in race mode
*/
time_bytes_p = (uint8_t*)(&out);
rtc_raw_read(DS3231_ALARM1_OFFSET, 4, false, time_bytes_p);
rtc_raw_read(DS3231_ALARM2_OFFSET, 1, false, ((uint8_t*)&racing)); // race on?
rtc_raw_read(DS3231_ALARM2_OFFSET + 1, 1, false, ((uint8_t*)&n_wave)); // n waves?
rtc_raw_read(DS3231_ALARM2_OFFSET + 2, 2, false, ((uint8_t*)&wave_sep)); // n separation?
rtc_raw_read(DS3231_ALARM2_OFFSET + 4, 2, false, ((uint8_t*)&countdown)); // countdown?
return out;
}
int bcd2dec(uint8_t bcd){
return (((bcd & 0b11110000)>>4)*10 + (bcd & 0b00001111));
}
bool rtc_raw_read(uint8_t addr,
uint8_t n_bytes,
bool is_bcd,
uint8_t *dest){
bool out = false;
Wire.beginTransmission(DS3231_ADDR);
// Wire.send(addr);
Wire.write((uint8_t)(addr));
Wire.endTransmission();
Wire.requestFrom(DS3231_ADDR, (int)n_bytes); // request n_bytes bytes
if(Wire.available()){
for(uint8_t i = 0; i < n_bytes; i++){
dest[i] = Wire.read();
if(is_bcd){ // needs to be converted to dec
dest[i] = bcd2dec(dest[i]);
}
}
out = true;
}
return out;
}
void rtc_raw_write(uint8_t addr,
uint8_t n_byte,
bool is_bcd,
uint8_t *source){
uint8_t byte;
Wire.beginTransmission(DS3231_ADDR);
Wire.write((uint8_t)(addr));
for(uint8_t i = 0; i < n_byte; i++){
if(is_bcd){
byte = dec2bcd(source[i]);
}
else{
byte = source[i];
}
Wire.write(byte);
}
Wire.endTransmission();
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2005 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#ifdef SVG_SUPPORT
#include "modules/svg/src/svgpch.h"
#include "modules/svg/src/SVGGradient.h"
#ifdef SVG_SUPPORT_GRADIENTS
#include "modules/svg/src/AttrValueStore.h"
#include "modules/svg/src/SVGUtils.h"
#include "modules/svg/src/SVGDocumentContext.h"
#include "modules/svg/src/SVGCanvasState.h"
#include "modules/svg/src/svgpaintnode.h"
#include "modules/layout/layout_workplace.h"
#include "modules/layout/layoutprops.h"
#include "modules/layout/cascade.h"
#include "modules/layout/box/box.h"
#define VNUM(s) ((s).GetVegaNumber())
OP_STATUS SVGGradient::GetFill(VEGAFill** vfill, VEGATransform& vfilltrans,
SVGPainter* painter, SVGPaintNode* context_node)
{
OP_ASSERT(painter && painter->GetRenderer());
unsigned stop_count = GetNumStops();
VEGA_FIX* ofs = OP_NEWA(VEGA_FIX, stop_count);
UINT32* col = OP_NEWA(UINT32, stop_count);
if (!ofs || !col)
{
OP_DELETEA(ofs);
OP_DELETEA(col);
return OpStatus::ERR_NO_MEMORY;
}
for (unsigned i = 0; i < stop_count; ++i)
{
const SVGStop* s = GetStop(i);
if (!s)
{
OP_DELETEA(ofs);
OP_DELETEA(col);
return OpStatus::ERR;
}
UINT32 color = s->GetColorRGB();
UINT8 a = GetSVGColorAValue(color);
UINT8 r = GetSVGColorRValue(color);
UINT8 g = GetSVGColorGValue(color);
UINT8 b = GetSVGColorBValue(color);
color = (a << 24) | (r << 16) | (g << 8) | b;
ofs[i] = VNUM(s->GetOffset());
col[i] = color;
}
VEGARenderer* renderer = painter->GetRenderer();
OP_STATUS status = OpStatus::OK;
if (Type() == SVGGradient::LINEAR)
{
VEGA_FIX f1x = VNUM(GetX1());
VEGA_FIX f1y = VNUM(GetY1());
VEGA_FIX f2x = VNUM(GetX2());
VEGA_FIX f2y = VNUM(GetY2());
status = renderer->createLinearGradient(vfill, f1x, f1y, f2x, f2y, stop_count, ofs, col);
}
else
{
VEGA_FIX fx = VNUM(GetFx());
VEGA_FIX fy = VNUM(GetFy());
VEGA_FIX cx = VNUM(GetCx());
VEGA_FIX cy = VNUM(GetCy());
VEGA_FIX r = VNUM(GetR());
status = renderer->createRadialGradient(vfill, fx, fy, 0, cx, cy, r, stop_count, ofs, col);
}
OP_DELETEA(ofs);
OP_DELETEA(col);
RETURN_IF_ERROR(status);
VEGAFill::Spread spr;
switch (GetSpreadMethod())
{
case SVGSPREAD_REFLECT:
spr = VEGAFill::SPREAD_REFLECT;
break;
case SVGSPREAD_REPEAT:
spr = VEGAFill::SPREAD_REPEAT;
break;
case SVGSPREAD_PAD:
default:
spr = VEGAFill::SPREAD_CLAMP;
break;
}
(*vfill)->setSpread(spr);
// vfilltrans = GradientTransform * BBOX
vfilltrans.loadIdentity();
if (GetUnits() == SVGUNITS_OBJECTBBOX)
{
// Additional transform needed for the gradient transform
SVGBoundingBox bbox = context_node->GetBBox();
vfilltrans[0] = VNUM(bbox.maxx - bbox.minx);
vfilltrans[2] = VNUM(bbox.minx);
vfilltrans[4] = VNUM(bbox.maxy - bbox.miny);
vfilltrans[5] = VNUM(bbox.miny);
}
// Gradient Transform
VEGATransform tmp;
m_transform.CopyToVEGATransform(tmp);
vfilltrans.multiply(tmp);
return OpStatus::OK;
}
#undef VNUM
void SVGGradient::PutFill(VEGAFill* vfill)
{
OP_DELETE(vfill);
}
UINT32 SVGStop::GetColorRGB() const
{
unsigned stop_a = GetSVGColorAValue(m_stopcolor);
stop_a = stop_a * m_stopopacity / 255;
return (stop_a << 24) | (m_stopcolor & 0x00FFFFFF);
}
/**
* Sets the boundingbox of the target to fill. Note that this may change as different objects are
* rendered, and that the box doesn't always equal the actual boundingbox on the canvas level.
* For example, text shouldn't paint the gradient using glyph bboxes, instead the entire text block
* should be used.
*
* @param x The starting x coordinate (userspace)
* @param y The starting y coordinate (userspace)
* @param w The width (userspace)
* @param h The height (userspace)
*/
void SVGGradient::SetTargetBoundingBox(SVGNumber x, SVGNumber y, SVGNumber w, SVGNumber h)
{
m_bbox.x = x;
m_bbox.y = y;
m_bbox.width = w;
m_bbox.height = h;
}
/**
* Creates a copy of this gradient.
*
* @param outcopy The copy will be allocated and returned here, pass a reference to a pointer.
* @return OK or ERR_NO_MEMORY
*/
OP_STATUS SVGGradient::CreateCopy(SVGGradient **outcopy) const
{
SVGGradient *newgrad = OP_NEW(SVGGradient, (m_type));
if (!newgrad)
return OpStatus::ERR_NO_MEMORY;
for (unsigned i = 0; i < m_stops.GetCount(); i++)
{
SVGStop* s = m_stops.Get(i);
if (s)
{
SVGStop* newstop = OP_NEW(SVGStop, (*s));
if (!newstop || OpStatus::IsError(newgrad->m_stops.Add(newstop)))
{
OP_DELETE(newstop);
OP_DELETE(newgrad);
return OpStatus::ERR_NO_MEMORY;
}
}
}
newgrad->m_a = m_a;
newgrad->m_b = m_b;
newgrad->m_c = m_c;
newgrad->m_d = m_d;
newgrad->m_e = m_e;
newgrad->m_transform.Copy(m_transform);
newgrad->m_spread = m_spread;
newgrad->m_units = m_units;
newgrad->m_bbox = m_bbox;
*outcopy = newgrad;
return OpStatus::OK;
}
struct SVGGradientParameters
{
SVGLengthObject* x1;
SVGLengthObject* y1;
SVGLengthObject* x2;
SVGLengthObject* y2;
SVGLengthObject* cx;
SVGLengthObject* cy;
SVGLengthObject* fx;
SVGLengthObject* fy;
SVGLengthObject* r;
};
void SVGGradient::ResolveGradientParameters(const SVGGradientParameters& params,
const SVGValueContext& vcxt)
{
if (m_type == SVGGradient::LINEAR)
{
SetX1(SVGUtils::ResolveLengthWithUnits(params.x1, SVGLength::SVGLENGTH_X,
GetUnits(), vcxt));
SetY1(SVGUtils::ResolveLengthWithUnits(params.y1, SVGLength::SVGLENGTH_Y,
GetUnits(), vcxt));
SetX2(SVGUtils::ResolveLengthWithUnits(params.x2, SVGLength::SVGLENGTH_X,
GetUnits(), vcxt));
SetY2(SVGUtils::ResolveLengthWithUnits(params.y2, SVGLength::SVGLENGTH_Y,
GetUnits(), vcxt));
}
else
{
SetCx(SVGUtils::ResolveLengthWithUnits(params.cx, SVGLength::SVGLENGTH_X,
GetUnits(), vcxt));
SetCy(SVGUtils::ResolveLengthWithUnits(params.cy, SVGLength::SVGLENGTH_Y,
GetUnits(), vcxt));
SVGNumber v = SVGUtils::ResolveLengthWithUnits(params.r, SVGLength::SVGLENGTH_OTHER,
GetUnits(), vcxt);
if (v < 0)
v = 0.5; // Lacuna value
SetR(v);
// If (fx, fy) is not set, use cx/cy as default
if (params.fx)
SetFx(SVGUtils::ResolveLengthWithUnits(params.fx, SVGLength::SVGLENGTH_X,
GetUnits(), vcxt));
else
SetFx(GetCx());
if (params.fy)
SetFy(SVGUtils::ResolveLengthWithUnits(params.fy, SVGLength::SVGLENGTH_Y,
GetUnits(), vcxt));
else
SetFy(GetCy());
// "If the point defined by fx and fy lies outside the circle
// defined by cx, cy and r, then the user agent shall set the
// focal point to the intersection of the line from (cx, cy) to
// (fx, fy) with the circle defined by cx, cy and r."
SVGNumber cfx = GetFx() - GetCx();
SVGNumber cfy = GetFy() - GetCy();
SVGNumber rad = GetR();
SVGNumber sqr_dist = cfx*cfx + cfy*cfy;
if (sqr_dist > rad*rad)
{
// Calculate intersection
SVGNumber sf = rad / sqr_dist.sqrt() - SVGNumber::eps();
SetFx(GetCx() + cfx * sf);
SetFy(GetCy() + cfy * sf);
}
}
}
/* static */
OP_STATUS SVGGradient::Create(HTML_Element *gradient_element,
SVGElementResolver* resolver, SVGDocumentContext* doc_ctx,
const SVGValueContext& vcxt,
SVGGradient **outgrad)
{
OP_ASSERT(outgrad);
OP_ASSERT(gradient_element->IsMatchingType(Markup::SVGE_LINEARGRADIENT, NS_SVG) ||
gradient_element->IsMatchingType(Markup::SVGE_RADIALGRADIENT, NS_SVG));
*outgrad = NULL;
RETURN_IF_ERROR(resolver->FollowReference(gradient_element));
GradientType type = SVGGradient::LINEAR;
if (gradient_element->Type() == Markup::SVGE_RADIALGRADIENT)
type = SVGGradient::RADIAL;
OP_STATUS result;
SVGGradient* gradient = OP_NEW(SVGGradient, (type));
if (gradient)
{
SVGGradientParameters params;
// This is the default for x1, y1 and y2
SVGLengthObject def_lin(SVGNumber(0), CSS_PERCENTAGE);
// This is the default for x2
SVGLengthObject def_lin_x2(SVGNumber(100), CSS_PERCENTAGE);
// Set unresolved defaults for linear parameters
params.x1 = params.y1 = params.y2 = &def_lin;
params.x2 = &def_lin_x2;
// This is the default for cx, cy and r
SVGLengthObject def_rad(SVGNumber(50), CSS_PERCENTAGE);
// Set unresolved defaults for radial parameters
params.cx = params.cy = params.r = &def_rad;
params.fx = params.fy = NULL;
// Setup defaults for attributes that needn't be resolved
gradient->SetTransform(SVGMatrix());
gradient->SetUnits(SVGUNITS_OBJECTBBOX);
gradient->SetSpreadMethod(SVGSPREAD_PAD);
HTML_Element* stop_root = NULL;
result = gradient->FetchValues(gradient_element, resolver, doc_ctx, ¶ms, &stop_root);
if (OpStatus::IsSuccess(result))
{
gradient->ResolveGradientParameters(params, vcxt);
if (stop_root)
result = gradient->FetchGradientStops(stop_root);
if (OpStatus::IsError(result))
{
OP_DELETE(gradient);
}
else
{
*outgrad = gradient;
}
}
else
{
OP_DELETE(gradient);
}
}
else
{
result = OpStatus::ERR_NO_MEMORY;
}
resolver->LeaveReference(gradient_element);
return result;
}
OP_STATUS SVGGradient::FetchValues(HTML_Element *gradient_element,
SVGElementResolver* resolver, SVGDocumentContext* doc_ctx,
SVGGradientParameters* params, HTML_Element** stop_root)
{
OP_ASSERT(gradient_element->IsMatchingType(Markup::SVGE_LINEARGRADIENT, NS_SVG) ||
gradient_element->IsMatchingType(Markup::SVGE_RADIALGRADIENT, NS_SVG));
if (AttrValueStore::HasObject(gradient_element, Markup::XLINKA_HREF, NS_IDX_XLINK))
{
// This means we should inherit from the referenced element
HTML_Element* inh_gradient_element = NULL;
// Note: use the base url of the document where the gradient
// element is (and note that it's always a document-local
// reference)
if (SVGDocumentContext* element_doc_ctx = AttrValueStore::GetSVGDocumentContext(gradient_element))
inh_gradient_element = SVGUtils::FindHrefReferredNode(resolver, element_doc_ctx, gradient_element);
if (inh_gradient_element)
{
Markup::Type inh_elm_type = inh_gradient_element->Type();
if (inh_elm_type == Markup::SVGE_LINEARGRADIENT || inh_elm_type == Markup::SVGE_RADIALGRADIENT)
{
OP_STATUS status = resolver->FollowReference(inh_gradient_element);
if (OpStatus::IsSuccess(status))
{
doc_ctx->RegisterDependency(gradient_element, inh_gradient_element);
status = FetchValues(inh_gradient_element, resolver, doc_ctx, params, stop_root);
resolver->LeaveReference(inh_gradient_element);
RETURN_IF_ERROR(status);
}
}
}
}
// Should we perhaps check m_type (set in Create), and not fetch if the type differs?
Markup::Type elm_type = gradient_element->Type();
if (elm_type == Markup::SVGE_RADIALGRADIENT)
{
AttrValueStore::GetLength(gradient_element, Markup::SVGA_CX, ¶ms->cx, params->cx);
AttrValueStore::GetLength(gradient_element, Markup::SVGA_CY, ¶ms->cy, params->cy);
AttrValueStore::GetLength(gradient_element, Markup::SVGA_R, ¶ms->r, params->r);
AttrValueStore::GetLength(gradient_element, Markup::SVGA_FX, ¶ms->fx, params->fx);
AttrValueStore::GetLength(gradient_element, Markup::SVGA_FY, ¶ms->fy, params->fy);
}
else /* elm_type == Markup::SVGE_LINEARGRADIENT */
{
AttrValueStore::GetLength(gradient_element, Markup::SVGA_X1, ¶ms->x1, params->x1);
AttrValueStore::GetLength(gradient_element, Markup::SVGA_Y1, ¶ms->y1, params->y1);
AttrValueStore::GetLength(gradient_element, Markup::SVGA_X2, ¶ms->x2, params->x2);
AttrValueStore::GetLength(gradient_element, Markup::SVGA_Y2, ¶ms->y2, params->y2);
}
// Check if we have gradientstop children, if not then inherit them
for (HTML_Element* child = gradient_element->FirstChild(); child; child = child->Suc())
{
if (child->IsMatchingType(Markup::SVGE_STOP, NS_SVG))
{
// This element has stops - set it as the stop root
*stop_root = gradient_element;
break;
}
}
if (AttrValueStore::HasTransform(gradient_element, Markup::SVGA_GRADIENTTRANSFORM, NS_IDX_SVG))
{
SVGMatrix matrix;
AttrValueStore::GetMatrix(gradient_element, Markup::SVGA_GRADIENTTRANSFORM, matrix);
SetTransform(matrix);
}
if (AttrValueStore::HasObject(gradient_element, Markup::SVGA_GRADIENTUNITS, NS_IDX_SVG))
{
SVGUnitsType units;
OP_STATUS status = AttrValueStore::GetUnits(gradient_element, Markup::SVGA_GRADIENTUNITS, units, SVGUNITS_OBJECTBBOX);
if (OpStatus::IsSuccess(status))
SetUnits(units);
}
if (AttrValueStore::HasObject(gradient_element, Markup::SVGA_SPREADMETHOD, NS_IDX_SVG))
{
SVGSpreadMethodType spread =
(SVGSpreadMethodType)AttrValueStore::GetEnumValue(gradient_element, Markup::SVGA_SPREADMETHOD,
SVGENUM_SPREAD_METHOD_TYPE,
SVGSPREAD_PAD);
SetSpreadMethod(spread);
}
return OpStatus::OK;
}
OP_STATUS SVGGradient::FetchGradientStops(HTML_Element* stop_root)
{
// Create new cascade to ensure inheritance in document order
SVGDocumentContext* element_doc_ctx = AttrValueStore::GetSVGDocumentContext(stop_root);
if (!element_doc_ctx)
return OpStatus::ERR;
HLDocProfile* hld_profile = element_doc_ctx->GetHLDocProfile();
if (!hld_profile)
return OpStatus::ERR;
Head prop_list;
LayoutProperties* props = LayoutProperties::CreateCascade(stop_root, prop_list,
LAYOUT_WORKPLACE(hld_profile));
if (!props)
return OpStatus::ERR_NO_MEMORY;
LayoutInfo info(hld_profile->GetLayoutWorkplace());
OP_STATUS err = OpStatus::OK;
// Figure out stops
SVGStop* last = NULL;
for (HTML_Element* child = stop_root->FirstChild(); child; child = child->Suc())
{
if (!child->IsMatchingType(Markup::SVGE_STOP, NS_SVG))
continue;
SVGStop* stop = NULL;
err = CreateStop(child, props, info, &stop);
if (OpStatus::IsError(err))
break;
err = AddStop(stop);
if (OpStatus::IsError(err))
{
OP_DELETE(stop);
break;
}
// Each gradient offset value is required to be equal to or
// greater than the previous gradient stop's offset value. If
// a given gradient stop's offset value is not equal to or
// greater than all previous offset values, then the offset
// value is adjusted to be equal to the largest of all
// previous offset values.
if (last && stop->GetOffset() < last->GetOffset())
stop->SetOffset(last->GetOffset());
last = stop;
}
// Remove cascade
props = NULL;
prop_list.Clear();
return err;
}
/* static */
OP_STATUS SVGGradient::CreateStop(HTML_Element *stopelm, LayoutProperties* lprops, LayoutInfo& info,
SVGStop **outstop)
{
OP_ASSERT(outstop);
SVGStop* stop = OP_NEW(SVGStop, ());
if (!stop)
return OpStatus::ERR_NO_MEMORY;
LayoutProperties* old_cascade = lprops;
#ifdef LAZY_LOADPROPS
if (stopelm->IsPropsDirty())
{
OP_STATUS status = info.workplace->UnsafeLoadProperties(stopelm);
if (OpStatus::IsError(status))
{
OP_DELETE(stop);
return status;
}
}
#endif // LAZY_LOADPROPS
LayoutProperties* child_cascade = lprops->GetChildCascade(info, stopelm);
if (!child_cascade)
{
OP_DELETE(stop);
return OpStatus::ERR_NO_MEMORY;
}
const HTMLayoutProperties& props = *child_cascade->GetProps();
const SvgProperties *svg_props = props.svg;
SVGNumberObject* offset = NULL;
AttrValueStore::GetNumberObject(stopelm, Markup::SVGA_OFFSET, &offset);
if (offset)
{
stop->SetOffset(offset->value);
// Gradient offset values less than 0 (or less than 0%) are rounded up to 0%.
// Gradient offset values greater than 1 (or greater than 100%) are rounded down to 100%.
if (stop->GetOffset() < 0)
{
stop->SetOffset(0);
}
else if (stop->GetOffset() > 1)
{
stop->SetOffset(1);
}
}
// Otherwise use default value of zero
const SVGColor& stop_color = svg_props->stopcolor;
switch (stop_color.GetColorType())
{
case SVGColor::SVGCOLOR_RGBCOLOR:
stop->SetColorRGB(stop_color.GetRGBColor());
break;
case SVGColor::SVGCOLOR_RGBCOLOR_ICCCOLOR:
stop->SetColorRGB(stop_color.GetRGBColor());
break;
case SVGColor::SVGCOLOR_CURRENT_COLOR:
OP_ASSERT(!"Hah! currentColor not resolved");
default:
break;
}
stop->SetOpacity(svg_props->stopopacity);
// Reset CSS
if (child_cascade)
old_cascade->CleanSuc();
*outstop = stop;
return OpStatus::OK;
}
#ifdef SELFTEST
BOOL SVGGradient::operator==(const SVGGradient& other) const
{
BOOL result = ((m_type == other.m_type) &&
(m_stops.GetCount() == other.m_stops.GetCount()) &&
(m_transform == other.m_transform) &&
(m_spread == other.m_spread) &&
(m_a.Equal(other.m_a)) &&
(m_b.Equal(other.m_b)) &&
(m_c.Equal(other.m_c)) &&
(m_d.Equal(other.m_d)) &&
(m_e.Equal(other.m_e)) &&
(m_units == other.m_units) &&
(m_bbox.IsEqual(other.m_bbox)));
if(result)
{
for(UINT32 i = 0; i < m_stops.GetCount(); i++)
{
SVGStop* s = m_stops.Get(i);
SVGStop* os = other.m_stops.Get(i);
if(!s || !os)
return FALSE;
result = result && (s->GetColorRGB() == os->GetColorRGB()) &&
(s->GetOffset().Equal(os->GetOffset()));
if(!result)
break;
}
}
return result;
}
#endif // SELFTEST
#ifdef _DEBUG
void SVGGradient::Print() const
{
OP_NEW_DBG("SVGGradient::Print()", "svg_gradient");
OP_DBG(("Type: %s. Units: %s.",
m_type == LINEAR ? "linear" : "radial",
m_units == SVGUNITS_USERSPACEONUSE ? "userSpaceOnUse" : "objBbox"));
if(m_type == LINEAR)
{
OP_DBG(("(x1: %g y1: %g) (x2: %g y2: %g)",
GetX1().GetFloatValue(), GetY1().GetFloatValue(),
GetX2().GetFloatValue(), GetY2().GetFloatValue()));
}
else
{
OP_DBG(("(Cx: %g Cy: %g) (Fx: %g Fy: %g) R: %g.",
GetCx().GetFloatValue(), GetCy().GetFloatValue(), GetFx().GetFloatValue(),
GetFy().GetFloatValue(), GetR().GetFloatValue()));
}
OP_DBG(("Spread method: %s.",
m_spread == SVGSPREAD_PAD ? "pad" : m_spread == SVGSPREAD_REFLECT ? "reflect" : "repeat"));
OP_DBG(("Transform: %g %g %g %g %g %g",
m_transform[0].GetFloatValue(), m_transform[1].GetFloatValue(),
m_transform[2].GetFloatValue(), m_transform[3].GetFloatValue(),
m_transform[4].GetFloatValue(), m_transform[5].GetFloatValue()));
for(UINT32 i = 0; i < m_stops.GetCount(); i++)
{
SVGStop* s = m_stops.Get(i);
OP_DBG(("SVGStop #%d: stopcolor: 0x%x. offset: %g.",
i, s->GetColorRGB(), s->GetOffset().GetFloatValue()));
}
}
#endif // _DEBUG
#endif // SVG_SUPPORT_GRADIENTS
#endif // SVG_SUPPORT
|
#include <bits/stdc++.h>
using namespace std;
class Graph{
int V;
list<int> *l;
public:
Graph(int V){
this->V = V;
l = new list<int>[V];
}
void addEdge(int x, int y, bool directed=true){
l[x].push_back(y);
if(!directed){
l[y].push_back(x);
}
}
bool cycle_helper(int node, bool *visited, bool *current){
//visit a node
visited[node] = true;
current[node] = true;
for(int nbr : l[node]){
if(current[nbr]){
return true;
}else if(!visited[nbr] && cycle_helper(nbr, visited, current)){
return true;
}
}
//leave a node
current[node] = false;
return false;
}
bool contains_cycle(){
//check for cycle in directed graph
bool *visited = new bool[V];
bool *current = new bool[V];
for(int i=0;i<V;i++){
visited[i]=current[i]=false;
}
return cycle_helper(0, visited, current);
}
bool cycle_helper_undirected(int node, bool *visited, int parent){
visited[node] = true;
for(auto nbr: l[node]){
//two cases
if(!visited[nbr]){
// go and recursively visit the nbr
bool cycle_mila = cycle_helper_undirected(nbr, visited, node);
if(cycle_mila) return true;
}else if(nbr!=parent){
return true;
}
}
return false;
}
bool contains_cycle_undirected(){
bool *visited = new bool[V];
for(int i=0;i<V;i++) visited[i]=false;
return cycle_helper_undirected(0,visited,-1);
}
};
int main(){
Graph g(5);
g.addEdge(0,1,false);
g.addEdge(1,2,false);
g.addEdge(2,3,false);
g.addEdge(3,4,false);
//g.addEdge(4,0,false);
cout << (g.contains_cycle_undirected() ? "Yes, it contains cycle" : "No, it doesn't contain a cycle")<< endl;
return 0;
}
|
#ifndef __TREE_H
#define __TREE_H
#include <cstdlib>
#include <vector>
#include <iostream>
#include <cstring>
#include <sstream>
#include <string>
using namespace std;
struct TreeItem
{
string value;
TreeItem *Parent; // parent node
TreeItem *FChild; // pointer to first child node
TreeItem *NextS; // pointer to next sibling node
/*You can add additional variables if necessary*/
TreeItem(string Val)
{
this->value = Val;
this->Parent = NULL;
this->FChild = NULL;
this->NextS = NULL;
}
};
class Tree
{
TreeItem *head;
public:
// Constructor
Tree();
Tree(string file); // constructor to load directory paths from the given file name
// Destructor
~Tree();
void insert(string item); // takes the complete path of the file as an input and inserts it into the tree
vector<string> Locate(string qry); // takes the file name as input and returns its path in the vector, returns empty vector if file not found
// Lowest Common Ancestor
string LComAc(string qry1, string qry2); // takes two filenames as an input and returns the name of lowest common ancestor, returns empty string if none exists
TreeItem *getHead(); // returns the root of the tree
int countFiles(); // returns the total count of the files in the system
/*You can add additional functions if necessary*/
vector<string> parsePath(string item);
TreeItem * searchRecursive(TreeItem *node, string item);
int countRecursive(TreeItem *node);
};
#endif
|
#pragma once
#include "singletonBase.h"
class enemyManager : public singletonBase <enemyManager>
{
private:
//boss _boss;
public:
HRESULT init();
void release();
enemyManager() {}
~enemyManager() {}
};
|
// ------------------------------------------------------------------------------------------------
// File name: PdbInspectorDlg.cpp
// Author: Marc Ochsenmeier
// Email: info@winitor.net
// Web: www.winitor.net -
// Updated: 27.06.2013
//
// Description: An MFC UI Application (PDB Inspector.exe) that consumes our PdbParser.dll
// to inspect the content of PDB files.
//
// ------------------------------------------------------------------------------------------------
#include "stdafx.h"
#include "PdbParser.h"
using namespace PdbParser;
#include "PdbInspector.h"
#include "PdbInspectorDlg.h"
#include "PdbInspectorAbout.h"
#include "afxcmn.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// ------------------------------------------------------------------------------------------------
// UI Messages
// ------------------------------------------------------------------------------------------------
const wchar_t* UI_TEXT_BUTTON_CLOSE = L"Close";
const wchar_t* UI_TEXT_BUTTON_LOAD = L"Load";
const wchar_t* UI_TEXT_NO_FILE_LOADED = L"No file loaded";
const wchar_t* UI_TEXT_NO_MODULE_FOUND = L"No module found";
const wchar_t* UI_TEXT_SELECT_MODULE = L"Please select a file in the Modules list";
const wchar_t* UI_TEXT_CANNOT_LOAD_FILE = L"Cannot load '%s'";
const wchar_t* UI_TEXT_MODULES = L"Modules";
const wchar_t* UI_TEXT_SOURCES = L"Source files";
const wchar_t* UI_TEXT_NO_PDB_FILE_LOADED = L"...";
const wchar_t* UI_TEXT_STRIPPED_SYMBOLS = L"Public symbols are available";
const wchar_t* UI_TEXT_UNSTRIPPED_SYMBOLS = L"Public and private symbols are available";
const wchar_t* UI_TEXT_DOTS = L"...";
const wchar_t* UI_TEXT_CHECKSUM_TYPE_NONE = L"None";
const wchar_t* UI_TEXT_CHECKSUM_TYPE_MD5 = L"MD5";
const wchar_t* UI_TEXT_CHECKSUM_TYPE_SHA1 = L"SHA1";
const wchar_t* UI_TEXT_CHECKSUM_TYPE_UNKNOWN = L"Unknown";
// ------------------------------------------------------------------------------------------------
// PdbInspectorDlg dialog
// ------------------------------------------------------------------------------------------------
PdbInspectorDlg::PdbInspectorDlg(CWnd* pParent /*=NULL*/)
: CDialog(PdbInspectorDlg::IDD, pParent)
{
m_pIPdbParser = NULL;
m_pIPdbfile = NULL;
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
PdbInspectorDlg::~PdbInspectorDlg()
{
// Shutdown our PDB parser engine
IPdbParserFactory::Destroy();
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void PdbInspectorDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_STATIC_PDB_GUID, m_sPdbGuid);
DDX_Text(pDX, IDC_STATIC_STRIPPED, m_sStrippedMsg);
DDX_Control(pDX, IDC_TREE_PDB, m_treeModules);
DDX_Control(pDX, IDC_BTN_PDB_LOAD, m_btnLoadPdbFile);
DDX_Control(pDX, IDC_LIST_SOURCES, m_listSources);
DDX_Control(pDX, IDC_STATIC_STRIPPED_ICO, m_staticStippedIcon);
DDX_Text(pDX, IDC_STATIC_GROUP_MODULES, m_sModules);
DDX_Text(pDX, IDC_STATIC_GROOUP_SOURCES, m_sSources);
DDX_Text(pDX, IDC_STATIC_COMPILER_NAME, m_compilerName);
DDX_Text(pDX, IDC_STATIC_BUILD_NBR, m_buildNbr);
DDX_Text(pDX, IDC_STATIC_CHECKSUM_TYPE, m_checksumType);
DDX_Text(pDX, IDC_STATIC_CHECKSUM_VALUE, m_checksumValue);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(PdbInspectorDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_BTN_PDB_LOAD, &OnBnClickedBtnPdbLoad)
ON_NOTIFY(TVN_SELCHANGED, IDC_TREE_PDB, &OnTreeModuleSelectionChanged)
ON_WM_DROPFILES()
ON_LBN_SELCHANGE(IDC_LIST_SOURCES, &OnSourceFileChanged)
END_MESSAGE_MAP()
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
BOOL PdbInspectorDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
// This Dialog accepts Drag and drop
DragAcceptFiles();
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// Instantiate our PDB parser engine
m_pIPdbParser = IPdbParserFactory::Create();
// Enable the Load button only when the PDB engine has been successfully started.
m_btnLoadPdbFile.EnableWindow(m_pIPdbParser?TRUE:FALSE);
InitControls();
return TRUE; // return TRUE unless you set the focus to a control
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void PdbInspectorDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
PdbInspectorAbout dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void PdbInspectorDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
HCURSOR PdbInspectorDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void PdbInspectorDlg::OnBnClickedBtnPdbLoad()
{
if( m_pIPdbfile )
{
InitControls();
m_pIPdbfile = NULL;
}
else
{
CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY , L"PDB file (*.pdb)|*.pdb", this, 0, TRUE);
if( dlg.DoModal()==IDOK )
{
if( LoadPdbFile( dlg.GetPathName()) )
{
m_btnLoadPdbFile.SetWindowText( UI_TEXT_BUTTON_CLOSE );
}
else
{
InitControls();
}
}
}
UpdateData( false);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void PdbInspectorDlg::InitControls()
{
// Tree
m_treeModules.DeleteAllItems();
m_treeModules.InsertItem( UI_TEXT_NO_FILE_LOADED );
// other controls
m_listSources.ResetContent();
m_listSources.AddString( UI_TEXT_NO_FILE_LOADED );
m_sStrippedMsg = "";
m_sPdbGuid = UI_TEXT_NO_PDB_FILE_LOADED;
m_sModules = UI_TEXT_MODULES;
m_sSources = UI_TEXT_SOURCES;
m_compilerName = UI_TEXT_DOTS;
m_buildNbr = UI_TEXT_DOTS;
m_checksumType = UI_TEXT_DOTS;
m_checksumValue = UI_TEXT_DOTS;
m_btnLoadPdbFile.SetWindowText( UI_TEXT_BUTTON_LOAD );
m_staticStippedIcon.ShowWindow( SW_HIDE );
UpdateData( false );
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
bool PdbInspectorDlg::LoadPdbFile( const CString& sPdbFile )
{
bool bRet = false;
try
{
if( m_pIPdbParser )
{
m_pIPdbfile = m_pIPdbParser->OpenFile((wstring)sPdbFile);
if( m_pIPdbfile )
{
m_treeModules.DeleteAllItems();
bRet = true;
// Root
HTREEITEM hItemRoot = m_treeModules.InsertItem( sPdbFile );
// Retrieve the file GUID
LPOLESTR lpGuid = NULL;
HRESULT hr = StringFromCLSID( m_pIPdbfile->GetGuid(), &lpGuid );
if( hr==S_OK )
{
m_sPdbGuid = lpGuid;
CoTaskMemFree(lpGuid);
}
// Check whether the PDB file has been stripped.
bool bStripped = m_pIPdbfile->IsStripped();
// Init Sources list message
m_listSources.ResetContent();
m_listSources.AddString( UI_TEXT_SELECT_MODULE );
// Update UI consequently
m_staticStippedIcon.ShowWindow(SW_NORMAL);
m_staticStippedIcon.UpdateWindow();
HICON hIcon = ::LoadIcon(
AfxGetApp()->m_hInstance,
bStripped?MAKEINTRESOURCE(IDI_ICON_RED):MAKEINTRESOURCE(IDI_ICON_GREEN));
CRect rect;
m_staticStippedIcon.GetClientRect(&rect);
CDC* pDC = m_staticStippedIcon.GetDC();
DrawIcon(pDC->m_hDC, rect.left, rect.top,hIcon);
ReleaseDC(pDC);
m_sStrippedMsg = bStripped?UI_TEXT_STRIPPED_SYMBOLS:UI_TEXT_UNSTRIPPED_SYMBOLS;
// Retrieve the Modules.
vector<IPdbModule*> vModules = m_pIPdbfile->GetModules();
if( vModules.size() )
{
// Show number of Compilands.
CString s;
s.Format(L" %i", vModules.size());
m_sModules = UI_TEXT_MODULES + s;
// Populate UI with the Compilands.
vector<IPdbModule*>::iterator it = vModules.begin();
for( ;it!=vModules.end();it++)
{
IPdbModule* module = *it;
HTREEITEM hItem = m_treeModules.InsertItem( module->GetName().c_str(), hItemRoot );
m_treeModules.SetItemData( hItem, (DWORD_PTR) module);
}
m_treeModules.Expand(hItemRoot, TVE_EXPAND);
}
else
{
m_treeModules.InsertItem( UI_TEXT_NO_MODULE_FOUND, hItemRoot );
m_treeModules.Expand( hItemRoot, TVE_EXPAND );
}
}
else
{
// File cannot be loaded!
CString sMsg;
sMsg.Format( UI_TEXT_CANNOT_LOAD_FILE, sPdbFile);
MessageBox( sMsg, L"Error", MB_ICONERROR);
}
UpdateData( false );
}
}
catch(...)
{
bRet = false;
}
return bRet;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void PdbInspectorDlg::ShowModuleSources( IPdbModule* module )
{
// Clear some UI elements
m_listSources.ResetContent();
m_listSources.AddString( UI_TEXT_SELECT_MODULE );
m_checksumType = UI_TEXT_DOTS;
m_checksumValue = UI_TEXT_DOTS;
UpdateData( false );
if( m_pIPdbfile && module )
{
std::vector< IPdbSourceFile* > vectorSources = module->GetSourceFiles();
size_t iSize = vectorSources.size();
if( iSize )
{
// Show their numbers
CString sNbr;
sNbr.Format( L" %i", vectorSources.size() );
m_sSources = UI_TEXT_SOURCES + sNbr;
}
// Clear Sources UI before adding items
m_listSources.ResetContent();
int iPos = 0;
std::vector<IPdbSourceFile*>::iterator it = vectorSources.begin();
for( ;it!=vectorSources.end(); it++)
{
IPdbSourceFile* source = *it;
m_listSources.InsertString( iPos, source->GetSourceFileName().c_str() );
// Populate list of sources
m_listSources.SetItemDataPtr( iPos, (void*)source );
}
// Show first item in the Sources list
if( m_listSources.GetCount()>0 )
{
m_listSources.SetCurSel( 0 );
OnSourceFileChanged();
}
}
UpdateData( false );
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void PdbInspectorDlg::OnTreeModuleSelectionChanged(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
// TODO: Add your control notification handler code here
HTREEITEM hItem = m_treeModules.GetSelectedItem();
IPdbModule* module = (IPdbModule*)m_treeModules.GetItemData(hItem);
if( module )
{
// Retrieve the Module's details
IPdbModuleDetails* details = module->GetModuleDetails();
if( details )
{
std::wstring s = details->GetCompilerName();
m_buildNbr = details->GetBackEndBuildNumber().c_str();
//PdbTargetCPU cpu = details->GetTargetCPU();
m_compilerName = s.c_str();
UpdateData( false );
}
// Show the source of the selected module
ShowModuleSources( module );
}
else
{
m_listSources.ResetContent();
m_listSources.AddString( UI_TEXT_SELECT_MODULE );
m_sSources = UI_TEXT_SOURCES;
UpdateData( false );
}
*pResult = 0;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void PdbInspectorDlg::OnDropFiles(HDROP hDropInfo)
{
// Retrieve the files dropped
vector<CString> vFiles;
int nFiles = ::DragQueryFile(hDropInfo, (UINT)-1, NULL, 0);
for( int i=0; i<nFiles; i++)
{
// Test whether file(s) or directory has been dropped!
CString s;
LPTSTR pFileName = s.GetBufferSetLength(_MAX_PATH);
::DragQueryFile(hDropInfo, i, pFileName, _MAX_PATH);
vFiles.push_back(s);
s.ReleaseBuffer();
}
::DragFinish(hDropInfo);
if( vFiles.size()>0)
{
// Open the first (valid) file
for( int i=0; i<nFiles; i++)
{
CString sFilePath = vFiles.at(i);
if( IsFileValid(sFilePath)==true )
{
if( LoadPdbFile( sFilePath) )
{
m_btnLoadPdbFile.SetWindowText( UI_TEXT_BUTTON_CLOSE );
}
else
{
InitControls();
}
UpdateData( false );
break;
}
}
}
// Default processing.
CDialog::OnDropFiles(hDropInfo);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void PdbInspectorDlg::OnSourceFileChanged()
{
m_checksumType = UI_TEXT_DOTS;
m_checksumValue = UI_TEXT_DOTS;
UpdateData( false );
int iSel = m_listSources.GetCurSel();
if( iSel != -1 )
{
wchar_t buffer[ _MAX_PATH ] = { 0 };
int size = m_listSources.GetText( iSel, (LPTSTR) &buffer );
if( size!=0 )
{
std::wstring entry;
entry.assign( buffer, size );
IPdbSourceFile* source = (IPdbSourceFile*)m_listSources.GetItemDataPtr( iSel );
if( source )
{
wstring file = source->GetSourceFileName();
//m_sSourceUID.Format( L"%i", source->GetUniqueId() );
// Get CheckSum
BYTE buffer[ _MAX_PATH ] = { 0 };
DWORD size = sizeof(buffer);
CheckSumType type = source->GetCheckSumType();
switch( type )
{
case CheckSumType_None:
m_checksumType = UI_TEXT_CHECKSUM_TYPE_NONE;
break;
case CheckSumType_MD5:
m_checksumType = UI_TEXT_CHECKSUM_TYPE_MD5;
break;
case CheckSumType_SHA1:
m_checksumType = UI_TEXT_CHECKSUM_TYPE_SHA1;
break;
default:
m_checksumType = UI_TEXT_CHECKSUM_TYPE_UNKNOWN;
break;
}
const char* p = source->GetCheckSum();
if( p )
{
m_checksumValue = p;
}
else
{
//m_checksumValue =
}
UpdateData( false );
}
}
}
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
bool PdbInspectorDlg::IsFileValid( const CString& file )
{
bool bRet = true;
return bRet;
}
|
// Aldvm: Ethereum C++ client, tools and libraries.
// Copyright 2014-2019 Aldvm Authors.
// Licensed under the GNU General Public License, Version 3.
#pragma once
#include <libdvm/VMFace.h>
#include <string>
#include <utility>
#include <vector>
namespace dev
{
namespace dvm
{
/// The wrapper implementing the VMFace interface with a DVMC VM as a backend.
class DVMC : public dvmc::VM, public VMFace
{
public:
DVMC(dvmc_vm* _vm, std::vector<std::pair<std::string, std::string>> const& _options) noexcept;
owning_bytes_ref exec(u256& io_gas, ExtVMFace& _ext, OnOpFunc const& _onOp) final;
};
} // namespace dvm
} // namespace dev
|
//
// GnITabButton.cpp
// Core
//
// Created by Max Yoon on 11. 7. 25..
// Copyright 2011년 __MyCompanyName__. All rights reserved.
//
#include "GnGamePCH.h"
#include "GnITabButton.h"
#include "GnITabPage.h"
GnITabButton::GnITabButton(GnITabPage* pTabPage, const gchar* pcDefaultImage, const gchar* pcClickImage
, const gchar* pcDisableImage, eButtonType eDefaultType) : GnIButton( pcDefaultImage, pcClickImage
, pcDisableImage, eDefaultType ), mpTabPage( pTabPage )
{
}
GnITabButton::~GnITabButton()
{
}
bool GnITabButton::PushUp(float fPointX, float fPointY)
{
return false;
}
bool GnITabButton::PushMove(float fPointX, float fPointY)
{
return false;
}
void GnITabButton::Push()
{
GnIButton::Push();
SubPushCount();
mpTabPage->SetIsVisible( true );
}
void GnITabButton::PushUp()
{
GnIButton::PushUp();
mpTabPage->SetIsVisible( false );
}
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool arr1[1000002];
ll i,j,co=0,arr[1000002],a,num,s=1000001,c,arr2[1000006],d,l;
void sive(){
for(i=3;i<=sqrt(s);i+=2){
if(!arr1[i])
for(j=3*i;j<=s;j+=2*i){
arr1[j]=1;
}
}
c=1;
arr[c++]=2;
for(i=3;i<=s;i+=2){
if(!arr1[i]){
arr[c++]=i;
}
}
co=0;
for(i=2;i<=1000001;i++){
l=0;
if((i%2==1 && !arr1[i]) || i==2)arr2[i]=++co;
else{
d=i;
for(j=1;j<=c;j++){
while(d%arr[j]==0){
d=d/arr[j];
co++;
if((!arr1[d] && d%2==1) || d==2){
co++;
l=1;
}
if(d==1 || l==1)break;
}
if(d==1 || l==1)break;
}
arr2[i]=co;
l=0;
}
}
}
int main(){
sive();
while(scanf("%lld",&a)!=EOF){
cout<<arr2[a]<<endl;
}
return 0;
}
|
#ifndef __mir_mobile__FlutteringFairy__
#define __mir_mobile__FlutteringFairy__
#include "publicDef/PublicDef.h"
typedef enum {
TypeAddExp,
TypeAddBlood,
TypeSubBlood,
TypeSubMagic
}FairyType;
class FlutteringFairy: public Node {
CC_SYNTHESIZE_READONLY(Node*, m_fairy, Fairy);
void initWithFairy(FlutteringFairy *fairy ,FairyType type, int value, Ref* target, SEL_CallFunc callfunc);
public:
FlutteringFairy();
virtual ~FlutteringFairy();
static FlutteringFairy* addFairy(Node* parent, Point point, FairyType type, int value, Ref* target, SEL_CallFunc callfunc);
virtual const Size& getContentSize() const;
};
#endif /* defined(__mir_mobile__FlutteringFairy__) */
|
#pragma once
#include <iberbar/RHI/Texture.h>
#include <iberbar/RHI/D3D9/Headers.h>
namespace iberbar
{
namespace RHI
{
namespace D3D9
{
class CDevice;
class __iberbarD3DApi__ CTexture
: public ITexture
{
public:
CTexture( CDevice* pDevice );
virtual ~CTexture();
public:
virtual CResult CreateEmpty( int w, int h ) override;
virtual CResult CreateFromFileInMemory( const void* pData, uint32 nDataSize ) override;
virtual CResult CreateFromFileA( const char* strFile ) override;
virtual CResult CreateFromFileW( const wchar_t* strFile ) override;
virtual CResult CreateFromPixels( int w, int h, void* pixels ) override;
virtual CResult SetPixels( const void* pixels, int nx, int ny, int nw, int nh ) override;
virtual CResult SaveToFileA( const char* strFile ) override;
virtual CResult SaveToFileW( const wchar_t* strFile ) override;
public:
inline IDirect3DTexture9* GetD3DTexture() { return m_pD3DTexture; }
protected:
CDevice* m_pDevice;
IDirect3DTexture9* m_pD3DTexture;
};
}
}
}
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "Marranconi.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Marranconi, "Marranconi" );
DEFINE_LOG_CATEGORY(LogMarranconi)
|
/**
* Copyright (c) 2015, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include "config.h"
#include "shlex.hh"
using namespace std;
const char* ST_TOKEN_NAMES[] = {
"eof",
"wsp",
"esc",
"dst",
"den",
"sst",
"sen",
"ref",
"qrf",
"til",
};
static void
put_underline(FILE* file, string_fragment frag)
{
for (int lpc = 0; lpc < frag.sf_end; lpc++) {
if (lpc == frag.sf_begin) {
fputc('^', stdout);
} else if (lpc == (frag.sf_end - 1)) {
fputc('^', stdout);
} else if (lpc > frag.sf_begin) {
fputc('-', stdout);
} else {
fputc(' ', stdout);
}
}
}
int
main(int argc, char* argv[])
{
if (argc < 2) {
fprintf(stderr, "error: expecting an argument to parse\n");
exit(EXIT_FAILURE);
}
shlex lexer(argv[1], strlen(argv[1]));
bool done = false;
printf(" %s\n", argv[1]);
while (!done) {
auto tokenize_res = lexer.tokenize();
if (tokenize_res.isErr()) {
auto te = tokenize_res.unwrapErr();
printf("err ");
put_underline(stdout, te.te_source);
printf(" -- %s\n", te.te_msg);
break;
}
auto tr = tokenize_res.unwrap();
if (tr.tr_token == shlex_token_t::eof) {
done = true;
}
printf("%s ", ST_TOKEN_NAMES[(int) tr.tr_token]);
put_underline(stdout, tr.tr_frag);
printf("\n");
}
lexer.reset();
std::string result;
std::map<std::string, scoped_value_t> vars;
if (lexer.eval(result, scoped_resolver{&vars})) {
printf("eval -- %s\n", result.c_str());
}
lexer.reset();
auto split_res = lexer.split(scoped_resolver{&vars});
if (split_res.isOk()) {
auto sresult = split_res.unwrap();
printf("split:\n");
for (size_t lpc = 0; lpc < sresult.size(); lpc++) {
printf("% 3zu ", lpc);
put_underline(stdout, sresult[lpc].se_origin);
printf(" -- %s\n", sresult[lpc].se_value.c_str());
}
}
return EXIT_SUCCESS;
}
|
/*////////////////////////////////////////////////////////////////////////////////////
display module for the renderer
////////////////////////////////////////////////////////////////////////////////////*/
#include<stdio.h>
#include "inc\essentials.h"
//---------------------models------------------------------
extern PLYObject *model;
//---------------------------------------------------------
//------external variables for the shader------------------------------
extern GLuint vertexLoc, colorLoc,normalLoc;
extern GLuint projMatrixLoc, viewMatrixLoc, cLoc, LightPosLoc, LightDifLoc, LightAmbLoc, LightSpecLoc, eyeLoc;
extern GLuint ProgramID,VertexID,FragmentID;
//---------------------------------------------------------------------
//-----------global variables for setting up the scene-----------------
static const double TwoPi = 2.0 * 3.1415926;
double theta = 0;
double phi = 0;//TwoPi/4;
double dist = 8.00;
double znear = 5.0;
double zfar = 20.0;
double zoom=0.0;
double alpha=0.0;
Vec3 eye;
Vec3 origin( 0, 0, 0 );
Vec3 up( 1, 1,0 );//default up vector specified by user
double L_theta = 0.2, L_phi = 1.6, L_dist = 2.0, shininess = 30;
float projMatrix[16];// storage for Matrices
float viewMatrix[16];// storage for Matrices
float LightPosition[4];
float DiffuseLight[4], AmbientLight[4], SpecularLight[4];
extern int Width,Height;
extern unsigned int FrameCount;
extern int MODE;
//-----------------------------------------------------------------------
//--------Vertex and Index buffers for rendering-------------------------
GLuint VertexBuffer, IndexBuffer,NormalBuffer;
// Vertex Array Objects Identifiers
GLuint VAO;
//-----------------------------------------------------------------------
//---------routines for setting up view-----------------------------------
void setIdentityMatrix( float *mat, int size) {
for (int i = 0; i < size * size; ++i)mat[i] = 0.0f;
for (int i = 0; i < size; ++i) mat[i + i * size] = 1.0f;
}
void setIdentityMatrix4x4( float *mat) {
int size=4;
for (int i = 0; i < size * size; ++i) mat[i] = 0.0f;
for (int i = 0; i < size; ++i) mat[i + i * size] = 1.0f;
}
void multMatrix(float *a, float *b) {
float res[16];
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
res[j*4 + i] = 0.0f;
for (int k = 0; k < 4; ++k) {
res[j*4 + i] += a[k*4 + i] * b[j*4 + k];
}
}
}
memcpy(a, res, 16 * sizeof(float));
}
// Defines a transformation matrix mat with a translation
void setTranslationMatrix(float *mat, float x, float y, float z) {
setIdentityMatrix(mat,4);
mat[12] = x;
mat[13] = y;
mat[14] = z;
}
// ----------------------------------------------------
// Projection Matrix
//
void buildProjectionMatrix(float fov, float ratio, float nr, float fr) {
double f = 1.0f / tan (fov * (TwoPi / 720.0));
setIdentityMatrix(projMatrix,4);
projMatrix[0] = float(f) / ratio;
projMatrix[1 * 4 + 1] = float(f);
projMatrix[2 * 4 + 2] = (fr + nr) / (nr - fr);
projMatrix[3 * 4 + 2] = (2.0f * fr * nr) / (nr - fr);
projMatrix[2 * 4 + 3] = -1.0f;
projMatrix[3 * 4 + 3] = 0.0f;
}
// ----------------------------------------------------
// View Matrix
//
//
void setCamera() {
Vec3 dir(Unit(origin-eye));
Vec3 right(Unit(dir^up));
up=Unit(right^dir);
float aux[16];
viewMatrix[0] = float(right.x);
viewMatrix[4] = float(right.y);
viewMatrix[8] = float(right.z);
viewMatrix[12] = 0.0f;
viewMatrix[1] = float(up.x);
viewMatrix[5] = float(up.y);
viewMatrix[9] = float(up.z);
viewMatrix[13] = 0.0f;
viewMatrix[2] = float(-dir.x);
viewMatrix[6] = float(-dir.y);
viewMatrix[10] = float(-dir.z);
viewMatrix[14] = 0.0f;
viewMatrix[3] = 0.0f;
viewMatrix[7] = 0.0f;
viewMatrix[11] = 0.0f;
viewMatrix[15] = 1.0f;
setTranslationMatrix(aux, float(-eye.x), float(-eye.y), float(-eye.z));
multMatrix(viewMatrix, aux);
//set the projection matrix
double d(1-zoom);
setIdentityMatrix4x4(projMatrix);
projMatrix[0]=float(1/d);
projMatrix[5]=float(1/d);
projMatrix[10]=float(-2/(zfar-znear));
projMatrix[14]=float(-(zfar+znear)/(zfar-znear));
}
// ----------------------------------------------------
void changeSize(int w, int h) {
Width=w;Height=h;
float ratio;
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
ratio = (1.0f * w) / h;
buildProjectionMatrix(53.13f, ratio, 1.0f, 30.0f);
}
void setupBuffers() {
glGenVertexArrays(1,&VAO);
glBindVertexArray(VAO);
// Generate two slots for the vertex and color buffers
glGenBuffers(1, &VertexBuffer);
// bind buffer for vertices and copy data into buffer
glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);
glBufferData(GL_ARRAY_BUFFER, 3*model->nv*sizeof(float), model->vrt.getVertices(), GL_STATIC_DRAW);
glEnableVertexAttribArray(vertexLoc);
glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, 0, 0, 0);
glGenBuffers(1, &NormalBuffer);
glBindBuffer(GL_ARRAY_BUFFER, NormalBuffer);
glBufferData(GL_ARRAY_BUFFER, 3*model->nv*sizeof(float), model->vrt.getNormals(), GL_STATIC_DRAW);
glEnableVertexAttribArray(normalLoc);
glVertexAttribPointer(normalLoc, 3, GL_FLOAT, 0, 0, 0);
glGenBuffers(1, &IndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 3*model->nf*sizeof(int), model->fac.getIndices(), GL_DYNAMIC_DRAW);
glBindVertexArray(0);
GLenum ErrorCheckValue = glGetError();
ErrorCheckValue = glGetError();
if (ErrorCheckValue != GL_NO_ERROR)
{
fprintf(
stderr,
"ERROR: Could not create a VBO: %s \n",
gluErrorString(ErrorCheckValue)
);
exit(-1);
}
}
void setLighting(void)
{
DiffuseLight[0] = 0.6; DiffuseLight[1] = 0.6;DiffuseLight[2] = 0.6;DiffuseLight[3] = 1.0;
AmbientLight[0]= 0.2;AmbientLight[1]= 0.2;AmbientLight[2]= 0.2;AmbientLight[3]= 1.0;
SpecularLight[0]= 1.0;SpecularLight[1]= 1.0;SpecularLight[2]= 1.0;SpecularLight[3]= 1.0;
Vec3 lgt( cos( L_theta ) * cos( L_phi ), sin( L_theta ) * cos( L_phi ), sin( L_phi ) );
//printf("%f %f %f\n",cos( L_theta ) * cos( L_phi ), sin( L_theta ) * cos( L_phi ), sin( L_phi ) );
Vec3 LP=L_dist * lgt;
LightPosition[0]=LP.x; //set the LightPosition to the specified values
LightPosition[1]=LP.y;
LightPosition[2]=LP.z;
//Vec3 LP=L_dist * eye;
//LightPosition[0]=-LP.x; //set the LightPosition to the specified values
//LightPosition[1]=-LP.y;
///LightPosition[2]=-LP.z;
LightPosition[3]=0;
}
void display(void) {
++FrameCount;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
eye=Vec3( dist * cos( theta ) * (cos( phi )), dist * sin( theta ) * (cos( phi )), dist * sin( phi ) );
setCamera();
setLighting();
//setCamera();
float EYE[]={eye.x,eye.y,eye.z};
glUseProgram(ProgramID);
glUniformMatrix4fv(projMatrixLoc, 1, false, projMatrix);
glUniformMatrix4fv(viewMatrixLoc, 1, false, viewMatrix);
glUniform4fv(LightPosLoc, 1, LightPosition);
glUniform4fv(LightDifLoc, 1, DiffuseLight);
glUniform4fv(LightAmbLoc, 1, AmbientLight);
glUniform4fv(LightSpecLoc, 1, SpecularLight);
glUniform3fv(eyeLoc, 1, EYE);
glBindVertexArray(VAO);
if(MODE==0){
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glDrawElements(GL_TRIANGLES,3*model->nf,GL_UNSIGNED_INT,(GLvoid*)0);
}
else if(MODE==1){
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glDrawElements(GL_TRIANGLES,3*model->nf,GL_UNSIGNED_INT,(GLvoid*)0);
}
else if(MODE==2){
glUniform3f(cLoc,0,0,0);
glDrawElements(GL_POINTS,3*model->nf,GL_UNSIGNED_INT,(GLvoid*)0);
}
glutSwapBuffers();
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* Copyright (C) 2008-2012 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef OPNS4PLUGIN_ADAPTER_H
#define OPNS4PLUGIN_ADAPTER_H
#include "modules/pi/OpPluginWindow.h"
#include "modules/ns4plugins/src/plugincommon.h"
#include "modules/ns4plugins/src/plug-inc/npapi.h"
#include "modules/ns4plugins/opns4plugin.h"
class VisualDevice;
/** @short Plug-in adapter for a Netscape 4 plug-in instance
*
* This class deals with the platform specific part of the Netscape 4 plug-in
* API. It will not interact directly with the plug-in library; it will however
* be passed the OpPluginWindow, NPWindow and NPPrint objects associated with
* the plug-in.
*
* In a more perfect world, the Netscape 4 plug-in API would actually be clean
* and without any platform-specific hacks, and as such there would be no need
* for this class.
*
* An instance of this class is created earlier than the OpPluginWindow (since
* it may provide information that affects creation of the OpPluginWindow). As
* soon as the OpPluginWindow has been created, it is passed to this class by
* calling SetPluginWindow().
*/
class OpNS4PluginAdapter
{
public:
/** Create an OpNS4PluginAdapter object.
*
* @param new_object (out) Set to the new object created.
* @param component_type (in) Component type of the plugin.
*/
static OP_STATUS Create(OpNS4PluginAdapter** new_object, OpComponentType component_type);
virtual ~OpNS4PluginAdapter() {}
/** Set the plug-in window.
*
* Should be called as soon as possible when the OpPluginWindow is created,
* and only once.
*
* @param plugin_window The OpPluginWindow associated with this
* plug-in. May not be NULL. It is guaranteed to be valid at least until
* this OpNS4PluginAdapter is deleted.
*/
virtual void SetPluginWindow(OpPluginWindow* plugin_window) = 0;
/** Set the visual device.
*
* Should be called as soon as possible when the OpPluginWindow is created,
* and only once. Used to "blitimage" on wingogi and getting view and painter on windows
*
* @param visual_device The visual device associated with this
* plug-in. May not be NULL. It is guaranteed to be valid at least until
* this OpNS4PluginAdapter is deleted.
*/
virtual void SetVisualDevice(VisualDevice* visual_device) = 0;
/** @short Get value from browser to be passed to plug-in.
*
* This method is called from NPN_GetValue(NPP, NPNVariable, void*). The
* implementation of this method should set values and return TRUE for as
* few variables as possible, as _most_ of this can be dealt with by core
* in a cross-platform manner.
*
* Most notably, the NPNVnetscapeWindow and NPNVSupportsWindowless
* variables should probably be implemented on the platform side.
*
* @param variable Variable to get. Same as the second parameter passed to
* NPN_GetValue().
* @param value (out) Destination address for the value. Data type depends
* entirely on what 'variable' is. Same as the third parameter passed to
* NPN_GetValue().
* @param result (out) Set to NPERR_NO_ERROR if everything went well. Refer
* to the plug-in spec for other possible values.
*
* @return TRUE if a value was set and core should pass this value to the
* plug-in. Set to FALSE if core should set the value on its own (and
* disregard the value of 'value' and 'result')
*/
virtual BOOL GetValue(NPNVariable variable, void* value, NPError* result) = 0;
/** @short Get value from browser to be passed to plug-in.
*
* This method is called from NPN_GetValue(NPP, NPNVariable, void*) if
* NPP argument is null. The implementation of this method should set values
* and return TRUE for as few variables as possible, as _most_ of this can
* be dealt with by core in a cross-platform manner.
*
* @param variable Variable to get. Same as the second parameter passed to
* NPN_GetValue().
* @param value (out) Destination address for the value. Data type depends
* entirely on what 'variable' is. Same as the third parameter passed to
* NPN_GetValue().
* @param result (out) Set to NPERR_NO_ERROR if everything went well. Refer
* to the plug-in spec for other possible values.
*
* @return TRUE if a value was set and core should pass this value to the
* plug-in. Set to FALSE if core should set the value on its own (and
* disregard the value of 'value' and 'result')
*/
static BOOL GetValueStatic(NPNVariable variable, void* value, NPError* result);
/** @short Set value by plug-in.
*
* This method is called from NPN_SetValue(NPP, NPPVariable, void*). The
* implementation of this method should set values and return TRUE for as
* few variables as possible, as _most_ of this can be dealt with by core
* in a cross-platform manner.
*
* @param variable Variable to set. Same as the second parameter passed to
* NPN_SetValue().
* @param value (in) The value of the specified variable to be set.
* Data type depends entirely on what 'variable' is. Same as the third
* parameter passed to NPN_SetValue().
* @param result (out) Set to NPERR_NO_ERROR if everything went well. Refer
* to the plug-in spec for other possible values.
*
* @return TRUE if a value was set and core should pass this value to the
* plug-in. Set to FALSE if core should set the value on its own (and
* disregard the value of 'value' and 'result')
*/
virtual BOOL SetValue(NPPVariable variable, void* value, NPError* result) = 0;
/** @short Convert platform specific region to NPRect.
*
* This method is used from NPN_InvalidateRegion to convert platform
* specific region to coordinates used for invalidating plugin area.
*
* Different platforms use different region types.
* See https://developer.mozilla.org/en/NPRegion for more details.
*
* @param invalidRegion Platform specific region. The area to invalidate,
* specified in a coordinate system that originates at the top left of the plug-in.
* @param[in,out] invalidRect NPRect whose coordinates are set on
* successful conversion.
*
* @return TRUE if region was converted to coordinates. FALSE otherwise.
*/
virtual BOOL ConvertPlatformRegionToRect(NPRegion invalidRegion, NPRect &invalidRect) = 0;
/** Prepare an NPWindow for a call to NPP_SetWindow().
*
* Calling this method before an OpPluginWindow has been set is pointless.
*
* @param[in,out] npwin NPWindow that will be passed in the
* NPP_SetWindow() call.
* @param rect Rectangle of plug-in window. Coordinates are relative to the
* to the upper left corner of the parent OpView. Dimensions (width and
* height) signify the size of the plug-in.
* @param paint_rect is the rectangle specifying what part of the plugin relative
* to the rendering viewport should be painted. Coordinates are scaled.
* @param view_rect is the rectangle of the plugin window (in scaled coordinates)
* relative to the parent OpView. The top-left corner of this rectangle has
* a different value than rect if the plugin is inside an iframe. The platform
* implementation can use this rectangle e.g. if the plugin window is painted
* off-screen. It then can blit the plugin's content to this rectangle.
* @param view_offset Offset of OpView relative to screen.
* @param show Whether to show/hide the plugin window.
* @param transparent Indicates whether windowless plugin is transparent or opaque.
*
* @return OK if successful, ERR_NO_MEMORY on OOM, ERR for other errors
*/
virtual OP_STATUS SetupNPWindow(NPWindow* npwin, const OpRect& rect, const OpRect& paint_rect, const OpRect& view_rect, const OpPoint& view_offset, BOOL show, BOOL transparent) = 0;
/** Prepare an NPPrint for a call to NPP_Print().
*
* Calling this method before an OpPluginWindow has been set is pointless.
*
* @param[in,out] npprint NPPrint that will be passed in the NPP_Print()
* call.
* @param rect Rectangle of plug-in window. Coordinates are relative to the
* to the upper left corner of the parent OpView. Dimensions (width and
* height) signify the size of the plug-in.
*
* @return OK if successful, ERR_NO_MEMORY on OOM, ERR for other errors
*/
virtual OP_STATUS SetupNPPrint(NPPrint* npprint, const OpRect& rect) = 0;
/** Save state before a synchronous call to the plug-in.
*
* This is an opportunity for the platform to save the state before a
* synchronous call is made to the plug-in. The information saved here can
* then be restored in RestoreState(), which will be called right after the
* synchronous plug-in call. Most platforms will probably do nothing here.
*
* @param event_type The type of event associated with the imminent call to
* the plug-in.
*/
virtual void SaveState(OpPluginEventType event_type) = 0;
/** Restore state after a synchronous call to the plug-in.
*
* This is an opportunity for the platform to restore the state after a
* synchronous call has been made to the plug-in. The information saved in
* SaveState() can then be restored in here. Most platforms will probably
* do nothing here.
*
* @param event_type The type of event associated with the call to the
* plug-in that just took place.
*/
virtual void RestoreState(OpPluginEventType event_type) = 0;
/** Give platform possibility to modify parameters passed to the plug-in.
* This method will be called right before NPP_New for each plugin instance.
*
* If platform modifies parameters without adding/removing any it should set:
* *new_args8 = NULL; *new_argc=0;
*
* @param[in] plugin plug-in interface
* @param[in,out] args8 array of plugin parameters,
* first argc pointers are names and remaining argc are values.
* @param[in] argc number of parameters (there are 2*argc strings - names and values)
* @param[out] new_args8 new plugin parameters or NULL
* @param[out] new_argc number of new parameters (there will be 2*new_argc strings in new_args8) or 0
* @return OK if successful, ERR_NO_MEMORY on OOM, ERR for other errors
*/
virtual OP_STATUS ModifyParameters(OpNS4Plugin* plugin, char** args8, int argc, char*** new_args8, int* new_argc) { *new_args8 = NULL; *new_argc = 0; return OpStatus::OK; }
#ifdef NS4P_COMPONENT_PLUGINS
/**
* Give platform possibility to block loading of a plug-in based on its filename/path.
*
* For example, on Linux if the plug-in file is a symlink, the platform can call
* realpath() and then run g_pcapp->IsPluginToBeIgnored() on the final filename.
* @param[in] plugin_filepath full path to a plug-in
* @return true if the plug-in should be ignored, false if the plug-in may load
*/
static bool IsBlacklistedFilename(UniString plugin_filepath);
/** Retrieve a channel for this adapter instance.
*
* The channel must remain constant for the lifetime of this object, and
* should, for OOM reasons, be allocated when constructing this object,
* such that this method becomes a simple accessor.
*
* This channel, if returned, will receive messages from platform code
* residing in the plug-in component. This allows typed platform-specific
* exchanges to occur between the plug-in component and the browser
* component without involving Core.
*
* The address of the channel will be supplied to OpPluginTranslator
* (in the plug-in component) on creation.
*
* @return Pointer to OpChannel, or NULL if none is available. NULL must not
* indicate OOM. Any potentially failing action should take place as
* part of the construction of this object.
*/
virtual OpChannel* GetChannel() { return NULL; }
/** Inform the platform that the plugin sent an IME Start request.
*
* Implement this if plugins in your system provide IME feedback.
*/
virtual void StartIME() { }
/** Return \c true if the platforms IME input is active.
*
* Implement if you are using the StartIME function above.
*
* @return \c true if the IME is active, otherwise \c false.
*/
virtual bool IsIMEActive() { return false; }
/** Inform the platform that the plugin sent a focus event.
*
* While the IME is active, your platform may need to be informed that
* the focus of the plugin has changed. You can update IME properties here,
* if required.
*
* @param focus \c True when the plugin receives focus, otherwise \c false.
* @param reason Reason for the focus.
*/
virtual void NotifyFocusEvent(bool focus, FOCUS_REASON reason) { }
#endif // NS4P_COMPONENT_PLUGINS
};
#endif // OPNS4PLUGIN_ADAPTER_H
|
#pragma once
class DxccCountryManager;
bool CheckDxccCountry(string arg, DxccCountryManager *dxccCountryManager);
|
// Created on: 1995-07-24
// Created by: Modelistation
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StdPrs_Plane_HeaderFile
#define _StdPrs_Plane_HeaderFile
#include <Prs3d_Root.hxx>
#include <Prs3d_Drawer.hxx>
class Adaptor3d_Surface;
//! A framework to display infinite planes.
class StdPrs_Plane : public Prs3d_Root
{
public:
DEFINE_STANDARD_ALLOC
//! Defines display of infinite planes.
//! The infinite plane aPlane is added to the display
//! aPresentation, and the attributes of the display are
//! defined by the attribute manager aDrawer.
Standard_EXPORT static void Add (const Handle(Prs3d_Presentation)& aPresentation, const Adaptor3d_Surface& aPlane, const Handle(Prs3d_Drawer)& aDrawer);
//! returns true if the distance between the point (X,Y,Z) and the
//! plane is less than aDistance.
Standard_EXPORT static Standard_Boolean Match (const Standard_Real X, const Standard_Real Y, const Standard_Real Z, const Standard_Real aDistance, const Adaptor3d_Surface& aPlane, const Handle(Prs3d_Drawer)& aDrawer);
};
#endif // _StdPrs_Plane_HeaderFile
|
#ifndef QITEMD_HPP
#define QITEMD_HPP
#include <QObject>
class QItemD : public QObject
{
Q_OBJECT
Q_SLOT
void go();
};
#endif
|
#pragma once
#include "../IO.h"
#include <iberbar/Utility/MsgQueue.h>
#include <iberbar/Utility/String.h>
namespace iberbar
{
namespace IO
{
class CSocketClient_UseLibevent;
// string 使用 polymorphic_allocator 分配器
typedef std::basic_string<char, std::char_traits<char>, std::pmr::polymorphic_allocator<char> > IOString;
#define IOStringFormat( buffer, format, ... ) StringFormat<char,std::pmr::polymorphic_allocator<char>>( buffer, format, __VA_ARGS__ );
#define IOStringFormatVa( buffer, format, va ) StringFormatVa<char,std::pmr::polymorphic_allocator<char>>( buffer, format, va );
// scoket
struct USocketWriteMsg
{
USocketWriteMsg()
: pSocketClient( nullptr )
, Data()
{
}
USocketWriteMsg( CSocketClient_UseLibevent* pClient, const std::pmr::polymorphic_allocator<char>& AL )
: pSocketClient( pClient )
, Data( AL )
{
}
USocketWriteMsg( const USocketWriteMsg& Msg )
: pSocketClient( Msg.pSocketClient )
, Data( Msg.Data )
{
}
CSocketClient_UseLibevent* pSocketClient;
IOString Data;
};
// IO消息队列,调度
// 线程安全
class CMsgQueue
{
public:
typedef TMsgQueue<USocketWriteMsg, std::pmr::polymorphic_allocator<USocketWriteMsg>> _SocketQueue;
public:
CMsgQueue( std::pmr::memory_resource* pMemoryRes );
_SocketQueue* GetQueue_SocketWrite() { return &m_Queue_SocketWrite; }
_SocketQueue* GetQueue_SocketRead() { return &m_Queue_SocketRead; }
private:
_SocketQueue m_Queue_SocketWrite;
_SocketQueue m_Queue_SocketRead;
};
extern CMsgQueue* g_pMsgQueues;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "modules/widgets/OpMonthView.h"
#include "modules/widgets/OpDateTime.h"
#ifdef PLATFORM_FONTSWITCHING
#include "modules/display/fontdb.h"
#endif // PLATFORM_FONTSWITCHING
#include "modules/widgets/OpEdit.h"
#include "modules/widgets/OpTime.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/display/vis_dev.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/viewers/viewers.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#include "modules/widgets/OpCalendar.h"
// == OpDateTime ===========================================================
DEFINE_CONSTRUCT(OpDateTime)
OpDateTime::OpDateTime() :
m_calendar(NULL),
m_time(NULL),
m_timezone_field(NULL),
m_has_min_value(FALSE),
m_has_max_value(FALSE),
m_has_step(FALSE),
m_include_timezone(FALSE)
{
OP_STATUS status;
status = OpCalendar::Construct(&m_calendar);
CHECK_STATUS(status);
AddChild(m_calendar, TRUE);
status = OpTime::Construct(&m_time);
CHECK_STATUS(status);
AddChild(m_time, TRUE);
m_calendar->SetTabStop(TRUE);
m_time->SetTabStop(TRUE);
// This might be deleted in SetIncludeTimezone, fixme: create on demand instead
status = OpEdit::Construct(&m_timezone_field);
CHECK_STATUS(status);
AddChild(m_timezone_field, TRUE);
m_timezone_field->SetText(UNI_L("UTC"));
m_timezone_field->SetFlatMode();
m_timezone_field->SetHasCssBorder(TRUE);
m_timezone_field->SetHasCssBackground(TRUE);
m_timezone_field->SetEnabled(FALSE);
m_time->SetListener(this);
m_calendar->SetListener(this);
}
OpDateTime::~OpDateTime()
{
}
/**
* This is called to refill the widget after reflow or history movement.
*/
OP_STATUS OpDateTime::SetText(const uni_char* text)
{
DateTimeSpec date_time;
if (!text || !*text)
{
RETURN_IF_ERROR(m_calendar->SetText(text));
return m_time->SetText(text);
}
else if (!date_time.SetFromISO8601String(text, m_include_timezone))
{
return OpStatus::ERR;
}
return SetValue(date_time);
}
OP_STATUS OpDateTime::SetValue(DateTimeSpec date_time)
{
OP_STATUS status;
status = m_calendar->SetValue(date_time.m_date);
if (OpStatus::IsSuccess(status))
{
status = m_time->SetValue(date_time.m_time);
}
UpdateMinMaxStepForTime();
return status;
}
/* virtual */
void OpDateTime::GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows)
{
INT32 date_w;
INT32 dummy_h;
m_calendar->GetPreferedSize(&date_w, &dummy_h, 0, 0);
INT32 time_w;
m_time->GetPreferedSize(&time_w, &dummy_h, 0, 0);
INT32 timezone_w = GetTimezoneWidth();
// margin of 2 pixels
*w = date_w + 2 + time_w + 2 + timezone_w;
}
void OpDateTime::SetMinValue(DateTimeSpec new_min)
{
if (!m_has_min_value || new_min.AsDouble() != m_min_value.AsDouble())
{
m_has_min_value = TRUE;
m_min_value = new_min;
m_calendar->SetMinValue(new_min.m_date);
UpdateMinMaxStepForTime();
}
}
void OpDateTime::SetMaxValue(DateTimeSpec new_max)
{
if (!m_has_max_value || new_max.AsDouble() != m_max_value.AsDouble())
{
m_has_max_value = TRUE;
m_max_value = new_max;
m_calendar->SetMaxValue(new_max.m_date);
UpdateMinMaxStepForTime();
}
}
void OpDateTime::SetStep(double step_base, double step)
{
if (!m_has_step || step_base != m_step_base || m_step != step)
{
m_has_step = TRUE;
m_step_base = step_base;
m_step = step;
// We have values in milliseconds and the calendar need values in days.
m_calendar->SetStep(step_base/86400000.0, step/86400000.0);
UpdateMinMaxStepForTime();
}
}
void OpDateTime::SetTimeStepForSpecificDate(DaySpec date)
{
// Convert the step to the timewidget by moving the step_base.
double date_in_ms = date.AsDouble()*86400000.0;
double distance_from_step_base_to_date = date_in_ms - m_step_base;
int steps = static_cast<int>(op_ceil(distance_from_step_base_to_date/m_step));
double time_step_base_double = steps*m_step + m_step_base - date_in_ms;
OP_ASSERT(time_step_base_double >= 0.0);
if (time_step_base_double >= 86400000.0)
{
// No values available this day. Should disable the time or something
m_time->ClearStep();
return;
}
OP_ASSERT(time_step_base_double < 86400000.0);
int time_step_base_int = static_cast<int>(time_step_base_double); // Don't want to round in case we end up on the next day
TimeSpec time_step_base;
time_step_base.Clear();
time_step_base.SetFromNumber(time_step_base_int, 1000);
m_time->SetStepMS(time_step_base, m_step);
}
void OpDateTime::UpdateMinMaxStepForTime()
{
if (m_calendar->HasValue())
{
DaySpec date = m_calendar->GetDaySpec();
TimeSpec min_time;
min_time.Clear(); // Midnight as min value if nothing else said
if (m_has_min_value && date.AsDouble() == m_min_value.m_date.AsDouble())
{
min_time = m_min_value.m_time;
}
m_time->SetMinValue(min_time);
TimeSpec max_time;
max_time.Clear();
max_time.SetFromNumber(86399999, 1000); // Midnight as max value if nothing else said
if (m_has_max_value && date.AsDouble() == m_max_value.m_date.AsDouble())
{
max_time = m_max_value.m_time;
}
m_time->SetMaxValue(max_time);
if (m_has_step && m_step > 0.0)
{
SetTimeStepForSpecificDate(date);
}
else
{
m_time->ClearStep();
}
}
else if (m_has_max_value && m_has_min_value &&
m_min_value.m_date.AsDouble() == m_max_value.m_date.AsDouble())
{
m_time->SetMinValue(m_min_value.m_time);
m_time->SetMaxValue(m_max_value.m_time);
SetTimeStepForSpecificDate(m_min_value.m_date);
}
else
{
TimeSpec min_time;
min_time.Clear(); // Midnight as min value if nothing else said
m_time->SetMinValue(min_time);
TimeSpec max_time;
max_time.Clear();
max_time.SetFromNumber(86399999, 1000); // Midnight as max value if nothing else said
m_time->SetMaxValue(max_time);
if (m_has_step &&
m_step > 0.0 &&
86400000.0 / m_step == static_cast<int>(86400000.0/m_step))
{
// Same step every day
DaySpec dummy_day = { 2000, 0, 1 };
SetTimeStepForSpecificDate(dummy_day);
}
else
{
m_time->ClearStep();
}
}
}
OP_STATUS OpDateTime::GetText(OpString &str)
{
// XXX Ever used?
OP_ASSERT(FALSE); // Remove this function?
if (m_calendar->HasValue())
{
DaySpec date = m_calendar->GetDaySpec();
uni_char* buf = str.Reserve(date.GetISO8601StringLength()+1);
if (!buf)
{
return OpStatus::ERR_NO_MEMORY;
}
date.ToISO8601String(buf);
OP_STATUS status = str.Append("T");
if (OpStatus::IsError(status))
{
return status;
}
}
TimeSpec time;
if (m_time->HasValue() && m_time->GetTime(time))
{
OpString time_string;
uni_char* buf = time_string.Reserve(time.GetISO8601StringLength()+1);
if (!buf)
{
return OpStatus::ERR_NO_MEMORY;
}
time.ToISO8601String(buf);
OP_STATUS status = str.Append(time_string);
if (OpStatus::IsError(status))
{
return status;
}
status = str.Append("Z"); // Timezone
if (OpStatus::IsError(status))
{
return status;
}
}
return OpStatus::OK;
}
void OpDateTime::SetReadOnly(BOOL readonly)
{
m_time->SetReadOnly(readonly);
m_calendar->SetReadOnly(readonly);
}
INT32 OpDateTime::GetTimezoneWidth() const
{
UINT32 width;
if (m_include_timezone)
{
// Guessing. Not very good. And I hope VisualDevice has the correct font set.
int border_padding_overhead = 6;
width = GetVisualDevice()->GetFontStringWidth(UNI_L("UTC"), 3) + border_padding_overhead;
}
else
{
width = 0;
}
return width;
}
void OpDateTime::OnResize(INT32* new_w, INT32* new_h)
{
INT32 time_w;
INT32 time_h;
m_time->GetPreferedSize(&time_w, &time_h, 0, 0); // dummy cols and rows
int max_time_w = 3 * *new_w / 5;
if (time_w > max_time_w) // if it's more than 3/5 of the available size, we restrict it to 3/5.
time_w = max_time_w;
INT32 timezone_width = GetTimezoneWidth();
int max_tz_width = 3 * (*new_w - time_w) / 5;
if (timezone_width > max_tz_width)
{
timezone_width = max_tz_width;
}
int calendar_width = *new_w - time_w - 2 - timezone_width - 2;
m_calendar->SetRect(OpRect(0, 0, calendar_width, *new_h));
// 2 pixel margin between the blocks
m_time->SetRect(OpRect(calendar_width+2, 0, time_w, *new_h));
if (m_timezone_field)
{
m_timezone_field->SetRect(OpRect(calendar_width + 2 + time_w + 2, 0, timezone_width, *new_h));
}
}
void OpDateTime::EndChangeProperties()
{
m_calendar->BeginChangeProperties();
m_time->BeginChangeProperties();
// propagate background color to edit field
if (!m_color.use_default_background_color)
{
m_calendar->SetBackgroundColor(m_color.background_color);
m_time->SetBackgroundColor(m_color.background_color);
}
m_calendar->SetHasCssBorder(HasCssBorder());
m_time->SetHasCssBorder(HasCssBorder());
m_time->EndChangeProperties();
m_calendar->EndChangeProperties();
}
void OpDateTime::OnFocus(BOOL focus, FOCUS_REASON reason)
{
if (focus)
{
m_calendar->SetFocus(reason);
}
// We look different with and without focus so we need to repaint ourselves.
Invalidate(GetBounds());
}
BOOL OpDateTime::HasValue() const
{
return m_calendar->HasValue() || m_time->HasValue();
}
void OpDateTime::OnChange(OpWidget *widget, BOOL changed_by_mouse /*= FALSE */)
{
if (widget == m_time || widget == m_calendar)
{
BOOL has_date = m_calendar->HasValue();
BOOL has_time = m_time->HasValue();
if (widget == m_calendar)
{
if (has_date)
{
if (!has_time)
{
TimeSpec t;
t.Clear();
t.m_hour = 12; // Default time
DateTimeSpec dt;
dt.m_date = m_calendar->GetDaySpec();
dt.m_time = t;
if (m_has_min_value && dt.IsBefore(m_min_value))
{
t = m_min_value.m_time;
}
else if (m_has_max_value && dt.IsAfter(m_max_value))
{
t = m_max_value.m_time;
}
m_time->SetValue(t);
}
}
else
{
if (has_time)
{
m_time->SetText(NULL);
}
}
UpdateMinMaxStepForTime();
}
else
{
OP_ASSERT(widget == m_time);
if (has_date)
{
if (!has_time)
{
m_calendar->SetText(NULL);
}
}
else
{
if (has_time)
{
TimeSpec current_written_time;
#ifdef DEBUG_ENABLE_OPASSERT
BOOL ok_time =
#endif // DEBUG_ENABLE_OPASSERT
m_time->GetTime(current_written_time);
OP_ASSERT(ok_time); // The time widget shouldn't allow malformed times.
DaySpec min_allowed_day_for_time = { 1973, 0, 15 }; // XXX
DaySpec max_allowed_day_for_time = { 2020, 4, 5 }; // XXX
if (m_has_min_value)
{
if (m_min_value.m_time.IsBefore(current_written_time))
{
min_allowed_day_for_time = m_min_value.m_date;
}
else
{
min_allowed_day_for_time = m_min_value.m_date.NextDay();
}
}
if (m_has_max_value)
{
if (m_max_value.m_time.IsAfter(current_written_time))
{
max_allowed_day_for_time = m_min_value.m_date;
}
else
{
max_allowed_day_for_time = m_min_value.m_date.PrevDay();
}
}
if (max_allowed_day_for_time.IsBefore(min_allowed_day_for_time))
{
// This time isn't allowed any day.
m_time->SetText(NULL); // Clear it
}
else
{
DaySpec d = OpMonthView::GetToday();
if (d.IsBefore(min_allowed_day_for_time))
{
d = min_allowed_day_for_time;
}
else if (d.IsAfter(max_allowed_day_for_time))
{
d = max_allowed_day_for_time;
}
m_calendar->SetValue(d);
}
}
}
}
if (listener)
{
listener->OnChange(this, FALSE);
}
}
}
BOOL OpDateTime::GetDateTime(DateTimeSpec& out_value) const
{
if (m_calendar->HasValue() && m_time->HasValue())
{
out_value.m_timezone.Clear();
out_value.m_date = m_calendar->GetDaySpec();
return m_time->GetTime(out_value.m_time);
}
return FALSE;
}
void OpDateTime::SetIncludeTimezone(BOOL val)
{
if (val != m_include_timezone)
{
m_include_timezone = val;
if (val && !m_timezone_field)
{
OP_STATUS status = OpEdit::Construct(&m_timezone_field);
if (OpStatus::IsSuccess(status))
{
AddChild(m_timezone_field, TRUE);
}
else
{
OP_ASSERT(FALSE);
}
}
else if (!val && m_timezone_field)
{
m_timezone_field->Remove();
OP_DELETE(m_timezone_field);
m_timezone_field = NULL;
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2008 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "modules/viewers/viewers.h"
ViewersModule::ViewersModule(void) :
viewer_list(0)
#if defined(_PLUGIN_SUPPORT_)
, plugin_viewer_list(0)
#endif
{
}
ViewersModule::~ViewersModule(void)
{
}
void ViewersModule::InitL(const OperaInitInfo&)
{
viewer_list = OP_NEW_L(Viewers, ());
viewer_list->ConstructL();
#ifdef _PLUGIN_SUPPORT_
plugin_viewer_list = OP_NEW_L(PluginViewers, ());
plugin_viewer_list->ConstructL();
#endif
}
void ViewersModule::Destroy(void)
{
OP_DELETE(viewer_list);
viewer_list = 0;
#ifdef _PLUGIN_SUPPORT_
OP_DELETE(plugin_viewer_list);
plugin_viewer_list = 0;
#endif // _PLUGIN_SUPPORT_
}
|
//
// main.cpp
// TOH - Tower of Hanoi
//
// Created by Sivaprasad Tamatam on 20/09/20.
//
#include <iostream>
using namespace std;
void TOH(int n, int A, int B, int C){
if(n>0){
TOH(n-1, A, C, B);
cout<<A<<" "<<C<<endl;
TOH(n-1, B, A, C);
}
}
int main(int argc, const char * argv[]) {
cout<<"From"<<" "<<"TO"<<endl;
TOH(3,1,2,3);
return 0;
}
|
/*!
* @copyright GNU General Public License (GNU GPL)
*
* @brief Implementação da classe mãe "mkl_TPM".
*
* @file mkl_TPM.cpp
* @version 1.0
* @date 02 Agosto 2017
*
* @section HARDWARES & SOFTWARES
* +board FRDM-KL25Z da NXP.
* +processor MKL25Z128VLK4 - ARM Cortex-M0+.
* +compiler Kinetis® Design Studio IDE.
* +manual L25P80M48SF0RM, Rev.3, September 2012.
* +revisions Versão (data): Descrição breve.
* ++ 1.0 (02 Agosto 2017): Versão inicial.
*
* @section AUTHORS & DEVELOPERS
* +institution Universidade Federal do Amazonas.
* +courses Engenharia da Computação / Engenharia Elétrica.
* +teacher Miguel Grimm <miguelgrimm@gmail.com>
* +student Versão inicial:
* ++ Hamilton Nascimento <hdan_neto@hotmail.com>
*
* @section LICENSE
*
* GNU General Public License (GNU GPL).
*
* Este programa é um software livre; Você pode redistribuí-lo
* e/ou modificá-lo de acordo com os termos do "GNU General Public
* License" como publicado pela Free Software Foundation; Seja a
* versão 3 da licença, ou qualquer versão posterior.
*
* Este programa é distribuído na esperança de que seja útil,
* mas SEM QUALQUER GARANTIA; Sem a garantia implícita de
* COMERCIALIZAÇÃO OU USO PARA UM DETERMINADO PROPÓSITO.
* Veja o site da "GNU General Public License" para mais detalhes.
*
* @htmlonly http://www.gnu.org/copyleft/gpl.html
*/
#include "mkl_TPM.h"
/*!
* @fn bindPeripheral
*
* @brief Associa o objeto de software ao periférico de hardware.
*
* Este método associa ao objeto de software o periférico de hardware,
* utilizando a inicialização dos ponteiros para os endereços de memória
* dos registradores correspondentes.
*
* @param[in] baseAddress - o endereço base do periférico TPM.
*
* @remarks Sigla e pagina do Manual de Referencia KL25:
* - TPMxSC: Status Control Register. Pág. 552.
* - TPMxCNT: Counter Register. Pág.554.
* - TPMxMOD: Modulo Register. Pág. 554.
*/
void mkl_TPM::bindPeripheral(uint8_t *baseAddress) {
addressTPMxSC = (volatile uint32_t *)(baseAddress);
addressTPMxCNT = (volatile uint32_t *)(baseAddress + 0x4);
addressTPMxMOD = (volatile uint32_t *)(baseAddress + 0x8);
}
/*!
* @fn bindChannel
*
* @brief Associa o canal do objeto de software ao hardware
*
* Este método associa os atributos do canal do objeto de software ao
* seu correspondente do periférico hardware.
*
* @param[in] baseAddress - o endereço base do periférico TPM.
* chnNumber - o número do canal do periférico TPM.
*
* @remarks Sigla e pagina do Manual de Referencia KL25:
* - TPMxCnV: Channel Value Register. Pág.557.
* - TPMxCnSC: Channel Status Control Register. Pág.555.
*/
void mkl_TPM::bindChannel(uint8_t *baseAddress,
uint8_t chnNumber) {
addressTPMxCnV = (volatile uint32_t *)(baseAddress + 0x10 + 8*chnNumber);
addressTPMxCnSC = (volatile uint32_t *)(baseAddress + 0xC + 8*chnNumber);
}
/*!
* @fn bindPin
*
* @brief Associa o pino do objeto ao periférico de hardare.
*
* Este método associa o pino do objeto de software ao pino do periférico.
*
* @param[in] pinNumber - o número do pino do objeto de software.
*
* @remarks Sigla e pagina do Manual de Referencia KL25:
* - PCR: Pin Control Register. Pág.183.
*/
void mkl_TPM::bindPin(uint8_t GPIONumber, uint8_t pinNumber) {
addressPortxPCRn = (volatile uint32_t *)(0x40049000
+ 0x1000*GPIONumber + 4*pinNumber);
}
/*!
* @fn enablePeripheralClock
*
* @brief Habilita o clock do periférico de hardware.
*
* Este método habilita o clock do periférico TPM solicitado.
*
* @remarks Sigla e pagina do Manual de Referencia KL25:
* - SCGC6: System Control Gating Clock Register 6. Pág.207.
* - SOPT2: System Options Register 2. Pág.195.
*/
void mkl_TPM::enablePeripheralClock(uint8_t TPMNumber) {
SIM_SCGC6 |= SIM_SCGC6_TPM0_MASK << TPMNumber;
SIM_SOPT2 |= SIM_SOPT2_TPMSRC(1);
}
/*!
* @fn enableGPIOClock
*
* @brief Habilita o clock do GPIO do pino.
*
* Este método habilita o clock do periférico GPIO do pino passado por
* parâmetro.
*
* @param[in] GPIONumber - o número do GPIO correspondente ao pino.
*
* @remarks Sigla e pagina do Manual de Referencia KL25:
* - SCGC5: System Control Gating Clock Register 5. Pág.199.
*/
void mkl_TPM::enableGPIOClock(uint8_t GPIONumber) {
SIM_SCGC5 |= SIM_SCGC5_PORTA_MASK << GPIONumber;
}
/*!
* @fn selectMuxAlternative
*
* @brief Seleciona a alternativa de trabalho do pino.
*
* Este método seleciona o modo de operação do pino correspondente para o
* modo de operação TPM.
*
* @param[in] muxAlt - alternativa de operação do pino para o canal e TPM
* especificados.
*
* @remarks Sigla e pagina do Manual de Referencia KL25:
* - PCR: Pin Control Register. Pág.183.
*/
void mkl_TPM::selectMuxAlternative(uint8_t muxAlt) {
*addressPortxPCRn = PORT_PCR_MUX(muxAlt);
}
/*!
* @fn setTPMParameters
*
* @brief Ajusta os parâmetros do TPM.
*
* Este método ajusta os parâmetros do TPM (números de pino, GPIO,
* canal, TPM) e a máscara de seleção do mux, de acordo com o membro
* da enum passado no construtor da classe filha.
*
* @param[in] pin - pino passado para o construtor da classe filha.
* pinNumber - número do pino.
* GPIONumber - número do GPIO.
* chnNumber - número do canal.
* TPMNumber - número do TPM.
* muxAltMask - máscara de seleção do mux.
*/
void mkl_TPM::setTPMParameters(tpm_Pin pin, uint8_t &pinNumber,
uint8_t &GPIONumber, uint8_t &chnNumber,
uint8_t &TPMNumber, uint8_t &muxAltMask) {
pinNumber = pin & 0x1F;
GPIONumber = (pin >> 5) & 0x7;
chnNumber = (pin >> 8) & 0x7;
TPMNumber = (pin >> 11) & 0x3;
muxAltMask = (pin >> 13) & 0x7;
}
/*!
* @fn setBaseAddress
*
* @brief Ajusta o endereço base do TPM.
*
* Este método ajusta o endereço base do TPM a partir do número do
* TPM.
*
* @param[in] TPMNumber - número do TPM.
* baseAddress - ponteiro para o endereço base do TPM.
*/
void mkl_TPM::setBaseAddress (uint8_t TPMNumber, uint8_t **baseAddress) {
*baseAddress = (uint8_t *)(TPM0_BASE + 0x1000*TPMNumber);
}
|
/*
* Copyright (C) 2013 Tom Wong. All rights reserved.
*/
#include "gtuserserver.h"
#include <QtArg/Arg>
#include <QtArg/CmdLine>
#include <QtArg/Help>
#include <QtCore/QCoreApplication>
using namespace Gather;
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QtArgCmdLine cmd(app.arguments());
QtArg argHost(QLatin1Char('i'),
QLatin1String("host"),
QLatin1String("Server host"),
false, true);
QtArg argPort(QLatin1Char('p'),
QLatin1String("port"),
QLatin1String("Server port (default 8701)"),
false, true);
QtArg argThread(QLatin1Char('t'),
QLatin1String("thread"),
QLatin1String("Max thread count"),
false, true);
cmd.addArg(argHost);
cmd.addArg(argPort);
cmd.addArg(argThread);
QtArgHelp help(&cmd);
help.printer()->setProgramDescription(QLatin1String("Gather user server."));
help.printer()->setExecutableName(QLatin1String(argv[0]));
cmd.addArg(help);
try {
cmd.parse();
}
catch (const QtArgHelpHasPrintedEx &x)\
{
return 0;
}
catch (const QtArgBaseException &x)
{
qDebug() << x.what();
return -1;
}
GtUserServer server;
QHostAddress host(QHostAddress::AnyIPv4);
quint16 port = argPort.value().isNull() ?
8701 : argPort.value().toInt();
if (!argHost.value().isNull())
host.setAddress(argHost.value().toString());
if (!argThread.value().isNull())
server.setMaxThread(argThread.value().toInt());
if (!server.listen(host, port)) {
qWarning() << "listen failed:" << host << port;
return -1;
}
return app.exec();
}
|
/***********************************************************
Starter code for Assignment 3
This code was originally written by Jack Wang for
CSC418, SPRING 2005
Implementations of functions in raytracer.h,
and the main function which specifies the
scene to be rendered.
***********************************************************/
#include "raytracer.h"
#include "bmp_io.h"
#include <cmath>
#include <iostream>
#include <cstdlib>
Raytracer::Raytracer() : _lightSource(NULL) {
_root = new SceneDagNode();
}
Raytracer::~Raytracer() {
delete _root;
}
SceneDagNode* Raytracer::addObject( SceneDagNode* parent,
SceneObject* obj, Material* mat ) {
SceneDagNode* node = new SceneDagNode( obj, mat );
node->parent = parent;
node->next = NULL;
node->child = NULL;
// Add the object to the parent's child list, this means
// whatever transformation applied to the parent will also
// be applied to the child.
if (parent->child == NULL) {
parent->child = node;
}
else {
parent = parent->child;
while (parent->next != NULL) {
parent = parent->next;
}
parent->next = node;
}
return node;;
}
LightListNode* Raytracer::addLightSource( LightSource* light ) {
LightListNode* tmp = _lightSource;
_lightSource = new LightListNode( light, tmp );
return _lightSource;
}
void Raytracer::rotate( SceneDagNode* node, char axis, double angle ) {
Matrix4x4 rotation;
double toRadian = 2*M_PI/360.0;
int i;
for (i = 0; i < 2; i++) {
switch(axis) {
case 'x':
rotation[0][0] = 1;
rotation[1][1] = cos(angle*toRadian);
rotation[1][2] = -sin(angle*toRadian);
rotation[2][1] = sin(angle*toRadian);
rotation[2][2] = cos(angle*toRadian);
rotation[3][3] = 1;
break;
case 'y':
rotation[0][0] = cos(angle*toRadian);
rotation[0][2] = sin(angle*toRadian);
rotation[1][1] = 1;
rotation[2][0] = -sin(angle*toRadian);
rotation[2][2] = cos(angle*toRadian);
rotation[3][3] = 1;
break;
case 'z':
rotation[0][0] = cos(angle*toRadian);
rotation[0][1] = -sin(angle*toRadian);
rotation[1][0] = sin(angle*toRadian);
rotation[1][1] = cos(angle*toRadian);
rotation[2][2] = 1;
rotation[3][3] = 1;
break;
}
if (i == 0) {
node->trans = node->trans*rotation;
angle = -angle;
}
else {
node->invtrans = rotation*node->invtrans;
}
}
}
void Raytracer::translate( SceneDagNode* node, Vector3D trans ) {
Matrix4x4 translation;
translation[0][3] = trans[0];
translation[1][3] = trans[1];
translation[2][3] = trans[2];
node->trans = node->trans*translation;
translation[0][3] = -trans[0];
translation[1][3] = -trans[1];
translation[2][3] = -trans[2];
node->invtrans = translation*node->invtrans;
}
void Raytracer::scale( SceneDagNode* node, Point3D origin, double factor[3] ) {
Matrix4x4 scale;
scale[0][0] = factor[0];
scale[0][3] = origin[0] - factor[0] * origin[0];
scale[1][1] = factor[1];
scale[1][3] = origin[1] - factor[1] * origin[1];
scale[2][2] = factor[2];
scale[2][3] = origin[2] - factor[2] * origin[2];
node->trans = node->trans*scale;
scale[0][0] = 1/factor[0];
scale[0][3] = origin[0] - 1/factor[0] * origin[0];
scale[1][1] = 1/factor[1];
scale[1][3] = origin[1] - 1/factor[1] * origin[1];
scale[2][2] = 1/factor[2];
scale[2][3] = origin[2] - 1/factor[2] * origin[2];
node->invtrans = scale*node->invtrans;
}
Matrix4x4 Raytracer::initInvViewMatrix( Point3D eye, Vector3D view,
Vector3D up ) {
Matrix4x4 mat;
Vector3D w;
view.normalize();
up = up - up.dot(view)*view;
up.normalize();
w = view.cross(up);
mat[0][0] = w[0];
mat[1][0] = w[1];
mat[2][0] = w[2];
mat[0][1] = up[0];
mat[1][1] = up[1];
mat[2][1] = up[2];
mat[0][2] = -view[0];
mat[1][2] = -view[1];
mat[2][2] = -view[2];
mat[0][3] = eye[0];
mat[1][3] = eye[1];
mat[2][3] = eye[2];
return mat;
}
void Raytracer::traverseScene( SceneDagNode* node, Ray3D& ray ) {
traverseScene(node,ray,_modelToWorld,_worldToModel);
}
void Raytracer::traverseScene( SceneDagNode* node, Ray3D& ray, const Matrix4x4& modelToWorld, const Matrix4x4& worldToModel ) {
SceneDagNode *childPtr;
// Applies transformation of the current node to the global
// transformation matrices.
Matrix4x4 myModelToWorld = modelToWorld*node->trans;
Matrix4x4 myWorldToModel = node->invtrans*worldToModel;
if (node->obj) {
// Perform intersection.
// Note that we pass the ray in WORLD COORDINATES at the moment
if (node->obj->intersect(ray, myWorldToModel, myModelToWorld)) {
ray.intersection.mat = node->mat;
}
}
// Traverse the children.
childPtr = node->child;
while (childPtr != NULL) {
traverseScene(childPtr, ray, myModelToWorld,myWorldToModel);
childPtr = childPtr->next;
}
}
void Raytracer::computeShading( Ray3D& ray ) {
// >> New
Colour totalCol = Colour(0.0,0.0,0.0);
LightListNode* curLight = _lightSource;
for (;;) {
if (curLight == NULL) break;
// std::cout << "Pos light " << curLight->light->get_id() << " X: " << curLight->light->get_position()[0] << " Y: " << curLight->light->get_position()[1] << " Z: " << curLight->light->get_position()[2] << "\n";
Vector3D lti = curLight->light->get_position() - ray.intersection.point;
lti.normalize();
Point3D ip = ray.intersection.point + 0.001 * lti;
Ray3D lightToIntersection = Ray3D(ip, lti);
traverseScene(_root, lightToIntersection);
if(lightToIntersection.intersection.none == false && lightToIntersection.intersection.shape.compare(ray.intersection.shape) != 0) {
curLight->light->shade(ray, 1.0);
}
else {
// std::cout << "light: " << curLight->light->get_id() << "\n";
curLight->light->shade(ray, 1.0);
}
totalCol = totalCol + ray.col;
curLight = curLight->next;
}
if (_numlights != 0) {
ray.col = (1.0/_numlights) * totalCol; // Get the average colour
}
else {
ray.col = totalCol;
}
}
void Raytracer::initPixelBuffer() {
int numbytes = _scrWidth * _scrHeight * sizeof(unsigned char);
_rbuffer = new unsigned char[numbytes];
_gbuffer = new unsigned char[numbytes];
_bbuffer = new unsigned char[numbytes];
for (int i = 0; i < _scrHeight; i++) {
for (int j = 0; j < _scrWidth; j++) {
_rbuffer[i*_scrWidth+j] = 0;
_gbuffer[i*_scrWidth+j] = 0;
_bbuffer[i*_scrWidth+j] = 0;
}
}
}
void Raytracer::flushPixelBuffer( char *file_name ) {
bmp_write( file_name, _scrWidth, _scrHeight, _rbuffer, _gbuffer, _bbuffer );
delete _rbuffer;
delete _gbuffer;
delete _bbuffer;
}
// The ray is in world coordinates right now
Colour Raytracer::shadeRay( Ray3D& ray ) {
Colour currCol(0.0, 0.0, 0.0);
Colour refCol(0.0, 0.0, 0.0);
Colour totalRef(0.0,0.0,0.0);
Colour glossCol(0.0, 0.0, 0.0);
Colour totalGloss(0.0,0.0,0.0);
Colour totalCol(0.0, 0.0, 0.0);
traverseScene(_root, ray);
// Don't bother shading if the ray didn't hit
// anything.
Vector3D incident = -1 * ray.dir; // We define incident as pointing away from intersection
incident.normalize();
double selfIntersect = ray.intersection.normal.dot(incident); // negative if self intersecting
if (!ray.intersection.none && selfIntersect > 0) {
computeShading(ray);
currCol = ray.col;
if (ray.reflectNum <= _reflecNum && _reflectionSwitch) {
// Calculate the reflected ray
// reflectedray = 2 * (normal . incident) * normal - incident
// std::cout << "direction: " << ray.intersection.normal.dot(incident) << "\n";
// Ensure that the incident and normal are pointing in the same direction;
Vector3D reflected_vector = 2 * (ray.intersection.normal.dot(incident)) * ray.intersection.normal - incident;
reflected_vector.normalize();
Point3D curr_int = ray.intersection.point + 0.001 * reflected_vector;
Ray3D reflectedRay = Ray3D(curr_int,
reflected_vector,
ray.reflectNum + 1,
ray.intersection.shape);
// std::cout << "Coeff: " << ray.intersection.mat->reflection_coeff << "\n";
// std::cout << "RN:" << ray.reflectNum << "\n";
// std::cout << "Power:" << pow(ray.intersection.mat->reflection_coeff, ray.reflectNum) << "\n\n";
refCol = shadeRay(reflectedRay);
// std::cout << "Curr Int" << ray.reflectNum << ": " << ray.intersection.shape << "\n";
// std::cout << "Next Int: " << reflectedRay.intersection.shape << "\n";
if(reflectedRay.intersection.none) { // hit nothing
// Calculate how far the the reflected ray was from the light source
// We want the reflected rays that are closer to the light source to be shaded more "phong"ly
// The ones that fire off into the distance should be dark
LightListNode* curLight = _lightSource;
Point3D clp = curLight -> light -> get_position();
Vector3D i2l = clp - curr_int;
i2l.normalize();
double dark_factor = reflected_vector.dot(i2l); // High if angle is small. Small if angle is large.
totalRef = dark_factor*currCol; // Only colour of the material that ray hit; no reflection
}
else {
// totalRef = currCol + refCol; // Display entirely the reflected stuff
// refCol = shadeRay(reflectedRay);
// totalRef = (0.4*(currCol) + 0.6*refCol);
totalRef = (0.4*currCol + 0.8* pow(ray.intersection.mat->reflection_coeff, ray.reflectNum) * refCol);
// totalRef = 0.2*currCol + 0.9*refCol;
}
}
if (ray.reflectNum <= _reflecNum && _glossSwitch) {
Vector3D reflected_vector = 2 * (ray.intersection.normal.dot(incident)) * ray.intersection.normal - incident;
reflected_vector.normalize();
Point3D curr_int = ray.intersection.point + 0.001 * reflected_vector;
Point3D ip = ray.intersection.point + 0.001 * reflected_vector;
// Generate a random vector
double randX = ((double) rand() / (RAND_MAX));
double randY = ((double) rand() / (RAND_MAX));
double randZ = ((double) rand() / (RAND_MAX));
Vector3D randoVec = Vector3D(randX, randY, randZ);
Vector3D pv_u = reflected_vector.cross(randoVec);
Vector3D pv_v = reflected_vector.cross(pv_u);
pv_u.normalize();
pv_v.normalize();
// Now we have the equations of the plane that's perpendicular to the reflected_vector
// We want to get the shading from all of these vectors and then average them
int a = 9;
for (int i = 0; i < a; i++ ) {
double jitterU = ((double) rand() / (RAND_MAX)); // from 0 to a
double jitterV = ((double) rand() / (RAND_MAX)); // from 0 to a
if (((double) rand() / (RAND_MAX)) > 0.5){ jitterU = -1 * jitterU;}
if (((double) rand() / (RAND_MAX)) > 0.5){ jitterV = -1 * jitterV;}
// std::cout<<"ju " << jitterU << "\n";
// std::cout<<"jv " << jitterV << "\n";
Vector3D jitteredVector = 2.8* reflected_vector + jitterU*pv_u + jitterV*pv_v;
jitteredVector.normalize();
Ray3D glossRay = Ray3D(ip,
jitteredVector,
ray.reflectNum + 1,
ray.intersection.shape);
glossCol = shadeRay(glossRay);
if(glossRay.intersection.none) {
LightListNode* curLight = _lightSource;
Point3D clp = curLight -> light -> get_position();
Vector3D i2l = clp - curr_int;
i2l.normalize();
double dark_factor = 0.5 + 0.5 * reflected_vector.dot(i2l)*ray.intersection.mat->gloss_coeff;
totalGloss = totalGloss + dark_factor * currCol; // Only colour of the material that ray hit; no reflection
}
else {
// std::cout << "r: " << glossCol[0] << "g: " << glossCol[1] << "b: " << glossCol[2] < "\n";
totalGloss = totalGloss + (0.8*currCol + 0.4* pow(ray.intersection.mat->gloss_coeff, ray.reflectNum) * glossCol);
// totalGloss = totalGloss + currCol;
}
}
totalGloss = (1/double(a)) * totalGloss;
}
if(!_reflectionSwitch && !_glossSwitch) {
totalCol = currCol;
}
else {
double tone_down = 1;
if (_reflectionSwitch && _glossSwitch) {
tone_down = 0.6;
}
totalCol = tone_down * (totalRef + totalGloss);
}
// std::cout << "omg: " << refCol << "\n";
}
// You'll want to call shadeRay recursively (with a different ray,
// of course) here to implement reflection/refraction effects.
totalCol.clamp();
return totalCol;
}
Colour Raytracer::shadeRay2( Ray3D& ray ) {
Colour col(0.0, 0.0, 0.0);
traverseScene(_root, ray);
// Don't bother shading if the ray didn't hit
// anything.
if (!ray.intersection.none) {
computeShading(ray);
col = ray.col;
}
return col;
}
void Raytracer::render( int width, int height, Point3D eye, Vector3D view,
Vector3D up, double fov, char* fileName, int numLights) {
Matrix4x4 viewToWorld;
_scrWidth = width;
_scrHeight = height;
_reflecNum = 2;
_numlights = numLights;
_reflectionSwitch = true;
_glossSwitch = true;
double factor = (double(height)/2)/tan(fov*M_PI/360.0);
initPixelBuffer();
viewToWorld = initInvViewMatrix(eye, view, up);
// Sets up ray origin and direction in view space,
// image plane is at z = -1.
Point3D origin(0, 0, 0);
Point3D imagePlane;
imagePlane[2] = -1;
// Construct a ray for each pixel.
for (int i = 0; i < _scrHeight; i++) {
std::cout << "Drawing row: " << i << "\n";
for (int j = 0; j < _scrWidth; j++) {
// Shoot 25 instead
// Add it to a colour object. Divide by number of rays
Colour col_tot;
for (int k = -2; k <= 2; k++) {
for (int l = -2; l<= 2; l++) {
// This gives us the x and y coordinates of the pixel we're shooting through
double jitterDirectionX = ((double) rand() / (RAND_MAX))/2.0;
double jitterDirectionY = ((double) rand() / (RAND_MAX))/2.0;
// Get rid of the 0.5 because now we use jitterDirection
imagePlane[0] = (-double(width)/2 + j + jitterDirectionX)/factor;
imagePlane[1] = (-double(height)/2 + i + jitterDirectionY)/factor;
Ray3D ray;
ray.origin = viewToWorld * origin;
ray.dir = viewToWorld * (imagePlane - origin);//Imageplane and origin?
ray.dir.normalize();
col_tot = col_tot + shadeRay(ray);
}
}
Colour col = (1.0/25.0) * col_tot; // Ray is in world coordinates right now
_rbuffer[i*width+j] = int(col[0]*255);
_gbuffer[i*width+j] = int(col[1]*255);
_bbuffer[i*width+j] = int(col[2]*255);
}
}
flushPixelBuffer(fileName);
}
int main(int argc, char* argv[])
{
// Build your scene and setup your camera here, by calling
// functions from Raytracer. The code here sets up an example
// scene and renders it from two different view points, DO NOT
// change this if you're just implementing part one of the
// assignment.
Raytracer raytracer;
bool _shadowSwitch = false;
// int width = 320; //600; //320;
// int height = 240;//450; //240;
int width = 320; //320;
int height = 150; //240;
if (argc == 3) {
width = atoi(argv[1]);
height = atoi(argv[2]);
}
// Camera parameters.
Point3D eye(0, 0, 1);
Vector3D view(0, 0, -1);
Vector3D up(0, 1, 0);
double fov = 60;
// Defines a material for shading.
Material gold( Colour(0.3, 0.3, 0.3),
Colour(0.75164, 0.60648, 0.22648),
Colour(0.628281, 0.555802, 0.366065),
70, 0.5, 0.8);
Material jade( Colour(0.3, 0.3, 0.3), Colour(0.54, 0.89, 0.63),
Colour(0.316228, 0.316228, 0.316228),
12.8, 0.6, 0.8);
Material skyblue( Colour(0.3, 0.3, 0.3),
Colour(0.0196078431, 103.0/255.0, 135.0/255.0),
Colour(0.316228, 0.316228, 0.316228),
// Colour(0.628281, 0.555802, 0.366065),
69, 0.8, 0.2);
Material slate( Colour(0.3, 0.3, 0.3),
Colour(62.0/255, 89.0/255.0, 89.0/255.0),
Colour(0.7, 0.7, 0.7),
69, 0.8, 0.2);
Material frosty( Colour (0.3, 0.3, 0.3),
Colour(123.0/255.0, 136.0/255.0, 140.0/255.0),
Colour(0.628281, 0.555802, 0.366065),
90, 0.6, 0.8);
// Defines a point light source.
double main_light_X = 0;
double main_light_Y = 0;
double main_light_Z = 3;
double toRadian = 2*M_PI/360.0;
raytracer.addLightSource( new PointLight(Point3D(main_light_X, main_light_Y, main_light_Z), Colour(0.9, 0.9, 0.9), 1));
// std::cout << "Coords: " << main_light_X << " " << main_light_Y << " " << main_light_Z << "\n";
// Define an area light source as a collection of point lights
int light_ring_num = 0;
int outer_ring_num = 0;
if (_shadowSwitch == true) {
double radius = 1.0; // From center point light to surrounding point lights
int light_ring_num = 50; // Number of lights in a ring around the center light
double angleSpacing = 360 / double(light_ring_num); // angle spacing between lights (5 lights would have 72 degrees between each light)
double currAngle = 0;
for (int i = 0; i < light_ring_num; i++) {
double currAngle = i * angleSpacing;
double sublight_X = radius * cos(currAngle * toRadian);
double sublight_Y = radius * sin(currAngle * toRadian);
// std::cout << "ILRCoords: " << sublight_X << ", " << sublight_Y << ", " << main_light_Z << "\n";
raytracer.addLightSource( new PointLight(Point3D(sublight_X, sublight_Y, main_light_Z),
Colour(0.7,0.7,0.7), i + 2) );
}
// Define moar points
radius = 1.5;
int outer_ring_num = 100;
angleSpacing = 360 / double(outer_ring_num); // angle spacing between lights (5 lights would have 72 degrees between each light)
for (int i = 0; i < outer_ring_num; i++) {
double currAngle = i * angleSpacing;
double sublight_X = radius * cos(currAngle * toRadian);
double sublight_Y = radius * sin(currAngle * toRadian);
// std::cout << "ORCoords: " << sublight_X << ", " << sublight_Y << ", " << main_light_Z << "\n";
raytracer.addLightSource( new PointLight(Point3D(sublight_X, sublight_Y, main_light_Z),
Colour(0.7,0.7,0.7), i + light_ring_num + 2) );
}
}
// Add a unit square into the scene with material mat.
// SceneDagNode* plane2 = raytracer.addObject( new UnitSquare2(), &jade );
SceneDagNode* sphere = raytracer.addObject( new UnitSphere(), &gold );
// SceneDagNode* cylinder = raytracer.addObject( new UnitCylinder(), &gold );
SceneDagNode* sphere2 = raytracer.addObject( new UnitSphere2(), &frosty);
SceneDagNode* plane = raytracer.addObject( new UnitSquare(), &skyblue );
// SceneDagNode* planeTexture = raytracer.addObject( new UnitSquareTextured(), &skyblue );
// Apply some transformations to the unit square.
double factor1[3] = { 1.0, 2.0, 1.0 };
double factor3[3] = { 0.5, 0.5, 0.5 };
double factor2[3] = { 6.0, 6.0, 6.0 };
// >> Draw Ellipsoid
raytracer.translate(sphere, Vector3D(0, 0, -5));
raytracer.rotate(sphere, 'x', -45);
raytracer.rotate(sphere, 'z', 45);
raytracer.scale(sphere, Point3D(0, 0, 0), factor1);
// >> Draw Spheres
raytracer.translate(sphere2, Vector3D(0, 3, -5));
// >> Draw Cylinder
// raytracer.translate(cylinder, Vector3D(0, 0, -4.5));
// // raytracer.rotate(cylinder, 'x', -45);
// // raytracer.rotate(cylinder, 'z', 45);
// raytracer.scale(cylinder, Point3D(0, 0, 0), factor1);
// >> Draw plane
// raytracer.translate(plane2, Vector3D(0, 0, -3));
// raytracer.scale(plane2, Point3D(0, 0, 0), factor3);
// raytracer.trans/late(sphere2, Vector3D(0, 1, -5));
// >> Non textured
raytracer.translate(plane, Vector3D(0, 0, -7));
raytracer.rotate(plane, 'z', 45);
raytracer.scale(plane, Point3D(0, 0, 0), factor2);
// >> Textured
// raytracer.translate(planeTexture, Vector3D(0, 0, -7));
// raytracer.rotate(planeTexture, 'z', 45);
// raytracer.scale(planeTexture, Point3D(0, 0, 0), factor2);
// Render the scene, feel free to make the image smaller for
// testing purposes.
// raytracer.render(width, height, eye, view, up, fov, "view1.bmp");
// Render it from a different point of view.
// Point3D eye2(1,0,-3);
// Vector3D view2(-1, 0, 1);
// Default
Point3D eye2(4, 2, 1);
Vector3D view2(-4, -2, -6);
// Side profile
// Point3D eye2(0, -4,2);
// Vector3D view2(0.2, 0.4, -1);
raytracer.render(width, height, eye2, view2, up, fov, "view2.bmp", light_ring_num + outer_ring_num);
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int n , a, b;
cin>>n>>a>>b;
n = n - a;
if (n<= b)
{
cout<< n ;
}
else if (n>b)
{
cout<<b+1;
}
return 0;
}
|
class Solution {
private:
int findKthElement(vector<int>& nums1, int beg1, vector<int>& nums2, int beg2, int k){
int m = nums1.size() - beg1, n = nums2.size() - beg2;
if(m < n)
return findKthElement(nums2, beg2, nums1, beg1, k);
if(!n)
return nums1[beg1+k-1];
if(k == 1)
return min(nums1[beg1], nums2[beg2]);
int i = beg1 + min(m, k/2);
int j = beg2 + min(n, k/2);
if(nums1[i-1] > nums2[j-1])
return findKthElement(nums1, beg1, nums2, j, k-j+beg2);
else
return findKthElement(nums1, i, nums2, beg2, k-i+beg1);
}
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size(), n = nums2.size();
int m1 = (n+m+1)/2, m2 = (n+m+2)/2;
int res1 = findKthElement(nums1, 0, nums2, 0, m1);
int res2 = findKthElement(nums1, 0, nums2, 0, m2);
return (res1 + res2) / 2.0;
}
};
|
/*
Name: Adrian Dy
SID: 861118847
Date: 5/07/2015
*/
#include <iostream>
#include <map>
#include "lab5.h"
using namespace std;
int main()
{ //Does not compile with -Wall -Werror -peadantic
BST<int> tree;
tree.insert(50);
tree.insert(20);
tree.insert(60);
tree.insert(10);
tree.insert(40);
tree.insert(70);
tree.insert(35);
tree.insert(45);
cout << "Part 1: " << endl;
tree.displayMinCover();
cout << "Part 2: fubar " << endl; //fubar
tree.findSumPath(80);
cout << endl;
cout << "Part 3: " << endl;
map<int,int> map0;
tree.vertSum(0,map0);
return 0;
}
|
/**
* Copyright (c) 2020, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file view_helpers.hh
*/
#ifndef lnav_view_helpers_hh
#define lnav_view_helpers_hh
#include "bookmarks.hh"
#include "help_text.hh"
#include "logfile_fwd.hh"
#include "vis_line.hh"
class textview_curses;
class hist_source2;
class logfile_sub_source;
/** The different views available. */
typedef enum {
LNV_LOG,
LNV_TEXT,
LNV_HELP,
LNV_HISTOGRAM,
LNV_DB,
LNV_SCHEMA,
LNV_PRETTY,
LNV_SPECTRO,
LNV_GANTT,
LNV__MAX
} lnav_view_t;
/** The command modes that are available while viewing a file. */
enum class ln_mode_t : int {
PAGING,
BREADCRUMBS,
FILTER,
FILES,
SPECTRO_DETAILS,
SEARCH_SPECTRO_DETAILS,
COMMAND,
SEARCH,
SEARCH_FILTERS,
SEARCH_FILES,
CAPTURE,
SQL,
EXEC,
USER,
BUSY,
};
extern const char* lnav_view_strings[LNV__MAX + 1];
extern const char* lnav_view_titles[LNV__MAX];
nonstd::optional<lnav_view_t> view_from_string(const char* name);
bool ensure_view(textview_curses* expected_tc);
bool ensure_view(lnav_view_t expected);
bool toggle_view(textview_curses* toggle_tc);
bool handle_winch();
void layout_views();
void update_hits(textview_curses* tc);
nonstd::optional<vis_line_t> next_cluster(
nonstd::optional<vis_line_t> (bookmark_vector<vis_line_t>::*f)(vis_line_t)
const,
const bookmark_type_t* bt,
vis_line_t top);
bool moveto_cluster(nonstd::optional<vis_line_t> (
bookmark_vector<vis_line_t>::*f)(vis_line_t) const,
const bookmark_type_t* bt,
vis_line_t top);
vis_line_t search_forward_from(textview_curses* tc);
textview_curses* get_textview_for_mode(ln_mode_t mode);
#endif
|
#ifndef SHOC_HASH_MD4_H
#define SHOC_HASH_MD4_H
#include "shoc/util.h"
namespace shoc {
struct Md4 : Eater<Md4> {
static constexpr size_t SIZE = 16;
static constexpr size_t STATE_SIZE = 4; // In words
static constexpr size_t BLOCK_SIZE = 64; // In bytes
public:
void init();
void feed(const void *in, size_t len);
void stop(byte *out);
private:
void pad();
void step();
private:
using word = uint32_t;
private:
word length_low;
word length_high;
word state[STATE_SIZE];
byte block[BLOCK_SIZE];
byte block_idx;
};
inline void Md4::init()
{
state[0] = 0x67452301;
state[1] = 0xefcdab89;
state[2] = 0x98badcfe;
state[3] = 0x10325476;
block_idx = length_high = length_low = 0;
}
inline void Md4::feed(const void *in, size_t len)
{
assert(in || !len);
auto p = static_cast<const byte*>(in);
while (len--) {
block[block_idx++] = *p++;
if ((length_low += 8) == 0)
length_high += 1;
if (block_idx == BLOCK_SIZE)
step();
}
}
inline void Md4::stop(byte *out)
{
assert(out);
pad();
for (size_t i = 0, j = 0; i < STATE_SIZE; ++i, j += 4) {
out[j + 0] = state[i] >> 0;
out[j + 1] = state[i] >> 8;
out[j + 2] = state[i] >> 16;
out[j + 3] = state[i] >> 24;
}
zero(this, sizeof(*this));
}
inline void Md4::pad()
{
static constexpr size_t pad_start = BLOCK_SIZE - 8;
block[block_idx++] = 0x80;
if (block_idx > pad_start) {
fill(block + block_idx, 0, BLOCK_SIZE - block_idx);
step();
}
fill(block + block_idx, 0, pad_start - block_idx);
for (size_t i = 0, j = 0; i < 4; ++i, j += 8) {
block[BLOCK_SIZE - 8 + i] = length_low >> j;
block[BLOCK_SIZE - 4 + i] = length_high >> j;
}
step();
}
inline void Md4::step()
{
word a = state[0];
word b = state[1];
word c = state[2];
word d = state[3];
word buf[16];
for (size_t i = 0, j = 0; j < BLOCK_SIZE; ++i, j +=4) {
buf[i] = block[j + 0] << 0;
buf[i] |= block[j + 1] << 8;
buf[i] |= block[j + 2] << 16;
buf[i] |= block[j + 3] << 24;
}
#define FF(a, b, c, d, x, s) \
a += ch(b, c, d) + x; \
a = rol(a, s);
#define GG(a, b, c, d, x, s) \
a += maj(b, c, d) + x + 0x5a827999; \
a = rol(a, s);
#define HH(a, b, c, d, x, s) \
a += parity(b, c, d) + x + 0x6ed9eba1; \
a = rol(a, s);
enum {
S11 = 3,
S12 = 7,
S13 = 11,
S14 = 19,
S21 = 3,
S22 = 5,
S23 = 9,
S24 = 13,
S31 = 3,
S32 = 9,
S33 = 11,
S34 = 15,
};
FF(a, b, c, d, buf[ 0], S11);
FF(d, a, b, c, buf[ 1], S12);
FF(c, d, a, b, buf[ 2], S13);
FF(b, c, d, a, buf[ 3], S14);
FF(a, b, c, d, buf[ 4], S11);
FF(d, a, b, c, buf[ 5], S12);
FF(c, d, a, b, buf[ 6], S13);
FF(b, c, d, a, buf[ 7], S14);
FF(a, b, c, d, buf[ 8], S11);
FF(d, a, b, c, buf[ 9], S12);
FF(c, d, a, b, buf[10], S13);
FF(b, c, d, a, buf[11], S14);
FF(a, b, c, d, buf[12], S11);
FF(d, a, b, c, buf[13], S12);
FF(c, d, a, b, buf[14], S13);
FF(b, c, d, a, buf[15], S14);
GG(a, b, c, d, buf[ 0], S21);
GG(d, a, b, c, buf[ 4], S22);
GG(c, d, a, b, buf[ 8], S23);
GG(b, c, d, a, buf[12], S24);
GG(a, b, c, d, buf[ 1], S21);
GG(d, a, b, c, buf[ 5], S22);
GG(c, d, a, b, buf[ 9], S23);
GG(b, c, d, a, buf[13], S24);
GG(a, b, c, d, buf[ 2], S21);
GG(d, a, b, c, buf[ 6], S22);
GG(c, d, a, b, buf[10], S23);
GG(b, c, d, a, buf[14], S24);
GG(a, b, c, d, buf[ 3], S21);
GG(d, a, b, c, buf[ 7], S22);
GG(c, d, a, b, buf[11], S23);
GG(b, c, d, a, buf[15], S24);
HH(a, b, c, d, buf[ 0], S31);
HH(d, a, b, c, buf[ 8], S32);
HH(c, d, a, b, buf[ 4], S33);
HH(b, c, d, a, buf[12], S34);
HH(a, b, c, d, buf[ 2], S31);
HH(d, a, b, c, buf[10], S32);
HH(c, d, a, b, buf[ 6], S33);
HH(b, c, d, a, buf[14], S34);
HH(a, b, c, d, buf[ 1], S31);
HH(d, a, b, c, buf[ 9], S32);
HH(c, d, a, b, buf[ 5], S33);
HH(b, c, d, a, buf[13], S34);
HH(a, b, c, d, buf[ 3], S31);
HH(d, a, b, c, buf[11], S32);
HH(c, d, a, b, buf[ 7], S33);
HH(b, c, d, a, buf[15], S34);
#undef FF
#undef GG
#undef HH
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
block_idx = 0;
}
}
#endif
|
//
// fps.cpp
// pendulum
//
// Created by Ran Bao on 9/23/13.
// Copyright (c) 2013 R&B. All rights reserved.
//
#include "fps.h"
#include <ctime>
#include <string>
/**
* Get the frame per second
* Method 1: Count the time for tick reach certain value
* @return FPS value
*/
double get_fps_1()
{
static int count;
static double save;
static clock_t last, current;
double timegap;
++count;
if (count <= 10)
return save;
count = 0;
last = current;
current = clock();
timegap = (current - last) / (double)CLOCKS_PER_SEC;
save = 10.0 / timegap;
return save;
}
/**
* Get the frame per second
* Method 2: Count the frame within certain tick interval
* @return FPS value
*/
float get_fps_2(){
static unsigned int frame = 0;
static unsigned int interval = 1000;
static unsigned int start, end;
static float f = 0.0f;
// start counting time
if (frame == 0){
start = (unsigned int)clock();
}
frame += 1;
end = (unsigned int)clock();
if ((end - start) >= interval){
f = (float)frame / (end - start) * CLOCKS_PER_SEC / 2;
frame = 0;
}
return f;
}
float get_fps_3(){
static unsigned int frame = 0;
static unsigned int interval = 10;
static unsigned int start, end;
static float f = 0.0f;
// start takeing time of frame0
if (frame == 0){
start = (unsigned int)clock();
}
frame += 1;
if (frame >= interval){
end = (unsigned int)clock();
f = (float)interval / (end - start) * CLOCKS_PER_SEC;
frame = 0;
}
return f;
}
|
// Copyright (c) 1999-2020 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Express_HeaderFile
#define _Express_HeaderFile
#include <Standard_Boolean.hxx>
#include <Standard_Type.hxx>
#include <Standard_OStream.hxx>
class Express_Schema;
class TCollection_AsciiString;
//! Provides data structures for representation of EXPRESS schema
//! (items, types, entities etc.)
//! and tools for generating XSTEP classes (HXX and CXX) from
//! items of the schema
class Express
{
public:
DEFINE_STANDARD_ALLOC
//! Returns (modifiable) handle to static schema object
Standard_EXPORT static Handle(Express_Schema)& Schema();
//! Writes standard copyright stamp (creation date/time, user, etc.)
Standard_EXPORT static void WriteFileStamp (Standard_OStream& theOS);
//! Writes standard comment for method in CXX file
Standard_EXPORT static void WriteMethodStamp (Standard_OStream& theOS, const TCollection_AsciiString& theName);
//! Converts item name from CASCADE to STEP style
//! e.g. BoundedCurve -> bounded_curve
Standard_EXPORT static TCollection_AsciiString ToStepName (const TCollection_AsciiString& theName);
//! Converts item name from CASCADE to STEP style
//! e.g. BoundedCurve -> bounded_curve
Standard_EXPORT static TCollection_AsciiString EnumPrefix (const TCollection_AsciiString& theName);
};
#endif // _Express_HeaderFile
|
#include <iostream>
#include <cmath>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int tc;
cin >> tc;
while(tc--){
int l, n;
cin >> l >> n;
int tn = n;
int mid = l / 2;
int min = 1000000, max = 1000000;
int vMin, vMax, ans1, ans2;
while(tn--){
int tp;
cin >> tp;
if(abs(tp - mid) < min){
min = abs(tp - mid);
vMin = tp;
}
if(tp <= mid && tp < max){
max = tp;
vMax = tp;
}
if(tp > mid && l - tp < max){
max = l - tp;
vMax = tp;
}
}
if(vMin <= mid){
ans1 = vMin;
}else{
ans1 = l - vMin;
}
if(vMax <= mid){
ans2 = l - vMax;
}else{
ans2 = vMax;
}
cout << ans1 << " " << ans2 << '\n';
}
return 0;
}
|
#include "TestFramework.h"
#define GLEW_STATIC
#include <GL/glew.h>
#include "treeface/gl/VertexTemplate.h"
#include "treeface/base/PackageManager.h"
#include "treeface/scene/Geometry.h"
#include "treeface/scene/GeometryManager.h"
#include <treecore/File.h>
#include <treecore/StringRef.h>
#include <treecore/MemoryBlock.h>
#include <SDL.h>
using namespace treeface;
using namespace treecore;
int window_w = 400;
int window_h = 400;
void build_up_sdl( SDL_Window** window, SDL_GLContext* context )
{
SDL_Init( SDL_INIT_VIDEO & SDL_INIT_TIMER & SDL_INIT_EVENTS );
Logger::writeToLog( "create window\n" );
*window = SDL_CreateWindow( "sdl_setup test", 50, 50, window_w, window_h, SDL_WINDOW_OPENGL );
if (!*window)
die( "error: failed to create window: %s\n", SDL_GetError() );
printf( "create opengl context\n" );
*context = SDL_GL_CreateContext( *window );
if (!context)
die( "error: failed to create GL context: %s\n", SDL_GetError() );
SDL_GL_MakeCurrent( *window, *context );
printf( "init glew\n" );
{
GLenum glew_err = glewInit();
if (glew_err != GLEW_OK)
{
fprintf( stderr, "error: failed to init glew: %s\n", glewGetErrorString( glew_err ) );
exit( 1 );
}
}
}
void TestFramework::content()
{
SDL_Window* window = nullptr;
SDL_GLContext context = nullptr;
build_up_sdl( &window, &context );
PackageManager* pkg_mgr = PackageManager::getInstance();
RefCountHolder<GeometryManager> geom_mgr = new GeometryManager();
pkg_mgr->add_package( File( "../examples/resource.zip" ), PackageManager::KEEP_EXISTING );
OK( pkg_mgr->has_resource( "geom_with_align.json" ) );
RefCountHolder<Geometry> geom = geom_mgr->get_geometry( "geom_with_align.json" );
OK( geom );
IS( geom->get_primitive(), GL_TRIANGLE_STRIP );
IS(geom->get_vertex_template().vertex_size(), 24);
{
Geometry::HostDrawScope scope( *geom );
Geometry::HostVertexCache& data_vtx = geom->get_host_vertex_cache();
GLbyte* data_p = (GLbyte*) data_vtx.get_raw_data_ptr();
IS( data_vtx.size(), 4 );
OK("vertex 0");
IS( *(float*) (data_p + 0), -0.5f );
IS( *(float*) (data_p + 4), -0.5f );
IS( *(float*) (data_p + 8), 0.0f );
IS( *(float*) (data_p + 16), 0.0f );
IS( *(float*) (data_p + 20), 0.0f );
OK("vertex 1");
IS( *(float*) (data_p + 24), 0.5f );
IS( *(float*) (data_p + 28), -0.5f );
IS( *(float*) (data_p + 32), 0.0f );
IS( *(float*) (data_p + 40), 1.0f );
IS( *(float*) (data_p + 44), 0.0f );
OK("vertex 2");
IS( *(float*) (data_p + 48), -0.5f );
IS( *(float*) (data_p + 52), 0.5f );
IS( *(float*) (data_p + 56), 0.0f );
IS( *(float*) (data_p + 64), 0.0f );
IS( *(float*) (data_p + 68), 1.0f );
OK("vertex 3");
IS( *(float*) (data_p + 72), 0.5f );
IS( *(float*) (data_p + 76), 0.5f );
IS( *(float*) (data_p + 80), 0.0f );
IS( *(float*) (data_p + 88), 1.0f );
IS( *(float*) (data_p + 92), 1.0f );
Array<IndexType>& data_idx = geom->get_host_index_cache();
IS( data_idx.size(), 4 );
IS( data_idx[0], 0 );
IS( data_idx[1], 1 );
IS( data_idx[2], 2 );
IS( data_idx[3], 3 );
}
SDL_GL_DeleteContext( context );
SDL_Quit();
}
|
#include <apriltags_ros/apriltag_detector.h>
#include <sensor_msgs/image_encodings.h>
#include <boost/foreach.hpp>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/PoseArray.h>
#include <apriltags_ros/AprilTagDetection.h>
#include <apriltags_ros/AprilTagDetectionArray.h>
#include <AprilTags/Tag16h5.h>
#include <AprilTags/Tag25h7.h>
#include <AprilTags/Tag25h9.h>
#include <AprilTags/Tag36h9.h>
#include <AprilTags/Tag36h11.h>
#include <XmlRpcException.h>
#include <QApplication>
#include <QThread>
namespace apriltags_ros
{
AprilTagDetector::AprilTagDetector(ros::NodeHandle &)
{
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
it_.reset(new image_transport::ImageTransport(nh));
XmlRpc::XmlRpcValue april_tag_descriptions;
if(!pnh.getParam("tag_descriptions", april_tag_descriptions))
{
ROS_WARN("No april tags specified");
}
else{
try{
descriptions_ = parse_tag_descriptions(april_tag_descriptions);
} catch(XmlRpc::XmlRpcException e){
ROS_ERROR_STREAM( "Error loading tag descriptions: " << e.getMessage() );
}
}
if(!pnh.getParam("sensor_frame_id", sensor_frame_id_)) sensor_frame_id_ = "";
std::string tag_family;
pnh.param<std::string>("tag_family", tag_family, "36h11");
pnh.param<bool>("projected_optics", projected_optics_, false);
const AprilTags::TagCodes* tag_codes;
if(tag_family == "16h5") tag_codes = &AprilTags::tagCodes16h5;
else if(tag_family == "25h7") tag_codes = &AprilTags::tagCodes25h7;
else if(tag_family == "25h9") tag_codes = &AprilTags::tagCodes25h9;
else if(tag_family == "36h9") tag_codes = &AprilTags::tagCodes36h9;
else if(tag_family == "36h11") tag_codes = &AprilTags::tagCodes36h11;
else
{
ROS_WARN("Invalid tag family specified; defaulting to 36h11");
tag_codes = &AprilTags::tagCodes36h11;
}
if (!pnh.getParam("tag_detections_image_topic", tag_detections_image_topic)) tag_detections_image_topic = "tag_detections_image";
if (!pnh.getParam("tag_detections_topic", tag_detections_topic))
throw std::runtime_error("AprilTagDetector::AprilTagDetector: failed to read param \"tag_detections_topic\"..." );
if (!pnh.getParam("use_gui", use_gui)) use_gui = false;
if (!pnh.getParam("apply_filter", apply_filter)) apply_filter = false;
double ap, aq;
if (!pnh.getParam("a_p", ap)) ap = 1.0;
if (!pnh.getParam("a_q", aq)) aq = 1.0;
a_p.set(ap);
a_q.set(aq);
int miss_fr_tol;
if (!pnh.getParam("miss_frames_tol", miss_fr_tol)) miss_fr_tol = 5;
miss_frames_tol.set(miss_fr_tol);
if (!pnh.getParam("publish_", publish_)) publish_ = false;
if (!pnh.getParam("publish_tag_tf", publish_tag_tf)) publish_tag_tf = false;
if (!pnh.getParam("publish_tag_im", publish_tag_im)) publish_tag_im = false;
if (publish_tag_tf || publish_tag_im) publish_ = true;
double pub_rate_msec;
if (!pnh.getParam("pub_rate_msec", pub_rate_msec)) pub_rate_msec = 33;
this->setPublishRate(pub_rate_msec);
tag_detector_= boost::shared_ptr<AprilTags::TagDetector>(new AprilTags::TagDetector(*tag_codes));
image_sub_ = it_->subscribeCamera("image_rect", 1, &AprilTagDetector::imageCb, this);
image_pub_ = it_->advertise(tag_detections_image_topic, 1);
detections_pub_ = nh.advertise<AprilTagDetectionArray>(tag_detections_topic, 1);
// pose_pub_ = nh.advertise<geometry_msgs::PoseArray>("tag_detections_pose", 1);
if (publish_) launchPublishThread();
if (use_gui) launchGUI();
}
AprilTagDetector::~AprilTagDetector()
{
emit gui->closeSignal();
new_msg_sem.notify();
image_sub_.shutdown();
gui_finished_sem.wait();
}
void AprilTagDetector::stopPublishThread()
{
this->publish_ = false;
}
void AprilTagDetector::setPublishRate(double pub_rate_sec)
{
this->pub_rate_nsec.set(pub_rate_sec*1e6);
}
void AprilTagDetector::launchPublishThread()
{
std::thread([this]()
{
while (publish_)
{
new_msg_sem.wait();
if (publish_tag_im)
{
// std::cerr << "this->cv_ptr: " << ((void *)this->getImage().get()) << "\n";
image_pub_.publish(this->getImage()->toImageMsg());
}
if (publish_tag_tf)
{
geometry_msgs::PoseStamped tag_pose;
for (auto it = descriptions_.begin(); it!=descriptions_.end(); it++)
{
const AprilTagDescription &tag_descr = it->second;
if (!tag_descr.isGood()) continue;
tag_pose = tag_descr.getPose();
tf::Stamped<tf::Transform> tag_transform;
tf::poseStampedMsgToTF(tag_pose, tag_transform);
tf_pub_.sendTransform(tf::StampedTransform(tag_transform, tag_transform.stamp_, tag_transform.frame_id_, tag_descr.frame_name()));
}
}
std::this_thread::sleep_for(std::chrono::nanoseconds(pub_rate_nsec.get()));
}
}).detach();
}
void AprilTagDetector::launchGUI()
{
Semaphore start_sem;
std::thread( [this, &start_sem]()
{
int argc = 0;
char **argv = 0;
QApplication app(argc, argv);
QThread::currentThread()->setPriority(QThread::LowestPriority);
gui = new MainWindow(this);
gui->show();
start_sem.notify();
app.exec();
delete gui;
gui_finished_sem.notify();
}).detach();
start_sem.wait();
}
void AprilTagDetector::imageCb(const sensor_msgs::ImageConstPtr& im_msg, const sensor_msgs::CameraInfoConstPtr& cam_info)
{
cv_bridge::CvImagePtr cv_ptr;
// std::cerr << "========> msg->header.frame_id: " << msg->header.frame_id << "\n";
try
{
cv_ptr = cv_bridge::toCvCopy(im_msg, sensor_msgs::image_encodings::BGR8);
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
// std::cerr << "cv_ptr: " << ((void *)cv_ptr.get()) << "\n";
cv::Mat gray;
cv::cvtColor(cv_ptr->image, gray, CV_BGR2GRAY);
std::vector<AprilTags::TagDetection> detections = tag_detector_->extractTags(gray);
ROS_DEBUG("%d tag detected", (int)detections.size());
double fx;
double fy;
double px;
double py;
if (projected_optics_) {
// use projected focal length and principal point
// these are the correct values
fx = cam_info->P[0];
fy = cam_info->P[5];
px = cam_info->P[2];
py = cam_info->P[6];
} else {
// use camera intrinsic focal length and principal point
// for backwards compatibility
fx = cam_info->K[0];
fy = cam_info->K[4];
px = cam_info->K[2];
py = cam_info->K[5];
}
// std::cout << "================================\n";
// std::cout << "--------- cam_info->P ----------\n ";
// std::cout << "fx: " << cam_info->P[0] << "\n";
// std::cout << "fy: " << cam_info->P[5] << "\n";
// std::cout << "px: " << cam_info->P[2] << "\n";
// std::cout << "py: " << cam_info->P[6] << "\n";
// std::cout << "================================\n";
// std::cout << "================================\n";
// std::cout << "--------- cam_info->K ----------\n ";
// std::cout << "fx: " << cam_info->K[0] << "\n";
// std::cout << "fy: " << cam_info->K[4] << "\n";
// std::cout << "px: " << cam_info->K[2] << "\n";
// std::cout << "py: " << cam_info->K[5] << "\n";
// std::cout << "================================\n";
if(!sensor_frame_id_.empty()) cv_ptr->header.frame_id = sensor_frame_id_;
for (auto descr_it = descriptions_.begin(); descr_it!=descriptions_.end(); descr_it++)
{
AprilTagDescription &description = descr_it->second;
description.missed_frames_num++;
if (description.missed_frames_num > miss_frames_tol.get())
{
description.missed_frames_num = 0;
description.is_good = false;
}
geometry_msgs::PoseStamped pose = description.getPose();
pose.header = im_msg->header;
description.setPose(pose);
}
BOOST_FOREACH(AprilTags::TagDetection detection, detections)
{
std::map<int, AprilTagDescription>::iterator description_itr = descriptions_.find(detection.id);
if(description_itr == descriptions_.end())
{
ROS_WARN_THROTTLE(10.0, "Found tag: %d, but no description was found for it", detection.id);
continue;
}
AprilTagDescription &description = description_itr->second;
double tag_size = description.size();
description.missed_frames_num = 0;
if (publish_tag_im) detection.draw(cv_ptr->image);
Eigen::Matrix4d transform = detection.getRelativeTransform(tag_size, fx, fy, px, py);
Eigen::Matrix3d rot = transform.block(0, 0, 3, 3);
Eigen::Quaternion<double> rot_quaternion = Eigen::Quaternion<double>(rot);
geometry_msgs::PoseStamped tag_pose;
tag_pose.pose.position.x = transform(0, 3);
tag_pose.pose.position.y = transform(1, 3);
tag_pose.pose.position.z = transform(2, 3);
tag_pose.pose.orientation.x = rot_quaternion.x();
tag_pose.pose.orientation.y = rot_quaternion.y();
tag_pose.pose.orientation.z = rot_quaternion.z();
tag_pose.pose.orientation.w = rot_quaternion.w();
tag_pose.header = cv_ptr->header;
if (apply_filter) tag_pose = filterPose(tag_pose, description);
description.setPose(tag_pose);
description.is_good = detection.good;
description.hamming_dist = detection.hammingDistance;
}
// important to do here and not inside the above loop, because in case of no detections
// the above loop in not entered and setImage won't be called leading initially to an
// empty image which will be attempted to be published by the the publishThread
// this->cv_im will be null so the program would crush.
this->setImage(cv_ptr);
AprilTagDetectionArray tag_detection_array;
for (auto descr_it = descriptions_.begin(); descr_it!=descriptions_.end(); descr_it++)
{
AprilTagDescription &description = descr_it->second;
if (!description.isGood()) continue;
AprilTagDetection tag_detection;
tag_detection.pose = description.getPose();
tag_detection.id = description.getId();
tag_detection.size = description.size();
tag_detection.is_good = description.isGood();
tag_detection.hamming_dist = description.hammingDis();
tag_detection_array.detections.push_back(tag_detection);
}
new_msg_sem.notify();
if (tag_detection_array.detections.size() != 0) detections_pub_.publish(tag_detection_array);
}
geometry_msgs::PoseStamped AprilTagDetector::filterPose(const geometry_msgs::PoseStamped &pose, const AprilTagDescription &description)
{
if (!description.isGood()) return pose;
geometry_msgs::PoseStamped filt_pose;
filt_pose.header = pose.header;
geometry_msgs::PoseStamped prev_pose = description.getPose();
double cp = std::min(1.0, a_p.get() * (description.missed_frames_num + 1) );
filt_pose.pose.position.x = (1-cp)*prev_pose.pose.position.x + cp*pose.pose.position.x;
filt_pose.pose.position.y = (1-cp)*prev_pose.pose.position.y + cp*pose.pose.position.y;
filt_pose.pose.position.z = (1-cp)*prev_pose.pose.position.z + cp*pose.pose.position.z;
double cq = std::min(1.0, a_q.get() * (description.missed_frames_num + 1) );
double w = (1-cq)*prev_pose.pose.orientation.w + cq*pose.pose.orientation.w;
double x = (1-cq)*prev_pose.pose.orientation.x + cq*pose.pose.orientation.x;
double y = (1-cq)*prev_pose.pose.orientation.y + cq*pose.pose.orientation.y;
double z = (1-cq)*prev_pose.pose.orientation.z + cq*pose.pose.orientation.z;
double norm = std::sqrt( w*w + x*x + y*y + z*z );
filt_pose.pose.orientation.w = w/norm;
filt_pose.pose.orientation.x = x/norm;
filt_pose.pose.orientation.y = y/norm;
filt_pose.pose.orientation.z = z/norm;
return filt_pose;
}
std::map<int, AprilTagDescription> AprilTagDetector::parse_tag_descriptions(XmlRpc::XmlRpcValue& tag_descriptions)
{
std::map<int, AprilTagDescription> descriptions;
ROS_ASSERT(tag_descriptions.getType() == XmlRpc::XmlRpcValue::TypeArray);
for (int32_t i = 0; i < tag_descriptions.size(); ++i)
{
XmlRpc::XmlRpcValue &tag_description = tag_descriptions[i];
ROS_ASSERT(tag_description.getType() == XmlRpc::XmlRpcValue::TypeStruct);
ROS_ASSERT(tag_description["id"].getType() == XmlRpc::XmlRpcValue::TypeInt);
ROS_ASSERT(tag_description["size"].getType() == XmlRpc::XmlRpcValue::TypeDouble);
int id = (int)tag_description["id"];
double size = (double)tag_description["size"];
std::string frame_name;
if(tag_description.hasMember("frame_id")){
ROS_ASSERT(tag_description["frame_id"].getType() == XmlRpc::XmlRpcValue::TypeString);
frame_name = (std::string)tag_description["frame_id"];
}
else{
std::stringstream frame_name_stream;
frame_name_stream << "tag_" << id;
frame_name = frame_name_stream.str();
}
AprilTagDescription description(id, size, frame_name);
ROS_INFO_STREAM("Loaded tag config: "<<id<<", size: "<<size<<", frame_name: "<<frame_name);
descriptions.insert(std::make_pair(id, description));
}
return descriptions;
}
}
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStringList>
#include <QStringListModel>
#include <QAbstractItemView>
#include <QListWidgetItem>
#include <QStandardItemModel>
#include <QDialog>
#include <QLabel>
#include <QStatusBar>
#include <QContextMenuEvent>
#include <QFileDialog>
#include <QMessageBox>
#include <stack>
#include "models/ParamsModel.hpp"
#include "models/InputsDelegate.hpp"
#include "RunWorkerThread.h"
#include "../framework/Configuration.hpp"
#include "../framework/Logger.hpp"
#include "../framework/ProcessingStep.hpp"
#include "../framework/ModuleManager.hpp"
#include "../framework/GUIEventDispatcher.hpp"
#include "graph/graphwidget.h"
#include "graph/node.h"
namespace Ui {
class MainWindow;
}
namespace uipf {
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
// loads a new configuration from file
void loadDataFlow(std::string);
private slots:
// Buttons addStep/deleteStep
void on_addButton_clicked();
void on_deleteButton_clicked();
//stepName changed
void on_stepNameChanged();
// Activation of Step (via clicking)
void on_stepSelectionChanged(const QItemSelection&);
// append messages from our logger to the log-textview
void on_appendToLog(const Logger::LogType&, const std::string& );
// moves the progressbar on every step of the processing chain
void on_reportProgress(const float& );
//this gets called from Backgroundthread when its work is finished or when it gets terminated by stop()
void on_backgroundWorkerFinished();
// change of module dropdown
void on_comboModule_currentIndexChanged(int);
// change of module category dropdown
void on_comboCategory_currentIndexChanged(int);
// change in the params table
void on_paramChanged(std::string, std::string);
void on_inputChanged(std::string, std::pair<std::string, std::string>);
void on_createWindow(const std::string& strTitle);
void on_closeWindow(const std::string& strTitle);
// menu bar
// File
void new_Data_Flow();
void load_Data_Flow();
void save_Data_Flow();
void save_Data_Flow_as();
void on_close();
// Help
void about();
// Edit
void undo();
void redo();
// Configuration
void run();
void stop();
void closeAllCreatedWindows();
void on_graphNodeSelected(const uipf::gui::Node* node);
void on_clearLogButton_clicked();
void on_logFiltertextChanged(const QString& text);
protected:
void closeEvent(QCloseEvent *event);
void keyReleaseEvent(QKeyEvent *event);
private:
// default window title that appears next to the file name
const std::string WINDOW_TITLE = "uipf";
Ui::MainWindow *ui;
// the module manager instance
ModuleManager mm_;
// model for the listView of processing steps
QStringListModel *modelStep;
// model for the params editor table
ParamsModel *modelTableParams;
// models for the input editor table
QStandardItemModel *modelTableInputs;
// model delegate for the input editor table
InputsDelegate *delegateTableInputs;
// the file name of the currently loaded configuration
std::string currentFileName;
// asks the user, whether he wants to save the file
bool okToContinue();
// the currently loaded configuration represented in the window
Configuration conf_;
// map of all available categories
std::map<std::string, std::vector<std::string> > categories_;
// counts the undo/redo, when = 0, it is the saved version
int savedVersion = 1;
// is true if file was at least one time saved
bool unknownFile = true;
// current name of a precessing step
std::string currentStepName;
// Redo and Undo stacks, which store configurations
std::stack<Configuration> undoStack;
std::stack<Configuration> redoStack;
// fills the undo and redo stacks
void beforeConfigChange();
// refresh UI triggers
void refreshCategoryAndModule();
void refreshParams();
void refreshInputs();
void refreshGraph();
void refreshSaveIcon();
// reset UI triggers
void resetCategoryAndModule();
void resetParams();
void resetInputs();
// menu bar
void createActions();
void deleteActions();
void createMenus();
QMenu *fileMenu;
QMenu *editMenu;
QMenu *configMenu;
QMenu *viewMenu;
QMenu *helpMenu;
// actions in fileMenu
QAction *newAct;
QAction *openAct;
QAction *saveAct;
QAction *saveAsAct;
QAction *exitAct;
// actions in editMenu
QAction *undoAct;
QAction *redoAct;
// actions in configMenu
QAction *runAct;
QAction *stopAct;
// actions in viewMenu
QAction *closeWindowsAct;
// actions in helpMenu
QAction *aboutAct;
//the view, that displays the graph
gui::GraphWidget* graphView_;
//our current backgroundworker or a nullptr
RunWorkerThread* workerThread_;
//keep track of all windows we created so we can close them later
std::vector<QGraphicsView* > createdWindwows_;
};
} // namespace
#endif // MAINWINDOW_H
|
/*
author chonepieceyb, operatiing-system lab2
2020年 03月 31日 星期二 21:24:51 CST
*/
#include<iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<string>
using namespace std;
int main( int argc, char** argv){
if(argc!=2){
cout<<"请输入一个参数\n";
exit(-1);
}
int parm = std::stoi(string(argv[1])); // 将字符串转化为 整形
if(parm<0){
cout<<"参数不能小于0!"<<endl;
exit(-1);
}
// 开辟子进程
int pid = fork();
if(pid<0){
cout<<"fail to fork child process!\n";
exit(-1);
}else if(pid ==0){
//如果是子进程的话
if(parm ==0){
printf("fib%d = %d\n", 0 , 0);
}else if(parm == 1){
printf("fib%d = %d\n", 1 , 1);
}else{
long fb1 = 0 , fb2 = 1;
printf("fib%d = %d\n", 0 , 0);
printf("fib%d = %d\n", 1 , 1);
for(int i =2 ; i<=parm;i++){
long v = fb1 + fb2;
printf("fib%d = %ld\n",i , v);
fb1 = fb2;
fb2 = v ;
}
}
exit(0);
}else{
int status;
waitpid(pid,&status,WUNTRACED); // waitpid的作用和wait 类似等待 pid = pid的子进程结束;
exit(0);
}
}
|
/* Copyright (c) 2005 Nokia Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Python_app.h
//
#ifndef __PYTHON_APP_H
#define __PYTHON_APP_H
#include <aknapp.h>
#include <AknDoc.h>
class CPythonDocument : public CAknDocument
{
public:
CPythonDocument(CEikApplication& aApp);
private:
CEikAppUi* CreateAppUiL();
};
class CPythonApplication : public CAknApplication
{
private:
CApaDocument* CreateDocumentL();
TUid AppDllUid() const;
};
#endif // __PYTHON_APP_H
|
#pragma once
#include "BaseService/BaseService.h"
class PassedTest;
class PassedTestPreview;
class PassedTestsService : public BaseService {
Q_OBJECT
public:
PassedTestsService(QObject *parent = nullptr);
public slots:
void getPreviews() const;
void getPassedTest(int id) const;
signals:
void previewsGot(const QList<PassedTestPreview> &previews);
void passedTestGot(const PassedTest &passedTest);
private slots:
void onPreviewsGot(const QJsonArray &jsonPreviews);
void onPassedTestGot(const QJsonObject &jsonPassedTest);
};
|
#ifndef SORT_BY_PRICE_VISITOR_H
#define SORT_BY_PRICE_VISITOR_H
#include <vector>
#include "iterator.h"
#include "menu.h"
#include "category.h"
#include "full_menu.h"
// class Item;
// class Menu;
// class Category;
// class FullMenu;
using namespace std;
class SortByPriceVisitor : public Visitor
{
public:
SortByPriceVisitor()
{
}
void visit(FullMenu *fm)
{
Iterator<Category> *it = fm->createIterator();
for (it->first(); !it->isDone(); it->next())
{
cout << it->currentItem().GetName() << endl;
it->currentItem().accept(*this);
}
}
void visit(Category *c)
{
Iterator<Item>* it = c->createIterator();
for(it->first(); !it->isDone(); it->next())
items.push_back(it->currentItem());
BubbleSort();
for(int n = 0; n < items.size(); n++)
std::cout << items[n].GetProductCode() << " " << items[n].GetName() << " " << items[n].GetDescription() << " " << fixed << setprecision(2) << items[n].GetPrice() << std::endl;
cout << endl;
items.clear();
}
void BubbleSort()
{
int size = items.size();
for(int n = 0; n < size; n++)
{
for(int i = 1; i < size - n; i++)
{
if(items[i - 1].GetPrice() > items[i].GetPrice())
Swap(i-1, i);
}
}
}
void Swap(int index1, int index2)
{
Item temp = items[index1];
items[index1] = items[index2];
items[index2] = temp;
}
private:
vector<Item> items;
};
#endif
|
// Created on: 2012-06-01
// Created by: Eugeny MALTCHIKOV
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepFeat_Builder_HeaderFile
#define _BRepFeat_Builder_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <BOPAlgo_BOP.hxx>
#include <Standard_Integer.hxx>
#include <TopTools_DataMapOfShapeShape.hxx>
#include <TopTools_ListOfShape.hxx>
#include <TopTools_MapOfShape.hxx>
class TopoDS_Shape;
class TopoDS_Face;
//! Provides a basic tool to implement features topological
//! operations. The main goal of the algorithm is to perform
//! the result of the operation according to the
//! kept parts of the tool.
//! Input data: a) DS;
//! b) The kept parts of the tool;
//! If the map of the kept parts of the tool
//! is not filled boolean operation of the
//! given type will be performed;
//! c) Operation required.
//! Steps: a) Fill myShapes, myRemoved maps;
//! b) Rebuild edges and faces;
//! c) Build images of the object;
//! d) Build the result of the operation.
//! Result: Result shape of the operation required.
class BRepFeat_Builder : public BOPAlgo_BOP
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT BRepFeat_Builder();
Standard_EXPORT virtual ~BRepFeat_Builder();
//! Clears internal fields and arguments.
Standard_EXPORT virtual void Clear() Standard_OVERRIDE;
//! Initializes the object of local boolean operation.
Standard_EXPORT void Init (const TopoDS_Shape& theShape);
//! Initializes the arguments of local boolean operation.
Standard_EXPORT void Init (const TopoDS_Shape& theShape, const TopoDS_Shape& theTool);
//! Sets the operation of local boolean operation.
//! If theFuse = 0 than the operation is CUT, otherwise FUSE.
Standard_EXPORT void SetOperation (const Standard_Integer theFuse);
//! Sets the operation of local boolean operation.
//! If theFlag = TRUE it means that no selection of parts
//! of the tool is needed, t.e. no second part. In that case
//! if theFuse = 0 than operation is COMMON, otherwise CUT21.
//! If theFlag = FALSE SetOperation(theFuse) function is called.
Standard_EXPORT void SetOperation (const Standard_Integer theFuse, const Standard_Boolean theFlag);
//! Collects parts of the tool.
Standard_EXPORT void PartsOfTool (TopTools_ListOfShape& theLT);
//! Initializes parts of the tool for second step of algorithm.
//! Collects shapes and all sub-shapes into myShapes map.
Standard_EXPORT void KeepParts (const TopTools_ListOfShape& theIm);
//! Adds shape theS and all its sub-shapes into myShapes map.
Standard_EXPORT void KeepPart (const TopoDS_Shape& theS);
//! Main function to build the result of the
//! local operation required.
Standard_EXPORT void PerformResult(const Message_ProgressRange& theRange = Message_ProgressRange());
//! Rebuilds faces in accordance with the kept parts of the tool.
Standard_EXPORT void RebuildFaces();
//! Rebuilds edges in accordance with the kept parts of the tool.
Standard_EXPORT void RebuildEdge (const TopoDS_Shape& theE, const TopoDS_Face& theF, const TopTools_MapOfShape& theME, TopTools_ListOfShape& aLEIm);
//! Collects the images of the object, that contains in
//! the images of the tool.
Standard_EXPORT void CheckSolidImages();
//! Collects the removed parts of the tool into myRemoved map.
Standard_EXPORT void FillRemoved();
//! Adds the shape S and its sub-shapes into myRemoved map.
Standard_EXPORT void FillRemoved (const TopoDS_Shape& theS, TopTools_MapOfShape& theM);
protected:
//! Prepares builder of local operation.
Standard_EXPORT virtual void Prepare() Standard_OVERRIDE;
//! Function is redefined to avoid the usage of removed faces.
Standard_EXPORT virtual void FillIn3DParts (TopTools_DataMapOfShapeShape& theDraftSolids,
const Message_ProgressRange& theRange) Standard_OVERRIDE;
//! Avoid the check for open solids and always use the splits
//! of solids for building the result shape.
virtual Standard_Boolean CheckArgsForOpenSolid() Standard_OVERRIDE
{
return Standard_False;
}
TopTools_MapOfShape myShapes;
TopTools_MapOfShape myRemoved;
Standard_Integer myFuse;
private:
};
#endif // _BRepFeat_Builder_HeaderFile
|
/*
* Inventory.cpp
*
* Created on: Aug 16, 2016
* Author: Kevin Koza
*/
#include "Inventory.h"
#include <cstddef>
namespace std {
Inventory::Inventory() {
// TODO Auto-generated constructor stub
item = NULL;
next = NULL;
}
Inventory::~Inventory() {
// TODO Auto-generated destructor stub
}
} /* namespace std */
|
#include "Calculator.h"
int main(){
const char* str = "/home/denis/CLionProjects/Calculator_Lec/factorial.txt";
Calculator electornika(str);
electornika.work_with_file();
electornika.Run_Calculator();
cout << electornika.array_of_reg[0] << endl;
return 0;
}
|
#include "../src/vector.h"
class VectorTest : public ::testing::Test {
protected:
void SetUp() override {
a[0] = 1;
a[1] = 3;
a_dim = 2;
b[0] = 3;
b[1] = 4;
b_dim = 2;
}
double a[2];
int a_dim;
double b[2];
int b_dim;
};
TEST_F(VectorTest, DefaultConstructor){
Vector v;
ASSERT_EQ(0, v.dim());
}
TEST_F(VectorTest, Constructor){
Vector v(a, a_dim);
ASSERT_EQ(2, v.dim());
ASSERT_EQ(1, v.at(1));
ASSERT_EQ(3, v.at(2));
}
TEST_F(VectorTest, CopyConstructor){
Vector v(a, a_dim);
Vector u = v;
ASSERT_EQ(2, u.dim());
ASSERT_EQ(1, u.at(1));
ASSERT_EQ(3, u.at(2));
}
TEST_F(VectorTest, Dim){
Vector v(a, a_dim);
ASSERT_EQ(2, v.dim());
}
TEST_F(VectorTest, At){
Vector v(a, a_dim);
ASSERT_EQ(1, v.at(1));
ASSERT_EQ(3, v.at(2));
}
TEST_F(VectorTest, AddOperator){
Vector u(a, a_dim);
Vector v(b, b_dim);
Vector result = u + v;
ASSERT_EQ(2, result.dim());
ASSERT_EQ(4, result.at(1));
ASSERT_EQ(7, result.at(2));
}
TEST_F(VectorTest, SubstractOperator){
Vector u(a, a_dim);
Vector v(b, b_dim);
Vector result = u - v;
ASSERT_EQ(2, result.dim());
ASSERT_EQ(-2, result.at(1));
ASSERT_EQ(-1, result.at(2));
}
TEST_F(VectorTest, Length){
Vector v(b, b_dim);
ASSERT_EQ(5, v.length());
}
TEST_F(VectorTest, Angle){
Vector u(a, a_dim);
Vector v(b, b_dim);
ASSERT_NEAR(18.434, u.angle(v),0.001);
}
|
#ifndef TIMEEDITDELEGATE_H
#define TIMEEDITDELEGATE_H
#include <QItemDelegate>
class TimeEditDelegate : public QItemDelegate
{
Q_OBJECT
public:
TimeEditDelegate(const QString timeFormat = "dd.MM.yyyy hh:mm:ss",QObject *parent = 0) : QItemDelegate(parent)
{this->timeformat = timeFormat;};
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
private:
QString timeformat;
};
#endif // TIMEEDITDELEGATE_H
|
#include "piece.h"
Piece::Piece(QImage q) {
q = p;
}
QImage Piece::getImager() {
return p;
}
|
#pragma once
#include "IMoveManager.h"
#include "MoveCalibration.h"
#include "MoveOrientation.h"
#include "EyeController.h"
#include "MoveController.h"
#include "NavController.h"
namespace Move
{
//forward decleration
class MoveController;
class EyeController;
class MoveManager : public IMoveManager
{
EyeController* eye;
int moveCount;
std::vector<MoveController*> moves;
std::vector<MoveData> moveData;
int navCount;
std::vector<NavController*> navs;
std::list<IMoveObserver*> observers;
volatile int FPS;
static MoveManager* instance;
private:
MoveManager();
public:
~MoveManager();
static MoveManager* getInstance()
{
if (instance==0)
instance=new MoveManager();
return instance;
}
//initialization
int initMoves();
void closeMoves();
bool initCamera(int numMoves);
void closeCamera();
int getMoveCount();
int getNavCount();
//observers
void subsribe(IMoveObserver* observer);
void unsubsribe(IMoveObserver* observer);
//move calibration
int pairMoves();
IMoveController* getMove(int moveId);
INavController* getNav(int navId);
IEyeController* getEye();
void moveUpdated(int moveId);
void moveKeyPressed(int moveId, MoveButton button);
void moveKeyReleased(int moveId, MoveButton button);
void navUpdated(int navId, NavData data);
void navKeyPressed(int navId, MoveButton button);
void navKeyReleased(int navId, MoveButton button);
void notify(int moveId, MoveMessage message);
MoveData& getMoveDataEx(int moveId);
};
}
|
/***********************************************************************
* File : pipeline.cpp
* Author : Moinuddin K. Qureshi
* Date : 19th February 2014
* Description : Out of Order Pipeline for Lab3 ECE 6100
**********************************************************************/
#include "pipeline.h"
#include <cstdlib>
#include <cstring>
#include <queue>
extern int32_t PIPE_WIDTH;
extern int32_t SCHED_POLICY;
extern int32_t LOAD_EXE_CYCLES;
// my helper variables
bool verbose = false;
extern int32_t NUM_REST_ENTRIES;
extern int32_t NUM_ROB_ENTRIES;
/**********************************************************************
* Support Function: Read 1 Trace Record From File and populate Fetch Inst
**********************************************************************/
void pipe_fetch_inst(Pipeline *p, Pipe_Latch* fe_latch){
static int halt_fetch = 0;
uint8_t bytes_read = 0;
Trace_Rec trace;
if(halt_fetch != 1) {
bytes_read = fread(&trace, 1, sizeof(Trace_Rec), p->tr_file);
Inst_Info *fetch_inst = &(fe_latch->inst);
// check for end of trace
// Send out a dummy terminate op
if( bytes_read < sizeof(Trace_Rec)) {
p->halt_inst_num=p->inst_num_tracker;
halt_fetch = 1;
fe_latch->valid=true;
fe_latch->inst.dest_reg = -1;
fe_latch->inst.src1_reg = -1;
fe_latch->inst.src1_reg = -1;
fe_latch->inst.inst_num=-1;
fe_latch->inst.op_type=4;
return;
}
// got an instruction ... hooray!
fe_latch->valid=true;
fe_latch->stall=false;
p->inst_num_tracker++;
fetch_inst->inst_num=p->inst_num_tracker;
fetch_inst->op_type=trace.op_type;
fetch_inst->dest_reg=trace.dest_needed? trace.dest:-1;
fetch_inst->src1_reg=trace.src1_needed? trace.src1_reg:-1;
fetch_inst->src2_reg=trace.src2_needed? trace.src2_reg:-1;
fetch_inst->dr_tag=-1;
fetch_inst->src1_tag=-1;
fetch_inst->src2_tag=-1;
fetch_inst->src1_ready=false;
fetch_inst->src2_ready=false;
fetch_inst->exe_wait_cycles=0;
} else {
fe_latch->valid = false;
}
return;
}
/**********************************************************************
* Pipeline Class Member Functions
**********************************************************************/
Pipeline * pipe_init(FILE *tr_file_in){
printf("\n** PIPELINE IS %d WIDE **\n\n", PIPE_WIDTH);
// Initialize Pipeline Internals
Pipeline *p = (Pipeline *) calloc (1, sizeof (Pipeline));
p->pipe_RAT=RAT_init();
p->pipe_ROB=ROB_init();
p->pipe_REST=REST_init();
p->pipe_EXEQ=EXEQ_init();
p->tr_file = tr_file_in;
p->halt_inst_num = ((uint64_t)-1) - 3;
int ii =0;
for(ii = 0; ii < PIPE_WIDTH; ii++) { // Loop over No of Pipes
p->FE_latch[ii].valid = false;
p->ID_latch[ii].valid = false;
p->EX_latch[ii].valid = false;
p->SC_latch[ii].valid = false;
}
return p;
}
/**********************************************************************
* Print the pipeline state (useful for debugging)
**********************************************************************/
void pipe_print_state(Pipeline *p){
std::cout << "--------------------------------------------" << std::endl;
std::cout <<"cycle count : " << p->stat_num_cycle << " retired_instruction : " << p->stat_retired_inst << std::endl;
uint8_t latch_type_i = 0;
uint8_t width_i = 0;
for(latch_type_i = 0; latch_type_i < 4; latch_type_i++) {
switch(latch_type_i) {
case 0:
printf(" FE: ");
break;
case 1:
printf(" ID: ");
break;
case 2:
printf(" SCH: ");
break;
case 3:
printf(" EX: ");
break;
default:
printf(" -- ");
}
}
printf("\n");
for(width_i = 0; width_i < PIPE_WIDTH; width_i++) {
if(p->FE_latch[width_i].valid == true) {
printf(" %d(%d)FE", (int)p->FE_latch[width_i].inst.inst_num, (int)p->FE_latch[width_i].inst.op_type);
} else {
printf(" -- ");
}
if(p->ID_latch[width_i].valid == true) {
printf(" %d(%d)ID", (int)p->ID_latch[width_i].inst.inst_num, (int)p->ID_latch[width_i].inst.op_type);
} else {
printf(" -- ");
}
if(p->SC_latch[width_i].valid == true) {
printf(" %d(%d)SC", (int)p->SC_latch[width_i].inst.inst_num, (int)p->SC_latch[width_i].inst.op_type);
} else {
printf(" -- ");
}
if(p->EX_latch[width_i].valid == true) {
for(int ii = 0; ii < MAX_BROADCASTS; ii++) {
if(p->EX_latch[ii].valid)
{
//std::cout << "ENTERED\n";
printf(" %d(%d)EX", (int)p->EX_latch[ii].inst.inst_num, (int)p->EX_latch[ii].inst.op_type);
}
}
} else {
printf(" -- ");
}
printf("\n");
}
printf("\n");
RAT_print_state(p->pipe_RAT);
REST_print_state(p->pipe_REST);
EXEQ_print_state(p->pipe_EXEQ);
ROB_print_state(p->pipe_ROB);
}
/**********************************************************************
* Pipeline Main Function: Every cycle, cycle the stage
**********************************************************************/
void pipe_cycle(Pipeline *p)
{
p->stat_num_cycle++;
if(verbose)
pipe_print_state(p);
pipe_cycle_commit(p);
pipe_cycle_broadcast(p);
pipe_cycle_exe(p);
pipe_cycle_schedule(p);
pipe_cycle_rename(p);
pipe_cycle_decode(p);
pipe_cycle_fetch(p);
if(p->stat_num_cycle > 20 && verbose)
exit(0);
}
//--------------------------------------------------------------------//
void pipe_cycle_fetch(Pipeline *p){
int ii = 0;
Pipe_Latch fetch_latch;
for(ii=0; ii<PIPE_WIDTH; ii++) {
if((p->FE_latch[ii].stall) || (p->FE_latch[ii].valid)) { // Stall
continue;
} else { // No Stall and Latch Empty
pipe_fetch_inst(p, &fetch_latch);
// copy the op in FE LATCH
p->FE_latch[ii]=fetch_latch;
}
}
// std::cout << "Fetch: " << p->FE_latch[0].valid << "\n";
}
//--------------------------------------------------------------------//
void pipe_cycle_decode(Pipeline *p){
int ii = 0;
int jj = 0;
static uint64_t start_inst_id = 1;
// Loop Over ID Latch
for(ii=0; ii<PIPE_WIDTH; ii++)
{
// std::cout << "DECODE: " << p->FE_latch[0].valid << "\n";
if((p->ID_latch[ii].stall == 1) || (p->ID_latch[ii].valid))
{ // Stall
continue;
}
else
{ // No Stall & there is Space in Latch
for(jj = 0; jj < PIPE_WIDTH; jj++)
{ // Loop Over FE Latch
if(p->FE_latch[jj].valid)
{
if(p->FE_latch[jj].inst.inst_num == start_inst_id)
{ // In Order Inst Found
p->ID_latch[ii] = p->FE_latch[jj];
p->ID_latch[ii].valid = true;
p->FE_latch[jj].valid = false;
start_inst_id++;
break;
}
}
}
}
}
}
//--------------------------------------------------------------------//
void pipe_cycle_exe(Pipeline *p){
int ii;
//If all operations are single cycle, simply copy SC latches to EX latches
if(LOAD_EXE_CYCLES == 1) {
for(ii=0; ii<PIPE_WIDTH; ii++){
if(p->SC_latch[ii].valid) {
p->EX_latch[ii]=p->SC_latch[ii];
p->EX_latch[ii].valid = true;
p->SC_latch[ii].valid = false;
}
}
return;
}
//---------Handling exe for multicycle operations is complex, and uses EXEQ
// All valid entries from SC get into exeq
for(ii = 0; ii < PIPE_WIDTH; ii++) {
if(p->SC_latch[ii].valid) {
EXEQ_insert(p->pipe_EXEQ, p->SC_latch[ii].inst);
p->SC_latch[ii].valid = false;
}
}
// Cycle the exeq, to reduce wait time for each inst by 1 cycle
EXEQ_cycle(p->pipe_EXEQ);
// Transfer all finished entries from EXEQ to EX_latch
int index = 0;
while(1) {
if(EXEQ_check_done(p->pipe_EXEQ)) {
p->EX_latch[index].valid = true;
p->EX_latch[index].stall = false;
p->EX_latch[index].inst = EXEQ_remove(p->pipe_EXEQ);
index++;
} else { // No More Entry in EXEQ
break;
}
}
}
/**********************************************************************
* ----------- DO NOT MODIFY THE CODE ABOVE THIS LINE ----------------
**********************************************************************/
void pipe_cycle_rename(Pipeline *p){
// TODO: If src1/src2 is remapped set src1tag, src2tag
// TODO: Find space in ROB and set drtag as such if successful
// TODO: Find space in REST and transfer this inst (valid=1, sched=0)
// TODO: If src1/src2 is not remapped marked as src ready
// TODO: If src1/src2 remapped and the ROB (tag) is ready then mark src ready
// FIXME: If there is stall, we should not do rename and ROB alloc twice
int prf_id = -1;
int src1_alias = -1;
int src2_alias = -1;
// rename oldest instruction first
if(PIPE_WIDTH > 1)
{
for(int ii = 0; ii < PIPE_WIDTH - 1; ii++)
{
for(int jj = 0; jj < PIPE_WIDTH - ii - 1; jj++)
{
if(p->ID_latch[jj].inst.inst_num > p->ID_latch[jj+1].inst.inst_num)
{
Pipe_Latch temp = p->ID_latch[jj];
p->ID_latch[jj] = p->ID_latch[jj+1];
p->ID_latch[jj+1] = temp;
}
}
}
}
/*if(PIPE_WIDTH == 2)
{
if(p->ID_latch[0].valid == true && p->ID_latch[1].valid == true && \
p->ID_latch[0].inst.inst_num > p->ID_latch[1].inst.inst_num)
{
Pipe_Latch temp = p->ID_latch[0];
p->ID_latch[0] = p->ID_latch[1];
p->ID_latch[1] = temp;
}
}*/
for(int ii = 0; ii < PIPE_WIDTH; ii++)
{
if(!ROB_check_space(p->pipe_ROB) || \
!REST_check_space(p->pipe_REST))
{
if(verbose)
std::cout << "REST OR ROB FULL: STALING ALL ID\n";
// for(int jj = 0; jj < PIPE_WIDTH; jj++)
// {
// p->ID_latch[jj].stall = true;
// }
break;
}
else
{
if(verbose)
std::cout << "REST OR ROB NOT FULL: UN-STALING ALL ID\n";
// for(int jj = 0; jj < PIPE_WIDTH; jj++)
// {
// p->ID_latch[jj].stall = false;
// }
}
// std::cout << p->ID_latch[ii].valid << "\n";
if(p->ID_latch[ii].valid == true && \
p->ID_latch[ii].stall == false)
{
if(verbose)
{
std::cout << "RENAMING INST " << p->ID_latch[ii].inst.inst_num << "\n";
std::cout << "PIPE " << ii << "ARF1 " << p->ID_latch[ii].inst.src1_reg << "\n";
std::cout << "PIPE " << ii << "ARF2 " << p->ID_latch[ii].inst.src2_reg << "\n";
std::cout << "PIPE " << ii << "DEST " << p->ID_latch[ii].inst.dest_reg << "\n";
}
Pipe_Latch_Struct latch_info = p->ID_latch[ii];
p->ID_latch[ii].valid = false;
if(latch_info.inst.src1_reg != -1) // src1_needed
{
latch_info.inst.src1_tag = RAT_get_remap(p->pipe_RAT, \
latch_info.inst.src1_reg);
}
else
{
latch_info.inst.src1_tag = -1;
// latch_info.inst.src1_ready = true;
}
if(latch_info.inst.src2_reg != -1) // src2_needed
{
latch_info.inst.src2_tag = RAT_get_remap(p->pipe_RAT, \
latch_info.inst.src2_reg);
}
else
{
latch_info.inst.src2_tag = -1;
// latch_info.inst.src2_ready = true;
}
src1_alias = latch_info.inst.src1_tag;
src2_alias = latch_info.inst.src2_tag;
if(src1_alias == -1) // no renaming - ready
{
latch_info.inst.src1_ready = true;
}
else if(p->pipe_ROB->ROB_Entries[src1_alias].valid == true && \
p->pipe_ROB->ROB_Entries[src1_alias].ready == true)
{
//latch_info.inst.src1_ready = true;
latch_info.inst.src1_ready = true;
}
else
{
latch_info.inst.src1_ready = false;
}
if(src2_alias == -1) // no renaming - ready
{
//latch_info.inst.src2_ready = true;
latch_info.inst.src2_ready = true;
}
else if(p->pipe_ROB->ROB_Entries[src2_alias].valid == true && \
p->pipe_ROB->ROB_Entries[src2_alias].ready == true)
{
//latch_info.inst.src2_ready = true;
latch_info.inst.src2_ready = true;
}
else
{
latch_info.inst.src2_ready = false;
}
prf_id = ROB_insert(p->pipe_ROB, latch_info.inst);
latch_info.inst.dr_tag = prf_id;
if(verbose)
{
std::cout << "INST TAG INFO FOR " << latch_info.inst.inst_num << "\n";
std::cout << "PIPE " << ii << "SRC1_TAG " << latch_info.inst.src1_tag << "\n";
std::cout << "PIPE " << ii << "SRC2_TAG " << latch_info.inst.src2_tag << "\n";
std::cout << "PIPE " << ii << "DR_TAG " << latch_info.inst.dr_tag << "\n";
}
//RAT_set_remap(p->pipe_RAT, latch_info.inst.dest_reg, prf_id);
if(latch_info.inst.dest_reg != -1) // dest needed
{
// latch_info.inst.dr_tag = prf_id;
RAT_set_remap(p->pipe_RAT, latch_info.inst.dest_reg, prf_id);
}
REST_insert(p->pipe_REST, latch_info.inst);
// std::cout << "Entered Rename\n";
}
}
// my code end
}
//--------------------------------------------------------------------//
void pipe_cycle_schedule(Pipeline *p){
// TODO: Implement two scheduling policies (SCHED_POLICY: 0 and 1)
// my code start
if(SCHED_POLICY==0)
{
for(int jj = 0; jj < PIPE_WIDTH; jj++)
{
uint64_t oldest_inst_num = p->halt_inst_num + 1;
int oldest_inst_ind = -1;
// for(int ii = 0; ii < NUM_REST_ENTRIES; ii++)
for(int ii = 0; ii < NUM_REST_ENTRIES; ii++)
{
if(p->pipe_REST->REST_Entries[ii].inst.inst_num < oldest_inst_num && \
p->pipe_REST->REST_Entries[ii].valid == true && \
(p->pipe_REST->REST_Entries[ii].scheduled == false))
{
oldest_inst_num = p->pipe_REST->REST_Entries[ii].inst.inst_num;
oldest_inst_ind = ii;
}
}
if(oldest_inst_ind == -1)
{
if(verbose)
{
std::cout << "ALL VALID INSTRUCTIONS ARE SCHEDULED\n";
}
p->SC_latch[jj].valid = false;
break; // all valid are scheduled
}
else
{
Inst_Info oldest_inst = p->pipe_REST->REST_Entries[oldest_inst_ind].inst;
if(verbose)
{
std::cout << "OLDEST INST IN REST" << oldest_inst.inst_num << "\n";
}
if(p->SC_latch[jj].valid == false && \
oldest_inst.src1_ready && oldest_inst.src2_ready)
{
REST_schedule(p->pipe_REST, oldest_inst);
p->SC_latch[jj].valid = true;
p->SC_latch[jj].stall = false;
p->SC_latch[jj].inst = oldest_inst;
if(verbose)
{
std::cout << "SCHEDULING INST " << p->SC_latch[jj].inst.inst_num << "\n";
}
}
else // instruction will remain in REST till it's ready
{
if(verbose)
{
std::cout << "NOT SCHEDULED BECAUSE OLDEST INST NOT READY IN REST\n";
}
p->SC_latch[jj].valid = false;
break;
}
}
}
}
if(SCHED_POLICY==1){
// out of order scheduling
// Find valid/unscheduled/src1ready/src2ready entries in REST
// Transfer them to SC_latch and mark that REST entry as scheduled
for(int jj = 0; jj < PIPE_WIDTH; jj++)
{
uint64_t oldest_ready_inst_num = p->halt_inst_num + 1;
int oldest_ready_inst_ind = -1;
// for(int ii = 0; ii < NUM_REST_ENTRIES; ii++)
for(int ii = 0; ii < NUM_REST_ENTRIES; ii++)
{
if(p->pipe_REST->REST_Entries[ii].inst.inst_num < oldest_ready_inst_num && \
p->pipe_REST->REST_Entries[ii].valid == true && \
p->pipe_REST->REST_Entries[ii].scheduled == false &&\
p->pipe_REST->REST_Entries[ii].inst.src1_ready == true && \
p->pipe_REST->REST_Entries[ii].inst.src2_ready == true)
{
oldest_ready_inst_num = p->pipe_REST->REST_Entries[ii].inst.inst_num;
oldest_ready_inst_ind = ii;
}
}
if(oldest_ready_inst_ind == -1)
{
if(verbose)
{
std::cout << "ALL VALID AND READY INSTRUCTIONS ARE SCHEDULED\n";
}
p->SC_latch[jj].valid = false;
break;
// break; // all valid are scheduled
}
Inst_Info oldest_ready_inst = p->pipe_REST->REST_Entries[oldest_ready_inst_ind].inst;
if(verbose)
{
std::cout << "OLDEST READY INST IN REST" << oldest_ready_inst.inst_num << "\n";
}
if(p->SC_latch[jj].valid == false)
{
REST_schedule(p->pipe_REST, p->pipe_REST->REST_Entries[oldest_ready_inst_ind].inst);
p->SC_latch[jj].valid = true;
p->SC_latch[jj].stall = false;
p->SC_latch[jj].inst = p->pipe_REST->REST_Entries[oldest_ready_inst_ind].inst;
if(verbose)
{
std::cout << "SCHEDULING INST " << p->SC_latch[jj].inst.inst_num << "\n";
}
}
else
{
p->SC_latch[jj].valid = false;
}
}
}
// my code end
}
//--------------------------------------------------------------------//
void pipe_cycle_broadcast(Pipeline *p){
// TODO: Go through all instructions out of EXE latch
// TODO: Broadcast it to REST (using wakeup function)
// TODO: Remove entry from REST (using inst_num)
// TODO: Update the ROB, mark ready, and update Inst Info in ROB
for(int ii = 0; ii < MAX_BROADCASTS; ii++)
{
// Inst_Info temp;
if(p->EX_latch[ii].valid == true && \
p->EX_latch[ii].stall == false)
{
if(verbose)
{
std::cout << "BROADCASTING INST " << p->EX_latch[ii].inst.inst_num << " WHICH HAS DEST_REG " << p->EX_latch[ii].inst.dest_reg << "\n";
std::cout << "HENCE BRAODCASTING TAG " << p->EX_latch[ii].inst.dr_tag << "\n";
}
// temp = p->EX_latch[ii].inst;
p->EX_latch[ii].valid = false;
p->pipe_ROB->ROB_Entries[p->EX_latch[ii].inst.dr_tag].inst = p->EX_latch[ii].inst;
REST_wakeup(p->pipe_REST, p->EX_latch[ii].inst.dr_tag);
REST_remove(p->pipe_REST, p->EX_latch[ii].inst);
ROB_mark_ready(p->pipe_ROB, p->EX_latch[ii].inst);
}
}
// my code end
}
//--------------------------------------------------------------------//
void pipe_cycle_commit(Pipeline *p) {
// int ii = 0;
// TODO: check the head of the ROB. If ready commit (update stats)
// TODO: Deallocate entry from ROB
// TODO: Update RAT after checking if the mapping is still valid
for(int ii = 0; ii < PIPE_WIDTH; ii++)
{
if(ROB_check_head(p->pipe_ROB) == true)
{
// Inst_Info ready_inst = p->pipe_ROB->ROB_Entries[p->pipe_ROB->head_ptr].inst;
// int head_ptr = p->pipe_ROB->head_ptr;
Inst_Info ready_inst = ROB_remove_head(p->pipe_ROB);
if(ready_inst.inst_num >= p->halt_inst_num)
{
// std::cout << "HAHAHALT\n";
p->halt = true;
}
if(verbose)
{
std::cout << "COMMITTING INST " << ready_inst.inst_num << "\n";
}
// if((int)p->pipe_RAT->RAT_Entries[ready_inst.dest_reg].prf_id == head_ptr)
if(RAT_get_remap(p->pipe_RAT, ready_inst.dest_reg) == ready_inst.dr_tag)
{
RAT_reset_entry(p->pipe_RAT, ready_inst.dest_reg);
}
p->stat_retired_inst++;
}
}
// my code end
// DUMMY CODE (for compiling, and ensuring simulation terminates!)
// for(ii=0; ii<PIPE_WIDTH; ii++){
// if(p->FE_latch[ii].valid){
// if(p->FE_latch[ii].inst.inst_num >= p->halt_inst_num){
// p->halt=true;
// }else{
// p->stat_retired_inst++;
// p->FE_latch[ii].valid=false;
// }
// }
// }
}
//--------------------------------------------------------------------//
|
#include <iostream>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
long weight;
cin >> weight;
if (weight % 2 == 0)
{
cout << "YES";
}
else
{
cout << "NO";
}
return 0;
}
|
#include "StdAfx.h"
#include "EaseAction.h"
namespace ui
{
bool EaseAction::InitWithAction(IntervalAction* action)
{
if (action == nullptr)
{
return false;
}
if (IntervalAction::InitWithDuration(action->GetDuration()))
{
inner_ = action;
return true;
}
return false;
}
EaseAction::~EaseAction(void)
{
if (inner_)
{
if (inner_->NeedToDeleteWhenStopped())
{
delete inner_;
}
inner_.Reset();
}
}
void EaseAction::StartWithTarget(Control* target)
{
if (target && inner_)
{
IntervalAction::StartWithTarget(target);
inner_->StartWithTarget(target_);
}
else
{
}
}
void EaseAction::Stop(void)
{
if (inner_)
{
inner_->Stop();
}
IntervalAction::Stop();
}
void EaseAction::Update(float time)
{
if (inner_)
{
inner_->Update(time);
}
}
IntervalAction* EaseAction::GetInnerAction()
{
return inner_;
}
EaseRateAction* EaseRateAction::Create(IntervalAction* action, float rate)
{
EaseRateAction *easeRateAction = new (std::nothrow) EaseRateAction();
if (easeRateAction && easeRateAction->InitWithAction(action, rate))
{
return easeRateAction;
}
delete easeRateAction;
return nullptr;
}
bool EaseRateAction::InitWithAction(IntervalAction *action, float rate)
{
if (EaseAction::InitWithAction(action))
{
rate_ = rate;
return true;
}
return false;
}
#define EASE_TEMPLATE_IMPL(CLASSNAME, TWEEN_FUNC, REVERSE_CLASSNAME) \
CLASSNAME* CLASSNAME::Create(IntervalAction* action) \
{ \
CLASSNAME *ease = new (std::nothrow) CLASSNAME(); \
if (ease && ease->InitWithAction(action)) { return ease; }\
delete ease; \
return nullptr; \
} \
CLASSNAME* CLASSNAME::Clone() const \
{ \
if (inner_) return CLASSNAME::Create(dynamic_cast<IntervalAction*>(inner_->Clone())); \
return nullptr; \
} \
EaseAction* CLASSNAME::Reverse() const \
{ \
return REVERSE_CLASSNAME::Create(dynamic_cast<IntervalAction*>(inner_->Reverse())); \
} \
void CLASSNAME::Update(float time) \
{ \
if (inner_) inner_->Update(TWEEN_FUNC(time)); \
}
EASE_TEMPLATE_IMPL(EaseExponentialIn, tweenfunc::expoEaseIn, EaseExponentialOut);
EASE_TEMPLATE_IMPL(EaseExponentialOut, tweenfunc::expoEaseOut, EaseExponentialIn);
EASE_TEMPLATE_IMPL(EaseExponentialInOut, tweenfunc::expoEaseInOut, EaseExponentialInOut);
EASE_TEMPLATE_IMPL(EaseSineIn, tweenfunc::sineEaseIn, EaseSineOut);
EASE_TEMPLATE_IMPL(EaseSineOut, tweenfunc::sineEaseOut, EaseSineIn);
EASE_TEMPLATE_IMPL(EaseSineInOut, tweenfunc::sineEaseInOut, EaseSineInOut);
EASE_TEMPLATE_IMPL(EaseBounceIn, tweenfunc::bounceEaseIn, EaseBounceOut);
EASE_TEMPLATE_IMPL(EaseBounceOut, tweenfunc::bounceEaseOut, EaseBounceIn);
EASE_TEMPLATE_IMPL(EaseBounceInOut, tweenfunc::bounceEaseInOut, EaseBounceInOut);
EASE_TEMPLATE_IMPL(EaseBackIn, tweenfunc::backEaseIn, EaseBackOut);
EASE_TEMPLATE_IMPL(EaseBackOut, tweenfunc::backEaseOut, EaseBackIn);
EASE_TEMPLATE_IMPL(EaseBackInOut, tweenfunc::backEaseInOut, EaseBackInOut);
EASE_TEMPLATE_IMPL(EaseQuadraticActionIn, tweenfunc::quadraticIn, EaseQuadraticActionIn);
EASE_TEMPLATE_IMPL(EaseQuadraticActionOut, tweenfunc::quadraticOut, EaseQuadraticActionOut);
EASE_TEMPLATE_IMPL(EaseQuadraticActionInOut, tweenfunc::quadraticInOut, EaseQuadraticActionInOut);
EASE_TEMPLATE_IMPL(EaseQuarticActionIn, tweenfunc::quartEaseIn, EaseQuarticActionIn);
EASE_TEMPLATE_IMPL(EaseQuarticActionOut, tweenfunc::quartEaseOut, EaseQuarticActionOut);
EASE_TEMPLATE_IMPL(EaseQuarticActionInOut, tweenfunc::quartEaseInOut, EaseQuarticActionInOut);
EASE_TEMPLATE_IMPL(EaseQuinticActionIn, tweenfunc::quintEaseIn, EaseQuinticActionIn);
EASE_TEMPLATE_IMPL(EaseQuinticActionOut, tweenfunc::quintEaseOut, EaseQuinticActionOut);
EASE_TEMPLATE_IMPL(EaseQuinticActionInOut, tweenfunc::quintEaseInOut, EaseQuinticActionInOut);
EASE_TEMPLATE_IMPL(EaseCircleActionIn, tweenfunc::circEaseIn, EaseCircleActionIn);
EASE_TEMPLATE_IMPL(EaseCircleActionOut, tweenfunc::circEaseOut, EaseCircleActionOut);
EASE_TEMPLATE_IMPL(EaseCircleActionInOut, tweenfunc::circEaseInOut, EaseCircleActionInOut);
EASE_TEMPLATE_IMPL(EaseCubicActionIn, tweenfunc::cubicEaseIn, EaseCubicActionIn);
EASE_TEMPLATE_IMPL(EaseCubicActionOut, tweenfunc::cubicEaseOut, EaseCubicActionOut);
EASE_TEMPLATE_IMPL(EaseCubicActionInOut, tweenfunc::cubicEaseInOut, EaseCubicActionInOut);
}
|
#include "GamePch.h"
#include "AI_TogglePlayerMovement.h"
#include "PlayerComp.h"
void AI_TogglePlayerMovement::LoadFromXML( tinyxml2::XMLElement* data )
{
bool movementOn;
data->QueryBoolAttribute( "movement_on", &movementOn );
m_PlayerMovementOn = movementOn;
m_PlayerComp = nullptr;
}
void AI_TogglePlayerMovement::Init(hg::Entity* entity)
{
if (m_PlayerComp == nullptr)
{
m_PlayerComp = Hourglass::Entity::FindByTag( SID( Player ) )->GetComponent<PlayerComp>();
}
}
Hourglass::IBehavior::Result AI_TogglePlayerMovement::Update( Hourglass::Entity* entity )
{
m_PlayerComp->SetMovementLock( m_PlayerMovementOn == 0 );
if (m_PlayerMovementOn)
{
m_PlayerComp->GetEntity()->GetComponent<hg::Motor>()->SetEnabled(false);
}
return IBehavior::kSUCCESS;
}
Hourglass::IBehavior* AI_TogglePlayerMovement::MakeCopy() const
{
AI_TogglePlayerMovement* copy = (AI_TogglePlayerMovement*)IBehavior::Create( SID(AI_TogglePlayerMovement) );
copy->m_PlayerMovementOn = m_PlayerMovementOn;
copy->m_PlayerComp = m_PlayerComp;
return copy;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef ESUTILS_PROFILER_SUPPORT
#include "modules/dom/src/opera/domprofilersupport.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/ecmascript_utils/esasyncif.h"
/* == DOM_ScriptStatistics_lines == */
/* static */ OP_STATUS
DOM_ScriptStatistics_lines::Make(DOM_ScriptStatistics_lines *&lines, DOM_ScriptStatistics *parent)
{
return DOMSetObjectRuntime(lines = OP_NEW(DOM_ScriptStatistics_lines, (parent)), parent->GetRuntime(), parent->GetRuntime()->GetArrayPrototype(), "LinesArray");
}
/* virtual */ ES_GetState
DOM_ScriptStatistics_lines::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_length:
DOMSetNumber(value, parent->statistics->lines.GetCount());
return GET_SUCCESS;
default:
return DOM_Object::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_ScriptStatistics_lines::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_length:
return PUT_READ_ONLY;
default:
return DOM_Object::PutName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_GetState
DOM_ScriptStatistics_lines::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index < 0 || (unsigned) property_index >= parent->statistics->lines.GetCount())
return GetNameDOMException(INDEX_SIZE_ERR, value);
DOMSetString(value, parent->statistics->lines.Get(property_index)->CStr());
return GET_SUCCESS;
}
/* virtual */ ES_PutState
DOM_ScriptStatistics_lines::PutIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index < 0 || (unsigned) property_index >= parent->statistics->lines.GetCount())
return PutNameDOMException(INDEX_SIZE_ERR, value);
else
return PUT_READ_ONLY;
}
/* virtual */ void
DOM_ScriptStatistics_lines::GCTrace()
{
GCMark(parent);
}
/* == DOM_ScriptStatistics_hits == */
/* static */ OP_STATUS
DOM_ScriptStatistics_hits::Make(DOM_ScriptStatistics_hits *&hits, DOM_ScriptStatistics *parent)
{
return DOMSetObjectRuntime(hits = OP_NEW(DOM_ScriptStatistics_hits, (parent)), parent->GetRuntime(), parent->GetRuntime()->GetArrayPrototype(), "HitsArray");
}
/* virtual */ ES_GetState
DOM_ScriptStatistics_hits::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_length:
DOMSetNumber(value, parent->statistics->lines.GetCount());
return GET_SUCCESS;
default:
return DOM_Object::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_ScriptStatistics_hits::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_length:
return PUT_READ_ONLY;
default:
return DOM_Object::PutName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_GetState
DOM_ScriptStatistics_hits::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index < 0 || (unsigned) property_index >= parent->statistics->hits.GetCount())
return GetNameDOMException(INDEX_SIZE_ERR, value);
DOMSetNumber(value, *parent->statistics->hits.Get(property_index));
return GET_SUCCESS;
}
/* virtual */ ES_PutState
DOM_ScriptStatistics_hits::PutIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index < 0 || (unsigned) property_index >= parent->statistics->hits.GetCount())
return PutNameDOMException(INDEX_SIZE_ERR, value);
else
return PUT_READ_ONLY;
}
/* virtual */ void
DOM_ScriptStatistics_hits::GCTrace()
{
GCMark(parent);
}
/* == DOM_ScriptStatistics_milliseconds == */
/* static */ OP_STATUS
DOM_ScriptStatistics_milliseconds::Make(DOM_ScriptStatistics_milliseconds *&milliseconds, DOM_ScriptStatistics *parent, OpVector<double> *vector)
{
return DOMSetObjectRuntime(milliseconds = OP_NEW(DOM_ScriptStatistics_milliseconds, (parent, vector)), parent->GetRuntime(), parent->GetRuntime()->GetArrayPrototype(), "MillisecondsArray");
}
/* virtual */ ES_GetState
DOM_ScriptStatistics_milliseconds::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_length:
DOMSetNumber(value, parent->statistics->lines.GetCount());
return GET_SUCCESS;
default:
return DOM_Object::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_ScriptStatistics_milliseconds::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_length:
return PUT_READ_ONLY;
default:
return DOM_Object::PutName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_GetState
DOM_ScriptStatistics_milliseconds::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index < 0 || (unsigned) property_index >= milliseconds->GetCount())
return GetNameDOMException(INDEX_SIZE_ERR, value);
DOMSetNumber(value, *milliseconds->Get(property_index));
return GET_SUCCESS;
}
/* virtual */ ES_PutState
DOM_ScriptStatistics_milliseconds::PutIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index < 0 || (unsigned) property_index >= milliseconds->GetCount())
return PutNameDOMException(INDEX_SIZE_ERR, value);
else
return PUT_READ_ONLY;
}
/* virtual */ void
DOM_ScriptStatistics_milliseconds::GCTrace()
{
GCMark(parent);
}
/* == DOM_ScriptStatistics == */
/* static */ OP_STATUS
DOM_ScriptStatistics::Make(DOM_ScriptStatistics *&script, DOM_ThreadStatistics *parent, ES_Profiler::ScriptStatistics *statistics)
{
RETURN_IF_ERROR(DOMSetObjectRuntime(script = OP_NEW(DOM_ScriptStatistics, (parent, statistics)), parent->GetRuntime(), parent->GetRuntime()->GetObjectPrototype(), "ScriptStatistics"));
RETURN_IF_ERROR(DOM_ScriptStatistics_lines::Make(script->lines, script));
RETURN_IF_ERROR(DOM_ScriptStatistics_hits::Make(script->hits, script));
RETURN_IF_ERROR(DOM_ScriptStatistics_milliseconds::Make(script->milliseconds_self, script, &statistics->milliseconds_self));
RETURN_IF_ERROR(DOM_ScriptStatistics_milliseconds::Make(script->milliseconds_total, script, &statistics->milliseconds_total));
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_ScriptStatistics::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_lines:
DOMSetObject(value, lines);
return GET_SUCCESS;
case OP_ATOM_hits:
DOMSetObject(value, hits);
return GET_SUCCESS;
case OP_ATOM_millisecondsSelf:
DOMSetObject(value, milliseconds_self);
return GET_SUCCESS;
case OP_ATOM_millisecondsTotal:
DOMSetObject(value, milliseconds_total);
return GET_SUCCESS;
case OP_ATOM_description:
DOMSetString(value, statistics->description.CStr());
return GET_SUCCESS;
default:
return DOM_Object::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_ScriptStatistics::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_lines:
case OP_ATOM_hits:
case OP_ATOM_millisecondsSelf:
case OP_ATOM_millisecondsTotal:
return PUT_READ_ONLY;
default:
return DOM_Object::PutName(property_name, value, origining_runtime);
}
}
/* virtual */ void
DOM_ScriptStatistics::GCTrace()
{
GCMark(parent);
GCMark(lines);
GCMark(hits);
GCMark(milliseconds_self);
GCMark(milliseconds_total);
}
/* == DOM_ThreadStatistics_scripts == */
/* static */ OP_STATUS
DOM_ThreadStatistics_scripts::Make(DOM_ThreadStatistics_scripts *&scripts, DOM_ThreadStatistics *parent)
{
RETURN_IF_ERROR(DOMSetObjectRuntime(scripts = OP_NEW(DOM_ThreadStatistics_scripts, (parent)), parent->GetRuntime(), parent->GetRuntime()->GetArrayPrototype(), "MillisecondsArray"));
unsigned count = parent->statistics->scripts.GetCount();
scripts->items = OP_NEWA(DOM_ScriptStatistics *, count);
for (unsigned index = 0; index < count; ++index)
RETURN_IF_ERROR(DOM_ScriptStatistics::Make(scripts->items[index], parent, parent->statistics->scripts.Get(index)));
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_ThreadStatistics_scripts::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_length:
DOMSetNumber(value, parent->statistics->scripts.GetCount());
return GET_SUCCESS;
default:
return DOM_Object::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_ThreadStatistics_scripts::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_length:
return PUT_READ_ONLY;
default:
return DOM_Object::PutName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_GetState
DOM_ThreadStatistics_scripts::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index < 0 || (unsigned) property_index >= parent->statistics->scripts.GetCount())
return GetNameDOMException(INDEX_SIZE_ERR, value);
DOMSetObject(value, items[property_index]);
return GET_SUCCESS;
}
/* virtual */ ES_PutState
DOM_ThreadStatistics_scripts::PutIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index < 0 || (unsigned) property_index >= parent->statistics->scripts.GetCount())
return PutNameDOMException(INDEX_SIZE_ERR, value);
else
return PUT_READ_ONLY;
}
/* virtual */ void
DOM_ThreadStatistics_scripts::GCTrace()
{
GCMark(parent);
unsigned count = parent->statistics->scripts.GetCount();
for (unsigned index = 0; index < count; ++index)
GCMark(items[index]);
}
/* == DOM_ThreadStatistics == */
/* static */ OP_STATUS
DOM_ThreadStatistics::Make(DOM_ThreadStatistics *&thread, DOM_Profiler *parent, ES_Profiler::ThreadStatistics *statistics)
{
RETURN_IF_ERROR(DOMSetObjectRuntime(thread = OP_NEW(DOM_ThreadStatistics, (statistics)), parent->GetRuntime(), parent->GetRuntime()->GetObjectPrototype(), "ThreadStatistics"));
RETURN_IF_ERROR(DOM_ThreadStatistics_scripts::Make(thread->scripts, thread));
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_ThreadStatistics::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_scripts:
DOMSetObject(value, scripts);
return GET_SUCCESS;
case OP_ATOM_description:
DOMSetString(value, statistics->description.CStr());
return GET_SUCCESS;
case OP_ATOM_hits:
DOMSetNumber(value, statistics->total_hits);
return GET_SUCCESS;
case OP_ATOM_millisecondsTotal:
DOMSetNumber(value, statistics->total_milliseconds);
return GET_SUCCESS;
default:
return DOM_Object::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_ThreadStatistics::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_scripts:
case OP_ATOM_description:
case OP_ATOM_hits:
case OP_ATOM_millisecondsTotal:
return PUT_READ_ONLY;
default:
return DOM_Object::PutName(property_name, value, origining_runtime);
}
}
/* virtual */ void
DOM_ThreadStatistics::GCTrace()
{
GCMark(scripts);
}
/* static */ OP_STATUS
DOM_Profiler::Make(DOM_Profiler *&profiler, DOM_Object *reference)
{
return DOMSetObjectRuntime(profiler = OP_NEW(DOM_Profiler, ()), reference->GetRuntime(), reference->GetRuntime()->GetObjectPrototype(), "Profiler");
}
/* virtual */ void
DOM_Profiler::Initialise(ES_Runtime *runtime)
{
AddFunctionL(start, "start");
AddFunctionL(start, "stop");
}
/* virtual */ ES_GetState
DOM_Profiler::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_onthread:
DOMSetObject(value, onthread);
return GET_SUCCESS;
default:
return DOM_Object::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_Profiler::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_onthread:
if (value->type == VALUE_OBJECT)
onthread = value->value.object;
return PUT_SUCCESS;
default:
return DOM_Object::PutName(property_name, value, origining_runtime);
}
}
/* virtual */ void
DOM_Profiler::GCTrace()
{
GCMark(onthread);
}
/* virtual */ void
DOM_Profiler::OnThreadExecuted(ES_Profiler::ThreadStatistics *statistics)
{
if (onthread)
{
DOM_ThreadStatistics *thread;
if (OpStatus::IsSuccess(DOM_ThreadStatistics::Make(thread, this, statistics)))
{
ES_Value argv[1];
DOMSetObject(&argv[0], thread);
OpStatus::Ignore(GetEnvironment()->GetAsyncInterface()->CallFunction(onthread, GetNativeObject(), 1, argv));
}
}
}
/* virtual */ void
DOM_Profiler::OnTargetDestroyed()
{
}
/* static */ int
DOM_Profiler::start(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
/* Note: this is dangerous. */
DOM_THIS_OBJECT(profiler, DOM_TYPE_OBJECT, DOM_Profiler);
if (!profiler->profiler)
{
CALL_FAILED_IF_ERROR(ES_Profiler::Make(profiler->profiler, profiler->GetRuntime()));
profiler->profiler->SetListener(profiler);
}
return ES_FAILED;
}
/* static */ int
DOM_Profiler::stop(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
/* Note: this is dangerous. */
DOM_THIS_OBJECT(profiler, DOM_TYPE_OBJECT, DOM_Profiler);
OP_DELETE(profiler->profiler);
profiler->profiler = NULL;
return ES_FAILED;
}
#endif // ESUTILS_PROFILER_SUPPORT
|
#ifndef GLOBALS_H
#define GLOBALS_H
/*
* actual definition of the global variables, to be included in the main program
* these are referred to as extern everywhere else
*/
long global_TCP_listen_port=22;
/* variables originally from frame.h */
FRAME* firstpanel;
FRM_ONOFF *ONOFF_hold;
//frame: information
FRAME *FRAME_mblf[2];
bool FRAME_mbl[2];
long* objtype;
FRAME *drg;
bool FRAME_drg_begin;
FRM_TYPE* FRM_type;
FRAME *pn,*lpn,*pn2,*pn3;
FRM_ONOFF *tonoff;
FRM_IMAGE *timage;
FRM_INPUT *tinp;
long FRAME_mb;
HFONT thfont;
FRM_TXT *ttxt;
// rrr
static unsigned int resxa = 1024;
static unsigned int resya = 768;
static unsigned int resxb = 512;
static unsigned int resyb = 384;
static unsigned int respb = resxb*resyb;
static unsigned int resxc = 1200;
static unsigned int resyc = resxc*3/4;
static unsigned int respc = resxc*resyc;
unsigned int resxo = resxa;
unsigned int resyo = resya;
unsigned int resxs = resxb;
unsigned int resys = resyb;
unsigned int resxn1w = resxc;
unsigned int resyn1w = resyc;
unsigned int resxn1m = resxn1w - 260;
unsigned int resyn1m = resxn1m*3/4;
unsigned int respn1m = resxn1m * resyn1m;
unsigned int resxz;
unsigned int resyz;
unsigned int windowsizecyclenum = 0;
unsigned int windowsizecyclemax = 1;
long omx3;
long omy3;
double scalexm = 1.0f;
double scaleym = 1.0f;
// r999 new
surf* uipanelsurf[UI_PANEL_MAX][UI_PANELWIDGET_MAX][UI_WIDGETSTATE_MAX];
int uipanelx[UI_PANEL_MAX][UI_PANELWIDGET_MAX][UI_WIDGETSTATE_MAX];
int uipanely[UI_PANEL_MAX][UI_PANELWIDGET_MAX][UI_WIDGETSTATE_MAX];
int uipanelsizex[UI_PANEL_MAX][UI_PANELWIDGET_MAX][UI_WIDGETSTATE_MAX];
int uipanelsizey[UI_PANEL_MAX][UI_PANELWIDGET_MAX][UI_WIDGETSTATE_MAX];
float uipanelscalex[UI_PANEL_MAX][UI_PANELWIDGET_MAX][UI_WIDGETSTATE_MAX];
float uipanelscaley[UI_PANEL_MAX][UI_PANELWIDGET_MAX][UI_WIDGETSTATE_MAX];
int uipanelscaling[UI_PANEL_MAX][UI_PANELWIDGET_MAX][UI_WIDGETSTATE_MAX];
int uipanelhitenable[UI_PANEL_MAX][UI_PANELWIDGET_MAX][UI_WIDGETSTATE_MAX];
int uipanelusedefaultstatedata[UI_PANEL_MAX][UI_PANELWIDGET_MAX][UI_WIDGETSTATE_MAX];
int uipaneli[UI_PANEL_MAX][UI_PANELWIDGET_MAX];
int uipanelcount;
int uipanelwidgetcount[UI_PANEL_MAX];
int uipanelsidebar, uipanelminimap, uipanelworldmap, uipanelworldmapbar, uipanelpartymemberparent, uipanelactionbarparent, uipanelactiontalkbarparent;
int uipanelactionbar1, uipanelactionbar2, uipaneloptionbar1, uipanelactiontalkbar1, uipanelactiontalkbar2, uipanelactiontalkbar3;
int uipanelpartymember0;
int uipaneloptioninfo;
// s555 turn on/off new changes
int easymodehostn1 = 0;
int enhancehostn1 = 0;
int enhanceclientn1 = 1;
/* function_both */
unsigned char OBJGETDIR_FRAME;
unsigned long BITSleftmask[33];//mask of index-many bits to keep
#ifdef HOST
/* variables originally from function_host.h */
unsigned long newsocket;
unsigned long newsocket_ip;
unsigned long tnewsocket;
unsigned long tnewsocket_ip;
HANDLE hsockets_accept;
DWORD idsockets_accept;
unsigned short AUTOPICKUPfirst;
unsigned short AUTOPICKUPnextfree;
object *AUTOPICKUPobject[65536];
double AUTOPICKUPett[65536];//time at which object was added to list (for later removal)
player *AUTOPICKUPplayer[65536];//player* of npc which used the item
object *AUTOPICKUPpartymember[65536];
unsigned char AUTOPICKUPflags[65536];//1=not-for-sale,2=?,...
unsigned char AUTOPICKUP_OBJECTVALID[1024];//array to quickly check if an item could be an autopickup item
DWORD WINAPI sockets_accept(LPVOID null_value);
unsigned char OBJcheckflags_flags;
unsigned long OBJcheckflags_td;
//unsigned char OBJadd_allow;
object *OBJtmp,*OBJtmp2,*OBJtmp3; /* luteijn: static global variables to make them init to 0? */
object *OBJaddtocontainer_containermore;
unsigned short housex1[HOUSEMAX],housey1[HOUSEMAX],housex2[HOUSEMAX],housey2[HOUSEMAX]; //x,y limits of house
unsigned short housepnext[HOUSEMAX];
unsigned short housepx[HOUSEMAX][512]; unsigned short housepy[HOUSEMAX][512];
unsigned short housecost[HOUSEMAX]; //gold cost per REAL day (deducted if current system day!=logged day)
unsigned short houseinitialcost[HOUSEMAX];
// s111 increase house storage max slots
//unsigned char housestoragenext[HOUSEMAX];
unsigned int housestoragenext[HOUSEMAX];
unsigned short housestoragex[HOUSEMAX][HOUSESTORAGESLOTMAX]; unsigned short housestoragey[HOUSEMAX][HOUSESTORAGESLOTMAX];
unsigned char housestorageadd;
unsigned char housestoragerestore; //flags used when saving/restoring house items in file
unsigned short houseentrancex[HOUSEMAX],houseentrancey[HOUSEMAX];
// t111
//object* moblistnew[50];
//int mobcountnew = 0;
int num;
int addmobnum = 1;
// b111
int buildtablewithstorage = BUILD_TABLEWITHSTORAGE_NO;
int hlocx[BUILD_HOUSEID_MAX][BUILD_SECTIONID_MAX];
int hlocy[BUILD_HOUSEID_MAX][BUILD_SECTIONID_MAX];
object* hobj[BUILD_HOUSEID_MAX][BUILD_OBJPOINTER_MAX];
int arenalocx[BUILD_ARENAID_MAX];
int arenalocy[BUILD_ARENAID_MAX];
int arenasizex[BUILD_ARENAID_MAX];
int arenasizey[BUILD_ARENAID_MAX];
int arenaaddmobnum[BUILD_ARENAID_MAX];
int arenacount = 0;
// c222 allowed to cast spells that are in the last "used/registered" spellbook, even if it's unequiped.
object* playerspellbook = NULL;
//house creation tool 1.0 variables
unsigned short patchx;
unsigned short patchy; //base offset for adding objects/changing basetiles
unsigned short housenumber; //house currently being created (1-?, 0 RESERVED, 65535=non-specific)
/* luteijn: mismatches with patches' use of housenumber=basehousenumber+... Quick fix..
* long basehousenumber=20;
*/
unsigned short basehousenumber;
object *MOVERNEW_OBJECT;
unsigned char OBJmove_allow;
object *OBJlist_list[65536]; //object list
long OBJlist_last;
unsigned long wpf_weight[512][512];//weight of that square (a constant throughout the pathfind process)
unsigned char wpf_sourcedest[512][512];//0=not set, 1=from source, 2=from dest
unsigned long wpf_bestweight[512][512];//lowest weight of the source/dest node that travelled through this point (used for path tracing)
//node array
unsigned short wpf_nx[65536];
unsigned short wpf_ny[65536];
unsigned long wpf_nweight[65536];
unsigned char wpf_nsource[65536];//1 if source else dest
long wpf_lastusedn;
unsigned short wpf_stackn[65536];
long wpf_laststackedn;
unsigned long nweight;//nodeweights to process next
unsigned long nextnweight;
unsigned char join2sourcepath[65536];
unsigned char join2destpath[65536];
unsigned char wpf_nextto;
npc *wpf_npc;
unsigned char wpf_pathfound;
unsigned char wpf_nodeaddflags;
//entry values
unsigned char WPF_NEXTTO;
object *WPF_OBJECT;
//return values
unsigned char WPF_RETURN;
unsigned long WPF_PATHLENGTH;
long WPF_OFFSETX,WPF_OFFSETY;//map offset of array
unsigned short OBJcheckbolt_x,OBJcheckbolt_y; //inpact (x,y) if TRUE
float Ocb_x,Ocb_y,Ocb_gx,Ocb_gy,Ocb_l;
short Ocb_ix,Ocb_iy,Ocb_i,Ocb_il;
object* Ocbo;
object* OBJtl[65536];
unsigned long WTf_i; //next to implement
unsigned long WTf_n; //next unused index
unsigned long WTf_w;
unsigned long WTf_w2;
unsigned long WTf_itemn;
long houseowner_FAILVALUE;
//CON temp
long CONreg[256];
unsigned long CONerr;
unsigned short CONnpc; //NPC tplayer is talking to
unsigned long CONrnd;
long CONnumber;
unsigned long CONqual;
unsigned char CONpartymember;
unsigned long CONport;
unsigned short CONhousecost;
unsigned short CONhouseinitialcost;
npc *CONnpc2; //only valid if #converse is derived from an NPC pointer!
txt *stealing_txt;
unsigned char stealing_MESSAGE;
long objsave_last;
unsigned short objsave_x[65536*4];
unsigned short objsave_y[65536*4];
object *objsave_obj[65536*4]; //pointer to first saved object
float objsave_wait[65536*4];
object *hirl_obj[HIRELINGS_MAX]; //list of hirelings for respawning
float hirl_wait[HIRELINGS_MAX];
object *objsave_node[65536];
long objsave_node_last;
long roundfloat_l;
//getwindspell return values
long WINDSPELL_boltn; long WINDSPELL_boltx[5]; long WINDSPELL_bolty[5];
long WINDSPELL_n; long WINDSPELL_x[128]; long WINDSPELL_y[128];
HANDLE hrevive_infiniteloopexit;
DWORD idrevive_infiniteloopexit;
unsigned char partyadd_checkarray[7][7];
/*
XXXXXXX
XX???XX
X?????X
X?? ??X
X?????X
XX???XX
XXXXXXX
*/
object *HORSEDISMOUNT_HORSEOBJECT;//NULL if unavailable
/* variables originally from function_host.h */
/* moved to function_both section */
#endif /* HOST */
#ifdef CLIENT
/* variables originally from function_client.h */
//GetInput variables
//tab_pressed allows program to trap the tab key
//once trapped it also counts as an enterpressed, so serves a dual purpose
//otherwise tab key inserts an undefined amount of spaces
//it MUST be set after a call to getinput_setup
unsigned char leak=0;
unsigned char GETINPUT_tab_pressed;
txt *GETINPUT_txt;
unsigned char *GETINPUT_enterpressed;
txt *GETINPUT_old; //used to detect new pointers
unsigned long GETINPUT_maxlength; //maximum length of GETINPUT_txt (0=infinite)
long gs_i; //getspr static data
long gs_i2; //getspr static data
long gs_x; //getspr static data
long gs_y; //getspr static data
long gs_t; //getspr static data
unsigned long GSs;
unsigned long GSx;
unsigned long GSy;
unsigned char midikeyboard2[256]; //reverse of midikeybaord array!
unsigned char midikeyboard2_keyon[256]; //whether key is being held or not
short midikeyboard_set;
unsigned char musickeyboard_set;
unsigned char midikeystack[16][256];
float midikeywait[16][256];
unsigned char clientinstrument;
unsigned char playinstrument;
unsigned char midipause;
unsigned char getsound_MOVERSOUND;
unsigned char AMBIENTLIGHT_LIGHTVALUE;
unsigned char AMBIENTLIGHT_SHOWSUN;
txt *STATUSMESSprev[8];//the previous 8 status messages are stored here
txt *STATUSMESSdisplaying;//the message currently being displayed
float STATUSMESSwait;
unsigned char STATUSMESSskipok;//the message will be skipped if any messages are pending
txt *STATUSMESSt;//temp txt for building messages (included to aid conversion from older system)
txt *STATUSMESSpending;
txt *GETSETTING_RAW;//the actualt text between the square brackets [...]
txt *li2_t;
#endif /* CLIENT */
/* variables originally defined in data_both.h */
WSAData wsaData;
struct sockaddr_in server;
bitstream *currentbitstream;
objectinfo obji[4096];
unsigned long oldtime;
unsigned long newtime;
float et;
double ett;
file *log2file;
unsigned long U6O_SIGNATURE;
unsigned char incorrectversionmessage[9];
unsigned char NEThost=0;
unsigned long u6osocket;//host?
unsigned long u6osocket2;//client?
//info for recv and send threads
long socketclientlast;
unsigned long socketclient[SOCKETLAST+1];
unsigned long socketclient_ip[SOCKETLAST+1];
unsigned char socketclient_verified[SOCKETLAST+1];
sockets_info *socketclient_si[SOCKETLAST+1];
sockets_info *socketclient_ri[SOCKETLAST+1];
unsigned short socketclient_packetsizedownloaded[SOCKETLAST+1];
unsigned short socketclient_packetsize[SOCKETLAST+1];
unsigned char socket_timeout[SOCKETLAST+1];
unsigned char socket_disconnect[SOCKETLAST+1];
//temp wait value used by sockets_disconnect to force thread closure if necessary
unsigned char socket_disconnect_wait[SOCKETLAST+1];
bool endprogram; //TRUE if program is ending
HINSTANCE hInst;
TCHAR szWindowClass[100];
TCHAR window_name[100];
TCHAR szTitle[100];
bool keyon[65536]; //TRUE if key is being held down
bool key[65536]; //TRUE if key has been pressed (manually set to FALSE)
bool key_gotrelease[65536]; //UNUSED?
bool keyasc[65536]; //TRUE if the ASCII indexed key has been pressed
long mx;
long my;
long mb; //mouse input values (mb returns the button status)
unsigned long mbclick; //mbclick: recieved mouse_down message for mouse button
unsigned long mbheld; //set if the physical mouse button is being held down and has not been released
long wheel_move;
unsigned char mb_release;
unsigned char SCRLOG_FILEONLY;
double dv;
double dv2;
unsigned short bt[1024][2048]; //4M, top 6 bits reserved (0-1023, valid)
unsigned long sprlnk[1024]; //actual physical offset
unsigned char objpassflags[4096];
unsigned char objfloatflags[4096];
unsigned char tclass_object[65536]; //1=object
unsigned char tclass_mover[65536]; //1=mover 2=2-square mover (used in conjunction with first bit)
unsigned char tclass_fixed[65536]; //1=fixed
unsigned char tclass_build[65536]; //1=square, 2=horizontal, 4=vertically, 8=unique
player *tplayer,*tplayer2,*tplayer3;
npc *tnpc,*tnpc2,*tnpc3;
void* NETplayer;
//storm cloak arrays
unsigned char stormcloak[8][480*480];
unsigned short stormcloak_x[65536];
unsigned short stormcloak_y[65536];
player *stormcloak_player[65536];
short stormcloak_last;
short stormcloak_x2[128]; //local offsets of storm cloak fields to display
short stormcloak_y2[128];
char stormcloak_last2;
unsigned char stormcloak_mask[8][8];
unsigned char u6orevive;
unsigned long u6opi; //u6o program index (0=unknown location)
unsigned long u6opi_old;
unsigned long u6opl; //u6o program line
file *u6orevive_fh;
unsigned long *objname;
unsigned char *objname2;
unsigned long *tsign;
unsigned char *tsign2;
txt *spellname[256];
unsigned char spellreagent[256];
unsigned char spelltarget[256];
unsigned short objfixed_next;
unsigned short objfixed_type[65536]; //number, object types
unsigned short objfixed_index[1024][2048];
unsigned short tobjfixed_next;
unsigned short tobjfixed_type[65536]; //[number of objects],[object type(s)],...
unsigned short tobjfixed_index[1024][2048];
float btime;
float btime_last;
double btime2; //ultra precise universal britannian clock!
unsigned char btimeh; //Britannian hour
unsigned char bday; //day is a value between 1 and 7
long tpx;
long tpy;
long tpl; //used to store each client position (temp)
bool exitrequest;
bool exitrequest_noconfirm;
//local comparison buffer
short mv_i;//number of indexes
short mv_x[MVLISTLAST+1];
short mv_y[MVLISTLAST+1];
unsigned short mv_type[MVLISTLAST+1];//not including top 6 bits
unsigned char mv_dir[MVLISTLAST+1];//direction (0=up, 1=right, 2=down, 3=left)
unsigned char mv_frame[MVLISTLAST+1];//movement frame (only used by host for comparison with previous frame)
object *mv_object[MVLISTLAST+1];//pointer to mover's object (if NULL movement cannot be performed)
unsigned short mv_flags[MVLISTLAST+1];//flags
unsigned char mv_hpmp[MVLISTLAST+1];//this way it's not updated unless a visible change has occurred
unsigned long mv_playerid[MVLISTLAST+1];
unsigned char mv_ktar[MVLISTLAST+1];
unsigned short mv_more[MVLISTLAST+1];//type specific (rider for horses)
//flags/pointers used while comparing buffers
unsigned long mv_last[MVLISTLAST+1];
unsigned long mv_new[MVLISTLAST+1];
unsigned char mover_offseti[7][7];
char mover_offsetx[32];
char mover_offsety[32];
txt *mess1;
txt *mess_UPDATEps;
txt *mess_SF;
unsigned long u6o_namecolour;
unsigned char HOST_portrait_loaded[65536];
unsigned long HOST_portrait_next;
unsigned short *HOST_portrait_data[65536];
unsigned long tu6oid; //temp U6OID
long lastsecond;
long framerate;
long framecount; //framerate frames/sec
#ifdef CLIENT
/* variables originally from data_client.h */
FRAME *pmf;
RECT desktop_rect;
HMIDIOUT midiout_handle;
unsigned char midiout_setup;
unsigned char U6O_DISABLEMUSIC;
unsigned char U6O_DISABLEJOYSTICK;
unsigned char JDISABLED;
unsigned char fonts_added;
float intro_timer;
unsigned short U6OK_DEFAULT[128][2];
unsigned short U6OK[128][2];
unsigned short U6OK_TEMP[128][2];
//1 INSTANTCLICK ON,?
unsigned char U6OK_DEFAULT_FLAGS[128];
unsigned char U6OK_FLAGS[128];
unsigned char U6OK_TEMP_FLAGS[128];
HFONT fnt1;
HFONT fnt2;
HFONT fnt3;
HFONT fnt4;
HFONT fnt5;
HFONT fnt6;
HFONT fnt7;
HFONT fnt1naa;
HFONT systemfont;
surf *intro_ultimavi;
surf *intro_ultimavi2;
//visibility checking arrays
unsigned char vis[34+2][26+2]; //will be used for pathfind as well!
unsigned char vis_window[34+2][26+2];//if =1 window exists here
unsigned char vis_chair[34+2][26+2];//1=up 2=right 3=down 4=left 0=none
unsigned char vischeck[32][24];//0=objects on this square are not visible, 1=they are
unsigned char visalways[256][1024];//bit array, if =1 force visibility
unsigned char vis_bed[34+2][26+2];//1=horizontal bed 2=vertical bed
unsigned char vis_slime[34+2][26+2];//1=slime
unsigned char x5option;
long mixer_volume;
unsigned char mixer_mute;
DWORD mixerid;
MIXERLINE mxl;
MIXERCONTROL mxc;
MIXERLINECONTROLS mxlc;
tMIXERCONTROLDETAILS mixer;
tMIXERCONTROLDETAILS_UNSIGNED mixervolume[2];
MIXERCONTROLDETAILS_BOOLEAN mcb={0} ;
MIXERCONTROLDETAILS mcd;
unsigned short customportrait[3584];
unsigned char customportrait_upload;
unsigned char clientframe;
long ctpx;
long ctpy; //client: screen offset
long ctpx2;
long ctpy2; //client: selected partymember offset
unsigned short cobjtype; //client: object type (selected partymember)
unsigned char pw_encrypt;
unsigned char setup_message;
unsigned char cur_type;
unsigned char userkey;
unsigned char userspell;
unsigned char userspellbook;
unsigned short portlast;
unsigned char deadglobalmessage;
unsigned char keyframe_backup;
unsigned short oceantiles;
unsigned rivertiles;
unsigned char britlens;
unsigned char garglens;
unsigned char xray;
unsigned char peer;
unsigned char tmap;
float wizardeyetimeleft;
float ktar_display;//seconds to display keyboard targetting numbers for
unsigned char talkprev;
unsigned char directionalmove_only;
unsigned char tremor;
unsigned long clientplayerid;//only valid if not 0
txt *namelast;
unsigned char localvoicemessage_return;
float autoscroll;
HKEY tempregkey;
float sysban;
unsigned long namecolour;
HFONT lastfont;
unsigned char voicechat_listeningplayers;
unsigned short voicechat_listeningplayerx[256];
unsigned short voicechat_listeningplayery[256];
unsigned char voicechat_listeningplayeri;
unsigned char voicechat_listeningplayervolume[256];
//VOICE CHAT 1.0+
unsigned char voicechat_permission;
unsigned char voicechat_permissionrequested;
char voicechat_recording;
float voicechat_mciwait;
char voicechat_devicedeallocrequired;
float voicechat_recordtime;
//portrait look
float portraitlook_wait;
unsigned short portraitlook_portrait;
unsigned char portraitlook_equip;
unsigned short portraitlook_type[8];
unsigned char portraitlook_plusbonus[8];
txt* portraitlook_name;
unsigned long portraitlook_namecolour;
//cloud info
unsigned char noclouds;
long cloudidealnum;
unsigned char cloudloaded;
surf *cloudimg[16][4];
unsigned char cloudactive[32];
unsigned char cloudtype[32];
long cloudx[32],cloudy[32];
long cloudheight[32];
unsigned char firstclouds;
//not4sale info
unsigned short not4sale_flags[8];//one index per partymember
DWORD dwMilliSeconds;
UINT wDeviceID;
DWORD dwReturn;
MCI_OPEN_PARMS mciOpenParms;
MCI_RECORD_PARMS mciRecordParms;
MCI_SAVE_PARMS mciSaveParms;
MCI_PLAY_PARMS mciPlayParms;
surf *vs;
unsigned char timelval; //0=full brightness, 15=total darkness
unsigned char endgame; //1=play endgame sequence
float endgame_timer;
unsigned char endgame_message;
long omx;
long omy;
long omb; //used by frame.h
long omx2;
long omy2;
unsigned short vf_mb2_x;
unsigned short vf_mb2_y;
bool U6O_WALKTHRU_REC;
bool U6O_WALKTHRU;
//master volume controls
unsigned char u6ovolume;
unsigned char u6omidivolume;
unsigned char u6omidisetup;
unsigned char u6ovoicevolume;
//wav
unsigned char u6osoundtype_volume[255];
sound *u6osound[255];
unsigned char u6osound_type[255]; //0=combat, etc.
short u6osound_volumechange[255]; //adjust volume of this sound (-255 to 255)
unsigned char u6osound_volume[255]; //0 to 255
bool wavinfo_loaded;
//midi
INFOPORT u6omidi_infoport;
CMidiMusic *u6omidi;
txt *u6omidi_filename[256];
unsigned char u6omidi_volume[255];
bool midiinfo_loaded;
//System information and advance function declarations
HWND hWnd;
HWND hWnd2;
HWND hWnd3;
// rrr
HWND hWnd4;
bool windowchange;
bool gotfocus; //TRUE if program is selected
long scrx; long scry; //size of the window required by the program
bool smallwindow; //use a 512x384 window
bool dxrefresh;
bool nodisplay;
bool isit;
bool host_minimize;
bool setupfail;
/* luteijn: old stuff no longer referenced anywhere:
txt* u6oip; //host ip address
HINTERNET u6o_internet; //internet session
bool u6o_offline=FALSE;
*/
bool u6o_sound;
tagSIZE tagxy;
HDC taghdc;
FRAME* musickeyboard;
client_settings cltset;
client_settings cltset2;
unsigned char clientsettingsvalid;
unsigned char spellrecall_partymember[8];
unsigned char spellrecall_i[8];
/* luteijn:
* option_hires never changes during execution, so made it a #define and #ifdef
*/
unsigned char moonlight;
//wind (local)
char windx2;
char windy2;
//light arrays
unsigned long ls_off,ls_off_add,ls2_off,ls2_off_add;
unsigned char *ls2_p;
unsigned short lval[16][65536];
unsigned char ls[1024*768];
unsigned char ls_moon1[1024*768];
unsigned char ls_moon2[1024*768];
unsigned char ls_moon3[1024*768];
unsigned char ls_moon4[1024*768];
unsigned char ls3[32*3][32*3];
unsigned char ls3b[32*3][32*3];
unsigned char ls5[32*5][32*5];
unsigned char ls5b[32*5][32*5];
unsigned char ls7[32*7][32*7];
unsigned char ls9[32*9][32*9];
unsigned char ls11[32*11][32*11];
unsigned char ls13[32*13][32*13];
unsigned short intro_starx[1024];
unsigned short intro_stary[1024];
long textdisplayi; //ideal line to finish on (can be changed by user)
unsigned char textdisplayupdate;
float client_globalwait = 10;
txt* tshiftnum;
unsigned char shiftnum_show;
unsigned long idlst[1024];
txt *idlst_name[1024];
//surf *idlst_port[1024];
unsigned char idlst_volume[1024];
unsigned long idlst_namecolour[1024];
long idlstn;
bool qkstf_update;
unsigned char inprec; //input receiving
unsigned char inprec_global; //input receiving global
unsigned char nonvis[32][24];
short osn;
short osx[1024]; //y
short osy[1024]; //x (centre)
unsigned short osi[1024]; //index of U6OID
unsigned char oshpmp[1024]; //statusbar
short osvol[1024];
file *u6o_error_file;
unsigned long keyframe;
unsigned long keyframe2;
unsigned long keyframe3;
unsigned long keyframe15;
unsigned long keyframe31; //animation/palette index (0-7)
unsigned long refreshcount; //incremented every refresh
surf* ps;
surf *ps2;
surf *ps3;
surf *ps4;
surf *ps5;
surf *ps6;
surf *ps7;
surf *ps8;
surf *ps640400;
surf *ps320200;
// rrr
surf* psnew1;
surf* psnew1b;
// r999
surf* panelsurf[PANEL_MAX];
int panelx[PANEL_MAX], panely[PANEL_MAX], panelx2[PANEL_MAX], panely2[PANEL_MAX];
long panelmx[PANEL_MAX], panelmy[PANEL_MAX];
double panelscalex[PANEL_MAX], panelscaley[PANEL_MAX];
FRAME panelnew[PANEL_MAX];
int panelcount = 0;
int panelsideui, panelactionbar1, panelactionbar2, panelactiontalkbar1, panelactiontalkbar2, panelminimap;
// r999 new
int hituipaneli, hituiwidgeti;
surf* uipanelimgsurf[UI_PANEL_IMG_MAX];
surf* uiwidgetimgsurf[UI_PANELWIDGET_IMG_MAX][UI_WIDGETSTATE_IMG_MAX];
float uiscalex, uiscaley;
int uiscaling = 0;
int uihover = 1;
surf *uihoveractionbuttonsurf, *uihoveractiontalkbuttonsurf;
// r444
surf *minimaptilesurf, *minimaptilesurf1, *minimaptilesurf2;
surf* minimap_surf_new;
unsigned int minimaptype;
unsigned int minimaptypemax = 0;
int minimapnewx, minimapnewy;
int minimapdeltax, minimaptilexstart, minimaptilexend;
int minimapdeltay, minimaptileystart, minimaptileyend;
int minimapplayerx, minimapplayery;
float minimapstepsize;
// r666
//surf* actionbarsurf[ACTIONBAR_MAX];
//int actionbarmax=1;
//int actionbarx[ACTIONBAR_MAX], actionbary[ACTIONBAR_MAX], actionbuttonsizex, actionbuttonsizey;
//int actionbuttonx[ACTIONBAR_MAX][ACTIONBUTTON_MAX], actionbuttony[ACTIONBAR_MAX][ACTIONBUTTON_MAX];
int actionpending = 0;
int actionlast = 0;
int actionreset = 0;
//surf* actiontalksurf[ACTIONTALKBAR_MAX];
//int actiontalkmax=1;
//int actiontalkx[ACTIONTALKBAR_MAX], actiontalky[ACTIONTALKBAR_MAX], actiontalkbuttonsizex, actiontalkbuttonsizey;
//int actiontalkbuttonx[ACTIONTALKBAR_MAX][ACTIONTALKBUTTON_MAX], actiontalkbuttony[ACTIONTALKBAR_MAX][ACTIONTALKBUTTON_MAX];
int actiontalkfilltext = 0;
//surf* actionbuttonsurf[ACTIONBUTTON_MAX][10];
/*
surf* actiondropsetbuttonsurf;
surf* actiondropupbuttonsurf;
surf* actiondropdownbuttonsurf;
surf* actiondropleftbuttonsurf;
surf* actiondroprightbuttonsurf;
surf* actionfoodfullbuttonsurf;
*/
// r777
int itemtoinv = 0;
int checkstatusmessage = 0;
int foodstatus = 0;
int setdroplocation = 0;
int droplocation = 1;
int droploc = 0;
int playeronscreenxn1, playeronscreenyn1;
// r222
//surf* pspartyorg;
//surf* pspartytemp;
//surf* pspartynew;
//surf* party_surf[8];
unsigned int partyframenewmax = 1;
FRAME* party_frame_new[1];
static unsigned int partyresxn1 = 128;
static unsigned int partyresyn1 = 128;
unsigned int partyresxo = 256;
unsigned int partyresyo = 256;
unsigned int partyresxz = partyresxo;
unsigned int partyresyz = partyresyo;
int newmodestatus = 1;
double partyresscale = 1.0;
// s333
int combatinfo = 0;
int hittarget = 0;
int checkpendingstatusmessage = 0;
int statusmessagependingprevlen = 0;
int statusmessagechanged = 0;
int txtcolprev = 0;
int objtypen1;
player combatinfoplayerprev;
int combatinfoplayerprevinit = 0;
int objremovedn1;
double combatinfoplayerprevett = 0.0f;
int resultinfon1 = 0;
int sfxonscreenn1 = 0;
// s222
int soundn1 = 2;
int combatsoundn1 = 2;
int playstatusmessagesound;
// s444
int enhancen1 = 2;
int showworldmapn1 = 0;
surf* worldmapsurfn1[5];
int worldmapindexn1 = 1;
int updateworldmapn1 = 1;
int showenhancehostn1 = 1;
HFONT txtfntoldn1;
// s555
int updatepartyframen1 = 0;
surf* bt32;
surf* bt16;
surf* spr84[16];
surf* spr8[8];
surf* sfx8;
surf* bt8[8];
sound* SNDhit;
//sf compatible information
sfxtype sfx[256]; //local sf
unsigned char update[8]; //set to 1 if party frame needs updating
unsigned char action; //active action key
unsigned char sprpi[65536];//index in pal emu spr8
//portraits 2.0 info
surf* portrait[65536];//regular size portraits
surf* portrait_doublesize[65536];//double size
surf* portrait_halfsize[65536];//half size
unsigned char portrait_loaded[65536];//TRUE=PORTRAIT LOADED
unsigned char portrait_requested[65536];//TRUE=portrait has been requested
txt *portrait_request_txt;
surf* PORTRAIT_UNAVAILABLE;
unsigned char wateri[32]; //used for hybrid sea tiles
object* mobj; //selected (mouse) object *local
object *moon1;
player *CLIENTplayer;
player *tplay; //client temp. player struct
short stolenitemwarningn;
unsigned short stolenitemwarningx[256];
unsigned short stolenitemwarningy[256];
unsigned short stolenitemwarningtype[256];
unsigned char client_spellwait[8];
txt* inpmess;
inpmess_index *inpmess_mostrecent;
long inpmess_selected;
surf *surf_tremor,*surf_tremor2,*surf_tremorcirclemask;
surf *intro_startup;
unsigned short walkthru_x;
unsigned short walkthru_y;
file *walkthru_fh;
unsigned long walkthru_pos_skip;
unsigned long walkthru_pos;
JOYINFOEX joy;
txt *u6o_user_name;
txt *u6o_user_password;
txt *u6o_name;
unsigned char u6o_malefemale;//0=male, 1=female
unsigned short u6o_portrait;
unsigned char u6o_type;
unsigned char u6o_vq[28];//0=a,1=b
unsigned char u6o_createcharacter;//obselete!
txt *u6o_new_user_password;
surf *spellicon[256];
unsigned long midi_song; //handle to current midi
short midi_loaded;
short midi_background;
short midi_foreground;
float midi_foreground_wait;
txt *con_txt[8];
surf* party_spellbook_surf[8];
FRAME* party_spellbook_frame[8];
unsigned short spell[8][256]; //number of times spell can be cast (+1)
unsigned char spellbook_page[8]; //current page in spellbook
unsigned char spellbook_flags[8]; //1=left dog-ear 2=right dog-ear
surf* party_surf[8];
FRAME* party_frame[8];
surf* minimap_surf;
FRAME* minimap_frame;
surf* minimap_b;
surf* treasuremap;
surf* tmap_surf;
FRAME* tmap_frame;
surf* tmap_markers;
surf* tmap_marker;
object* tobj_i[8][16+1+4+1];
object* tobj_e[8][8];
unsigned char intro; //part of intro to process (0=ingame!)
unsigned char cltset2_restored;
file* messagelog;
FRAME* fs;
surf* status8;
surf* darrow;
surf* uarrow;
surf* horizon;
surf* horizon2;
surf* cave;
surf* sun;
surf* sun2;
surf* mini_1;
surf* tmini_1;
surf* mini_2;
surf* mini_3;
surf* u6ob;
surf* dhno;
surf* not4sale;
surf* not4salemask;
surf* converse_arrows;
surf* spellbook;
surf* spellbookmini;
surf* statusmessage_arrowup;
surf *spellcircle[8];
surf *statusbar_r255;
surf *statusbar_r128;
surf *statusbar_b255;
surf *statusbar_b128;
surf *statusbar_g255;
surf *statusbar_g128;
surf* statusbar;
surf *dogearr;
surf *dogearl;
surf *spellbookline;
surf *intro_gypsy;
surf *intro_gypsy2;
surf *intro_vial;
surf *intro_svial;
surf *intro_bigvial;
surf *intro_hpl0;
surf *intro_hpl2;
surf *intro_hpl3;
surf *intro_hps0;
surf *intro_hps2;
surf *intro_hps3;
surf *intro_hpr0;
surf *intro_hpr2;
surf *intro_hpr3;
surf *intro_arml;
surf *intro_armr;
surf *intro_s64;
surf *intro_s64b;
surf *intro_s128;
surf *intro_ab;
surf *intro_aba;
surf *intro_abb;
surf *intro_caravan;
surf *intro_flask;
surf *intro_ccsave1;
surf *intro_ccsave2;
surf *intro_ccsave3;
surf *intro_tacinfo;
surf *intro_newchar;
surf *intro_newchar2;
surf *intro_x;
surf *intro_back;
surf *intro_next;
surf *intro_ifield;
surf *blr[4];
surf *glr[4];
surf *instantclickx;
surf *instantclickok;
surf *endgame_image[10];
surf *spellbookmini2;
surf *voicechat_voicebar;
surf *voicechat_voice1;
surf *voicechat_voiceof;
surf *inventoryadd_icon;
surf *horsemask;
surf *horsemask2;
surf *horsemaskdress;
surf *horsemask2dress;
surf *horsemaskdressb;
surf *horsemask2dressb;
surf* port_temp;
surf* vm_volumem;
surf* vm_volmmute;
surf* vm_voltab2m;
surf* volcontrol_background;
surf* volcontrol_surf;
surf* volcontrol_tab1;
surf* volcontrol_tab2;
surf* volcontrol_tab3;
surf* viewnpc;
surf* viewnpc2;
surf* viewnpc_temp;
surf* viewnpc2_temp;
FRAME* statusmessage_viewnpc;
FRAME* statusmessage_viewprev;
FRAME* voicechat_frame;
FRAME* volcontrol;
FRAME* qkstf;
FRM_IMAGE *con_frm_img;
FRAME* con_frm;
FRM_TXT* inpft;
FRM_INPUT *inpf2;
txt *inpftxt;
FRAME* inpf;
FRAME* vf;
HCURSOR cur1;
HCURSOR cur2;
HCURSOR cur3;
HCURSOR cur4;
HCURSOR cur5;
HCURSOR cur6;
HCURSOR cur7;
HCURSOR cur8;
HCURSOR cur9;
HCURSOR cur_u;
HCURSOR cur_ru;
HCURSOR cur_r;
HCURSOR cur_rd;
HCURSOR cur_d;
HCURSOR cur_ld;
HCURSOR cur_l;
HCURSOR cur_lu;
#endif /* CLIENT */
#ifdef HOST
/* variables originally from data_host.h */
unsigned char save_buffer[SAVESLOTLAST+1];
txt *save_username[SAVESLOTLAST+1];
txt *save_password[SAVESLOTLAST+1];
txt *save_name[SAVESLOTLAST+1];
unsigned long save_exp[SAVESLOTLAST+1];
unsigned long save_bytes[SAVESLOTLAST+1];
unsigned char save_dump;
unsigned char login_dead_callback;
//1=mover drops blood, 0=mover doesn't drop blood
unsigned char mover_blood[1024];
unsigned short mover_body[1024];
unsigned char sfbuffersend;
float sfbufferwait;
unsigned char cast_spell;
unsigned char staff_cast_spell;
long CASTSPELL_SPELLTYPE;
txt *admins[ADMINSMAX];
txt *motd;
txt *inbritannia;
long inbritannia_totalplayers;
unsigned long U6ONEWID; //never 0
housesav_info housesav[256];
//orb of the moons destinations
unsigned short orbx[5][5];
unsigned short orby[5][5];
//wind direction (global)
char windx;
char windy;
unsigned char windnew;
unsigned char party_ok[8];
unsigned short save_version;
unsigned char encryptcode[65536];
unsigned char itemused;
bool spellattcrt;
unsigned short autosetup;
bool autosetup_next;
unsigned short autosetup_counter;
bool autospell;
unsigned long treagent[8];
unsigned long tspell[256]; //set to 1 if spell exists, then added to if reagents exist
//jump/call-back flag for formatting username and charactername
unsigned char format_usernames;
unsigned long objr_x;
unsigned long objr_y;
schedule_i schedule[256][32];
schedule_i schedule2[1024][32];
unsigned long npci[256];
unsigned char *npcinf;
npcbin_i *npcbin;
unsigned long sfi[256][256]; //pointer to first sf
sfxtype sf[65536]; //clear every cycle
unsigned long sf_playerid[65536];//only valid for text messages where top bit of port is set
long sfn; //last sf
unsigned long sfx_playerid[256];
unsigned char btu6[1024][1024];
unsigned char btu60[256][256];
unsigned short npcobj[256];
objentry ol[32768]; //modify to allow for more complex base maps
long oln;
unsigned char btflags[256];
object objb[524228]; //host object buffer ~10M
long objb_last; //last objb
unsigned long objb_free[524228]; //free objb index
long objb_free_last; //last free objb index
//doorclose: automatically locks unlocked doors after 2 hours if unused and noone has passed through
long doorclose_last;
float doorclose_wait[1024];
object *doorclose_obj[1024],*doorclose_obj2[1024];
unsigned short doorclose_oldtype[1024],doorclose_oldtype2[1024];
//leverchange
long leverchange_last;
float leverchange_wait[1024];
object *leverchange_obj[1024];
unsigned short leverchange_oldtype[1024];
unsigned char showmoongates;
unsigned short moongatex[8],moongatey[8];
object *moongate[8][2];
unsigned char moonphase;
object *nuggetsfix;
//volatile links (vlnk)
void *vlnkb_lnk[65536]; //vlnk buffer ~0.25M lnk (dest) object
unsigned long vlnkb_off[65536]; //vlnk buffer ~0.25M lnk offset
void *vlnkb_lnks[65536]; //vlnk buffer ~0.25M lnk source object
long vlnkb_last; //last
unsigned long vlnkb_free[65536]; //free vlnkb index
long vlnkb_free_last; //last free vlnkb index
//functions
//VLNK_new(_lnks,_lnk,_off)
//VLNK_remove(_lnk) NULL any link pointing to this object, then remove vlnk
//VLNK_sremove(_lnk) remove any vlnk belonging to _lnk
object* portcullis[256][16];
object* lever[256][16];
object* efield[256][16]; //electric field
object* eswitch[256][16]; //electric switch
crtenum_struct crtenum[1073];
object* crtenum_pathok_castok[1024]; short crtenum_pathok_castok_i;
object* crtenum_pathok[1024]; short crtenum_pathok_i;
object* crtenum_castok[1024]; short crtenum_castok_i;
//resurrect info
object *resu[65536]; //object
object *resu_body[65536]; //dead body object
unsigned short resu_body_type[65536];//object type of dead body (used to remake lost body and check if correct)
float resu_wait[65536]; //time until object automatically resurrected
player *resu_player[65536]; //player object belongs to
unsigned char resu_partymember[65536]; //party member index
unsigned short resu_x[65536],resu_y[65536];
long nresu;
//wizard eye(s) list: locations of wizard eyes currently displayed in britannia
unsigned char wizardeyesi;
unsigned short wizardeyesx[256];
unsigned short wizardeyesy[256];
unsigned char wizardeyesi2;
unsigned char wizardeyesadded;
object *wizardeyesobj;
unsigned char economy_setup[1024][4];
long economy_limit[1024][4];
long economy_value[1024][4];
long economy_change[1024][4];
//when a monster is "killed" it is added to the respawn list
//a delay is also set
//
//respawn info
object *respawn[1200];
unsigned short respawn_delay[1200]; //number of seconds till creature will respawn
//*note: creature will not respawn if player is too near (eg. 8 squares or less)
long respawn_last;
player* playerlist[1024]; //supports up to 1024 online players
long playerlist_last;
unsigned char chunks[1024][8][8]; //"c:\ultima6\chunk."
unsigned char u6wci2[8][8][16][8][3];
unsigned short u6wci[128][128];
unsigned char u60ci2[32][16][3];
unsigned short u60ci[32][32];
object *od[1024][2048]; //8M, pointers to all data, NULL pointers are common
object *oul[65536]; //list of active objects to update (size: 1M)
long ouln;
object *f_oul[65536]; //list of fixed objects to update
long f_ouln;
txt *tname;
txt *tusername;
txt *tuserpassword;
txt *tnewuserpassword;
unsigned char tcustomportrait_upload;
unsigned short tcustomportrait[3584];
unsigned long tnamecolour;
unsigned char tmale_female;
unsigned short tport;
unsigned short ttype;
unsigned char tcreatecharacter;
//keyb target
char ktar_x[768];
char ktar_y[768];
float ktar_xydis[768];
/*
MOVERNEW: FLAGS
flags can be set globally, in which case they need to be reset when finished
or locally by being passed as flags
local flags and OR-ed with global flags
*/
unsigned long MOVERNEW_GLOBALFLAGS;
unsigned char MOVERNEW_ERROR;//valid when movernew(...) returns 0
//1=FAILED (object is not a mover)
//2=IGNORED (object is not the primary part of a mover)
#ifndef CLIENT
//STUBS TO SUPPORT EXTERNAL LINKING (DATA NOT ACTUALLY USED!)
unsigned char u6omidisetup;
HWND hWnd;
HWND hWnd2;
HWND hWnd3;
HWND hWnd4;
RECT desktop_rect;
bool smallwindow;
unsigned char u6ovolume;
#endif /* !CLIENT */
unsigned long revive_infiniteloopexit_i;
unsigned long revive_infiniteloopexit_i2;
unsigned short revive_infiniteloopexit_i3;
unsigned long mycount;
long newschedule2;
object* newll;
unsigned long ol_tag;
unsigned long ol_tag_prev;
#endif /* HOST */
/* */
#endif /* GLOBALS_H */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.