blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aa78586b2020a29e2c084994201e24d99fc4abfe | bcbe36507f65b110e91ae676b664705ea1c4fad7 | / cudaandmfc --username ct.radiate/stdafx.cpp | 4976b3f978e21fb5cb255f1913f88bfdfb54e01d | [] | no_license | kimjinchoul/cudaandmfc | 7d22f968aa325823ca2b466daf1287d21a068908 | 3237b553b5cb212b0d74e54558afcd89c7e4636b | refs/heads/master | 2020-12-24T15:32:19.590406 | 2008-12-17T09:08:50 | 2008-12-17T09:08:50 | 33,848,804 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 171 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// TestDialog.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
| [
"ct.radiate@c46f0c90-cbed-11dd-8ca8-e3ff79f713b6"
] | [
[
[
1,
7
]
]
] |
6906a368076273f4b77c40e9f40da1014f97e68f | b8ac0bb1d1731d074b7a3cbebccc283529b750d4 | /Code/controllers/RecollectionBenchmark/vision/Garbage.h | 14ee0b900196017d2bae940840a0fd5a6ffd373f | [] | no_license | dh-04/tpf-robotica | 5efbac38d59fda0271ac4639ea7b3b4129c28d82 | 10a7f4113d5a38dc0568996edebba91f672786e9 | refs/heads/master | 2022-12-10T18:19:22.428435 | 2010-11-05T02:42:29 | 2010-11-05T02:42:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | h | #ifndef vision_Garbage_h
#define vision_Garbage_h
#include <vision/MinimalBoundingRectangle.h>
#include <vector>
#include "Contours.h"
namespace vision{
class Garbage {
public:
vision::MinimalBoundingRectangle * boundingBox();
Garbage(vision::MinimalBoundingRectangle * mbr);
Garbage(vision::MinimalBoundingRectangle * mbr,std::vector<int> centroid);
Garbage(vision::MinimalBoundingRectangle * mbr,std::vector<int> centroid,Contours * contour);
std::vector<int> getCentroid();
~Garbage();
double area;
double perimeter;
//benchmark purposes
bool isPredicted;
bool isVisualized;
bool isFocused;
private:
std::vector<int> centroid;
vision::MinimalBoundingRectangle * mbr;
};
}
#endif // vision_Garbage_h
| [
"nachogoni@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a"
] | [
[
[
1,
40
]
]
] |
64f367708f76cd2d581ff21d36c25400e0c5d39a | b6a6fa4324540b94fb84ee68de3021a66f5efe43 | /Duplo/include/Dup_ModuleOutput.h | 86532685a5b4cc8fb6e035cd245a03663e971395 | [] | no_license | southor/duplo-scs | dbb54061704f8a2ec0514ad7d204178bfb5a290e | 403cc209039484b469d602b6752f66b9e7c811de | refs/heads/master | 2021-01-20T10:41:22.702098 | 2010-02-25T16:44:39 | 2010-02-25T16:44:39 | 34,623,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,697 | h |
#ifndef _DUP_MODULE_OUTPUT_
#define _DUP_MODULE_OUTPUT_
#include "Dup_Declares.h"
#include "Dup_List.h"
#include "Dup_ModuleInput.h"
namespace Dup
{
//const static dup_val DUP_VAL_ZERO = 0.0; // how to fix this?
class Dup_ModuleOutput
{
private:
dup_val *sourceValue;
Dup_List<void *, NULL> destinations;
public:
Dup_ModuleOutput(dup_val *sourceValue) : destinations()
{
this->sourceValue = sourceValue;
}
// warning, point sourceValue to a zero value
Dup_ModuleOutput() : destinations()
{
}
/*
* returns true if soruce value pointer where NULL
* before call
*/
bool setSourcePointer(dup_val *sourceValue)
{
if (sourceValue == NULL)
{
this->sourceValue = sourceValue;
return true;
}
this->sourceValue = sourceValue;
return false;
}
/*
* returns the pointer to the sourcevalue
* that this unit outputs.
*/
dup_val *getSourcePointer()
{
return sourceValue;
}
/*
* returns the sourcevalue
* that this unit outputs.
*/
dup_val getSourceValue()
{
return *sourceValue;
}
/*
* adds a destinationUnit to this outputUnit
*/
void addDestinationUnit(Dup_ModuleInput *dest)
{
destinations.add(dest);
}
/*
* get all destinationUnits
*/
Dup_List<void *, NULL> *getDestinationUnits()
{
return &destinations;
}
inline bool connect(Dup_ModuleInput *destUnit, bool check = true)
{
return destUnit->connect(this, check);
}
inline bool disconnect(Dup_ModuleInput *destUnit)
{
return destUnit->disconnect(this);
}
};
};
#endif | [
"t.soderberg8@2b3d9118-3c8b-11de-9b50-8bb2048eb44c"
] | [
[
[
1,
106
]
]
] |
7c58aa6728dad42ec31087d5e678f5e1191d6632 | c1996db5399aecee24d81cd9975937d3c960fa6c | /src/treeitem.h | 98032c585dc433cd6d46e5355d46e619f2a93b1d | [] | no_license | Ejik/Life-organizer | 7069a51a4a0dc1112b018f162c00f0292c718334 | 1954cecab75ffd4ce3e7ff87606eb11975ab872d | refs/heads/master | 2020-12-24T16:50:25.616728 | 2009-10-28T06:30:18 | 2009-10-28T06:30:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 816 | h | #ifndef TREEITEM_H
#define TREEITEM_H
#include <QList>
#include <QVariant>
#include <QVector>
//! [0]
class TreeItem
{
public:
TreeItem(const QVector<QVariant> &data, TreeItem *parent = 0);
~TreeItem();
TreeItem *child(int number);
int childCount() const;
int columnCount() const;
QVariant data(int column) const;
bool insertChildren(int position, int count, int columns);
bool insertColumns(int position, int columns);
TreeItem *parent();
bool removeChildren(int position, int count);
bool removeColumns(int position, int columns);
int childNumber() const;
bool setData(int column, const QVariant &value);
private:
QList<TreeItem*> childItems;
QVector<QVariant> itemData;
TreeItem *parentItem;
};
//! [0]
#endif
| [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
d477cf1f7a3f3f5014c6542ab9910fac72c0422a | 27bde5e083cf5a32f75de64421ba541b3a23dd29 | /source/Log.h | 07fb916e8d8cbb59a4225736b78aad42db38cd57 | [] | no_license | jbsheblak/fatal-inflation | 229fc6111039aff4fd00bb1609964cf37e4303af | 5d6c0a99e8c4791336cf529ed8ce63911a297a23 | refs/heads/master | 2021-03-12T19:22:31.878561 | 2006-10-20T21:48:17 | 2006-10-20T21:48:17 | 32,184,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | h | //---------------------------------------------------
// Name: Game : Log
// Desc: logs information
// Author: John Sheblak
// Contact: [email protected]
//---------------------------------------------------
#ifndef _GAME_LOG_H_
#define _GAME_LOG_H_
#include <vector>
namespace Game
{
//-----------------------------------------------------------
// Name: Log
// Desc: the log serves as a central hub for all debug msg
// processing. Callback functions register themselves
// with the log and the Log will pass them msgs. We
// could have one callback that prints to screen and
// another that prints to file and call SLog->Print()
// will give the msgs to both.
//-----------------------------------------------------------
class Log
{
public:
typedef void (*LogCallback)( const char* msg );
public:
void RegisterCallback( LogCallback cb );
void Print( const char* msg );
static Log* GetLog();
private:
typedef std::vector<LogCallback> CallbackList;
CallbackList mCallbacks;
};
#define SLog (Log::GetLog())
}; //end Game
#endif // end _GAME_LOG_H_
| [
"jbsheblak@5660b91f-811d-0410-8070-91869aa11e15"
] | [
[
[
1,
49
]
]
] |
8cdec264d31a787045353d487f1f2acd634d96a2 | 78aa965c7ca9fc4a09d8a6156a2d3f0741ebd3ee | /3-IHM/IHM_CIAI/widgetcommande.h | d9ba3a6a37fd96f6e350513d8012ba78564b018e | [] | no_license | h4402/CIAI | b784e3aa73adc0f2e39949a6ac926a1934c70f49 | bf4e16d97dca8752b7ed61b2549c6a82728af310 | refs/heads/master | 2021-01-10T18:31:01.121410 | 2011-11-21T17:35:38 | 2011-11-21T17:35:38 | 2,758,537 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | h | #ifndef WIDGETCOMMANDE_H
#define WIDGETCOMMANDE_H
#include <QtGui/QWidget>
#include "ciaiProtocol.h"
namespace Ui {
class WidgetCommande;
}
class WidgetCommande : public QWidget {
Q_OBJECT
Q_DISABLE_COPY(WidgetCommande)
public:
explicit WidgetCommande(unsigned int numCom, unsigned int nNbT1,
unsigned int nNbT2, unsigned short noQuai,
const char dest[10], QWidget *parent = 0);
virtual ~WidgetCommande();
protected:
virtual void changeEvent(QEvent *e);
private:
Ui::WidgetCommande *m_ui;
MsgExpOrd commande;
};
#endif // WIDGETCOMMANDE_H
| [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
53da362e39f227cb757ed4a3e7c1b424b48883ae | 1add5c4fe49767e1abf7afeaf97a75244f5cfee8 | /ActiveContoursWithoutEdges/Algorithms/Sparse/itkSparseMultiphaseLevelSetImageFilter.h | 64565eb3e3b04e95a4b52389970258de2a7d2fb6 | [] | no_license | midas-journal/midas-journal-322 | ba4613d01d01f4df12b4f4f30d58e786d3d613a6 | 3b91c15af4bb19d30575d50d47f95ec37b9ead11 | refs/heads/master | 2021-01-25T12:14:39.791030 | 2011-08-22T13:46:18 | 2011-08-22T13:46:18 | 2,248,622 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,055 | h | #ifndef __itkSparseMultiphaseLevelSetImageFilter_h_
#define __itkSparseMultiphaseLevelSetImageFilter_h_
#include "itkSparseMultiphaseSegmentationLevelSetImageFilter.h"
#include "itkScalarChanAndVeseSharedFunctionData.h"
#ifdef VIZU
#include "vtkVisualize2DImplicitFunction.h"
#include "vtkVisualize3DImplicitFunction.h"
#endif
namespace itk
{
template < class TInputImage, // LevelSetImageType
class TFeatureImage, // FeatureImageType
class TFunctionType,
typename TOutputPixel = typename TInputImage::PointType::CoordRepType >
class ITK_EXPORT SparseMultiphaseLevelSetImageFilter:
public SparseMultiphaseSegmentationLevelSetImageFilter< TInputImage, TFeatureImage, TOutputPixel >
{
public:
typedef SparseMultiphaseLevelSetImageFilter Self;
typedef SparseMultiphaseSegmentationLevelSetImageFilter< TInputImage,
TFeatureImage, TOutputPixel > Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( SparseMultiphaseLevelSetImageFilter,
SparseMultiphaseSegmentationLevelSetImageFilter );
void PrintSelf( std::ostream& os, Indent indent) const;
/** Repeat definition from Superclass to satisfy Borland compiler quirks */
itkStaticConstMacro( ImageDimension, unsigned int,
TInputImage::ImageDimension );
/** Inherited typedef from the superclass. */
typedef TFeatureImage FeatureImageType;
typedef typename FeatureImageType::PixelType FeaturePixelType;
/** Output image type typedefs */
typedef Image< TOutputPixel, ImageDimension > OutputImageType;
typedef typename OutputImageType::ValueType ValueType;
typedef typename OutputImageType::IndexType IndexType;
typedef typename Superclass::TimeStepType TimeStepType;
typedef typename Superclass::FiniteDifferenceFunctionType
FiniteDifferenceFunctionType;
typedef typename Superclass::InputImageType InputImageType;
typedef TFunctionType FunctionType;
typedef ScalarChanAndVeseSharedFunctionData< InputImageType,
FeatureImageType > SharedDataType;
typedef typename SharedDataType::Pointer SharedDataPointer;
#ifdef VIZU
typedef vtkVisualize2DImplicitFunction< InputImageType, FeatureImageType >
vtkVisualizeImplicitFunctionType;
#endif
#ifdef ITK_USE_CONCEPT_CHECKING
/** Begin concept checking */
itkConceptMacro(OutputHasNumericTraitsCheck,
(Concept::HasNumericTraits<TOutputPixel>) );
/** End concept checking */
#endif
virtual FunctionType *GetTypedDifferenceFunction(
unsigned int functionIndex )
{
return static_cast< FunctionType* >
( & ( **this->m_DifferenceFunctions[functionIndex] ) );
}
void SetFunctionCount( unsigned int n )
{
Superclass::SetFunctionCount( n );
for( unsigned int i = 0; i < this->FunctionCount; i++ )
{
this->m_DifferenceFunctions[i] = new typename
FiniteDifferenceFunctionType::Pointer();
(*this->m_DifferenceFunctions[i]) = FunctionType::New();
SetSegmentationFunction( i, GetTypedDifferenceFunction( i ) );
}
}
protected:
SparseMultiphaseLevelSetImageFilter()
{
this->SetNumberOfLayers(5); // Narrow-band usage
sharedData = SharedDataType::New();
}
~SparseMultiphaseLevelSetImageFilter()
{
for ( unsigned int i = 0; i < this->FunctionCount; i++ )
delete this->m_DifferenceFunctions[i];
}
#ifdef VIZU
vtkVisualizeImplicitFunctionType func;
#endif
SharedDataPointer sharedData;
virtual void Initialize();
virtual void InitializeIteration();
virtual void UpdatePixel( unsigned int functionIndex,
unsigned int idx, NeighborhoodIterator< OutputImageType > &iterator,
ValueType &newValue, bool &status );
};
} //end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkSparseMultiphaseLevelSetImageFilter.txx"
#endif
#endif
| [
"[email protected]"
] | [
[
[
1,
124
]
]
] |
dac9e24cb5fd0298d8b046562119905fc10eb583 | 6f8721dafe2b841f4eb27237deead56ba6e7a55b | /src/WorldOfAnguis/Controllers/KeyboardController.h | 7d37e2c0faa36c89e283a0d923c7b45270e428ca | [] | no_license | worldofanguis/WoA | dea2abf6db52017a181b12e9c0f9989af61cfa2a | 161c7bb4edcee8f941f31b8248a41047d89e264b | refs/heads/master | 2021-01-19T10:25:57.360015 | 2010-02-19T16:05:40 | 2010-02-19T16:05:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,314 | h | /*
* ___ ___ __
* \ \ / / / \
* \ \ / / / \
* \ \ /\ / /___ / /\ \
* \ \/ \/ /| | / ____ \
* \___/\___/ |___|/__/ \__\
* World Of Anguis
*
*/
/* Class: KeyboardController
* Description: The only purpose of this class is handling the keyboard,
* if we want to use it we have to inherit it.
*
* Functions: ReadKeyboard()
* this function reads in the keystates, so we have to call it in every loop once
*/
#pragma once
#pragma comment(lib,"dinput8.lib")
#pragma comment(lib,"dxguid.lib")
#include "Common.h"
/* Keystate macros */
#define KEY_DOWN(key) (Keys[key] & 0x80)
#define KEY_UP(key) (!(Keys[key] & 0x80))
#define KEY_PRESSED(key) ((Keys[key] & 0x80) && !PrevKeys[key])
#define KEY_RELEASED(key) (!Keys[key] && (PrevKeys[key] & 0x80))
class KeyboardController
{
protected:
KeyboardController();
virtual ~KeyboardController() {Release();}
void ReadKeyboard();
BYTE Keys[256]; // The keyboard state //
BYTE PrevKeys[256];
private:
void Release();
void InitController();
static IDirectInput8* DXInput; // DirectX input device //
static IDirectInputDevice8* DXKeyboardDevice; // DirectX keyboard device //
}; | [
"[email protected]"
] | [
[
[
1,
52
]
]
] |
3eea65b85c89e00f3bb2e7648e3c1d6b0c3db757 | 2ca3ad74c1b5416b2748353d23710eed63539bb0 | /Pilot/CBDTest/CBDTest/CBDTestDlg.h | 17b8b8bfa1ca210252e022d5c79ec06a2cce8c68 | [] | no_license | sjp38/lokapala | 5ced19e534bd7067aeace0b38ee80b87dfc7faed | dfa51d28845815cfccd39941c802faaec9233a6e | refs/heads/master | 2021-01-15T16:10:23.884841 | 2009-06-03T14:56:50 | 2009-06-03T14:56:50 | 32,124,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | h | // CBDTestDlg.h : header file
//
#pragma once
// CCBDTestDlg dialog
class CCBDTestDlg : public CDialog
{
// Construction
public:
CCBDTestDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_CBDTEST_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedOk();
};
| [
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
] | [
[
[
1,
33
]
]
] |
c4a7bbd945be17da0760cc620ef8f838af44eb61 | c2abb873c8b352d0ec47757031e4a18b9190556e | /src/MyGUIEngine/src/MyGUI_Progress.cpp | df21e634f0f15959c251749a84e849b86eb8b1b8 | [] | no_license | twktheainur/vortex-ee | 70b89ec097cd1c74cde2b75f556448965d0d345d | 8b8aef42396cbb4c9ce063dd1ab2f44d95e994c6 | refs/heads/master | 2021-01-10T02:26:21.913972 | 2009-01-30T12:53:21 | 2009-01-30T12:53:21 | 44,046,528 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 7,991 | cpp | /*!
@file
@author Albert Semenov
@date 01/2008
@module
*/
#include "MyGUI_Progress.h"
#include "MyGUI_WidgetSkinInfo.h"
#include "MyGUI_Widget.h"
#include "MyGUI_Gui.h"
#include "MyGUI_SkinManager.h"
namespace MyGUI
{
Ogre::String Progress::WidgetTypeName = "Progress";
const size_t PROGRESS_AUTO_WIDTH = 200;
const size_t PROGRESS_AUTO_RANGE = 1000;
const float PROGRESS_AUTO_COEF = 400;
Progress::Progress(const IntCoord& _coord, Align _align, const WidgetSkinInfoPtr _info, CroppedRectanglePtr _parent, WidgetCreator * _creator, const Ogre::String & _name) :
Widget(_coord, _align, _info, _parent, _creator, _name),
mClient(null),
mTrackWidth(1),
mTrackStep(0),
mRange(0), mEndPosition(0), mStartPosition(0),
mAutoTrack(false),
mFillTrack(false),
mStartPoint(ALIGN_LEFT)
{
for (VectorWidgetPtr::iterator iter=mWidgetChild.begin(); iter!=mWidgetChild.end(); ++iter) {
if ((*iter)->_getInternalString() == "Client") {
mClient = (*iter);
}
}
if (null == mClient) mClient = this;
const MapString & param = _info->getParams();
MapString::const_iterator iterS = param.find("TrackSkin");
if (iterS != param.end()) mTrackSkin = iterS->second;
iterS = param.find("TrackWidth");
if (iterS != param.end()) mTrackWidth = utility::parseInt(iterS->second);
if (1 > mTrackWidth) mTrackWidth = 1;
iterS = param.find("TrackStep");
if (iterS != param.end()) mTrackStep = utility::parseInt(iterS->second);
else mTrackStep = mTrackWidth;
iterS = param.find("TrackFill");
if (iterS != param.end()) mFillTrack = utility::parseBool(iterS->second);
iterS = param.find("StartPoint");
if (iterS != param.end()) setProgressStartPoint(SkinManager::parseAlign(iterS->second));
}
Progress::~Progress()
{
if (mAutoTrack) Gui::getInstance().removeFrameListener(this);
}
void Progress::setProgressRange(size_t _range)
{
if (mAutoTrack) return;
mRange = _range;
if (mEndPosition > mRange) mEndPosition = mRange;
if (mStartPosition > mRange) mStartPosition = mRange;
updateTrack();
}
void Progress::setProgressPosition(size_t _pos)
{
if (mAutoTrack) return;
mEndPosition = _pos;
if (mEndPosition > mRange) mEndPosition = mRange;
updateTrack();
}
void Progress::setProgressAutoTrack(bool _auto)
{
if (mAutoTrack == _auto) return;
mAutoTrack = _auto;
if (mAutoTrack) {
Gui::getInstance().addFrameListener(this);
mRange = PROGRESS_AUTO_RANGE;
mEndPosition = mStartPosition = 0;
mAutoPosition = 0.0f;
}
else {
Gui::getInstance().removeFrameListener(this);
mRange = mEndPosition = mStartPosition = 0;
}
updateTrack();
}
void Progress::_frameEntered(float _time)
{
if (false == mAutoTrack) return;
mAutoPosition += (PROGRESS_AUTO_COEF * _time);
size_t pos = (size_t)mAutoPosition;
if (pos > (mRange + PROGRESS_AUTO_WIDTH)) mAutoPosition = 0.0f;
if (pos > mRange) mEndPosition = mRange;
else mEndPosition = mAutoPosition;
if (pos < PROGRESS_AUTO_WIDTH) mStartPosition = 0;
else mStartPosition = pos - PROGRESS_AUTO_WIDTH;
updateTrack();
}
void Progress::setPosition(const IntCoord& _coord)
{
updateTrack();
Widget::setPosition(_coord);
}
void Progress::setSize(const IntSize& _size)
{
updateTrack();
Widget::setSize(_size);
}
void Progress::setProgressFillTrack(bool _fill)
{
mFillTrack = _fill;
updateTrack();
}
void Progress::updateTrack()
{
// все скрыто
if ((0 == mRange) || (0 == mEndPosition)) {
for (VectorWidgetPtr::iterator iter=mVectorTrack.begin(); iter!=mVectorTrack.end(); ++iter) {
(*iter)->hide();
}
return;
}
// тут попроще расчеты
if (mFillTrack) {
if (mVectorTrack.empty()) {
WidgetPtr widget = mClient->createWidget<Widget>(mTrackSkin, IntCoord(/*(int)mVectorTrack.size() * mTrackStep, 0, mTrackWidth, getClientHeight()*/), ALIGN_LEFT | ALIGN_VSTRETCH);
mVectorTrack.push_back(widget);
}
else {
// первый показываем и ставим норм альфу
VectorWidgetPtr::iterator iter=mVectorTrack.begin();
(*iter)->show();
(*iter)->setAlpha(ALPHA_MAX);
// все начиная со второго скрываем
++iter;
for (; iter!=mVectorTrack.end(); ++iter) {
(*iter)->hide();
}
}
WidgetPtr wid = mVectorTrack.front();
// полностью виден
if ((0 == mStartPosition) && (mRange == mEndPosition)) {
setTrackPosition(wid, 0, 0, getClientWidth(), getClientHeight());
}
// эх
else {
int pos = (int)mStartPosition * getClientWidth() / (int)mRange;
setTrackPosition(wid, pos, 0, ((int)mEndPosition * getClientWidth() / (int)mRange) - pos, getClientHeight());
}
return;
}
// сначала проверяем виджеты для трека
int width = getClientWidth();
int count = width / mTrackStep;
int ost = (width % mTrackStep);
if (ost > 0) {
width += mTrackStep - ost;
count ++;
}
while ((int)mVectorTrack.size() < count) {
WidgetPtr widget = mClient->createWidget<Widget>(mTrackSkin, IntCoord(/*(int)mVectorTrack.size() * mTrackStep, 0, mTrackWidth, getClientHeight()*/), ALIGN_LEFT | ALIGN_VSTRETCH);
widget->hide();
mVectorTrack.push_back(widget);
}
// все видно
if ((0 == mStartPosition) && (mRange == mEndPosition)) {
int pos = 0;
for (VectorWidgetPtr::iterator iter=mVectorTrack.begin(); iter!=mVectorTrack.end(); ++iter) {
(*iter)->setAlpha(ALPHA_MAX);
(*iter)->show();
setTrackPosition(*iter, pos * mTrackStep, 0, mTrackWidth, getClientHeight());
pos++;
}
}
// эх, придется считать
else {
// сколько не видно
int hide_pix = (width * (int)mStartPosition / (int)mRange);
int hide = hide_pix / mTrackStep;
// сколько видно
int show_pix = (width * (int)mEndPosition / (int)mRange);
int show = show_pix / mTrackStep;
int pos = 0;
for (VectorWidgetPtr::iterator iter=mVectorTrack.begin(); iter!=mVectorTrack.end(); ++iter) {
if (0 > show) {
(*iter)->hide();
}
else if (0 == show) {
(*iter)->setAlpha((float)(show_pix % mTrackStep) / (float)mTrackStep);
(*iter)->show();
setTrackPosition(*iter, pos * mTrackStep, 0, mTrackWidth, getClientHeight());
}
else {
if (0 < hide) {
(*iter)->hide();
}
else if (0 == hide) {
(*iter)->setAlpha(1.0f - ((float)(hide_pix % mTrackStep) / (float)mTrackStep));
(*iter)->show();
setTrackPosition(*iter, pos * mTrackStep, 0, mTrackWidth, getClientHeight());
}
else {
(*iter)->setAlpha(ALPHA_MAX);
(*iter)->show();
setTrackPosition(*iter, pos * mTrackStep, 0, mTrackWidth, getClientHeight());
}
}
hide --;
show --;
pos ++;
}
}
}
void Progress::setTrackPosition(WidgetPtr _widget, int _left, int _top, int _width, int _height)
{
if (IS_ALIGN_LEFT(mStartPoint)) _widget->setPosition(_left, _top, _width, _height);
else if (IS_ALIGN_RIGHT(mStartPoint)) _widget->setPosition(mClient->getWidth() - _left - _width, _top, _width, _height);
else if (IS_ALIGN_TOP(mStartPoint)) _widget->setPosition(_top, _left, _height, _width);
else if (IS_ALIGN_BOTTOM(mStartPoint)) _widget->setPosition(_top, mClient->getHeight() - _left - _width, _height, _width);
}
void Progress::setProgressStartPoint(Align _align)
{
if ((_align == ALIGN_LEFT) || (_align == ALIGN_RIGHT) || (_align == ALIGN_TOP) || (_align == ALIGN_BOTTOM)) {
mStartPoint = _align;
}
else {
mStartPoint = ALIGN_LEFT;
MYGUI_LOG(Warning, "Progress bar support only ALIGN_LEFT, ALIGN_RIGHT, ALIGN_TOP or ALIGN_BOTTOM align values");
}
updateTrack();
}
} // namespace MyGUI
| [
"twk.theainur@37e2baaa-b253-11dd-9381-bf584fb1fa83"
] | [
[
[
1,
261
]
]
] |
9892b51510aa4b3127bb4e9f6035b6358295dc36 | 31009164b9c086f008b6196b0af0124c1a451f04 | /src/Test/TestSemaphore.cpp | d9ffd061b8032a5fb07f667a6d982d2ca90145d5 | [
"Apache-2.0"
] | permissive | duarten/slimthreading-windows | e8ca8c799e6506fc5c35c63b7e934037688fbcc2 | a685d14ca172856f5a329a93aee4d00a4d0dd879 | refs/heads/master | 2021-01-16T18:58:45.758109 | 2011-04-19T10:16:38 | 2011-04-19T10:16:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,967 | cpp | // Copyright 2011 Carlos Martins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "stdafx.h"
//
// The number of threads.
//
#define THREADS 20
//
// The semaphore
//
static StSemaphore Semaphore(1, 1, 200);
//
// The alerter and the count down event used to synchronize shutdown.
//
static StAlerter Shutdown;
static StCountDownEvent Done(THREADS);
//
// The counters.
//
static ULONG Counts[THREADS];
//
// Acquire/release probability.
//
#define P 100
//
// The acquirer/Releaser thread
//
static
ULONG
WINAPI
StAcquirerReleaser (
__in PVOID Argument
)
{
ULONG WaitStatus;
ULONG Timeouts = 0;
ULONG Id = (ULONG)Argument;
LONG Rnd;
StWaitable *Semaphores[] = { &Semaphore };
printf("+++a/r #%d started...\n", Id);
srand(((ULONG)&Id) >> 12);
Rnd = rand();
do {
if ((Rnd % 100) < P) {
do {
//WaitStatus = Semaphore.TryAcquire(1, 1, &Shutdown);
//WaitStatus = Semaphore.WaitOne(1, &Shutdown);
//WaitStatus = StWaitable::WaitAny(1, Semaphores, 1, &Shutdown);
WaitStatus = StWaitable::WaitAll(1, Semaphores, 10, &Shutdown);
if (WaitStatus == WAIT_ALERTED) {
goto Exit;
}
if (WaitStatus == WAIT_SUCCESS) {
break;
}
Timeouts++;
} while (true);
Rnd = rand();
Semaphore.Release();
} else {
Rnd = rand();
}
Counts[Id]++;
} while (!Shutdown.IsSet());
Exit:
printf("+++a/r #%d exists: [%d/%d]\n", Id, Counts[Id], Timeouts);
Done.Signal();
return 0;
}
//
// Semaphore test.
//
VOID
RunSemaphoreTest(
)
{
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_HIGHEST);
for (int i = 0; i < THREADS; i++) {
HANDLE Thread = CreateThread(NULL, 0, StAcquirerReleaser, (PVOID)(i), 0, NULL);
CloseHandle(Thread);
}
int Start = GetTickCount();
getchar();
int Elapsed = GetTickCount() - Start;
Shutdown.Set();
Done.Wait();
ULONGLONG Total = 0;
for (int i = 0; i < THREADS; i++) {
Total += Counts[i];
}
printf("Total a/r: %I64d, unit cost: %d ns\n", Total,
(LONG)((Elapsed * 1000000.0)/ Total));
}
| [
"[email protected]"
] | [
[
[
1,
126
]
]
] |
96c221f747b01db857e982f902225101159b1d85 | fe7a7f1385a7dd8104e6ccc105f9bb3141c63c68 | /protocol.h | 5bf3aa926b7815a8ef44777b97dbe41a01ff550a | [] | no_license | divinity76/ancient-divinity-ots | d29efe620cea3fe8d61ffd66480cf20c8f77af13 | 0c7b5bfd5b9277c97d28de598f781dbb198f473d | refs/heads/master | 2020-05-16T21:01:29.130756 | 2010-10-11T22:58:07 | 2010-10-11T22:58:07 | 29,501,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,563 | h | //////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
//////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////
#ifndef __OTSERV_PROTOCOL_H__
#define __OTSERV_PROTOCOL_H__
#include <stdio.h>
#include <boost/utility.hpp>
class NetworkMessage;
class OutputMessage;
typedef boost::shared_ptr<OutputMessage> OutputMessage_ptr;
class Connection;
#define CLIENT_VERSION_MIN 760
#define CLIENT_VERSION_MAX 760
#define STRING_CLIENT_VERSION "This server requires client version 7.6."
class Protocol : boost::noncopyable
{
public:
Protocol(Connection* connection)
{
m_connection = connection;
m_rawMessages = false;
m_refCount = 0;
}
virtual ~Protocol() {}
virtual void parsePacket(NetworkMessage& msg){};
void onSendMessage(OutputMessage_ptr msg);
void onRecvMessage(NetworkMessage& msg);
virtual void onRecvFirstMessage(NetworkMessage& msg) = 0;
Connection* getConnection() { return m_connection;}
const Connection* getConnection() const { return m_connection;}
void setConnection(Connection* connection) { m_connection = connection; }
uint32_t getIP() const;
int32_t addRef() {return ++m_refCount;}
int32_t unRef() {return --m_refCount;}
protected:
//Use this function for autosend messages only
OutputMessage_ptr getOutputBuffer();
void setRawMessages(bool value) { m_rawMessages = value; }
virtual void releaseProtocol();
virtual void deleteProtocolTask();
friend class Connection;
private:
OutputMessage_ptr m_outputBuffer;
Connection* m_connection;
bool m_rawMessages;
uint32_t m_refCount;
};
#endif
| [
"[email protected]@6be3b30e-f956-11de-ba51-6b4196a2b81e"
] | [
[
[
1,
81
]
]
] |
0145eba83db04c431c190501134e3ee689c9dd3a | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/contrib/esdout/EsdOut.h | 3560f99fb5925f90cffa6d1b37c3c7e28cd2d5c9 | [
"BSD-3-Clause"
] | permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,702 | h | //////////////////////////////////////////////////////////////////////////////
// Copyright © 2009, Julian Cromarty
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
#include "pch.h"
#include "EsdOutBuffer.h"
/*
#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>
#include <core/audio/IAudioCallback.h>
#include <core/audio/IAudioOutput.h>
*/
#include <core/audio/IOutput.h>
#include <list>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
using namespace musik::core::audio;
class EsdOut : public IOutput{
public:
EsdOut();
~EsdOut();
virtual void Destroy();
//virtual void Initialize(IPlayer *player);
virtual void Pause();
virtual void Resume();
virtual void SetVolume(double volume);
virtual void ClearBuffers();
virtual bool PlayBuffer(IBuffer *buffer,IPlayer *player);
virtual void ReleaseBuffers();
int* getWaveHandle();
public:
typedef boost::shared_ptr<EsdOutBuffer> EsdOutBufferPtr;
//static void CALLBACK WaveCallback(HWAVEOUT hWave, UINT msg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD dw2);
void RemoveBuffer(EsdOutBuffer *buffer);
private:
void SetFormat(IBuffer *buffer);
char *device; /* playback device */
protected:
friend class EsdOutBuffer;
//IPlayer *player;
// Audio stuff
char* host;
int esd;
int waveHandle;
esd_format_t waveFormat;
/*int bits = ESD_BITS16, channels = ESD_STEREO;
int mode = ESD_STREAM, func = ESD_PLAY ;*/
// Current format
int currentBits;
int currentChannels;
long currentSampleRate;
double currentVolume;
typedef std::list<EsdOutBufferPtr> BufferList;
BufferList buffers;
BufferList removedBuffers;
size_t maxBuffers;
boost::mutex mutex;
bool addToRemovedBuffers;
};
| [
"urioxis@6a861d04-ae47-0410-a6da-2d49beace72e"
] | [
[
[
1,
106
]
]
] |
4dd9fdf1dcc48b319cbe80a3cf0a47403cf256c6 | b93e541a32e4489ad141d3807cda27a7d5bee859 | /imagefeatures.h | 7c042aa07d573f0e7dfae73c193fcc53c816659a | [] | no_license | leblancdavid/CraterDetection | dea433d414a0ef68e00e9e654e427a3ac6422d52 | 590bbdeb9d3e4d0559e30283b8cba8dd3fb35b47 | refs/heads/master | 2021-01-10T21:29:23.270743 | 2010-11-30T04:15:03 | 2010-11-30T04:15:03 | 1,089,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,871 | h | /***********************************************************
Image Feature class
object to manage the features found in images
Histogram class
************************************************************/
#include <fstream>
#include <iostream>
using namespace std;
class ImageFeatures
{
public:
// Destructor
~ImageFeatures();
// Constructor
ImageFeatures();
// Copy Constructor
ImageFeatures(const ImageFeatures &cpy);
// Default constructor
ImageFeatures(int len);
ImageFeatures(int len, int s);
// Allocating the descriptors
void alloc(int len, int s);
// Deallocate the descriptors
bool dealloc();
//Check to see if the descriptor was allocated
bool checkAlloc();
// Copy the values in
void copyDescriptors(const float** input, int count, int len);
bool copyDescriptorAt(const float* vector, int location);
bool copyDescriptorAt(const double* vector, int location);
float** descriptors;
int size;
int length;
};
class HistogramFeatures
{
public:
~HistogramFeatures();
HistogramFeatures();
HistogramFeatures(int n, int l, int t);
bool alloc(int n, int l, int t);
bool dealloc();
float getValAt(int i, int j);
bool addToBin(int i, int j);
// Normalize the bins in the histogram from 0 to 1
void normalizeHist();
int bins;
int totalHist;
float *label;
float **histogram;
};
class ObjectSet
{
public:
~ObjectSet();
ObjectSet();
ObjectSet(const ObjectSet &cpy);
ObjectSet(int l);
bool alloc(int l);
void dealloc();
ImageFeatures* featureSet;
HistogramFeatures histogramSet;
int setCount;
};
| [
"david@david-laptop.(none)"
] | [
[
[
1,
81
]
]
] |
c03c215044710141525800c64ef811d79eaf3d00 | ad8657ad14520fa5740fd98be37061dc2962c5c7 | /ConfigFile/ConfigFile.cpp | d0f424f0d20b46136f34ed8e4f89509d27d3df12 | [] | no_license | tjkolev/ibaplayer | 9bc86a837a7e1f87ac1e989f32727ccc1594f998 | 3a90f60502aea9f28406b7d6aac5cb5b09a21048 | refs/heads/master | 2020-05-17T17:20:19.198590 | 2009-07-11T04:12:14 | 2009-07-11T04:12:14 | 183,848,558 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,957 | cpp | // ConfigFile.cpp
// ConfigFile.h
// Class for reading named values from configuration files
// Richard J. Wagner v2.1 24 May 2004 [email protected]
// Copyright (c) 2004 Richard J. Wagner
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
#include "ConfigFile.h"
using std::string;
ConfigFile::ConfigFile( string filename, string delimiter,
string comment, string sentry )
: myDelimiter(delimiter), myComment(comment), mySentry(sentry)
{
// Construct a ConfigFile, getting keys and values from given file
std::ifstream in( filename.c_str() );
if( !in ) throw file_not_found( filename );
//in >> (*this);
(*this) << in;
}
ConfigFile::ConfigFile()
: myDelimiter( string(1,'=') ), myComment( string(1,'#') )
{
// Construct a ConfigFile without a file; empty
}
void ConfigFile::remove( const string& key )
{
// Remove key and its value
myContents.erase( myContents.find( key ) );
return;
}
bool ConfigFile::keyExists( const string& key ) const
{
// Indicate whether key is found
mapci p = myContents.find( key );
return ( p != myContents.end() );
}
/* static */
void ConfigFile::trim( string& s )
{
// Remove leading and trailing whitespace
static const char whitespace[] = " \n\t\v\r\f";
s.erase( 0, s.find_first_not_of(whitespace) );
s.erase( s.find_last_not_of(whitespace) + 1U );
}
std::ostream& ConfigFile::operator>>( std::ostream& os)//, const ConfigFile& cf )
{
ConfigFile& cf = *this;
// Save a ConfigFile to os
for( ConfigFile::mapci p = cf.myContents.begin();
p != cf.myContents.end();
++p )
{
os << p->first << " " << cf.myDelimiter << " ";
os << p->second << std::endl;
}
return os;
}
std::istream& ConfigFile::operator<<( std::istream& is)//, ConfigFile& cf )
{
ConfigFile& cf = *this;
// Load a ConfigFile from is
// Read in keys and values, keeping internal whitespace
typedef string::size_type pos;
const string& delim = cf.myDelimiter; // separator
const string& comm = cf.myComment; // comment
const string& sentry = cf.mySentry; // end of file sentry
const pos skip = delim.length(); // length of separator
string nextline = ""; // might need to read ahead to see where value ends
while( is || nextline.length() > 0 )
{
// Read an entire line at a time
string line;
if( nextline.length() > 0 )
{
line = nextline; // we read ahead; use it now
nextline = "";
}
else
{
std::getline( is, line );
}
// Ignore comments
line = line.substr( 0, line.find(comm) );
// Check for end of file sentry
if( sentry != "" && line.find(sentry) != string::npos ) return is;
// Parse the line if it contains a delimiter
pos delimPos = line.find( delim );
if( delimPos < string::npos )
{
// Extract the key
string key = line.substr( 0, delimPos );
line.replace( 0, delimPos+skip, "" );
// See if value continues on the next line
// Stop at blank line, next line with a key, end of stream,
// or end of file sentry
bool terminate = false;
while( !terminate && is )
{
std::getline( is, nextline );
terminate = true;
string nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy == "" ) continue;
nextline = nextline.substr( 0, nextline.find(comm) );
if( nextline.find(delim) != string::npos )
continue;
if( sentry != "" && nextline.find(sentry) != string::npos )
continue;
nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy != "" ) line += "\n";
line += nextline;
terminate = false;
}
// Store key and value
ConfigFile::trim(key);
ConfigFile::trim(line);
cf.myContents[key] = line; // overwrites if key is repeated
}
}
return is;
}
| [
"[email protected]"
] | [
[
[
1,
170
]
]
] |
c99a421c5d49d22ce012dc6c6463723835647393 | 0ee189afe953dc99825f55232cd52b94d2884a85 | /mstd/itoa.hpp | 777498bd04fe36da211ff0a349289e063a26f201 | [] | no_license | spolitov/lib | fed99fa046b84b575acc61919d4ef301daeed857 | 7dee91505a37a739c8568fdc597eebf1b3796cf9 | refs/heads/master | 2016-09-11T02:04:49.852151 | 2011-08-11T18:00:44 | 2011-08-11T18:00:44 | 2,192,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,799 | hpp | #pragma once
#include <boost/config.hpp>
#include <string.h>
#include <wchar.h>
#include <algorithm>
#ifndef BOOST_NO_EXCEPTIONS
#include <typeinfo>
#endif
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_signed.hpp>
#include "config.hpp"
namespace mstd {
namespace detail {
const size_t blockLen = 4;
const size_t blockPow = 10000;
extern MSTD_DECL const char * const digitBlocks;
extern MSTD_DECL const char * const hexTable;
template<class T, class Char>
Char * pitoa(T i, Char * buf)
{
Char * p = buf;
while(i) {
const char * src = digitBlocks + (i % blockPow) * blockLen;
std::copy(src, src + blockLen, p);
p += blockLen;
i = static_cast<T>(i / blockPow);
}
if(*(p - 1) == '0')
{
--p;
if(*(p - 1) == '0')
{
--p;
if(*(p - 1) == '0')
--p;
}
}
std::reverse(buf, p);
return p;
}
}
template<class T, class Char>
typename boost::disable_if<boost::is_signed<T>, Char*>::type
itoa(T i, Char * buf)
{
Char * p = buf;
if(i)
p = detail::pitoa(i, p);
else
*p++ = '0';
*p = 0;
return buf;
}
template<class T, class Char>
typename boost::disable_if<boost::is_signed<T>, Char*>::type
itoa16(T i, Char * buf)
{
Char * p = buf;
if(i) {
while(i) {
*p++ = detail::hexTable[i & 0xf];
i >>= 4;
}
std::reverse(buf, p);
} else
*p++ = '0';
*p = 0;
return buf;
}
template<class T, class Char>
typename boost::enable_if<boost::is_signed<T>, Char*>::type
itoa(T i, Char * buf)
{
Char * p = buf;
if(i)
{
if(i < 0)
{
i = -i;
*p = '-';
++p;
}
p = detail::pitoa(i, p);
} else {
*p++ = '0';
}
*p = 0;
return buf;
}
#ifndef BOOST_NO_EXCEPTIONS
class bad_str2int_cast : public std::bad_cast {
public:
bad_str2int_cast() {}
virtual const char *what() const throw()
{
return "bad str2int cast";
}
virtual ~bad_str2int_cast() throw() {}
};
#endif
template<class T, class Check, class It>
T str2int10_impl(It inp, It end)
{
typedef typename std::iterator_traits<It>::reference ref;
T result = 0;
for(; inp != end; ++inp)
{
ref c = *inp;
#ifndef BOOST_NO_EXCEPTIONS
if(Check::value && (c < '0' || c > '9'))
throw bad_str2int_cast();
#endif
result = result * 10 + (c - '0');
}
return result;
}
template<class T, class Check, class It>
typename boost::enable_if<boost::is_signed<T>, T>::type
str2int10_i1(It inp, It end)
{
if(inp != end && *inp == '-')
return -str2int10_impl<T, Check>(++inp, end);
else
return str2int10_impl<T, Check>(inp, end);
}
template<class T, class Check, class It>
typename boost::disable_if<boost::is_signed<T>, T>::type
str2int10_i1(It inp, It end)
{
return str2int10_impl<T, Check>(inp, end);
}
template<class T, class It>
T str2int10(It inp, It end)
{
return str2int10_i1<T, boost::mpl::false_>(inp, end);
}
template<class T, class It>
T str2int10_checked(It inp, It end)
{
return str2int10_i1<T, boost::mpl::true_>(inp, end);
}
template<class T, class Ch>
T str2int10(const Ch * inp, size_t len)
{
return str2int10_i1<T, boost::mpl::false_>(inp, inp + len);
}
template<class T, class Ch>
T str2int10_checked(const Ch * inp, size_t len)
{
return str2int10_i1<T, boost::mpl::true_>(inp, inp + len);
}
template<class T, class C>
T str2int10(const C & c)
{
return str2int10_i1<T, boost::mpl::false_>(c.begin(), c.end());
}
template<class T, class C>
T str2int10_checked(const C & c)
{
return str2int10_i1<T, boost::mpl::true_>(c.begin(), c.end());
}
template<class T>
T str2int10(const char * c)
{
return str2int10_i1<T, boost::mpl::false_>(c, c + strlen(c));
}
template<class T, class C>
T str2int10_checked(const char * c)
{
return str2int10_i1<T, boost::mpl::true_>(c, c + strlen(c));
}
template<class T>
T str2int10(const wchar_t * c)
{
return str2int10_i1<T, boost::mpl::false_>(c, c + wcslen(c));
}
template<class T, class C>
T str2int10_checked(const wchar_t * c)
{
return str2int10_i1<T, boost::mpl::true_>(c, c + wcslen(c));
}
template<class T, class Ch>
typename boost::disable_if<boost::is_signed<T>, T>::type
str2int16(const Ch * inp, size_t len)
{
T result = 0;
for(const Ch * end = inp + len; inp != end; ++inp)
{
result = result << 4;
Ch ch = *inp;
if(ch <= '9')
result += (ch - '0');
else if(ch <= 'F')
result += (ch - 'A' + 10);
else
result += (ch - 'a' + 10);
}
return result;
}
template<class T, class Ch>
typename boost::enable_if<boost::is_signed<T>, T>::type
str2int16(const Ch * inp, size_t len)
{
T result = 0;
T sign = 1;
const Ch * end = inp + len;
if(inp != end && *inp == '-')
{
sign = -1;
++inp;
}
for(; inp != end; ++inp)
{
result = result << 4;
Ch ch = *inp;
if(ch <= '9')
result += (ch - '0');
else if(ch <= L'F')
result += (ch - 'A' + 10);
else
result += (ch - 'a' + 10);
}
return result * sign;
}
}
| [
"[email protected]"
] | [
[
[
1,
260
]
]
] |
7acfbbd0e6dc9c2ef5104115da3b4a9041a86fb8 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/conjurer/conjurer/src/conjurer/nimpostorbuilder_main.cc | aa6c1b1196c340468c4c2c11206077bdc4f4c0f4 | [] | no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,818 | cc | #include "precompiled/pchconjurerapp.h"
//------------------------------------------------------------------------------
// nimpostorbuilder_main.cc
// (C) 2006 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "conjurer/nimpostorbuilder.h"
#include "ndebug/nceditorclass.h"
#include "nscene/ncscenelodclass.h"
#include "nspatial/ncspatialclass.h"
#include "nspatial/ncspatial.h"
#include "zombieentity/ncassetclass.h"
#include "zombieentity/ncloader.h"
#include "nscene/ngeometrynode.h"
#include "nscene/nsurfacenode.h"
#include "nscene/nscenegraph.h"
#include "nscene/ncviewport.h"
#include "tools/ntexturebuilder.h"
#include "nmaterial/nmaterialserver.h"
#include "mathlib/rectanglei.h"
int nImpostorBuilder::uniqueSurfaceId = 0;
namespace
{
//ColorBufferName, NormalBufferName must be the same as in impostor_renderpath.xml
const char *ColorBufferName("ImpostorColorBuffer");
const char *NormalBufferName("ImpostorNormalBuffer");
const char *ViewportClassName("Impostorcam");
const char *ViewportClassResource("wc:libs/system/cameras/impostorcam.n2");
}
//------------------------------------------------------------------------------
/**
*/
nImpostorBuilder::nImpostorBuilder() :
sourceLevel(0)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nImpostorBuilder::~nImpostorBuilder()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
nImpostorBuilder::BuildImpostorAsset()
{
//get access to source entity class
n_assert(!this->className.IsEmpty());
nEntityClass* sourceClass = nEntityClassServer::Instance()->GetEntityClass(this->className.Get());
if (!sourceClass)
{
return;
}
//check for all required components within the source
ncEditorClass* editorClass = sourceClass->GetComponent<ncEditorClass>();
ncAssetClass* assetClass = sourceClass->GetComponent<ncAssetClass>();
ncSpatialClass* spatialClass = sourceClass->GetComponent<ncSpatialClass>();
ncSceneLodClass* sceneLodClass = sourceClass->GetComponent<ncSceneLodClass>();
if (!editorClass || !assetClass || !spatialClass)
{
return;
}
//TODO- if there is a single level, move to scene level 0, build impostor as 1
if (!sceneLodClass || assetClass->GetNumLevels() == 0)
{
return;
}
//generate impostor asset name, as a[className]_impostor
this->impostorAssetName.Format("a%s_impostor", this->className.Get());
//set the nceditor class key "impostorResource" if not set.
editorClass->SetClassKeyString("impostorResource", this->impostorAssetName);
//TODO- if the asset already exists, reuse it somehow?
//somehow identify that it needs saving with the imposted class is saved.
int impostorLevel;
if (editorClass->IsSetClassKey("impostorLevel"))
{
impostorLevel = editorClass->GetClassKeyInt("impostorLevel");
}
else
{
impostorLevel = assetClass->GetNumLevels();
}
//build the impostor textures
this->sourceLevel = impostorLevel - 1;
this->BuildImpostorTextures();
//build a scene resource using them,
this->impostorBBox = spatialClass->GetOriginalBBox();
nSceneNode* sceneRoot = this->BuildImpostorScene();
if (!sceneRoot)
{
return;
}
//TODO- somehow identify that it needs saving with the imposted class is saved.
editorClass->SetClassKeyInt("impostorLevel", impostorLevel);
editorClass->SetClassKeyInt("editableLevel", impostorLevel);
//set the name of the impostor resource into the asset component
nString assetPath("wc:export/assets/");
assetPath.Append(this->impostorAssetName);
assetClass->SetLevelResource(impostorLevel, assetPath.Get());
assetClass->SetAssetEditable(true);
//set the scene root as an additional detail level into the target class
sceneLodClass->SetLevelRoot(impostorLevel, sceneRoot);
//set lod distance for the impostor level in the spatial class comp-
spatialClass->SetLevelDistance(impostorLevel, 1000);
//set class as dirty, to force saving
nEntityClassServer::Instance()->SetEntityClassDirty(sourceClass, true);
}
//------------------------------------------------------------------------------
/**
*/
nSceneNode*
nImpostorBuilder::BuildImpostorScene()
{
n_assert(!this->impostorAssetName.IsEmpty());
//build a node with the impostor asset name
//set a single impostor node, with a fixed impostor surface.
//(do not use materials for impostors for now- useless)
nAutoRef<nRoot> refLibScene("/lib/scene");
n_assert(refLibScene.isvalid());//TEMP
nSceneNode* rootNode = static_cast<nSceneNode*>(refLibScene->Find(this->impostorAssetName.Get()));
if (rootNode)
{
//TODO- rebuild impostor scene if it is already there?
nGeometryNode* impostorNode = static_cast<nGeometryNode*>(rootNode->Find("impostor.0"));
if (impostorNode && impostorNode->IsA("nimpostornode"))
{
nSurfaceNode* surface = impostorNode->GetSurfaceNode();
surface->SetTexture(nShaderState::diffMap, this->impostorTexturePath.Get());
surface->SetTexture(nShaderState::bumpMap, this->impostorNormalPath.Get());
surface->LoadResources();
}
return rootNode;
}
//create the root transform node
nKernelServer::ks->PushCwd(refLibScene.get());
rootNode = static_cast<nSceneNode*>(nKernelServer::ks->New("ntransformnode", this->impostorAssetName.Get()));
n_assert(rootNode);
nKernelServer::ks->PopCwd();
//create an impostor geometry node
nKernelServer::ks->PushCwd(rootNode);
nGeometryNode* impostorNode;
impostorNode = static_cast<nGeometryNode*>(nKernelServer::ks->New("nimpostornode", "impostor.0"));
nKernelServer::ks->PopCwd();
n_assert(impostorNode);
//build impostor surface, or reuse one
//TEMP- use a standard surface for all impostors generated this way
nSurfaceNode* surface = nMaterialServer::Instance()->LoadSurfaceFromFile("wc:libs/system/materials/surface0_impostor.n2");
nString impostorSurfacePath;
impostorSurfacePath.Format("/tmp/impostorbuilder/surface%04u", uniqueSurfaceId++);
surface = static_cast<nSurfaceNode*>(surface->Clone(impostorSurfacePath.Get()));
surface->SetTexture(nShaderState::diffMap, this->impostorTexturePath.Get());
surface->SetTexture(nShaderState::bumpMap, this->impostorNormalPath.Get());
//nSurfaceNode* surface = refLibSurfaces->Find();
//refLibSurfaces->
impostorNode->SetSurface(surface->GetFullName().Get());
impostorNode->SetLocalBox(this->impostorBBox);
return rootNode;
}
//------------------------------------------------------------------------------
/**
*/
void
nImpostorBuilder::BuildImpostorTextures()
{
//build the render target texture (before loading the impostor render path)
//SetupImpostorTexture()
this->impostorTexturePath.Clear();
const int texSize = 128;
const nTexture2::Format texFormat = nTexture2::A8R8G8B8;
nTexture2* colorRenderTarget = nGfxServer2::Instance()->NewRenderTarget(ColorBufferName, texSize, texSize, texFormat, nTexture2::RenderTargetColor|nTexture2::RenderTargetDepth);
if (!colorRenderTarget)
{
n_message("nImpostorBuilder::BuildImpostorTextures() failed: couldn't create render target '%s'", ColorBufferName);
return;
}
nTexture2* normalRenderTarget = nGfxServer2::Instance()->NewRenderTarget(NormalBufferName, texSize, texSize, texFormat, nTexture2::RenderTargetColor|nTexture2::RenderTargetDepth);
if (!normalRenderTarget)
{
n_message("nImpostorBuilder::BuildImpostorTextures() failed: couldn't create render target '%s'", NormalBufferName);
return;
}
//SetupImpostorRender()
//build a builder render path, and a local viewport
const int LEVEL_EDITOR = 4;//TODO- customize from the tool
//const char *viewportClassName("Impostorcam");
//const char *viewportClassResource("wc:libs/system/cameras/impostorcam.n2");
nEntityClass* viewportClass = nEntityClassServer::Instance()->GetEntityClass("neviewport");
viewportClass = nEntityClassServer::Instance()->NewEntityClass(viewportClass, ViewportClassName);
viewportClass->GetComponentSafe<ncLoaderClass>()->SetResourceFile(ViewportClassResource);
if (viewportClass->GetComponentSafe<ncLoaderClass>()->LoadResources())
{
//build an entity of the source class and a scene graph, set the camera
nEntityObject* viewportEntity = nEntityObjectServer::Instance()->NewLocalEntityObject(ViewportClassName);
n_assert(viewportEntity);
if (viewportEntity->GetComponentSafe<ncLoader>()->LoadComponents())
{
nEntityObject* sourceEntity = nEntityObjectServer::Instance()->NewLocalEntityObject(this->className.Get());
n_assert(sourceEntity);
if (sourceEntity->GetClassComponentSafe<ncLoaderClass>()->LoadResources() &&
sourceEntity->GetComponentSafe<ncLoader>()->LoadComponents())
{
nSceneServer* sceneServer = nSceneServer::Instance();
int trfmPassIndex = sceneServer->GetPassIndexByFourCC(FOURCC('trfm'));
int rtgtPassIndex = sceneServer->GetPassIndexByFourCC(FOURCC('rtgt'));
nSceneGraph* sceneGraph = sceneServer->NewSceneGraph("impostor");
//and render offline to texture(s) as many times as needed.
sourceEntity->GetComponentSafe<ncScene>()->SetAttachIndex(this->sourceLevel);
int prevMaterialLevel = sourceEntity->GetClassComponentSafe<ncSceneClass>()->GetMaxMaterialLevel();
sourceEntity->GetClassComponentSafe<ncSceneLodClass>()->SetLevelMaterialProfile(this->sourceLevel, LEVEL_EDITOR);
//BeginImpostorRender();
//position: looking at the center of the entity bbox, from at least the bbox distance * 10
const bbox3& lookAtBox = sourceEntity->GetComponent<ncSpatial>()->GetBBox();
vector3 camPos(lookAtBox.center());
camPos.z = camPos.z + (lookAtBox.extents().z * 10.0f);
float projSize = n_max(lookAtBox.extents().x, lookAtBox.extents().y) * 2.0f;
viewportEntity->GetComponent<ncTransform>()->SetPosition(camPos);
viewportEntity->GetComponent<ncViewport>()->SetOrthogonal(projSize, projSize, 1, 1000);
nCamera2 cam = viewportEntity->GetComponentSafe<ncViewport>()->GetCamera();
nGfxServer2::Instance()->SetCamera(cam);
//rotation: none, look in the Z- axis for now
//RenderImpostor()
//TODO- repeat for all angles from which we want to create an impostor
//attach'em all
nGfxServer2::Instance()->BeginFrame();
sceneGraph->BeginAttach();
viewportEntity->GetComponent<ncScene>()->Render(sceneGraph);
sourceEntity->GetComponent<ncScene>()->Render(sceneGraph);
sceneGraph->EndAttach();
//render'em all
sceneGraph->RenderPass(trfmPassIndex);
sceneGraph->RenderPass(rtgtPassIndex);
nGfxServer2::Instance()->EndFrame();
//SaveImpostorTexture()
//define a convention to save all these source textures.
//save the texture(s) to wc:export/assets/[assetName]/textures
nString texturesPath;
texturesPath.Format("wc:export/assets/%s/textures/", this->impostorAssetName.Get());
nKernelServer::ks->GetFileServer()->MakePath(texturesPath);
//save impostor color texture
nString texturePath(texturesPath);
texturePath.Append("impostor.dds");
if (this->SaveRenderTarget(colorRenderTarget, texturePath.Get()))
{
this->impostorTexturePath = texturePath.Get();
}
//save impostor normal
texturePath.Set(texturesPath.Get());
texturePath.Append("impostor_NORMAL.dds");
if (this->SaveRenderTarget(normalRenderTarget, texturePath.Get()))
{
this->impostorNormalPath = texturePath.Get();
}
//CleanupImpostorRender()
//restore values, get rid of all helper objects
sourceEntity->GetClassComponentSafe<ncSceneLodClass>()->SetLevelMaterialProfile(this->sourceLevel, prevMaterialLevel);
sceneGraph->Release();
}
nEntityObjectServer::Instance()->RemoveEntityObject(sourceEntity);
}
nEntityObjectServer::Instance()->RemoveEntityObject(viewportEntity);
viewportClass->GetComponentSafe<ncLoaderClass>()->UnloadResources();
}
nEntityClassServer::Instance()->RemoveEntityClass(ViewportClassName);
//FIXME- this triggers an assert when removing the texture
//renderTarget->Release();
}
//------------------------------------------------------------------------------
/**
*/
bool
nImpostorBuilder::SaveRenderTarget(nTexture2* renderTarget, const char *texturePath)
{
nTexture2* copyTexture = this->CopyTextureFrom(renderTarget);
n_assert(copyTexture);
nTextureBuilder texBuilder;
texBuilder.SetTexture(copyTexture);
bool success = texBuilder.Save(texturePath);
if (!success)
{
n_message("nImpostorBuilder::BuildImpostorTextures() failed: couldn't save texture '%s'", texturePath);
}
copyTexture->Release();
return success;
}
//------------------------------------------------------------------------------
/**
*/
nTexture2*
nImpostorBuilder::CopyTextureFrom(nTexture2* src)
{
ushort width = src->GetWidth();
ushort height = src->GetHeight();
nTexture2* dst = nGfxServer2::Instance()->NewTexture(0);
n_assert(dst);
dst->SetType(nTexture2::TEXTURE_2D);
dst->SetFormat(nTexture2::A8R8G8B8);
dst->SetUsage(nTexture2::CreateEmpty | nTexture2::Dynamic);
dst->SetWidth(width);
dst->SetHeight(height);
dst->Load();
n_assert(dst->IsLoaded());
rectanglei rect( 0, 0, width - 1, height - 1);
src->Copy(dst, rect, rect, nTexture2::FILTER_POINT);
return dst;
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
329
]
]
] |
eb8288431d48abfd53cc8b9cccc824284233885a | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /200904/G_PARSER.H | f052285c54874643a2d6475382b42e3e636322c7 | [] | no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,954 | h | /* A generic parser.
Call this file g_parser.h
*/
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
const int NUMVARS = 26;
template <class PType> class parser {
enum typesT { UNDEFTOK, OPERATOR, NUMBER, VARIABLE };
enum errorsT { SERROR, PARENS, NOEXP, DIVZERO };
char *exp_ptr; // points to the expression
char token[80]; // holds current token
typesT tok_type; // holds token's type
PType vars[NUMVARS]; // holds variable's values
void eval_exp1(PType &result);
void eval_exp2(PType &result);
void eval_exp3(PType &result);
void eval_exp4(PType &result);
void eval_exp5(PType &result);
void eval_exp6(PType &result);
void atom(PType &result);
void get_token(), putback();
void serror(errorsT error);
PType find_var(char *s);
bool isdelim(char c);
public:
parser();
PType eval_exp(char *exp);
};
// Constructor
template <class PType> parser<PType>::parser()
{
int i;
exp_ptr = 0;
for(i=0; i<NUMVARS; i++) vars[i] = (PType) 0;
}
// Parser entry point.
template <class PType> PType parser<PType>::eval_exp(char *exp)
{
PType result;
exp_ptr = exp;
get_token();
if(!*token) {
serror(NOEXP); // no expression present
return (PType) 0;
}
eval_exp1(result);
if(*token) serror(SERROR); // last token must be null
return result;
}
// Process an assignment.
template <class PType> void parser<PType>::eval_exp1(PType &result)
{
int slot;
typesT ttok_type;
char temp_token[80];
if(tok_type==VARIABLE) {
// save old token
strcpy(temp_token, token);
ttok_type = tok_type;
// compute the index of the variable
slot = toupper(*token) - 'A';
get_token();
if(*token != '=') {
putback(); // return current token
// restore old token - not assignment
strcpy(token, temp_token);
tok_type = ttok_type;
}
else {
get_token(); // get next part of exp
eval_exp2(result);
vars[slot] = result;
return;
}
}
eval_exp2(result);
}
// Add or subtract two terms.
template <class PType> void parser<PType>::eval_exp2(PType &result)
{
register char op;
PType temp;
eval_exp3(result);
while((op = *token) == '+' || op == '-') {
get_token();
eval_exp3(temp);
switch(op) {
case '-':
result = result - temp;
break;
case '+':
result = result + temp;
break;
}
}
}
// Multiply or divide two factors.
template <class PType> void parser<PType>::eval_exp3(PType &result)
{
register char op;
PType temp;
eval_exp4(result);
while((op = *token) == '*' || op == '/' || op == '%') {
get_token();
eval_exp4(temp);
switch(op) {
case '*':
result = result * temp;
break;
case '/':
if(!temp) serror(DIVZERO); // division by zero attempted
else result = result / temp;
break;
case '%':
result = (int) result % (int) temp;
break;
}
}
}
// Process an exponent.
template <class PType> void parser<PType>::eval_exp4(PType &result)
{
PType temp, ex;
register int t;
eval_exp5(result);
if(*token== '^') {
get_token();
eval_exp4(temp);
ex = result;
if(temp== (PType) 0) {
result = (PType) 1;
return;
}
for(t=(int)temp-1; t>0; --t) result = result * ex;
}
}
// Evaluate a unary + or -.
template <class PType> void parser<PType>::eval_exp5(PType &result)
{
register char op;
op = 0;
if((tok_type == OPERATOR) && *token=='+' || *token == '-') {
op = *token;
get_token();
}
eval_exp6(result);
if(op=='-') result = -result;
}
// Process a parenthesized expression.
template <class PType> void parser<PType>::eval_exp6(PType &result)
{
if((*token == '(')) {
get_token();
eval_exp2(result);
if(*token != ')')
serror(PARENS);
get_token();
}
else atom(result);
}
// Get the value of a number or a variable.
template <class PType> void parser<PType>::atom(PType &result)
{
switch(tok_type) {
case VARIABLE:
result = find_var(token);
get_token();
return;
case NUMBER:
result = (PType) atof(token);
get_token();
return;
default:
serror(SERROR);
}
}
// Return a token to the input stream.
template <class PType> void parser<PType>::putback()
{
char *t;
t = token;
for(; *t; t++) exp_ptr--;
}
// Display a syntax error.
template <class PType> void parser<PType>::serror(errorsT error)
{
static char *e[]= {
"Syntax Error",
"Unbalanced Parentheses",
"No expression Present",
"Division by zero"
};
cout << e[error] << endl;
}
// Obtain the next token.
template <class PType> void parser<PType>::get_token()
{
register char *temp;
tok_type = UNDEFTOK;
temp = token;
*temp = '\0';
if(!*exp_ptr) return; // at end of expression
while(isspace(*exp_ptr)) ++exp_ptr; // skip over white space
if(strchr("+-*/%^=()", *exp_ptr)){
tok_type = OPERATOR;
// advance to next char
*temp++ = *exp_ptr++;
}
else if(isalpha(*exp_ptr)) {
while(!isdelim(*exp_ptr)) *temp++ = *exp_ptr++;
tok_type = VARIABLE;
}
else if(isdigit(*exp_ptr)) {
while(!isdelim(*exp_ptr)) *temp++ = *exp_ptr++;
tok_type = NUMBER;
}
*temp = '\0';
}
// Return true if c is a delimiter.
template <class PType> bool parser<PType>::isdelim(char c)
{
if(strchr(" +-/*%^=()", c) || c==9 || c=='\r' || c==0)
return true;
return false;
}
// Return the value of a variable.
template <class PType> PType parser<PType>::find_var(char *s)
{
if(!isalpha(*s)){
serror(SERROR);
return (PType) 0;
}
return vars[toupper(*token)-'A'];
}
| [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
] | [
[
[
1,
277
]
]
] |
9403b703845cb6455bb2d3c6534522a1233f0650 | c1b7571589975476405feab2e8b72cdd2a592f8f | /paradebot10/Autonomous.h | 4810b872746d1b82099d51ebc9cd6ee8b36459b9 | [] | no_license | chopshop-166/frc-2010 | ea9cd83f85c9eb86cc44156f21894410a9a4b0b5 | e15ceff05536768c29fad54fdefe65dba9a5fab5 | refs/heads/master | 2021-01-21T11:40:07.493930 | 2010-12-10T02:04:05 | 2010-12-10T02:04:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | h | /*******************************************************************************
* Project : Framework
* File Name : Autonomous.h
* Owner : Software Group (FIRST Chopshop Team 166)
* Creation Date : January 18, 2010
* File Description : Header for robot code to execute in autonomous mode
*******************************************************************************/
/*----------------------------------------------------------------------------*/
/* Copyright (c) MHS Chopshop Team 166, 2010. All Rights Reserved. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "Robot.h"
#include "MemoryLog166.h"
#include "WPILib.h"
#include "BaeUtilities.h"
#include <cmath>
#define AUTONOMOUS_WAIT_TIME (0.050)
class AutonomousTask
{
public:
AutonomousTask(void);
// <<CHANGEME>>
// Add any extra functions your autonomous needs
};
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
],
[
4,
10
],
[
12,
20
],
[
22,
23
],
[
27,
27
]
],
[
[
2,
3
],
[
11,
11
],
[
21,
21
],
[
24,
26
]
]
] |
9e65e6ca417f98f36243d49c535b888f4171dd78 | 591d777610b94a1a3c36dedcf29aed0e1b4885a7 | /tinyxml/tinywxuni.h | 9c3147151aedcfb2b1d9296a3a1a7cfccf85ff70 | [] | no_license | ro91/ofcodeblocksplugin | 8aa15e0aa5220132cc233888487b3fa82503ef3e | fb247aa310a11ebb4ceb7170246eaaee61220fbf | refs/heads/master | 2021-01-02T09:43:22.325059 | 2009-11-22T21:53:27 | 2009-11-22T21:53:27 | 33,658,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 322 | h | #ifndef TINYWXUNI_H
#define TINYWXUNI_H
class wxString;
class TiXmlDocument;
namespace TinyXML
{
bool LoadDocument(const wxString& filename, TiXmlDocument *doc);
TiXmlDocument* LoadDocument(const wxString& filename);
bool SaveDocument(const wxString& filename, TiXmlDocument* doc);
}
#endif
| [
"[email protected]@9ec9ae00-852e-11de-aa25-37732fe6e1e3"
] | [
[
[
1,
15
]
]
] |
ceba46f63274f674580a91a14f7b8aade2693097 | 8be41f8425a39f7edc92efb3b73b6a8ca91150f3 | /MFCOpenGLTest/MyTriangle.h | dc94aecf4df0b6a2ef9638c7243e439f2d672736 | [] | no_license | SysMa/msq-summer-project | b497a061feef25cac1c892fe4dd19ebb30ae9a56 | 0ef171aa62ad584259913377eabded14f9f09e4b | refs/heads/master | 2021-01-23T09:28:34.696908 | 2011-09-16T06:39:52 | 2011-09-16T06:39:52 | 34,208,886 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,079 | h | // MyTriangle.h: interface for the CMyTriangle class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_MYTRIANGLE_H__18B742B8_09CC_48FE_A143_ACD6D6D849F9__INCLUDED_)
#define AFX_MYTRIANGLE_H__18B742B8_09CC_48FE_A143_ACD6D6D849F9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Base.h"
class CMyTriangle : public CBase
{
public:
CMyTriangle();
virtual ~CMyTriangle();
void Draw();
void DrawCurrentOperation();
void OnLButtonDown(float x, float y);
bool OnLButtonUp(float x, float y);
void OnMouseMove(float x, float );
void OnKeyMove(UINT nChar);
bool Pick(float x,float y);
bool GetTheFeildCrect();
bool Read(CString str);
CString Save();
CString GetClassName(){return "CMyTriangle";};
float m_x0;
float m_y0;
float m_x1;
float m_y1;
float m_x2;
float m_y2;
float m_lastx;
float m_lasty;
int m_first;
};
#endif // !defined(AFX_MYTRIANGLE_H__18B742B8_09CC_48FE_A143_ACD6D6D849F9__INCLUDED_)
| [
"[email protected]@551f4f89-5e81-c284-84fc-d916aa359411"
] | [
[
[
1,
55
]
]
] |
28099c22257fbea2f0cc7635f4fcf0c7a4c6be94 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_1_024.cpp | 4a4bb9a1db05cc7468c567bb1d976604184e8d1e | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,445 | cpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2006 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// Tests more complex macro expansion.
// token-pasting macro
#define CAT(a, b) PRIMITIVE_CAT(a, b)
#define PRIMITIVE_CAT(a, b) a ## b
// splits a value that is about to expand into two parameters and returns
// either the zero-th or one-th element.
#define SPLIT(n, im) PRIMITIVE_CAT(SPLIT_, n)(im)
#define SPLIT_0(a, b) a
#define SPLIT_1(a, b) b
// detects if the parameter is nullary parentheses () or something else.
// passing non-nullary parenthesis is invalid input.
#define IS_NULLARY(expr) \
SPLIT( \
0, \
CAT(IS_NULLARY_R_, IS_NULLARY_T expr) \
) \
/**/
#define IS_NULLARY_T() 1
#define IS_NULLARY_R_1 1, ?
#define IS_NULLARY_R_IS_NULLARY_T 0, ?
// expands to a macro that eats an n-element parenthesized expression.
#define EAT(n) PRIMITIVE_CAT(EAT_, n)
#define EAT_0()
#define EAT_1(a)
#define EAT_2(a, b)
#define EAT_3(a, b, c)
// expands to a macro that removes the parentheses from an n-element
// parenthesized expression
#define REM(n) PRIMITIVE_CAT(REM_, n)
#define REM_0()
#define REM_1(a) a
#define REM_2(a, b) a, b
#define REM_3(a, b, c) a, b, c
// expands to nothing
#define NIL
// expands to 1 if x is less than y otherwise, it expands to 0
#define LESS(x, y) \
IS_NULLARY( \
PRIMITIVE_CAT(LESS_, y)( \
EAT(1), PRIMITIVE_CAT(LESS_, x) \
)() \
) \
/**/
#define LESS_0(a, b) a(EAT(2)) b(REM(1), NIL)
#define LESS_1(a, b) a(LESS_0) b(REM(1), NIL)
#define LESS_2(a, b) a(LESS_1) b(REM(1), NIL)
#define LESS_3(a, b) a(LESS_2) b(REM(1), NIL)
#define LESS_4(a, b) a(LESS_3) b(REM(1), NIL)
#define LESS_5(a, b) a(LESS_4) b(REM(1), NIL)
// expands to the binary one's compliment of a binary input value. i.e. 0 or 1
#define COMPL(n) PRIMITIVE_CAT(COMPL_, n)
#define COMPL_0 1
#define COMPL_1 0
// these do the obvious...
#define GREATER(x, y) LESS(y, x)
#define LESS_EQUAL(x, y) COMPL(LESS(y, x))
#define GREATER_EQUAL(x, y) COMPL(LESS(x, y))
// causes another rescan...
#define SCAN(x) x
// expands to 1 if x is not equal to y. this one contains a workaround...
#define NOT_EQUAL(x, y) \
IS_NULLARY( \
SCAN( \
PRIMITIVE_CAT(LESS_, x)( \
EAT(1), \
PRIMITIVE_CAT(LESS_, y) EAT(2) \
)((), ...) \
) \
) \
/**/
#define EQUAL(x, y) COMPL(NOT_EQUAL(x, y))
//R #line 95 "t_1_024.cpp"
LESS(2, 3) //R 1
LESS(3, 2) //R 0
LESS(3, 3) //R 0
GREATER(2, 3) //R 0
GREATER(3, 2) //R 1
GREATER(3, 3) //R 0
LESS_EQUAL(2, 3) //R 1
LESS_EQUAL(3, 2) //R 0
LESS_EQUAL(3, 3) //R 1
GREATER_EQUAL(2, 3) //R 0
GREATER_EQUAL(3, 2) //R 1
GREATER_EQUAL(3, 3) //R 1
NOT_EQUAL(2, 3) //R 1
NOT_EQUAL(3, 2) //R 1
NOT_EQUAL(3, 3) //R 0
EQUAL(2, 3) //R 0
EQUAL(3, 2) //R 0
EQUAL(3, 3) //R 1
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
112
]
]
] |
8e5d524c0e465532ef4861afcc04d0840c732862 | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_media_util/EncodedBuffer.cpp | c2fef8fe1675b99daa240b700dfd809870e243ea | [] | no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,972 | cpp | #include "shared/compat.h"
#include "EncodedBuffer.h"
#include "global_error.h"
#include "INSSBuffer.h"
#include "ASFDataPacket.h"
#include "mediapkt.h"
#include "shared/ithread.h"
#include "ASFPktSink.h"
#include "media_utilities.h"
#include "shared/common.h"
#include "SimposiumSink.h"
EncodedBuffer::EncodedBuffer() : m_pSimpSink(NULL)
{
Reset();
}
EncodedBuffer::~EncodedBuffer()
{
}
void EncodedBuffer::Reset()
{
m_wVideoStream = 0;
m_bLastKeyFrame = FALSE;
m_ulLastPacketTime = 0;
m_ulPktsDelivered = 0;
m_ulMediaId = 0;
m_ulSeq = 0;
}
unsigned EncodedBuffer::AllocateDataUnit(DWORD cbDataUnit, INSSBuffer** ppDataUnit)
{
if (!ppDataUnit)
{
return RET_INVALID_ARG;
}
INSSBuffer * pNSSBuf = new INSSBuffer();
if (!pNSSBuf || pNSSBuf->SetLength(cbDataUnit) != RET_OK)
{
return RET_LOW_MEMORY;
}
*ppDataUnit = pNSSBuf;
return RET_OK;
}
void EncodedBuffer::SetVideoStream(WORD _wVideoStream)
{
m_wVideoStream = _wVideoStream;
}
unsigned EncodedBuffer::OnDataUnit(INSSBuffer* pDataUnit)
{
if (!pDataUnit)
return RET_INVALID_ARG;
DWORD dwLen;
CHECK_ERROR(pDataUnit->GetLength(&dwLen), RET_OK)
LPBYTE pPayload;
CHECK_ERROR(pDataUnit->GetBuffer(&pPayload), RET_OK)
ASFDataPacket packet(dwLen, -1, m_wVideoStream);
packet.Attach(pPayload);
packet.Refresh();
if (GetTickCount() <= m_ulLastPacketTime + MC_ENCODER_ASF_INTERVAL_BETWEEN_PACKETS)
{
//printf("EncodedBuffer.cpp - EncodedBuffer::OnDataUnit - Waiting MC_ENCODER_ASF_INTERVAL_BETWEEN_PACKETS = %u ms...\n", MC_ENCODER_ASF_INTERVAL_BETWEEN_PACKETS);
Wait(MC_ENCODER_ASF_INTERVAL_BETWEEN_PACKETS);
}
m_ulLastPacketTime = GetTickCount();
DWORD dwFlags = 0;
if (packet.HasKeyFrame())
{
dwFlags |= PKT_KEYFRAME;
}
dwFlags |= PKT_VIDEO | PKT_AUDIO;
BYTE pBuf[MC_MAX_IRM_RAW_PACKETSIZE];
MediaPkt *pMediaPkt = (MediaPkt *)pBuf;
pMediaPkt->id = m_ulMediaId;
pMediaPkt->datalen = (WORD) dwLen;
pMediaPkt->seq = ++m_ulSeq;
pMediaPkt->type = MTYPE_MEDIA;
pMediaPkt->flags = (BYTE) dwFlags;
BYTE *pData = &pBuf[sizeof(MediaPkt)];
memcpy(pData, pPayload, dwLen);
unsigned uPktLen = dwLen + sizeof(MediaPkt);
CHECK_ERROR(m_pSimpSink->OnPacket(pBuf, uPktLen), RET_OK)
m_ulPktsDelivered++;
//printf("EncodedBuffer.cpp - EncodedBuffer::OnDataUnit - Packet no. %lu sent, pkt.payload first byte: %x, pPayload first byte: %x\n", m_ulPktsDelivered, *pkt.payload, *pPayload);
return RET_OK;
}
unsigned EncodedBuffer::OnHeader(INSSBuffer* pHeader)
{
if (!pHeader)
return RET_INVALID_ARG;
DWORD dwLen;
CHECK_ERROR(pHeader->GetLength(&dwLen), RET_OK)
LPBYTE pBuf;
CHECK_ERROR(pHeader->GetBuffer(&pBuf), RET_OK)
BYTE pEnc64Buf[MC_MAX_IRM_RAW_PACKETSIZE];
int uEnc64BufLen = MC_MAX_IRM_RAW_PACKETSIZE;
unsigned ret;
if (encode64((const char *)pBuf, dwLen, (char *)pEnc64Buf, &uEnc64BufLen) == 0)
{
pEnc64Buf[uEnc64BufLen] = '\0';
m_Header.SetData(pEnc64Buf, uEnc64BufLen+1);
BYTE *pHeader;
ULONG uHeaderSize;
if (GetHeader(&pHeader, uHeaderSize) == RET_OK)
{
m_pSimpSink->OnHeader(pHeader, uHeaderSize);
}
ret = RET_OK;
}
else
{
ret = RET_ERROR;
}
return ret;
}
void EncodedBuffer::NotifyEOF()
{
if (m_pSimpSink)
{
m_pSimpSink->OnEOF();
}
}
unsigned EncodedBuffer::GetHeader(BYTE **_ppHeader, ULONG & _uHeaderLen)
{
_uHeaderLen = 0;
if (!_ppHeader)
return RET_INVALID_ARG;
*_ppHeader = NULL;
if (!m_Header.Size())
return RET_INIT_ERROR;
*_ppHeader = m_Header.GetDataPtr();
_uHeaderLen = m_Header.Size()-1;
return RET_OK;
} | [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
] | [
[
[
1,
174
]
]
] |
b947be423ac9adec8db7592f50cce13fdfc9aab4 | bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918 | /TPs CPOO/Gareth & Maxime/Projet/CanonNoir_Moteur_C++/fichiers/ProposeDeplacement.cpp | a286c8a292ff8f0bffa3421d95faf339a88b1315 | [] | no_license | Issam-Engineer/tp4infoinsa | 3538644b40d19375b6bb25f030580004ed4a056d | 1576c31862ffbc048890e72a81efa11dba16338b | refs/heads/master | 2021-01-10T17:53:31.102683 | 2011-01-27T07:46:51 | 2011-01-27T07:46:51 | 55,446,817 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,631 | cpp | /**
*\file ProposeDeplacement.cpp
*\brief File containing the functionalities and the attributes of the ProposeDeplacement class
*\author Maxime HAVEZ
*\author Gareth THIVEUX
*\version 1.0
*/
#include "ProposeDeplacement.h"
#include "Joueur.h"
ProposeDeplacement::ProposeDeplacement(MoteurJeu* m){
motor=m;
cout << "Constructeur : ProposeDeplacement" << endl;
}
void ProposeDeplacement::traverseIle(pair<int,int>* tab, int i){
for(int d=(tab[0].first); d<=(tab[i].first); d++){
for(int e=(tab[0].second); e<=(tab[i].second); e++){
if(motor->getCase(d,e)->getTypeCase() == 'I'){
motor->setInaccessible(tab[i]);
}
}
}
for(int d=(tab[0].first); d<=(tab[i].first); d++){
for(int e=(tab[0].second); e>=(tab[i].second); e--){
if(motor->getCase(d,e)->getTypeCase() == 'I'){
motor->setInaccessible(tab[i]);
}
}
}
for(int d=(tab[0].first); d>=(tab[i].first); d--){
for(int e=(tab[0].second); e<=(tab[i].second); e++){
if(motor->getCase(d,e)->getTypeCase() == 'I'){
motor->setInaccessible(tab[i]);
}
}
}
for(int d=(tab[0].first); d>(tab[i].first); d--){
for(int e=(tab[0].second); e>(tab[i].second); e--){
/*cout<<"("<<d<<","<<e<<")"<<endl;
cout<<"i : "<<i<<endl;*/
if(motor->getCase(d,e)->getTypeCase() == 'I'){
/*cout<<"("<<d<<","<<e<<")"<<endl;
cout<<"i : "<<i<<endl;
cout<<"tab[0] : ("<<tab[0].first<<","<<tab[0].second<<")"<<endl;
cout<<"tab[i] : ("<<tab[i].first<<","<<tab[i].second<<")"<<endl;*/
//motor->setInaccessible(tab[i]);
}
}
}
}
void ProposeDeplacement::execute(){
cout<<"ProposeDeplacement.execute()"<<endl;
pair<int,int> casespossibles[24];
int valde1 = motor->getDe()->getDe1();
int valde2 = motor->getDe()->getDe2();
int valdede = motor->getDe()->getSommeDe();
//motor->getJoueurInd(motor->getJCourant())->getBateau1()->getPosition()->getPosition();
pair<int,int> posit =motor->getJoueurInd(motor->getJCourant())->getBateauCourant()->getPosition()->getPosition();
cout<<"Position x :"<<posit.first<<" et y :"<<posit.second<<endl;
cout<<"Type du bateau du joueur : " << motor->getJoueurInd(motor->getJCourant())->getBateauCourant()->type() <<endl;
int indice=0;
int x_actuel = posit.first;
int y_actuel = posit.second;
casespossibles[indice] = make_pair(x_actuel,y_actuel);
indice++;
int x1 = x_actuel + valde1;
int y1 = y_actuel;
if(x1>0 && x1<=11 && y1>0 && y1<=8){
casespossibles[indice] = make_pair(x1,y1);
indice++;
}
int x2 = x_actuel - valde1;
int y2 = y_actuel;
if(x2>0 && x2<=11 && y2>0 && y2<=8){
casespossibles[indice] = make_pair(x2,y2);
indice++;
}
int x3 = x_actuel;
int y3 = y_actuel + valde1;
if(x3>0 && x3<=11 && y3>0 && y3<=8){
casespossibles[indice] = make_pair(x3,y3);
indice++;
}
int x4 = x_actuel;
int y4 = y_actuel - valde1;
if(x4>0 && x4<=11 && y4>0 && y4<=8){
casespossibles[indice] = make_pair(x4,y4);
indice++;
}
int x5 = x_actuel + valde1;
int y5 = y_actuel + valde1;
if(x5>0 && x5<=11 && y5>0 && y5<=8){
casespossibles[indice] = make_pair(x5,y5);
indice++;
}
int x6 = x_actuel - valde1;
int y6 = y_actuel + valde1;
if(x6>0 && x6<=11 && y6>0 && y6<=8){
casespossibles[indice] = make_pair(x6,y6);
indice++;
}
int x7 = x_actuel + valde1;
int y7 = y_actuel - valde1;
if(x7>0 && x7<=11 && y7>0 && y7<=8){
casespossibles[indice] = make_pair(x7,y7);
indice++;
}
int x8 = x_actuel - valde1;
int y8 = y_actuel - valde1;
if(x8>0 && x8<=11 && y8>0 && y8<=8){
casespossibles[indice] = make_pair(x8,y8);
indice++;
}
//Cas d'une caravelle
if( motor->getJoueurInd(motor->getJCourant())->getBateauCourant()->type() == 'C'){
cout<<"Le joueur possède une caravelle -> Proposer les deux dés et la somme"<<endl;
int x9 = x_actuel + valde2;
int y9 = y_actuel;
if(x9>0 && x9<=11 && y9>0 && y9<=8){
casespossibles[indice] = make_pair(x9,y9);
indice++;
}
int x10 = x_actuel - valde2;
int y10 = y_actuel;
if(x10>0 && x10<=11 && y10>0 && y10<=8){
casespossibles[indice] = make_pair(x10,y10);
indice++;
}
int x11 = x_actuel;
int y11 = y_actuel + valde2;
if(x11>0 && x11<=11 && y11>0 && y11<=8){
casespossibles[indice] = make_pair(x11,y11);
indice++;
}
int x12 = x_actuel;
int y12 = y_actuel - valde2;
if(x12>0 && x12<=11 && y12>0 && y12<=8){
casespossibles[indice] = make_pair(x12,y12);
indice++;
}
int x13 = x_actuel + valde2;
int y13 = y_actuel + valde2;
if(x13>0 && x13<=11 && y13>0 && y13<=8){
casespossibles[indice] = make_pair(x13,y13);
indice++;
}
int x14 = x_actuel - valde2;
int y14 = y_actuel + valde2;
if(x14>0 && x14<=11 && y14>0 && y14<=8){
casespossibles[indice] = make_pair(x14,y14);
indice++;
}
int x15 = x_actuel + valde2;
int y15 = y_actuel - valde2;
if(x15>0 && x15<=11 && y15>0 && y15<=8){
casespossibles[indice] = make_pair(x15,y15);
indice++;
}
int x16 = x_actuel - valde2;
int y16 = y_actuel - valde2;
if(x16>0 && x16<=11 && y16>0 && y16<=8){
casespossibles[16] = make_pair(x16,y16);
indice++;
}
int x17 = x_actuel + valdede;
int y17 = y_actuel;
if(x17>0 && x17<=11 && y17>0 && y17<=8){
casespossibles[indice] = make_pair(x17,y17);
indice++;
}
int x18 = x_actuel - valdede;
int y18 = y_actuel;
if(x18>0 && x18<=11 && y18>0 && y18<=8){
casespossibles[indice] = make_pair(x18,y18);
indice++;
}
int x19 = x_actuel;
int y19 = y_actuel + valdede;
if(x19>0 && x19<=11 && y19>0 && y19<=8){
casespossibles[indice] = make_pair(x19,y19);
indice++;
}
int x20 = x_actuel;
int y20 = y_actuel - valdede;
if(x20>0 && x20<=11 && y20>0 && y20<=8){
casespossibles[indice] = make_pair(x20,y20);
indice++;
}
int x21 = x_actuel + valdede;
int y21 = y_actuel + valdede;
if(x21>0 && x21<=11 && y21>0 && y21<=8){
casespossibles[indice] = make_pair(x21,y21);
indice++;
}
int x22 = x_actuel - valdede;
int y22 = y_actuel + valdede;
if(x22>0 && x22<=11 && y22>0 && y22<=8){
casespossibles[indice] = make_pair(x22,y22);
indice++;
}
int x23 = x_actuel + valdede;
int y23 = y_actuel - valdede;
if(x23>0 && x23<=11 && y23>0 && y23<=8){
casespossibles[indice] = make_pair(x23,y23);
indice++;
}
int x24 = x_actuel - valdede;
int y24 = y_actuel - valdede;
if(x24>0 && x24<=11 && y24>0 && y24<=8){
casespossibles[indice] = make_pair(x24,y24);
indice++;
}
for(int c=0;c<indice;c++){
if(casespossibles[c].first>=1 && casespossibles[c].first<=11 &&
casespossibles[c].second>=1 && casespossibles[c].second<=8){
motor->setAccessible(casespossibles[c]);
}
traverseIle(casespossibles, c);
}
} else {
for(int c=0; c<indice ;c++){
if(casespossibles[c].first>=1 && casespossibles[c].first<=11 &&
casespossibles[c].second>=1 && casespossibles[c].second<=8){
motor->setAccessible(casespossibles[c]);
cout<<"est accessible la case"<< casespossibles[c].first<<" "<<casespossibles[c].second<<endl;
}
traverseIle(casespossibles, c);
}
}
motor->getFacade()->setCoulBateauCourant(motor->getJoueurInd(motor->getJCourant())->getBateauCourant()->getCouleur());
motor->modifCourant(ATTENTEDEPLACEMENT);
} | [
"havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6",
"garethiveux@9f3b02c3-fd90-5378-97a3-836ae78947c6"
] | [
[
[
1,
1
],
[
3,
17
],
[
45,
46
],
[
48,
48
],
[
51,
51
],
[
59,
66
],
[
68,
70
],
[
75,
77
],
[
80,
80
],
[
82,
82
],
[
85,
88
],
[
92,
95
],
[
98,
101
],
[
104,
107
],
[
110,
113
],
[
116,
119
],
[
122,
125
],
[
128,
131
],
[
134,
140
],
[
142,
143
],
[
147,
150
],
[
153,
156
],
[
159,
162
],
[
165,
168
],
[
171,
174
],
[
177,
180
],
[
183,
186
],
[
189,
192
],
[
195,
198
],
[
201,
204
],
[
207,
210
],
[
213,
216
],
[
219,
222
],
[
225,
228
],
[
231,
234
],
[
237,
243
],
[
250,
252
],
[
254,
255
],
[
261,
264
]
],
[
[
2,
2
],
[
18,
44
],
[
47,
47
],
[
49,
50
],
[
52,
58
],
[
67,
67
],
[
71,
74
],
[
78,
79
],
[
81,
81
],
[
83,
84
],
[
89,
91
],
[
96,
97
],
[
102,
103
],
[
108,
109
],
[
114,
115
],
[
120,
121
],
[
126,
127
],
[
132,
133
],
[
141,
141
],
[
144,
146
],
[
151,
152
],
[
157,
158
],
[
163,
164
],
[
169,
170
],
[
175,
176
],
[
181,
182
],
[
187,
188
],
[
193,
194
],
[
199,
200
],
[
205,
206
],
[
211,
212
],
[
217,
218
],
[
223,
224
],
[
229,
230
],
[
235,
236
],
[
244,
249
],
[
253,
253
],
[
256,
260
]
]
] |
bcecf0245099591df8f440d397471b0467995c1a | cc5b962dfd2dc6acc0d401b1ab7b456c99c7e8c4 | /Bomberman 1.0/playerobject.h | eb7a70cd5a735ff44177c303a44359aa8ee2d0f1 | [] | no_license | andreapachas/bomberman-tsbk05 | c9e47b784982185077eec2d659a217897abbacc7 | 8ca28cb3095428e41db12d0060fc5573b614d3de | refs/heads/master | 2021-05-30T06:30:25.413561 | 2007-04-25T07:52:39 | 2007-04-25T07:52:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | h | #include "object.h"
#ifndef PLAYEROBJECT_H
#define PLAYEROBJECT_H
class PlayerObject : public Object {
static const int bombFrequency = 0;
float lastBombDrop;
bool isDeadVar;
int light;
public:
PlayerObject(Model*, GLfloat, GLfloat, GLfloat = 0, GLfloat = 0, GLfloat = 1, int = -1);
bool canDropBomb(float currentTime);
void droppedBomb(float currentTime);
bool isDead() {
return isDeadVar;
};
void die() {
isDeadVar = true;
};
void draw();
};
#endif
| [
"jonas.lindgren@774f44fe-ff29-0410-bf63-e573c7ae51ad",
"mrrayan@774f44fe-ff29-0410-bf63-e573c7ae51ad"
] | [
[
[
1,
23
]
],
[
[
24,
24
]
]
] |
e6aa65c9f8ea6f6206c59dccd0813f3bd4e8cc32 | a6f42311df3830117e9590e446b105db78fdbd3a | /src/framework/gui/Image.cpp | f859bbfd1fc1ae6325db12a6ebbc8f3de3581259 | [] | no_license | wellsoftware/temporal-lightfield-reconstruction | a4009b9da01b93d6d77a4d0d6830c49e0d4e225f | 8d0988b5660ba0e53d65e887a51e220dcbc985ca | refs/heads/master | 2021-01-17T23:49:05.544012 | 2011-09-25T10:47:49 | 2011-09-25T10:47:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,355 | cpp | /*
* Copyright (c) 2009-2011, NVIDIA Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA Corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "gui/Image.hpp"
#include "io/ImageBinaryIO.hpp"
#include "io/ImageLodePngIO.hpp"
#include "io/ImageRawPngIO.hpp"
#include "io/ImageTargaIO.hpp"
#include "io/ImageTiffIO.hpp"
#include "io/ImageBmpIO.hpp"
#include "io/File.hpp"
using namespace FW;
//------------------------------------------------------------------------
#define C8(TYPE, OFS) { ChannelType_ ## TYPE, ChannelFormat_Clamp, OFS, 1, 0, 8 }
#define C16(TYPE, OFS, SIZE) { ChannelType_ ## TYPE, ChannelFormat_Clamp, 0, 2, OFS, SIZE }
#define C32(TYPE, OFS) { ChannelType_ ## TYPE, ChannelFormat_Clamp, 0, 4, OFS, 8 }
#define CF32(TYPE, OFS) { ChannelType_ ## TYPE, ChannelFormat_Float, OFS, 4, 0, 32 }
const ImageFormat::StaticFormat ImageFormat::s_staticFormats[] =
{
/* R8_G8_B8 */ { 3, 3, { C8(R,0), C8(G,1), C8(B,2) }, GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, false },
/* R8_G8_B8_A8 */ { 4, 4, { C8(R,0), C8(G,1), C8(B,2), C8(A,3) }, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, false },
/* A8 */ { 1, 1, { C8(A,0) }, GL_ALPHA8, GL_ALPHA, GL_UNSIGNED_BYTE, false },
/* XBGR_8888 */ { 4, 3, { C32(R,0), C32(G,8), C32(B,16) }, GL_RGB8, GL_RGBA, GL_UNSIGNED_BYTE, true },
/* ABGR_8888 */ { 4, 4, { C32(R,0), C32(G,8), C32(B,16), C32(A,24) }, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true },
/* RGB_565 */ { 2, 3, { C16(R,11,5), C16(G,5,6), C16(B,0,5) }, GL_RGB5, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, false },
/* RGBA_5551 */ { 2, 4, { C16(R,11,5), C16(G,6,5), C16(B,1,5), C16(A,0,1) }, GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, false },
/* RGB_Vec3f */ { 12, 3, { CF32(R,0), CF32(G,4), CF32(B,8) }, GL_RGB32F, GL_RGB, GL_FLOAT, false },
/* RGBA_Vec4f */ { 16, 4, { CF32(R,0), CF32(G,4), CF32(B,8), CF32(A,12) }, GL_RGBA32F, GL_RGBA, GL_FLOAT, false },
/* A_F32 */ { 4, 1, { CF32(A,0) }, GL_ALPHA32F_ARB, GL_ALPHA, GL_FLOAT, false },
};
#undef C8
#undef C16
#undef C32
#undef CF32
//------------------------------------------------------------------------
#define RGB_565_TO_ABGR_8888(V) ((V >> 8) & 0x000000F8) | (V >> 13) | ((V << 5) & 0x0000FC00) | ((V >> 1) & 0x00000300) | ((V << 19) & 0x00F80000) | ((V >> 14) & 0x00070000) | 0xFF000000
#define ABGR_8888_TO_RGB_565(V) (U16)(((V << 8) & 0xF800) | ((V >> 5) & 0x07E0) | ((V >> 19) & 0x001F))
#define RGBA_5551_TO_ABGR_8888(V) ((V >> 8) & 0x000000F8) | (V >> 13) | ((V << 5) & 0x0000F800) | (V & 0x00000700) | ((V << 18) & 0x00F80000) | ((V >> 13) & 0x00070000) | ((S32)(V << 31) >> 7)
#define ABGR_8888_TO_RGBA_5551(V) (U16)(((V << 8) & 0xF800) | ((V >> 5) & 0x07C0) | ((V >> 18) & 0x003E) | (V >> 31))
//------------------------------------------------------------------------
ImageFormat::ID ImageFormat::getID(void) const
{
if (m_id != ID_Max)
return m_id;
FW_ASSERT(FW_ARRAY_SIZE(s_staticFormats) == ID_Generic);
for (int i = 0; i < (int)ID_Generic; i++)
{
const StaticFormat& f = s_staticFormats[i];
if (m_genericBPP == f.bpp &&
m_genericChannels.getSize() == f.numChannels &&
memcmp(m_genericChannels.getPtr(), f.channels, m_genericChannels.getNumBytes()) == 0)
{
m_id = (ID)i;
return m_id;
}
}
m_id = ID_Generic;
return m_id;
}
//------------------------------------------------------------------------
const ImageFormat::StaticFormat* ImageFormat::getStaticFormat(void) const
{
ID id = getID();
FW_ASSERT(FW_ARRAY_SIZE(s_staticFormats) == ID_Generic);
return (id < ID_Generic) ? &s_staticFormats[id] : NULL;
}
//------------------------------------------------------------------------
int ImageFormat::getBPP(void) const
{
FW_ASSERT(FW_ARRAY_SIZE(s_staticFormats) == ID_Generic);
return (m_id < ID_Generic) ? s_staticFormats[m_id].bpp : m_genericBPP;
}
//------------------------------------------------------------------------
int ImageFormat::getNumChannels(void) const
{
FW_ASSERT(FW_ARRAY_SIZE(s_staticFormats) == ID_Generic);
return (m_id < ID_Generic) ? s_staticFormats[m_id].numChannels : m_genericChannels.getSize();
}
//------------------------------------------------------------------------
const ImageFormat::Channel& ImageFormat::getChannel(int idx) const
{
FW_ASSERT(idx >= 0 && idx < getNumChannels());
FW_ASSERT(FW_ARRAY_SIZE(s_staticFormats) == ID_Generic);
return (m_id < ID_Generic) ? s_staticFormats[m_id].channels[idx] : m_genericChannels[idx];
}
//------------------------------------------------------------------------
int ImageFormat::findChannel(ChannelType type) const
{
int num = getNumChannels();
for (int i = 0; i < num; i++)
if (getChannel(i).type == type)
return i;
return -1;
}
//------------------------------------------------------------------------
void ImageFormat::set(const ImageFormat& other)
{
m_id = other.m_id;
if (m_id >= ID_Generic)
{
m_genericBPP = other.m_genericBPP;
m_genericChannels = other.m_genericChannels;
}
}
//------------------------------------------------------------------------
void ImageFormat::clear(void)
{
m_id = ID_Generic;
m_genericBPP = 0;
m_genericChannels.clear();
}
//------------------------------------------------------------------------
void ImageFormat::addChannel(const Channel& channel)
{
if (m_id < ID_Generic)
{
const StaticFormat& f = s_staticFormats[m_id];
m_genericBPP = f.bpp;
m_genericChannels.set(f.channels, f.numChannels);
}
m_id = ID_Max;
m_genericBPP = max(m_genericBPP, channel.wordOfs + channel.wordSize);
m_genericChannels.add(channel);
}
//------------------------------------------------------------------------
ImageFormat::ID ImageFormat::getGLFormat(void) const
{
const ImageFormat::StaticFormat* sf = getStaticFormat();
// Requires little endian machine => check.
if (sf && sf->glLittleEndian)
{
U32 tmp = 0x12345678;
if (*(U8*)&tmp != 0x78)
sf = NULL;
}
// Maps directly to a GL format => done.
if (sf && sf->glInternalFormat != GL_NONE)
return getID();
// Otherwise => select the closest match.
U32 channels = 0;
bool isFloat = false;
for (int i = 0; i < getNumChannels(); i++)
{
const ImageFormat::Channel& c = getChannel(i);
if (c.type > ImageFormat::ChannelType_A)
continue;
channels |= 1 < c.type;
if (c.format == ImageFormat::ChannelFormat_Float)
isFloat = true;
}
if ((channels & 7) == 0)
return (isFloat) ? ImageFormat::A_F32 : ImageFormat::A8;
if ((channels & 8) == 0)
return (isFloat) ? ImageFormat::RGB_Vec3f : ImageFormat::R8_G8_B8;
return (isFloat) ? ImageFormat::RGBA_Vec4f : ImageFormat::R8_G8_B8_A8;
}
//------------------------------------------------------------------------
bool ImageFormat::operator==(const ImageFormat& other) const
{
if (m_id < ID_Generic || other.m_id < ID_Generic)
return (getID() == other.getID());
return (
m_genericBPP == other.m_genericBPP &&
m_genericChannels.getSize() == other.m_genericChannels.getSize() &&
memcmp(m_genericChannels.getPtr(), other.m_genericChannels.getPtr(), m_genericChannels.getNumBytes()) == 0);
}
//------------------------------------------------------------------------
Image::Image(const Vec2i& size, const ImageFormat& format, void* ptr, S64 stride)
{
init(size, format);
FW_ASSERT(size.min() == 0 || ptr);
S64 lo = 0;
S64 hi = 0;
if (size.min() != 0)
{
lo = min(stride * (size.y - 1), (S64)0);
hi = max(stride * (size.y - 1), (S64)0) + size.x * format.getBPP();
}
m_stride = stride;
m_buffer = new Buffer((U8*)ptr + lo, hi - lo);
m_ownBuffer = true;
m_offset = -lo;
}
//------------------------------------------------------------------------
Image::Image(const Vec2i& size, const ImageFormat& format, Buffer& buffer, S64 ofs, S64 stride)
{
init(size, format);
FW_ASSERT(size.min() == 0 || ofs + min(stride * (size.y - 1), (S64)0) >= 0);
FW_ASSERT(size.min() == 0 || ofs + max(stride * (size.y - 1), (S64)0) + size.x * format.getBPP() <= buffer.getSize());
m_stride = stride;
m_buffer = &buffer;
m_ownBuffer = false;
m_offset = ofs;
}
//------------------------------------------------------------------------
Image::~Image(void)
{
if (m_ownBuffer)
delete m_buffer;
}
//------------------------------------------------------------------------
U32 Image::getABGR(const Vec2i& pos) const
{
FW_ASSERT(contains(pos, 1));
const U8* p = getPtr(pos);
switch (m_format.getID())
{
case ImageFormat::R8_G8_B8: return p[0] | (p[1] << 8) | (p[2] << 16) | 0xFF000000;
case ImageFormat::R8_G8_B8_A8: return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
case ImageFormat::A8: return *p << 24;
case ImageFormat::XBGR_8888: return *(const U32*)p | 0xFF000000;
case ImageFormat::ABGR_8888: return *(const U32*)p;
case ImageFormat::RGB_565: { U16 v = *(const U16*)p; return RGB_565_TO_ABGR_8888(v); }
case ImageFormat::RGBA_5551: { U16 v = *(const U16*)p; return RGBA_5551_TO_ABGR_8888(v); }
case ImageFormat::RGB_Vec3f: return Vec4f(*(const Vec3f*)p, 1.0f).toABGR();
case ImageFormat::RGBA_Vec4f: return ((const Vec4f*)p)->toABGR();
case ImageFormat::A_F32: return clamp((int)(*(const F32*)p * 255.0f + 0.5f), 0x00, 0xFF) << 24;
default:
{
getChannels(pos);
bool hasAlpha = false;
U32 value = 0;
for (int i = 0; i < m_channelTmp.getSize(); i++)
{
U32 v = clamp((int)(m_channelTmp[i] * 255.0f + 0.5f), 0x00, 0xFF);
switch (m_format.getChannel(i).type)
{
case ImageFormat::ChannelType_R: value |= v; break;
case ImageFormat::ChannelType_G: value |= v << 8; break;
case ImageFormat::ChannelType_B: value |= v << 16; break;
case ImageFormat::ChannelType_A: value |= v << 24; hasAlpha = true; break;
}
}
if (!hasAlpha)
value |= 0xFF000000;
return value;
}
}
}
//------------------------------------------------------------------------
void Image::setABGR(const Vec2i& pos, U32 value)
{
FW_ASSERT(contains(pos, 1));
U8* p = getMutablePtr(pos);
switch (m_format.getID())
{
case ImageFormat::R8_G8_B8: p[0] = (U8)value; p[1] = (U8)(value >> 8); p[2] = (U8)(value >> 16); break;
case ImageFormat::R8_G8_B8_A8: p[0] = (U8)value; p[1] = (U8)(value >> 8); p[2] = (U8)(value >> 16); p[3] = (U8)(value >> 24); break;
case ImageFormat::A8: *p = (U8)(value >> 24); break;
case ImageFormat::XBGR_8888: *(U32*)p = value; break;
case ImageFormat::ABGR_8888: *(U32*)p = value; break;
case ImageFormat::RGB_565: *(U16*)p = ABGR_8888_TO_RGB_565(value); break;
case ImageFormat::RGBA_5551: *(U16*)p = ABGR_8888_TO_RGBA_5551(value); break;
case ImageFormat::RGB_Vec3f: *(Vec3f*)p = Vec4f::fromABGR(value).getXYZ(); break;
case ImageFormat::RGBA_Vec4f: *(Vec4f*)p = Vec4f::fromABGR(value); break;
case ImageFormat::A_F32: *(F32*)p = (F32)(value >> 24) / 255.0f; break;
default:
for (int i = 0; i < m_channelTmp.getSize(); i++)
{
F32& channel = m_channelTmp[i];
switch (m_format.getChannel(i).type)
{
case ImageFormat::ChannelType_R: channel = (F32)(value & 0xFF) / 255.0f; break;
case ImageFormat::ChannelType_G: channel = (F32)((value >> 8) & 0xFF) / 255.0f; break;
case ImageFormat::ChannelType_B: channel = (F32)((value >> 16) & 0xFF) / 255.0f; break;
case ImageFormat::ChannelType_A: channel = (F32)(value >> 24) / 255.0f; break;
default: channel = 0.0f; break;
}
}
setChannels(pos, m_channelTmp.getPtr());
break;
}
}
//------------------------------------------------------------------------
Vec4f Image::getVec4f(const Vec2i& pos) const
{
FW_ASSERT(contains(pos, 1));
const U8* p = getPtr(pos);
switch (m_format.getID())
{
case ImageFormat::A8: return Vec4f(0.0f, 0.0f, 0.0f, (F32)(*p / 255.0f));
case ImageFormat::XBGR_8888: return Vec4f::fromABGR(*(const U32*)p | 0xFF000000);
case ImageFormat::ABGR_8888: return Vec4f::fromABGR(*(const U32*)p);
case ImageFormat::RGB_Vec3f: return Vec4f(*(const Vec3f*)p, 1.0f);
case ImageFormat::RGBA_Vec4f: return *(const Vec4f*)p;
case ImageFormat::A_F32: return Vec4f(0.0f, 0.0f, 0.0f, *(const F32*)p);
case ImageFormat::R8_G8_B8:
case ImageFormat::R8_G8_B8_A8:
case ImageFormat::RGB_565:
case ImageFormat::RGBA_5551:
return Vec4f::fromABGR(getABGR(pos));
default:
{
getChannels(pos);
Vec4f value(0.0f, 0.0f, 0.0f, 1.0f);
for (int i = 0; i < m_channelTmp.getSize(); i++)
{
ImageFormat::ChannelType t = m_format.getChannel(i).type;
if (t <= ImageFormat::ChannelType_A)
value[t] = m_channelTmp[i];
}
return value;
}
}
}
//------------------------------------------------------------------------
void Image::setVec4f(const Vec2i& pos, const Vec4f& value)
{
FW_ASSERT(contains(pos, 1));
U8* p = getMutablePtr(pos);
switch (m_format.getID())
{
case ImageFormat::A8: *p = (U8)clamp((int)(value.w * 255.0f + 0.5f), 0x00, 0xFF); break;
case ImageFormat::XBGR_8888: *(U32*)p = value.toABGR(); break;
case ImageFormat::ABGR_8888: *(U32*)p = value.toABGR(); break;
case ImageFormat::RGB_Vec3f: *(Vec3f*)p = value.getXYZ(); break;
case ImageFormat::RGBA_Vec4f: *(Vec4f*)p = value; break;
case ImageFormat::A_F32: *(F32*)p = value.w; break;
case ImageFormat::R8_G8_B8:
case ImageFormat::R8_G8_B8_A8:
case ImageFormat::RGB_565:
case ImageFormat::RGBA_5551:
setABGR(pos, value.toABGR());
break;
default:
for (int i = 0; i < m_channelTmp.getSize(); i++)
{
ImageFormat::ChannelType t = m_format.getChannel(i).type;
m_channelTmp[i] = (t <= ImageFormat::ChannelType_A) ? value[t] : 0.0f;
}
setChannels(pos, m_channelTmp.getPtr());
break;
}
}
//------------------------------------------------------------------------
void Image::flipX(void)
{
int bpp = getBPP();
for (int y = 0; y < m_size.y; y++)
{
U8* ptrA = getMutablePtr(Vec2i(0, y));
U8* ptrB = getMutablePtr(Vec2i(m_size.x - 1, y));
for (int x = (m_size.x >> 1); x > 0; x--)
{
for (int i = 0; i < bpp; i++)
swap(ptrA[i], ptrB[i]);
ptrA += bpp;
ptrB -= bpp;
}
}
}
//------------------------------------------------------------------------
void Image::flipY(void)
{
int scanBytes = m_size.x * getBPP();
Array<U8> tmp(NULL, scanBytes);
for (int y = (m_size.y >> 1) - 1; y >= 0; y--)
{
U8* ptrA = getMutablePtr(Vec2i(0, y));
U8* ptrB = getMutablePtr(Vec2i(0, m_size.y - 1 - y));
memcpy(tmp.getPtr(), ptrA, scanBytes);
memcpy(ptrA, ptrB, scanBytes);
memcpy(ptrB, tmp.getPtr(), scanBytes);
}
}
//------------------------------------------------------------------------
GLuint Image::createGLTexture(ImageFormat::ID desiredFormat, bool generateMipmaps) const
{
// Select format.
ImageFormat::ID formatID;
if (desiredFormat == ImageFormat::ID_Max)
formatID = m_format.getGLFormat();
else
formatID = ImageFormat(desiredFormat).getGLFormat();
const ImageFormat::StaticFormat* sf = ImageFormat(formatID).getStaticFormat();
FW_ASSERT(sf);
// Image data not usable directly => convert.
Image* converted = NULL;
const Image* img = this;
if (m_size.min() == 0 || m_format.getID() != formatID || m_stride != getBPP() * m_size.x)
{
converted = new Image(max(m_size, 1), formatID);
converted->set(*this);
img = converted;
}
// Create texture.
GLContext::staticInit();
GLint oldTex = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldTex);
GLuint tex = 0;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, generateMipmaps);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (generateMipmaps) ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Uncomment to enable anisotropic filtering:
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, FW_S32_MAX);
glTexImage2D(GL_TEXTURE_2D, 0, sf->glInternalFormat,
img->getSize().x, img->getSize().y,
0, sf->glFormat, sf->glType, img->getPtr());
glBindTexture(GL_TEXTURE_2D, oldTex);
GLContext::checkErrors();
// Clean up.
delete converted;
return tex;
}
//------------------------------------------------------------------------
ImageFormat Image::chooseCudaFormat(CUDA_ARRAY_DESCRIPTOR* desc, ImageFormat::ID desiredFormat) const
{
#if (!FW_USE_CUDA)
FW_UNREF(desc);
FW_UNREF(desiredFormat);
fail("Image::chooseCudaFormat(): Built without FW_USE_CUDA!");
return m_format;
#else
// Gather requirements.
ImageFormat refFormat = m_format;
if (desiredFormat != ImageFormat::ID_Max)
refFormat = desiredFormat;
int numChannels = min(refFormat.getNumChannels(), 4);
int channelBits = 0;
bool isFloat = false;
for (int i = 0; i < numChannels; i++)
{
const ImageFormat::Channel& chan = refFormat.getChannel(i);
channelBits = max(channelBits, chan.fieldSize);
isFloat = (chan.format == ImageFormat::ChannelFormat_Float);
}
// Select format.
CUarray_format datatype;
int wordSize;
if (isFloat) datatype = CU_AD_FORMAT_FLOAT, wordSize = 4;
else if (channelBits <= 8) datatype = CU_AD_FORMAT_UNSIGNED_INT8, wordSize = 1;
else if (channelBits <= 16) datatype = CU_AD_FORMAT_UNSIGNED_INT16, wordSize = 2;
else datatype = CU_AD_FORMAT_UNSIGNED_INT32, wordSize = 4;
ImageFormat formatA; // word per channel
ImageFormat formatB; // single word
for (int i = 0; i < numChannels; i++)
{
const ImageFormat::Channel& ref = refFormat.getChannel(i);
ImageFormat::Channel chan;
chan.type = ref.type;
chan.format = (isFloat) ? ImageFormat::ChannelFormat_Float : ref.format;
chan.wordOfs = i * wordSize;
chan.wordSize = wordSize;
chan.fieldOfs = 0;
chan.fieldSize = wordSize * 8;
formatA.addChannel(chan);
chan.wordOfs = 0;
chan.wordSize = wordSize * numChannels;
chan.fieldOfs = i * wordSize * 8;
chan.fieldSize = wordSize * 8;
formatB.addChannel(chan);
}
// Fill in the descriptor.
if (desc)
{
desc->Width = m_size.x;
desc->Height = m_size.y;
desc->Format = datatype;
desc->NumChannels = numChannels;
}
return (formatB == refFormat) ? formatB : formatA;
#endif
}
//------------------------------------------------------------------------
CUarray Image::createCudaArray(ImageFormat::ID desiredFormat) const
{
#if (!FW_USE_CUDA)
FW_UNREF(desiredFormat);
fail("Image::createCudaArray(): Built without FW_USE_CUDA!");
return NULL;
#else
// Choose format.
CUDA_ARRAY_DESCRIPTOR arrayDesc;
ImageFormat cudaFormat = chooseCudaFormat(&arrayDesc, desiredFormat);
// Image data not usable directly => convert.
Image* converted = NULL;
const Image* img = this;
if (m_size.min() == 0 || m_format != cudaFormat)
{
converted = new Image(max(m_size, 1), cudaFormat);
converted->set(*this);
img = converted;
arrayDesc.Width = img->getSize().x;
arrayDesc.Height = img->getSize().y;
}
// Create CUDA array.
CudaModule::staticInit();
CUarray cudaArray;
CudaModule::checkError("cuArrayCreate", cuArrayCreate(&cudaArray, &arrayDesc));
CUDA_MEMCPY2D copyDesc;
copyDesc.srcXInBytes = 0;
copyDesc.srcY = 0;
copyDesc.srcMemoryType = CU_MEMORYTYPE_HOST;
copyDesc.srcHost = img->getPtr();
copyDesc.srcPitch = img->getSize().x * 4;
copyDesc.dstXInBytes = 0;
copyDesc.dstY = 0;
copyDesc.dstMemoryType = CU_MEMORYTYPE_ARRAY;
copyDesc.dstArray = cudaArray;
copyDesc.WidthInBytes = img->getSize().x * 4;
copyDesc.Height = img->getSize().y;
CudaModule::checkError("cuMemcpy2D", cuMemcpy2D(©Desc));
// Clean up.
delete converted;
return cudaArray;
#endif
}
//------------------------------------------------------------------------
// Implements a polyphase filter with round-down semantics from:
//
// Non-Power-of-Two Mipmapping
// (NVIDIA whitepaper)
// http://developer.nvidia.com/object/np2_mipmapping.html
Image* Image::downscale2x(void) const
{
// 1x1 or smaller => Bail out.
int area = m_size.x * m_size.y;
if (area <= 1)
return NULL;
// Choose filter dimensions.
int fw = (m_size.x == 1) ? 1 : ((m_size.x & 1) == 0) ? 2 : 3;
int fh = (m_size.y == 1) ? 1 : ((m_size.y & 1) == 0) ? 2 : 3;
Vec2i resSize = max(m_size >> 1, 1);
int halfArea = area >> 1;
// Allocate temporary scanline buffer and result image.
Image tmp(Vec2i(m_size.x, fh), ImageFormat::ABGR_8888);
Image* res = new Image(resSize, ImageFormat::ABGR_8888);
U32* resPtr = (U32*)res->getMutablePtr();
// Process each scanline in the result.
for (int y = 0; y < resSize.y; y++)
{
// Copy source scanlines into the temporary buffer.
tmp.set(0, *this, Vec2i(0, y * 2), Vec2i(m_size.x, fh));
// Choose weights along the Y-axis.
Vec3i wy(resSize.y);
if (fh == 3)
wy = Vec3i(resSize.y - y, resSize.y, y + 1);
// Process each pixel in the result.
for (int x = 0; x < resSize.x; x++)
{
// Choose weights along the X-axis.
Vec3i wx(resSize.x);
if (fw == 3)
wx = Vec3i(resSize.x - x, resSize.x, x + 1);
// Compute weighted average of pixel values.
Vec4i sum = 0;
const U32* tmpPtr = (const U32*)tmp.getPtr(Vec2i(x * 2, 0));
for (int yy = 0; yy < fh; yy++)
{
for (int xx = 0; xx < fw; xx++)
{
U32 abgr = tmpPtr[xx];
int weight = wx[xx] * wy[yy];
sum.x += (abgr & 0xFF) * weight;
sum.y += ((abgr >> 8) & 0xFF) * weight;
sum.z += ((abgr >> 16) & 0xFF) * weight;
sum.w += (abgr >> 24) * weight;
}
tmpPtr += m_size.x;
}
sum = (sum + halfArea) / area;
*resPtr++ = sum.x | (sum.y << 8) | (sum.z << 16) | (sum.w << 24);
}
}
return res;
}
//------------------------------------------------------------------------
void Image::init(const Vec2i& size, const ImageFormat& format)
{
FW_ASSERT(size.min() >= 0);
m_size = size;
m_format = format;
m_channelTmp.resize(m_format.getNumChannels());
}
//------------------------------------------------------------------------
void Image::createBuffer(void)
{
m_stride = m_size.x * m_format.getBPP();
m_buffer = new Buffer;
m_buffer->resize(m_stride * m_size.y);
m_ownBuffer = true;
m_offset = 0;
}
//------------------------------------------------------------------------
void Image::replicatePixel(void)
{
if (m_size.min() == 0)
return;
int bpp = getBPP();
U8* ptr = getMutablePtr();
int scanBytes = m_size.x * bpp;
for (int x = 1; x < m_size.x; x++)
memcpy(ptr + x * bpp, ptr, bpp);
for (int y = 1; y < m_size.y; y++)
memcpy(ptr + y * m_stride, ptr, scanBytes);
}
//------------------------------------------------------------------------
bool Image::canBlitDirectly(const ImageFormat& format)
{
switch (format.getID())
{
case ImageFormat::R8_G8_B8: return true;
case ImageFormat::R8_G8_B8_A8: return true;
case ImageFormat::A8: return true;
case ImageFormat::XBGR_8888: return true;
case ImageFormat::ABGR_8888: return true;
case ImageFormat::RGB_565: return true;
case ImageFormat::RGBA_5551: return true;
case ImageFormat::RGB_Vec3f: return true;
case ImageFormat::RGBA_Vec4f: return true;
case ImageFormat::A_F32: return true;
default: return false;
}
}
//------------------------------------------------------------------------
bool Image::canBlitThruABGR(const ImageFormat& format)
{
switch (format.getID())
{
case ImageFormat::R8_G8_B8: return true;
case ImageFormat::R8_G8_B8_A8: return true;
case ImageFormat::A8: return true;
case ImageFormat::XBGR_8888: return true;
case ImageFormat::ABGR_8888: return true;
case ImageFormat::RGB_565: return true;
case ImageFormat::RGBA_5551: return true;
case ImageFormat::RGB_Vec3f: return false;
case ImageFormat::RGBA_Vec4f: return false;
case ImageFormat::A_F32: return false;
default: return false;
}
}
//------------------------------------------------------------------------
void Image::blit(
const ImageFormat& dstFormat, U8* dstPtr, S64 dstStride,
const ImageFormat& srcFormat, const U8* srcPtr, S64 srcStride,
const Vec2i& size)
{
FW_ASSERT(size.min() >= 0);
if (size.min() == 0)
return;
// Same format?
if (dstFormat == srcFormat)
{
int scanBytes = size.x * dstFormat.getBPP();
for (int y = 0; y < size.y; y++)
memcpy(dstPtr + dstStride * y, srcPtr + srcStride * y, scanBytes);
return;
}
// To ABGR_8888?
if (dstFormat.getID() == ImageFormat::ABGR_8888 && canBlitDirectly(srcFormat))
{
for (int y = 0; y < size.y; y++)
blitToABGR((U32*)(dstPtr + dstStride * y), srcFormat, srcPtr + srcStride * y, size.x);
return;
}
// From ABGR_8888?
if (srcFormat.getID() == ImageFormat::ABGR_8888 && canBlitDirectly(dstFormat))
{
for (int y = 0; y < size.y; y++)
blitFromABGR(dstFormat, dstPtr + dstStride * y, (const U32*)(srcPtr + srcStride * y), size.x);
return;
}
// From integer-based format to another => convert thru ABGR_8888.
if (canBlitDirectly(srcFormat) && canBlitDirectly(dstFormat) && canBlitThruABGR(srcFormat))
{
Array<U32> tmp(NULL, size.x);
for (int y = 0; y < size.y; y++)
{
blitToABGR(tmp.getPtr(), srcFormat, srcPtr + srcStride * y, size.x);
blitFromABGR(dstFormat, dstPtr + dstStride * y, tmp.getPtr(), size.x);
}
return;
}
// General case.
S64 dstBPP = dstFormat.getBPP();
S64 srcBPP = srcFormat.getBPP();
Array<F32> dv(NULL, dstFormat.getNumChannels());
Array<F32> sv(NULL, srcFormat.getNumChannels());
Array<Vec2i> map;
for (int i = 0; i < dstFormat.getNumChannels(); i++)
{
ImageFormat::ChannelType t = dstFormat.getChannel(i).type;
dv[i] = (t == ImageFormat::ChannelType_A) ? 1.0f : 0.0f;
int si = srcFormat.findChannel(t);
if (si != -1)
map.add(Vec2i(i, si));
}
for (int y = 0; y < size.y; y++)
{
U8* dstPixel = dstPtr + dstStride * y;
const U8* srcPixel = srcPtr + srcStride * y;
for (int x = 0; x < size.x; x++)
{
getChannels(sv.getPtr(), srcPixel, srcFormat, 0, sv.getSize());
for (int i = 0; i < map.getSize(); i++)
dv[map[i].x] = sv[map[i].y];
setChannels(dstPixel, dv.getPtr(), dstFormat, 0, dv.getSize());
dstPixel += dstBPP;
srcPixel += srcBPP;
}
}
}
//------------------------------------------------------------------------
void Image::blitToABGR(U32* dstPtr, const ImageFormat& srcFormat, const U8* srcPtr, int width)
{
FW_ASSERT(width > 0);
FW_ASSERT(dstPtr && srcPtr);
FW_ASSERT(canBlitDirectly(srcFormat));
const U8* s8 = srcPtr;
const U16* s16 = (const U16*)srcPtr;
const Vec3f* sv3 = (const Vec3f*)srcPtr;
const Vec4f* sv4 = (const Vec4f*)srcPtr;
const F32* sf = (const F32*)srcPtr;
switch (srcFormat.getID())
{
case ImageFormat::R8_G8_B8: for (int x = width; x > 0; x--) { *dstPtr++ = s8[0] | (s8[1] << 8) | (s8[2] << 16) | 0xFF000000; s8 += 3; } break;
case ImageFormat::R8_G8_B8_A8: for (int x = width; x > 0; x--) { *dstPtr++ = s8[0] | (s8[1] << 8) | (s8[2] << 16) | (s8[3] << 24); s8 += 4; } break;
case ImageFormat::A8: for (int x = width; x > 0; x--) *dstPtr++ = *s8++ << 24; break;
case ImageFormat::XBGR_8888: memcpy(dstPtr, srcPtr, width * sizeof(U32)); break;
case ImageFormat::ABGR_8888: memcpy(dstPtr, srcPtr, width * sizeof(U32)); break;
case ImageFormat::RGB_565: for (int x = width; x > 0; x--) { U16 v = *s16++; *dstPtr++ = RGB_565_TO_ABGR_8888(v); } break;
case ImageFormat::RGBA_5551: for (int x = width; x > 0; x--) { U16 v = *s16++; *dstPtr++ = RGBA_5551_TO_ABGR_8888(v); } break;
case ImageFormat::RGB_Vec3f: for (int x = width; x > 0; x--) *dstPtr++ = Vec4f(*sv3++, 1.0f).toABGR(); break;
case ImageFormat::RGBA_Vec4f: for (int x = width; x > 0; x--) *dstPtr++ = (sv4++)->toABGR(); break;
case ImageFormat::A_F32: for (int x = width; x > 0; x--) *dstPtr++ = clamp((int)(*sf++ * 255.0f + 0.5f), 0x00, 0xFF) << 24; break;
default: FW_ASSERT(false); break;
}
}
//------------------------------------------------------------------------
void Image::blitFromABGR(const ImageFormat& dstFormat, U8* dstPtr, const U32* srcPtr, int width)
{
FW_ASSERT(width > 0);
FW_ASSERT(dstPtr && srcPtr);
FW_ASSERT(canBlitDirectly(dstFormat));
U8* d8 = dstPtr;
U16* d16 = (U16*)dstPtr;
Vec3f* dv3 = (Vec3f*)dstPtr;
Vec4f* dv4 = (Vec4f*)dstPtr;
F32* df = (F32*)dstPtr;
switch (dstFormat.getID())
{
case ImageFormat::R8_G8_B8: for (int x = width; x > 0; x--) { U32 v = *srcPtr++; *d8++ = (U8)v; *d8++ = (U8)(v >> 8); *d8++ = (U8)(v >> 16); } break;
case ImageFormat::R8_G8_B8_A8: for (int x = width; x > 0; x--) { U32 v = *srcPtr++; *d8++ = (U8)v; *d8++ = (U8)(v >> 8); *d8++ = (U8)(v >> 16); *d8++ = (U8)(v >> 24); } break;
case ImageFormat::A8: for (int x = width; x > 0; x--) *d8++ = (U8)(*srcPtr++ >> 24); break;
case ImageFormat::XBGR_8888: memcpy(dstPtr, srcPtr, width * sizeof(U32)); break;
case ImageFormat::ABGR_8888: memcpy(dstPtr, srcPtr, width * sizeof(U32)); break;
case ImageFormat::RGB_565: for (int x = width; x > 0; x--) { U32 v = *srcPtr++; *d16++ = ABGR_8888_TO_RGB_565(v); } break;
case ImageFormat::RGBA_5551: for (int x = width; x > 0; x--) { U32 v = *srcPtr++; *d16++ = ABGR_8888_TO_RGBA_5551(v); } break;
case ImageFormat::RGB_Vec3f: for (int x = width; x > 0; x--) *dv3++ = Vec4f::fromABGR(*srcPtr++).getXYZ(); break;
case ImageFormat::RGBA_Vec4f: for (int x = width; x > 0; x--) *dv4++ = Vec4f::fromABGR(*srcPtr++); break;
case ImageFormat::A_F32: for (int x = width; x > 0; x--) *df++ = (F32)(*srcPtr++ >> 24) / 255.0f; break;
default: FW_ASSERT(false); break;
}
}
//------------------------------------------------------------------------
void Image::getChannels(F32* values, const U8* pixelPtr, const ImageFormat& format, int first, int num)
{
FW_ASSERT(num >= 0);
FW_ASSERT((values && pixelPtr) || !num);
FW_ASSERT(first >= 0 && first + num <= format.getNumChannels());
for (int i = 0; i < num; i++)
{
const ImageFormat::Channel& c = format.getChannel(i + first);
const U8* wordPtr = pixelPtr + c.wordOfs;
U32 field;
switch (c.wordSize)
{
case 1: field = *wordPtr; break;
case 2: field = *(const U16*)wordPtr; break;
case 4: field = *(const U32*)wordPtr; break;
default: FW_ASSERT(false); return;
}
field >>= c.fieldOfs;
U32 mask = (1 << c.fieldSize) - 1;
switch (c.format)
{
case ImageFormat::ChannelFormat_Clamp: values[i] = (F32)(field & mask) / (F32)mask; break;
case ImageFormat::ChannelFormat_Int: values[i] = (F32)(field & mask); break;
case ImageFormat::ChannelFormat_Float: FW_ASSERT(c.fieldSize == 32); values[i] = bitsToFloat(field); break;
default: FW_ASSERT(false); return;
}
}
}
//------------------------------------------------------------------------
void Image::setChannels(U8* pixelPtr, const F32* values, const ImageFormat& format, int first, int num)
{
FW_ASSERT(num >= 0);
FW_ASSERT((pixelPtr && values) || !num);
FW_ASSERT(first >= 0 && first + num <= format.getNumChannels());
memset(pixelPtr, 0, format.getBPP());
for (int i = 0; i < num; i++)
{
const ImageFormat::Channel& c = format.getChannel(i + first);
U32 mask = (1 << c.fieldSize) - 1;
U32 field;
switch (c.format)
{
case ImageFormat::ChannelFormat_Clamp: field = min((U32)max(values[i] * (F32)mask + 0.5f, 0.0f), mask); break;
case ImageFormat::ChannelFormat_Int: field = min((U32)max(values[i] + 0.5f, 0.0f), mask); break;
case ImageFormat::ChannelFormat_Float: FW_ASSERT(c.fieldSize == 32); field = floatToBits(values[i]); break;
default: FW_ASSERT(false); return;
}
field <<= c.fieldOfs;
U8* wordPtr = pixelPtr + c.wordOfs;
switch (c.wordSize)
{
case 1: *wordPtr |= (U8)field; break;
case 2: *(U16*)wordPtr |= (U16)field; break;
case 4: *(U32*)wordPtr |= field; break;
default: FW_ASSERT(false); return;
}
}
}
//------------------------------------------------------------------------
Image* FW::importImage(const String& fileName)
{
String lower = fileName.toLower();
#define STREAM(CALL) { File file(fileName, File::Read); BufferedInputStream stream(file); return CALL; }
if (lower.endsWith(".bin")) STREAM(importBinaryImage(stream))
if (lower.endsWith(".png")) STREAM(importLodePngImage(stream))
if (lower.endsWith(".tga") || lower.endsWith(".targa")) STREAM(importTargaImage(stream))
if (lower.endsWith(".tif") || lower.endsWith(".tiff")) STREAM(importTiffImage(stream))
if (lower.endsWith(".bmp")) STREAM(importBmpImage(stream))
#undef STREAM
setError("importImage(): Unsupported file extension '%s'!", fileName.getPtr());
return NULL;
}
//------------------------------------------------------------------------
void FW::exportImage(const String& fileName, const Image* image)
{
FW_ASSERT(image);
String lower = fileName.toLower();
#define STREAM(CALL) { File file(fileName, File::Create); BufferedOutputStream stream(file); CALL; stream.flush(); return; }
if (lower.endsWith(".bin")) STREAM(exportBinaryImage(stream, image))
if (lower.endsWith(".png")) STREAM(exportLodePngImage(stream, image))
if (lower.endsWith(".png")) STREAM(exportRawPngImage(stream, image))
if (lower.endsWith(".tga") || lower.endsWith(".targa")) STREAM(exportTargaImage(stream, image))
if (lower.endsWith(".tif") || lower.endsWith(".tiff")) STREAM(exportTiffImage(stream, image))
if (lower.endsWith(".bmp")) STREAM(exportBmpImage(stream, image))
#undef STREAM
setError("exportImage(): Unsupported file extension '%s'!", fileName.getPtr());
}
//------------------------------------------------------------------------
String FW::getImageImportFilter(void)
{
return
"png:PNG Image,"
"tga;targa:Targa Image,"
"tif;tiff:TIFF Image,"
"bmp:BMP Image,"
"bin:Binary Image";
}
//------------------------------------------------------------------------
String FW::getImageExportFilter(void)
{
return
"png:PNG Image,"
"tga;targa:Targa Image,"
"tif;tiff:TIFF Image,"
"bmp:BMP Image,"
"bin:Binary Image";
}
//------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
1109
]
]
] |
d5a147fce3c7de645b4642d780884646dd5c768b | 296387b2289a05b29cf72e276e0fc9c9db82e42f | /vc5_headers/math.h | 9982961b604112954280407b32d48b2fef6a01b7 | [] | no_license | jaykrell/jsvn | c469435ece6e8b11a4a9e6dd5bb4e500574b17ac | 474b5afe0a515fe384de4bfb16f7483a25ead6ca | refs/heads/master | 2020-04-01T19:27:12.846133 | 2011-10-16T22:16:03 | 2011-10-16T22:16:03 | 60,684,877 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,490 | h | /***
*math.h - definitions and declarations for math library
*
* Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
* This file contains constant definitions and external subroutine
* declarations for the math subroutine library.
* [ANSI/System V]
*
* [Public]
*
****/
#if _MSC_VER > 1000
#pragma once
#endif
#ifndef _INC_MATH
#define _INC_MATH
#if !defined(_WIN32) && !defined(_MAC)
#error ERROR: Only Mac or Win32 targets supported!
#endif
#ifdef _MSC_VER
/*
* Currently, all MS C compilers for Win32 platforms default to 8 byte
* alignment.
*/
#pragma pack(push,8)
#endif /* _MSC_VER */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef __assembler /* Protect from assembler */
/* Define _CRTIMP */
#ifndef _CRTIMP
#ifdef _DLL
#define _CRTIMP __declspec(dllimport)
#else /* ndef _DLL */
#define _CRTIMP
#endif /* _DLL */
#endif /* _CRTIMP */
/* Define __cdecl for non-Microsoft compilers */
#if ( !defined(_MSC_VER) && !defined(__cdecl) )
#define __cdecl
#endif
/* Definition of _exception struct - this struct is passed to the matherr
* routine when a floating point exception is detected
*/
#ifndef _EXCEPTION_DEFINED
struct _exception {
int type; /* exception type - see below */
char *name; /* name of function where error occured */
double arg1; /* first argument to function */
double arg2; /* second argument (if any) to function */
double retval; /* value to be returned by function */
} ;
#define _EXCEPTION_DEFINED
#endif
/* Definition of a _complex struct to be used by those who use cabs and
* want type checking on their argument
*/
#ifndef _COMPLEX_DEFINED
struct _complex {
double x,y; /* real and imaginary parts */
} ;
#if !__STDC__ && !defined (__cplusplus)
/* Non-ANSI name for compatibility */
#define complex _complex
#endif
#define _COMPLEX_DEFINED
#endif
#endif /* __assembler */
/* Constant definitions for the exception type passed in the _exception struct
*/
#define _DOMAIN 1 /* argument domain error */
#define _SING 2 /* argument singularity */
#define _OVERFLOW 3 /* overflow range error */
#define _UNDERFLOW 4 /* underflow range error */
#define _TLOSS 5 /* total loss of precision */
#define _PLOSS 6 /* partial loss of precision */
#define EDOM 33
#define ERANGE 34
/* Definitions of _HUGE and HUGE_VAL - respectively the XENIX and ANSI names
* for a value returned in case of error by a number of the floating point
* math routines
*/
#ifndef __assembler /* Protect from assembler */
_CRTIMP extern double _HUGE;
#endif /* __assembler */
#define HUGE_VAL _HUGE
/* Function prototypes */
#if !defined(__assembler) /* Protect from assembler */
#if _M_MRX000
/*_CRTIMP*/ int __cdecl abs(int);
/*_CRTIMP*/ double __cdecl acos(double);
/*_CRTIMP*/ double __cdecl asin(double);
/*_CRTIMP*/ double __cdecl atan(double);
/*_CRTIMP*/ double __cdecl atan2(double, double);
/*_CRTIMP*/ double __cdecl cos(double);
/*_CRTIMP*/ double __cdecl cosh(double);
/*_CRTIMP*/ double __cdecl exp(double);
/*_CRTIMP*/ double __cdecl fabs(double);
/*_CRTIMP*/ double __cdecl fmod(double, double);
/*_CRTIMP*/ long __cdecl labs(long);
/*_CRTIMP*/ double __cdecl log(double);
/*_CRTIMP*/ double __cdecl log10(double);
/*_CRTIMP*/ double __cdecl pow(double, double);
/*_CRTIMP*/ double __cdecl sin(double);
/*_CRTIMP*/ double __cdecl sinh(double);
/*_CRTIMP*/ double __cdecl tan(double);
/*_CRTIMP*/ double __cdecl tanh(double);
/*_CRTIMP*/ double __cdecl sqrt(double);
#else
int __cdecl abs(int);
double __cdecl acos(double);
double __cdecl asin(double);
double __cdecl atan(double);
double __cdecl atan2(double, double);
double __cdecl cos(double);
double __cdecl cosh(double);
double __cdecl exp(double);
double __cdecl fabs(double);
double __cdecl fmod(double, double);
long __cdecl labs(long);
double __cdecl log(double);
double __cdecl log10(double);
double __cdecl pow(double, double);
double __cdecl sin(double);
double __cdecl sinh(double);
double __cdecl tan(double);
double __cdecl tanh(double);
double __cdecl sqrt(double);
#endif
/*_CRTIMP*/ double __cdecl atof(const char *);
/*_CRTIMP*/ double __cdecl _cabs(struct _complex);
/*_CRTIMP*/ double __cdecl ceil(double);
/*_CRTIMP*/ double __cdecl floor(double);
/*_CRTIMP*/ double __cdecl frexp(double, int *);
/*_CRTIMP*/ double __cdecl _hypot(double, double);
/*_CRTIMP*/ double __cdecl _j0(double);
/*_CRTIMP*/ double __cdecl _j1(double);
/*_CRTIMP*/ double __cdecl _jn(int, double);
/*_CRTIMP*/ double __cdecl ldexp(double, int);
int __cdecl _matherr(struct _exception *);
/*_CRTIMP*/ double __cdecl modf(double, double *);
/*_CRTIMP*/ double __cdecl _y0(double);
/*_CRTIMP*/ double __cdecl _y1(double);
/*_CRTIMP*/ double __cdecl _yn(int, double);
#if defined(_M_MRX000)
/* MIPS fast prototypes for float */
/* ANSI C, 4.5 Mathematics */
/* 4.5.2 Trigonometric functions */
/*_CRTIMP*/ float __cdecl acosf( float );
/*_CRTIMP*/ float __cdecl asinf( float );
/*_CRTIMP*/ float __cdecl atanf( float );
/*_CRTIMP*/ float __cdecl atan2f( float , float );
/*_CRTIMP*/ float __cdecl cosf( float );
/*_CRTIMP*/ float __cdecl sinf( float );
/*_CRTIMP*/ float __cdecl tanf( float );
/* 4.5.3 Hyperbolic functions */
/*_CRTIMP*/ float __cdecl coshf( float );
/*_CRTIMP*/ float __cdecl sinhf( float );
/*_CRTIMP*/ float __cdecl tanhf( float );
/* 4.5.4 Exponential and logarithmic functions */
/*_CRTIMP*/ float __cdecl expf( float );
/*_CRTIMP*/ float __cdecl logf( float );
/*_CRTIMP*/ float __cdecl log10f( float );
/*_CRTIMP*/ float __cdecl modff( float , float* );
/* 4.5.5 Power functions */
/*_CRTIMP*/ float __cdecl powf( float , float );
float __cdecl sqrtf( float );
/* 4.5.6 Nearest integer, absolute value, and remainder functions */
float __cdecl ceilf( float );
float __cdecl fabsf( float );
float __cdecl floorf( float );
/*_CRTIMP*/ float __cdecl fmodf( float , float );
/*_CRTIMP*/ float __cdecl hypotf(float, float);
#endif /* _M_MRX000 */
#if defined(_M_ALPHA)
/* ALPHA fast prototypes for float */
/* ANSI C, 4.5 Mathematics */
/* 4.5.2 Trigonometric functions */
float __cdecl acosf( float );
float __cdecl asinf( float );
float __cdecl atanf( float );
float __cdecl atan2f( float , float );
float __cdecl cosf( float );
float __cdecl sinf( float );
float __cdecl tanf( float );
/* 4.5.3 Hyperbolic functions */
float __cdecl coshf( float );
float __cdecl sinhf( float );
float __cdecl tanhf( float );
/* 4.5.4 Exponential and logarithmic functions */
float __cdecl expf( float );
float __cdecl logf( float );
float __cdecl log10f( float );
/*_CRTIMP*/ float __cdecl modff( float , float* );
/* 4.5.5 Power functions */
float __cdecl powf( float , float );
float __cdecl sqrtf( float );
/* 4.5.6 Nearest integer, absolute value, and remainder functions */
float __cdecl ceilf( float );
float __cdecl fabsf( float );
float __cdecl floorf( float );
float __cdecl fmodf( float , float );
/*_CRTIMP*/ float __cdecl hypotf(float, float);
#endif /* _M_ALPHA */
#if !defined(_M_M68K)
/* Macros defining long double functions to be their double counterparts
* (long double is synonymous with double in this implementation).
*/
#ifndef __cplusplus
#define acosl(x) ((long double)acos((double)(x)))
#define asinl(x) ((long double)asin((double)(x)))
#define atanl(x) ((long double)atan((double)(x)))
#define atan2l(x,y) ((long double)atan2((double)(x), (double)(y)))
#define _cabsl _cabs
#define ceill(x) ((long double)ceil((double)(x)))
#define cosl(x) ((long double)cos((double)(x)))
#define coshl(x) ((long double)cosh((double)(x)))
#define expl(x) ((long double)exp((double)(x)))
#define fabsl(x) ((long double)fabs((double)(x)))
#define floorl(x) ((long double)floor((double)(x)))
#define fmodl(x,y) ((long double)fmod((double)(x), (double)(y)))
#define frexpl(x,y) ((long double)frexp((double)(x), (y)))
#define _hypotl(x,y) ((long double)_hypot((double)(x), (double)(y)))
#define ldexpl(x,y) ((long double)ldexp((double)(x), (y)))
#define logl(x) ((long double)log((double)(x)))
#define log10l(x) ((long double)log10((double)(x)))
#define _matherrl _matherr
#define modfl(x,y) ((long double)modf((double)(x), (double *)(y)))
#define powl(x,y) ((long double)pow((double)(x), (double)(y)))
#define sinl(x) ((long double)sin((double)(x)))
#define sinhl(x) ((long double)sinh((double)(x)))
#define sqrtl(x) ((long double)sqrt((double)(x)))
#define tanl(x) ((long double)tan((double)(x)))
#define tanhl(x) ((long double)tanh((double)(x)))
#else /* __cplusplus */
inline long double acosl(long double _X)
{return (acos((double)_X)); }
inline long double asinl(long double _X)
{return (asin((double)_X)); }
inline long double atanl(long double _X)
{return (atan((double)_X)); }
inline long double atan2l(long double _X, long double _Y)
{return (atan2((double)_X, (double)_Y)); }
inline long double ceill(long double _X)
{return (ceil((double)_X)); }
inline long double cosl(long double _X)
{return (cos((double)_X)); }
inline long double coshl(long double _X)
{return (cosh((double)_X)); }
inline long double expl(long double _X)
{return (exp((double)_X)); }
inline long double fabsl(long double _X)
{return (fabs((double)_X)); }
inline long double floorl(long double _X)
{return (floor((double)_X)); }
inline long double fmodl(long double _X, long double _Y)
{return (fmod((double)_X, (double)_Y)); }
inline long double frexpl(long double _X, int *_Y)
{return (frexp((double)_X, _Y)); }
inline long double ldexpl(long double _X, int _Y)
{return (ldexp((double)_X, _Y)); }
inline long double logl(long double _X)
{return (log((double)_X)); }
inline long double log10l(long double _X)
{return (log10((double)_X)); }
inline long double modfl(long double _X, long double *_Y)
{double _Di, _Df = modf((double)_X, &_Di);
*_Y = (long double)_Di;
return (_Df); }
inline long double powl(long double _X, long double _Y)
{return (pow((double)_X, (double)_Y)); }
inline long double sinl(long double _X)
{return (sin((double)_X)); }
inline long double sinhl(long double _X)
{return (sinh((double)_X)); }
inline long double sqrtl(long double _X)
{return (sqrt((double)_X)); }
inline long double tanl(long double _X)
{return (tan((double)_X)); }
inline long double tanhl(long double _X)
{return (tanh((double)_X)); }
inline float frexpf(float _X, int *_Y)
{return ((float)frexp((double)_X, _Y)); }
inline float ldexpf(float _X, int _Y)
{return ((float)ldexp((double)_X, _Y)); }
#if !defined(_M_MRX000) && !defined(_M_ALPHA)
inline float acosf(float _X)
{return ((float)acos((double)_X)); }
inline float asinf(float _X)
{return ((float)asin((double)_X)); }
inline float atanf(float _X)
{return ((float)atan((double)_X)); }
inline float atan2f(float _X, float _Y)
{return ((float)atan2((double)_X, (double)_Y)); }
inline float ceilf(float _X)
{return ((float)ceil((double)_X)); }
inline float cosf(float _X)
{return ((float)cos((double)_X)); }
inline float coshf(float _X)
{return ((float)cosh((double)_X)); }
inline float expf(float _X)
{return ((float)exp((double)_X)); }
inline float fabsf(float _X)
{return ((float)fabs((double)_X)); }
inline float floorf(float _X)
{return ((float)floor((double)_X)); }
inline float fmodf(float _X, float _Y)
{return ((float)fmod((double)_X, (double)_Y)); }
inline float logf(float _X)
{return ((float)log((double)_X)); }
inline float log10f(float _X)
{return ((float)log10((double)_X)); }
inline float modff(float _X, float *_Y)
{ double _Di, _Df = modf((double)_X, &_Di);
*_Y = (float)_Di;
return ((float)_Df); }
inline float powf(float _X, float _Y)
{return ((float)pow((double)_X, (double)_Y)); }
inline float sinf(float _X)
{return ((float)sin((double)_X)); }
inline float sinhf(float _X)
{return ((float)sinh((double)_X)); }
inline float sqrtf(float _X)
{return ((float)sqrt((double)_X)); }
inline float tanf(float _X)
{return ((float)tan((double)_X)); }
inline float tanhf(float _X)
{return ((float)tanh((double)_X)); }
#endif /* !defined(_M_MRX000) && !defined(_M_ALPHA) */
#endif /* __cplusplus */
#endif /* _M_M68K */
#endif /* __assembler */
#if !__STDC__
/* Non-ANSI names for compatibility */
#define DOMAIN _DOMAIN
#define SING _SING
#define OVERFLOW _OVERFLOW
#define UNDERFLOW _UNDERFLOW
#define TLOSS _TLOSS
#define PLOSS _PLOSS
#ifndef _MAC
#define matherr _matherr
#endif /* ndef _MAC */
#ifndef __assembler /* Protect from assembler */
_CRTIMP extern double HUGE;
/*_CRTIMP*/ double __cdecl cabs(struct _complex);
/*_CRTIMP*/ double __cdecl hypot(double, double);
/*_CRTIMP*/ double __cdecl j0(double);
/*_CRTIMP*/ double __cdecl j1(double);
/*_CRTIMP*/ double __cdecl jn(int, double);
int __cdecl matherr(struct _exception *);
/*_CRTIMP*/ double __cdecl y0(double);
/*_CRTIMP*/ double __cdecl y1(double);
/*_CRTIMP*/ double __cdecl yn(int, double);
#endif /* __assembler */
#endif /* __STDC__ */
#ifdef _M_M68K
/* definition of _exceptionl struct - this struct is passed to the _matherrl
* routine when a floating point exception is detected in a long double routine
*/
#ifndef _LD_EXCEPTION_DEFINED
struct _exceptionl {
int type; /* exception type - see below */
char *name; /* name of function where error occured */
long double arg1; /* first argument to function */
long double arg2; /* second argument (if any) to function */
long double retval; /* value to be returned by function */
} ;
#define _LD_EXCEPTION_DEFINED
#endif
/* definition of a _complexl struct to be used by those who use _cabsl and
* want type checking on their argument
*/
#ifndef _LD_COMPLEX_DEFINED
struct _complexl {
long double x,y; /* real and imaginary parts */
} ;
#define _LD_COMPLEX_DEFINED
#endif
long double __cdecl acosl(long double);
long double __cdecl asinl(long double);
long double __cdecl atanl(long double);
long double __cdecl atan2l(long double, long double);
long double __cdecl _atold(const char *);
long double __cdecl _cabsl(struct _complexl);
long double __cdecl ceill(long double);
long double __cdecl cosl(long double);
long double __cdecl coshl(long double);
long double __cdecl expl(long double);
long double __cdecl fabsl(long double);
long double __cdecl floorl(long double);
long double __cdecl fmodl(long double, long double);
long double __cdecl frexpl(long double, int *);
long double __cdecl _hypotl(long double, long double);
long double __cdecl _j0l(long double);
long double __cdecl _j1l(long double);
long double __cdecl _jnl(int, long double);
long double __cdecl ldexpl(long double, int);
long double __cdecl logl(long double);
long double __cdecl log10l(long double);
int __cdecl _matherrl(struct _exceptionl *);
long double __cdecl modfl(long double, long double *);
long double __cdecl powl(long double, long double);
long double __cdecl sinl(long double);
long double __cdecl sinhl(long double);
long double __cdecl sqrtl(long double);
long double __cdecl tanl(long double);
long double __cdecl tanhl(long double);
long double __cdecl _y0l(long double);
long double __cdecl _y1l(long double);
long double __cdecl _ynl(int, long double);
#endif /* _M_M68K */
#ifdef __cplusplus
}
#if !defined(_M_M68K)
template<class _Ty> inline
_Ty _Pow_int(_Ty _X, int _Y)
{unsigned int _N = _Y; // sic
if (_Y < 0)
_N = -_N;
for (_Ty _Z = _Ty(1); ; _X *= _X)
{if ((_N & 1) != 0)
_Z *= _X;
if ((_N >>= 1) == 0)
return (_Y < 0 ? _Ty(1) / _Z : _Z); }}
#ifndef _MSC_EXTENSIONS
inline long __cdecl abs(long _X)
{return (labs(_X)); }
inline double __cdecl abs(double _X)
{return (fabs(_X)); }
inline double __cdecl pow(double _X, int _Y)
{return (_Pow_int(_X, _Y)); }
inline double __cdecl pow(int _X, int _Y)
{return (_Pow_int(_X, _Y)); }
inline float __cdecl abs(float _X)
{return (fabsf(_X)); }
inline float __cdecl acos(float _X)
{return (acosf(_X)); }
inline float __cdecl asin(float _X)
{return (asinf(_X)); }
inline float __cdecl atan(float _X)
{return (atanf(_X)); }
inline float __cdecl atan2(float _Y, float _X)
{return (atan2f(_Y, _X)); }
inline float __cdecl ceil(float _X)
{return (ceilf(_X)); }
inline float __cdecl cos(float _X)
{return (cosf(_X)); }
inline float __cdecl cosh(float _X)
{return (coshf(_X)); }
inline float __cdecl exp(float _X)
{return (expf(_X)); }
inline float __cdecl fabs(float _X)
{return (fabsf(_X)); }
inline float __cdecl floor(float _X)
{return (floorf(_X)); }
inline float __cdecl fmod(float _X, float _Y)
{return (fmodf(_X, _Y)); }
inline float __cdecl frexp(float _X, int * _Y)
{return (frexpf(_X, _Y)); }
inline float __cdecl ldexp(float _X, int _Y)
{return (ldexpf(_X, _Y)); }
inline float __cdecl log(float _X)
{return (logf(_X)); }
inline float __cdecl log10(float _X)
{return (log10f(_X)); }
inline float __cdecl modf(float _X, float * _Y)
{return (modff(_X, _Y)); }
inline float __cdecl pow(float _X, float _Y)
{return (powf(_X, _Y)); }
inline float __cdecl pow(float _X, int _Y)
{return (_Pow_int(_X, _Y)); }
inline float __cdecl sin(float _X)
{return (sinf(_X)); }
inline float __cdecl sinh(float _X)
{return (sinhf(_X)); }
inline float __cdecl sqrt(float _X)
{return (sqrtf(_X)); }
inline float __cdecl tan(float _X)
{return (tanf(_X)); }
inline float __cdecl tanh(float _X)
{return (tanhf(_X)); }
inline long double __cdecl abs(long double _X)
{return (fabsl(_X)); }
inline long double __cdecl acos(long double _X)
{return (acosl(_X)); }
inline long double __cdecl asin(long double _X)
{return (asinl(_X)); }
inline long double __cdecl atan(long double _X)
{return (atanl(_X)); }
inline long double __cdecl atan2(long double _Y, long double _X)
{return (atan2l(_Y, _X)); }
inline long double __cdecl ceil(long double _X)
{return (ceill(_X)); }
inline long double __cdecl cos(long double _X)
{return (cosl(_X)); }
inline long double __cdecl cosh(long double _X)
{return (coshl(_X)); }
inline long double __cdecl exp(long double _X)
{return (expl(_X)); }
inline long double __cdecl fabs(long double _X)
{return (fabsl(_X)); }
inline long double __cdecl floor(long double _X)
{return (floorl(_X)); }
inline long double __cdecl fmod(long double _X, long double _Y)
{return (fmodl(_X, _Y)); }
inline long double __cdecl frexp(long double _X, int * _Y)
{return (frexpl(_X, _Y)); }
inline long double __cdecl ldexp(long double _X, int _Y)
{return (ldexpl(_X, _Y)); }
inline long double __cdecl log(long double _X)
{return (logl(_X)); }
inline long double __cdecl log10(long double _X)
{return (log10l(_X)); }
inline long double __cdecl modf(long double _X, long double * _Y)
{return (modfl(_X, _Y)); }
inline long double __cdecl pow(long double _X, long double _Y)
{return (powl(_X, _Y)); }
inline long double __cdecl pow(long double _X, int _Y)
{return (_Pow_int(_X, _Y)); }
inline long double __cdecl sin(long double _X)
{return (sinl(_X)); }
inline long double __cdecl sinh(long double _X)
{return (sinhl(_X)); }
inline long double __cdecl sqrt(long double _X)
{return (sqrtl(_X)); }
inline long double __cdecl tan(long double _X)
{return (tanl(_X)); }
inline long double __cdecl tanh(long double _X)
{return (tanhl(_X)); }
#endif /* _MSC_EXTENSIONS */
#endif /* _M_M68K */
#endif /* __cplusplus */
#ifdef _MSC_VER
#pragma pack(pop)
#endif /* _MSC_VER */
#endif /* _INC_MATH */
#pragma once
| [
"[email protected]"
] | [
[
[
1,
627
]
]
] |
ed513579a5eb3a477447061ff5c45d5ea07015b5 | 74e7667ad65cbdaa869c6e384fdd8dc7e94aca34 | /MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/corlib_native_System_AppDomain_mshl.cpp | a5c83ecacab001004f4322941c9b5a0fc19272b5 | [
"BSD-3-Clause",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | gezidan/NETMF-LPC | 5093ab223eb9d7f42396344ea316cbe50a2f784b | db1880a03108db6c7f611e6de6dbc45ce9b9adce | refs/heads/master | 2021-01-18T10:59:42.467549 | 2011-06-28T08:11:24 | 2011-06-28T08:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,035 | cpp | //-----------------------------------------------------------------------------
//
// ** DO NOT EDIT THIS FILE! **
// This file was generated by a tool
// re-running the tool will overwrite this file.
//
//-----------------------------------------------------------------------------
#include "corlib_native.h"
#include "corlib_native_System_AppDomain.h"
using namespace System;
HRESULT Library_corlib_native_System_AppDomain::GetAssemblies___SZARRAY_SystemReflectionAssembly( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
UNSUPPORTED_TYPE retVal = AppDomain::GetAssemblies( pMngObj, hr );
TINYCLR_CHECK_HRESULT( hr );
SetResult_UNSUPPORTED_TYPE( stack, retVal );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_AppDomain::LoadInternal___SystemReflectionAssembly__STRING__BOOLEAN__I4__I4__I4__I4( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack );
FAULT_ON_NULL(pMngObj);
UNSUPPORTED_TYPE param0;
TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 1, param0 ) );
UNSUPPORTED_TYPE param1;
TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 2, param1 ) );
LPCSTR param2;
TINYCLR_CHECK_HRESULT( Interop_Marshal_LPCSTR( stack, 3, param2 ) );
INT8 param3;
TINYCLR_CHECK_HRESULT( Interop_Marshal_INT8( stack, 4, param3 ) );
INT32 param4;
TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 5, param4 ) );
INT32 param5;
TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 6, param5 ) );
UNSUPPORTED_TYPE retVal = AppDomain::LoadInternal( pMngObj, param0, param1, param2, param3, param4, param5, hr );
TINYCLR_CHECK_HRESULT( hr );
SetResult_UNSUPPORTED_TYPE( stack, retVal );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_AppDomain::CreateDomain___STATIC__SystemAppDomain__STRING( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
UNSUPPORTED_TYPE param0;
TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 0, param0 ) );
UNSUPPORTED_TYPE retVal = AppDomain::CreateDomain( param0, hr );
TINYCLR_CHECK_HRESULT( hr );
SetResult_UNSUPPORTED_TYPE( stack, retVal );
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_AppDomain::Unload___STATIC__VOID__SystemAppDomain( CLR_RT_StackFrame& stack )
{
TINYCLR_HEADER(); hr = S_OK;
{
UNSUPPORTED_TYPE param0;
TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 0, param0 ) );
AppDomain::Unload( param0, hr );
TINYCLR_CHECK_HRESULT( hr );
}
TINYCLR_NOCLEANUP();
}
| [
"[email protected]"
] | [
[
[
1,
92
]
]
] |
3f630f261496e457a053abf414a1d7eddd222679 | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /APSVis/source/chart child.h | 23d5228c68ee7f889634c2992474e5bc38b1aa69 | [] | no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,341 | h | //----------------------------------------------------------------------------
#ifndef ChartChildH
#define ChartChildH
//----------------------------------------------------------------------------
#include <vcl\Controls.hpp>
#include <vcl\Forms.hpp>
#include <vcl\Graphics.hpp>
#include <vcl\Classes.hpp>
#include <vcl\Windows.hpp>
#include <vcl\System.hpp>
#include "Chart.hpp"
#include "TeEngine.hpp"
#include "TeeProcs.hpp"
#include <vcl\ExtCtrls.hpp>
#include <chart\high_level\high_level_screen.h>
#include <chart\high_level\high_level_chart_base.h>
#include <data\database.h>
#include "Chart.hpp"
#include "TeEngine.hpp"
#include "TeeProcs.hpp"
#include <vcl\ExtCtrls.hpp>
// ------------------------------------------------------------------
// Short description:
// This class is a pure virtual base class encapsulating the
// functionality of a chart form (window).
// Notes:
// Changes:
// DPH 25/7/97
// ------------------------------------------------------------------
class TChart_child : public TForm
{
__published:
void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
void __fastcall FormResize(TObject *Sender);
private:
High_level_screen My_screen;
Database Predicted_database;
Database Observed_database;
void Create_chart (void);
protected:
High_level_chart_base* Chart_ptr;
void Get_field_names (Database& DB, TStringList* Return_list);
// virtuals to be overwritten by derived children.
virtual High_level_chart_base* Create_chart_object (void) = 0;
Table_base* Create_table (const char* File_name);
virtual void Setup_chart_object (High_level_chart_base* Chart_ptr,
bool Is_predicted) = 0;
virtual void Setup_properties (Database& DB) = 0;
virtual bool Show_properties (void) = 0;
virtual void Setup_filter (Record_filter& Filter) {Filter.Clear();};
public:
virtual __fastcall TChart_child(TComponent *Owner);
void Set_predicted_files (list<string>& File_names);
void Set_observed_files (list<string>& File_names);
bool Edit_properties (void);
void Edit_chart (void);
void Print (void);
void Copy_to_clipboard (void);
};
//----------------------------------------------------------------------------
#endif
| [
"devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8"
] | [
[
[
1,
72
]
]
] |
e0520f8247f2c09e3a0f796ac793bf041237c2ea | 9ad9345e116ead00be7b3bd147a0f43144a2e402 | /Integration_WAH_&_Extraction/SMDataExtraction/SMPreprocessing/DataPreProcessor.h | ab991f5d87bbc6b85698bc5de959137c45a1868d | [] | no_license | asankaf/scalable-data-mining-framework | e46999670a2317ee8d7814a4bd21f62d8f9f5c8f | 811fddd97f52a203fdacd14c5753c3923d3a6498 | refs/heads/master | 2020-04-02T08:14:39.589079 | 2010-07-18T16:44:56 | 2010-07-18T16:44:56 | 33,870,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | h | #pragma once
#include "WrapDataSource.h"
/************************************************************************/
/* Class :DataPreprocessor.h
/* Started:18.05.2010 21:28:12
/* Updated:18.05.2010 21:38:12
/* Author :SEEDMiner
/* Subj :Base class for all preprocessor filters
/* Version:
/************************************************************************/
class DataPreProcessor
{
public:
#pragma region Constructors & Destructor
__declspec(dllexport) DataPreProcessor(void);
__declspec(dllexport) ~DataPreProcessor(void);
#pragma endregion Constructors & Destructor
/** original wrapped data source*/
WrapDataSource *m_original_datasource;
};
| [
"jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1",
"samfernandopulle@c7f6ba40-6498-11de-987a-95e5a5a5d5f1"
] | [
[
[
1,
3
],
[
12,
14
],
[
17,
18
],
[
23,
24
]
],
[
[
4,
11
],
[
15,
16
],
[
19,
22
]
]
] |
72adc842f259a8644255a1888ba573944b5fde27 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Collide/Query/Collector/RayCollector/hkpClosestRayHitCollector.h | ee8b18a6bdc6a69673222a9b2ffc54ab0b3edacf | [] | no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,434 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_MIN_DISTANCE_COLLISION_INFO_COLLECTOR_H
#define HK_MIN_DISTANCE_COLLISION_INFO_COLLECTOR_H
#include <Physics/Collide/Shape/Query/hkpRayHitCollector.h>
#include <Physics/Collide/Query/CastUtil/hkpWorldRayCastOutput.h>
/// hkpClosestRayHitCollector collects the closest contact point and information about a cast along a linear path.
/// Both the closest contact point for non-penetrating (cast) and for penetrating cases are collected.
class hkpClosestRayHitCollector : public hkpRayHitCollector
{
public:
/// Constructor calls reset.
inline hkpClosestRayHitCollector();
/// Resets this structure if you want to reuse it for another raycast.
inline void reset();
inline virtual ~hkpClosestRayHitCollector();
/// returns true, if this class has collected a hit
inline hkBool hasHit( ) const;
/// returns the full hit information
inline const hkpWorldRayCastOutput& getHit() const;
protected:
virtual void addRayHit( const hkpCdBody& cdBody, const hkpShapeRayCastCollectorOutput& hitInfo );
protected:
hkpWorldRayCastOutput m_rayHit;
};
#include <Physics/Collide/Query/Collector/RayCollector/hkpClosestRayHitCollector.inl>
#endif //HK_MIN_DISTANCE_COLLISION_INFO_COLLECTOR_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
] | [
[
[
1,
60
]
]
] |
edc6190cf86c7e8531787f9407c735681f63f33d | 2bd485a1b68c396d80d455d1f68a052359a28fbd | /DigBuild/DigBuild/HUD.h | f90b99006695b92550b8fa3196737515dd3613a9 | [] | no_license | dks-project-repository/dks-project-repository | f7cba5f5df207bd2a24306bf56b58587e6c395c6 | 8c3622b8ab173e8043557e55186b3b482a05d8bf | refs/heads/master | 2021-01-10T18:45:58.502005 | 2011-02-28T18:37:03 | 2011-02-28T18:37:03 | 32,180,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 426 | h | #pragma once
#include "EventHandler.h"
#include <SDL_ttf.h>
#include <string>
class HUD : public Movable, public Inputable
{
public:
HUD();
~HUD();
void Draw();
void Update(unsigned int ticks);
void HandleInput(const SDL_Event& event);
void InitText();
void FreeText();
private:
void DrawText(int x, int y, std::string text);
TTF_Font* font;
std::string fps;
bool showFps;
};
| [
"sbarnett87@28314c55-5b4b-0410-b444-2fc7fe15ad56"
] | [
[
[
1,
23
]
]
] |
d5517708c9d8698570c2cb850b364fd400f4b8bc | 95d583eacc45df62b6b6459e2ec79404686cb2b1 | /source/Params.cpp | 7eb1ad1fc8a4c90420c16868208293a80727dced | [] | no_license | sebasrodriguez/teoconj | 81a917c57724a718e6288798f7c58863a1dad523 | aee99839a8ddb293b0ed1402dfe72b80dbfe0af0 | refs/heads/master | 2021-01-01T15:36:42.773692 | 2010-03-13T01:04:12 | 2010-03-13T01:04:12 | 32,334,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,348 | cpp | #include "Params.h"
void ParamsCreate(Params &p)
{
ListaStringCreate(p);
}
int ParamsCount(Params p)
{
return ListaStringCount(p);
}
bool ParamsValidate(Comando cmd, Params params)
{
bool valid = true;
switch (cmd)
{
case HELP:
case LISTALL:
case EXIT:
case CLEAR:
valid = ListaStringEmpty(params);
break;
case UNION:
case INTERSECTION:
case DIFFERENCE:
case INCLUDED:
case EQUALS:
valid = ParamsCount(params) >=2;
while (valid && params != NULL)
{
valid = validateParamConjunto(params->info);
params = params->sig;
}
break;
case ADD:
case REMOVE:
case MEMBER:
if (ParamsCount(params) < 2) valid = false;
else
{
valid = validateParamConjunto(params->info);
params = params->sig;
while (valid && params != NULL)
{
valid = validateParamValor(params->info);
params = params->sig;
}
}
break;
case CREATE:
while (valid && params != NULL)
{
valid = validateParamValor(params->info);
params = params->sig;
}
break;
case SHOW:
valid = ParamsCount(params) == 1;
while (valid && params != NULL)
{
valid = validateParamConjunto(params->info);
params = params->sig;
}
break;
case SAVE:
if (ParamsCount(params) != 2) valid = false;
else valid = validateParamConjunto(params->info) && validateParamName(params->sig->info);
break;
case LOAD:
if (ParamsCount(params) != 1) valid = false;
else valid = validateParamName(params->info);
break;
}
return valid;
}
bool validateParamConjunto(string s)
{
bool valid = false;
if (s[0] == 'c')
{
s ++;
if (atoi(s) != 0) valid = true;
}
return valid;
}
bool validateParamValor(string s)
{
return streq(s, "0") || atoi(s) > 0;
}
bool validateParamName(string s)
{
return true;
}
int parseParamConjunto(string s)
{
s++;
return atoi(s);
}
int parseParamValor(string s)
{
return atoi(s);
}
| [
"srpabliyo@861ad466-0edf-11df-a223-d798cd56f61e",
"sebasrodriguez@861ad466-0edf-11df-a223-d798cd56f61e"
] | [
[
[
1,
2
],
[
5,
7
],
[
10,
12
],
[
15,
15
],
[
46,
48
],
[
74,
77
],
[
80,
80
],
[
83,
83
],
[
85,
87
],
[
90,
91
],
[
94,
96
],
[
99,
101
],
[
104,
105
]
],
[
[
3,
4
],
[
8,
9
],
[
13,
14
],
[
16,
45
],
[
49,
73
],
[
78,
79
],
[
81,
82
],
[
84,
84
],
[
88,
89
],
[
92,
93
],
[
97,
98
],
[
102,
103
]
]
] |
fff5698a9bc59e778cd563767744f3a244d7fc70 | 56d19e2be913ff0bf884b2a462374d9acb6f91ce | /Controls.cpp | a6ef69800d9a87975081bb08f0dac8a1600f0db4 | [] | no_license | cgoakley/laser-surfsprint | 0169dddae05e0baf52cd86dc5d82ad6a32ecd402 | 52466d80978fb2530bcb6107196f089163d62ef4 | refs/heads/master | 2020-07-23T11:43:14.813042 | 2006-03-15T12:00:00 | 2016-11-17T15:57:36 | 73,809,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,309 | cpp | #define WINDOBJ_MAIN
#include <WindObj/Private.h>
#include <WindObj/MiniWindow.h>
#include <malloc.h>
// Push buttons ...
static WNDPROC s_oldButtonProc = NULL;
static LRESULT CALLBACK NewButtonProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
Window *w = (Window *)GetWindowLong(hWnd, GWL_USERDATA);
LRESULT lRes;
if (w && message != WM_PAINT && StdMessageProcessing(&lRes, w, hWnd, message, wParam, lParam))
return lRes;
return CallWindowProc(s_oldButtonProc, hWnd, message, wParam, lParam);
}
Button::Button() {}
Button::Button(Window *parent, Rect rect, const char *text, Style bs, Font *font)
{
ControlData *cd = new ControlData;
m_windowData = cd;
HWND hWndParent = parent->m_windowData->hWnd;
m_parent = parent;
memset(cd, 0, sizeof(ControlData));
cd->hWnd = CreateWindow("BUTTON", text, WS_CHILD | WS_VISIBLE | WS_TABSTOP |
(bs == defaultAction? BS_DEFPUSHBUTTON: BS_PUSHBUTTON),
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
hWndParent, (HMENU)(bs == defaultAction? IDOK: bs == cancel? IDCANCEL: 0), g_hInst, NULL);
HFONT hFont;
if (font) hFont = CloneFont((HFONT)font->m_fontData);
else
{
hFont = (HFONT)SendMessage(hWndParent, WM_GETFONT, 0, 0);
if (!hFont) hFont = (HFONT)GetStockObject(ANSI_VAR_FONT);
}
SendMessage(cd->hWnd, WM_SETFONT, (WPARAM)hFont, 0);
cd->foreColour = GetSysColor(COLOR_WINDOWTEXT);
cd->backBrush = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
SetWindowLong(cd->hWnd, GWL_USERDATA, (LONG)this);
WNDPROC bp = (WNDPROC)SetWindowLong(cd->hWnd, GWL_WNDPROC, (LONG)NewButtonProc);
if (!s_oldButtonProc) s_oldButtonProc = bp;
}
Button::Button(Window *parent, Rect rect, const Bitmap &bm, Style bs)
{
ControlData *cd = new ControlData;
m_windowData = cd;
m_parent = parent;
memset(cd, 0, sizeof(ControlData));
cd->hWnd = CreateWindow("BUTTON", "JIM", WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_BITMAP |
(bs == defaultAction? BS_DEFPUSHBUTTON: BS_PUSHBUTTON),
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
parent->m_windowData->hWnd, (HMENU)(bs == defaultAction? IDOK: bs == cancel? IDCANCEL: 0), g_hInst, NULL);
cd->foreColour = GetSysColor(COLOR_WINDOWTEXT);
cd->backBrush = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
SetWindowLong(cd->hWnd, GWL_USERDATA, (LONG)this);
SendMessage(cd->hWnd, BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)bm.m_bitmapData->hBitmap);
WNDPROC bp = (WNDPROC)SetWindowLong(cd->hWnd, GWL_WNDPROC, (LONG)NewButtonProc);
if (!s_oldButtonProc) s_oldButtonProc = bp;
}
Button::~Button()
{
HBRUSH hBr = ((ControlData *)m_windowData)->backBrush;
if (hBr) DeleteObject(hBr);
}
void Button::Clicked() {}
Colour Button::TextColour()
{
COLORREF clr = ((ControlData *)m_windowData)->foreColour;
return Colour(GetRValue(clr), GetGValue(clr), GetBValue(clr));
}
void Button::TextColour(Colour clr)
{
((ControlData *)m_windowData)->foreColour = CVTCLR(clr);
Draw();
}
SimpleButton::SimpleButton(Window *parent, Rect rect, const char *text, ButtonClickedAction bca, Style buttonStyle, Font *font) :
Button(parent, rect, text, buttonStyle, font)
{
m_bca = bca;
}
void SimpleButton::Clicked()
{
(*m_bca)(this);
}
// Check boxes ...
CheckBox::CheckBox() {}
CheckBox::CheckBox(Window *parent, Rect rect, const char *text)
{
ControlData *cd = new ControlData;
m_windowData = cd;
HWND hWndParent = parent->m_windowData->hWnd;
m_parent = parent;
memset(cd, 0, sizeof(ControlData));
cd->hWnd = CreateWindow("BUTTON", text, WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
hWndParent, 0, g_hInst, NULL);
SendMessage(cd->hWnd, WM_SETFONT, SendMessage(hWndParent, WM_GETFONT, 0, 0), 0);
cd->foreColour = GetSysColor(COLOR_WINDOWTEXT);
cd->backBrush = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
SetWindowLong(cd->hWnd, GWL_USERDATA, (LONG)this);
WNDPROC bp = (WNDPROC)SetWindowLong(cd->hWnd, GWL_WNDPROC, (LONG)NewButtonProc);
if (!s_oldButtonProc) s_oldButtonProc = bp;
}
bool CheckBox::Check(bool state)
{
SendMessage(m_windowData->hWnd, BM_SETCHECK,
state? BST_CHECKED: BST_UNCHECKED, 0);
return state;
}
CheckBox::operator bool()
{
return (SendMessage(m_windowData->hWnd, BM_GETSTATE, 0, 0) & 3) == BST_CHECKED;
}
// Radio buttons ...
RadioButton::RadioButton(Window *parent, Rect rect, const char *text, Style bs)
{
ControlData *cd = new ControlData;
m_windowData = cd;
HWND hWndParent = parent->m_windowData->hWnd;
m_parent = parent;
memset(cd, 0, sizeof(ControlData));
cd->hWnd = CreateWindow("BUTTON", text, WS_CHILD | WS_VISIBLE | WS_TABSTOP |
BS_AUTORADIOBUTTON | (bs == startOfGroup? WS_GROUP: 0),
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
hWndParent, 0, g_hInst, NULL);
SendMessage(cd->hWnd, WM_SETFONT, SendMessage(hWndParent, WM_GETFONT, 0, 0), 0);
cd->foreColour = GetSysColor(COLOR_WINDOWTEXT);
cd->backBrush = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
SetWindowLong(cd->hWnd, GWL_USERDATA, (LONG)this);
WNDPROC bp = (WNDPROC)SetWindowLong(cd->hWnd, GWL_WNDPROC, (LONG)NewButtonProc);
if (!s_oldButtonProc) s_oldButtonProc = bp;
}
SimpleRadioButton::SimpleRadioButton(Window *parent, Rect rect, const char *text, ButtonClickedAction bca, Style bs) :
RadioButton(parent, rect, text, bs)
{
m_bca = bca;
}
void SimpleRadioButton::Clicked()
{
if (m_bca) (*m_bca)(this);
}
// Combo boxes ...
static WNDPROC s_oldComboProc = NULL;
static LRESULT CALLBACK NewComboProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
Window *w = (Window *)GetWindowLong(hWnd, GWL_USERDATA);
LRESULT lRes;
if (w && message != WM_PAINT && StdMessageProcessing(&lRes, w, hWnd, message, wParam, lParam))
return lRes;
return CallWindowProc(s_oldComboProc, hWnd, message, wParam, lParam);
}
ComboBox::ComboBox(){}
ComboBox::ComboBox(Window *parent, Rect rect, int maxChars, int style, Font *font)
{
ControlData *cd = new ControlData;
m_windowData = cd;
HWND hWndParent = parent->m_windowData->hWnd;
m_parent = parent;
memset(cd, 0, sizeof(ControlData));
cd->hWnd = CreateWindow("COMBOBOX", "", WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
CBS_AUTOHSCROLL | style,
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
hWndParent, 0, g_hInst, NULL);
SendMessage(cd->hWnd, WM_SETFONT, font? (LRESULT)CloneFont((HFONT)font->m_fontData): SendMessage(hWndParent, WM_GETFONT, 0, 0), 0);
if (maxChars > 0) SendMessage(cd->hWnd, CB_LIMITTEXT, maxChars, 0);
cd->backBrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
cd->foreColour = GetSysColor(COLOR_WINDOWTEXT);
SetWindowLong(cd->hWnd, GWL_USERDATA, (LONG)this);
WNDPROC cbp = (WNDPROC)SetWindowLong(cd->hWnd, GWL_WNDPROC, (LONG)NewComboProc);
if (!s_oldComboProc) s_oldComboProc = cbp;
}
ComboBox::~ComboBox()
{
DeleteObject(((ControlData *)m_windowData)->backBrush);
}
void ComboBox::Clear()
{
SendMessage(m_windowData->hWnd, CB_RESETCONTENT, 0, 0);
}
void ComboBox::Delete(int idx)
{
SendMessage(m_windowData->hWnd, CB_DELETESTRING, idx, 0);
}
int ComboBox::Insert(const char *buff)
{
g_hWndNuu = m_windowData->hWnd;
LRESULT lRes = SendMessage(m_windowData->hWnd, CB_ADDSTRING, 0, (LPARAM)buff);
g_hWndNuu = NULL;
return lRes;
}
int ComboBox::Insert(int idx, const char *buff)
{
g_hWndNuu = m_windowData->hWnd;
LRESULT lRes = SendMessage(m_windowData->hWnd, CB_INSERTSTRING, idx, (LPARAM)buff);
g_hWndNuu = NULL;
return lRes;
}
int ComboBox::ListIndex()
{
return SendMessage(m_windowData->hWnd, CB_GETCURSEL, 0, 0);
}
void ComboBox::ListIndex(int idx)
{
SendMessage(m_windowData->hWnd, CB_SETCURSEL, idx, 0);
}
int ComboBox::ListCount()
{
return SendMessage(m_windowData->hWnd, CB_GETCOUNT, 0, 0);
}
int ComboBox::GetText(char *text, int idx)
{
if (idx < 0) idx = ListIndex();
LRESULT lRes = SendMessage(m_windowData->hWnd, CB_GETLBTEXTLEN, idx, 0);
int n = lRes == LB_ERR? 0: lRes;
if (text) SendMessage(m_windowData->hWnd, CB_GETLBTEXT, idx, (LPARAM)text);
return n;
}
int ComboBox::GetText(char *text)
{
return Window::GetText(text);
}
void ComboBox::SetText(int idx, const char *text)
{
g_hWndNuu = m_windowData->hWnd;
int i, n = ListCount();
if (idx < 0)
SendMessage(g_hWndNuu, CB_INSERTSTRING, (WPARAM)-1, (LPARAM)text);
else if (idx >= n)
{
for (i = idx; i < n; i++)
SendMessage(g_hWndNuu, CB_ADDSTRING, 0, (LPARAM)"");
SendMessage(g_hWndNuu, CB_ADDSTRING, 0, (LPARAM)text);
}
else
{
SendMessage(g_hWndNuu, CB_DELETESTRING, idx, 0);
SendMessage(g_hWndNuu, CB_INSERTSTRING, idx, (LPARAM)text);
}
g_hWndNuu = NULL;
}
void ComboBox::SetText(int idx, const char *text, int nText)
{
char *buff = (char *)_alloca(nText + 1);
memcpy(buff, text, nText);
buff[nText] = '\0';
SetText(idx, buff);
}
void ComboBox::SetText(const char *text)
{
Window::SetText(text);
}
void ComboBox::SetText(const char *text, int nText)
{
Window::SetText(text, nText);
}
Colour ComboBox::TextColour()
{
COLORREF clr = ((ControlData *)m_windowData)->foreColour;
return Colour(GetRValue(clr), GetGValue(clr), GetBValue(clr));
}
void ComboBox::TextColour(Colour clr)
{
((ControlData *)m_windowData)->foreColour = CVTCLR(clr);
Draw();
}
void ComboBox::ListIndexChanged() {}
void ComboBox::TextChanged() {}
// Drop down list ...
DropDownList::DropDownList(Window *parent, Rect rect, Font *font)
{
ControlData *cd = new ControlData;
m_windowData = cd;
HWND hWndParent = parent->m_windowData->hWnd;
m_parent = parent;
memset(cd, 0, sizeof(ControlData));
cd->hWnd = CreateWindow("COMBOBOX", "", WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
CBS_DROPDOWNLIST, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
hWndParent, 0, g_hInst, NULL);
SendMessage(cd->hWnd, WM_SETFONT, font? (LRESULT)CloneFont((HFONT)font->m_fontData): SendMessage(hWndParent, WM_GETFONT, 0, 0), 0);
cd->backBrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
cd->foreColour = GetSysColor(COLOR_WINDOWTEXT);
SetWindowLong(cd->hWnd, GWL_USERDATA, (LONG)this);
WNDPROC oldComboProc = (WNDPROC)SetWindowLong(cd->hWnd, GWL_WNDPROC, (LONG)NewComboProc);
if (!s_oldComboProc) s_oldComboProc = oldComboProc;
}
// methods same as Combo, except that edit box ones will not do anything
void SimpleDropDownList::ListIndexChanged()
{
(*m_lica)(this);
}
// Edit boxes ...
static WNDPROC s_oldEditProc = NULL;
static LRESULT CALLBACK NewEditProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
Window *w = (Window *)GetWindowLong(hWnd, GWL_USERDATA);
LRESULT lRes;
if (w && message != WM_PAINT && StdMessageProcessing(&lRes, w, hWnd, message, wParam, lParam))
return lRes;
return CallWindowProc(s_oldEditProc, hWnd, message, wParam, lParam);
}
EditBox::EditBox(Window *parent, Rect rect, const Font *font, int maxChars, int style, const char *text,
const Colour &backColour, const Colour &foreColour)
{
ControlData *cd = new ControlData;
m_windowData = cd;
HWND hWndParent = parent->m_windowData->hWnd;
m_parent = parent;
memset(cd, 0, sizeof(ControlData));
cd->hWnd = CreateWindow("EDIT", "", WS_CHILD | WS_VISIBLE | WS_BORDER | WS_GROUP | WS_TABSTOP | style,
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
hWndParent, 0, g_hInst, NULL);
SendMessage(cd->hWnd, WM_SETFONT, font? (LPARAM)CloneFont((HFONT)font->m_fontData):
SendMessage(hWndParent, WM_GETFONT, 0, 0), 0);
if (maxChars > 0) SendMessage(cd->hWnd, EM_SETLIMITTEXT, maxChars, 0);
if (text) SetWindowText(cd->hWnd, text);
cd->backBrush = CreateSolidBrush(&backColour? CVTCLR(backColour): GetSysColor(COLOR_WINDOW));
cd->foreColour = &foreColour? CVTCLR(foreColour): GetSysColor(COLOR_WINDOWTEXT);
SetWindowLong(cd->hWnd, GWL_USERDATA, (LONG)this);
WNDPROC ep = (WNDPROC)SetWindowLong(cd->hWnd, GWL_WNDPROC, (LONG)NewEditProc);
if (!s_oldEditProc) s_oldEditProc = ep;
}
EditBox::~EditBox()
{
ControlData *cd = (ControlData *)m_windowData;
DeleteObject((HFONT)SendMessage(cd->hWnd, WM_GETFONT, 0, 0));
DeleteObject(cd->backBrush);
}
void EditBox::Clear()
{
SendMessage(m_windowData->hWnd, WM_SETTEXT, 0, (LPARAM)"");
}
void EditBox::TextChanged() {}
int EditBox::Selection(int &selStart, int &selStop)
{
SendMessage(m_windowData->hWnd, EM_GETSEL, (WPARAM)&selStart, (LPARAM)&selStop);
return selStop - selStart;
}
int EditBox::SetSelection(int selStart, int selStop)
{
SendMessage(m_windowData->hWnd, EM_SETSEL, (WPARAM)selStart, (LPARAM)selStop);
return selStop - selStart;
}
int Selection(int &selStart, int &selStop)
{
char buff[6] = {'\0'};
HWND hWnd;
GetAtomName(GetClassWord(hWnd = GetFocus(), GCW_ATOM), buff, 6);
if (!_stricmp(buff, "edit")) SendMessage(hWnd, EM_GETSEL,
(WPARAM)&selStart, (LPARAM)&selStop);
else selStart = selStop = 0;
return selStop - selStart;
}
Colour EditBox::TextColour()
{
COLORREF clr = ((ControlData *)m_windowData)->foreColour;
return Colour(GetRValue(clr), GetGValue(clr), GetBValue(clr));
}
void EditBox::TextColour(Colour clr)
{
((ControlData *)m_windowData)->foreColour = CVTCLR(clr);
Draw();
}
SimpleEditBox::SimpleEditBox(Window *parent, Rect rect, int maxChars, TextChangedAction tca, int style, const char *text,
Font *font, const Colour &backColour, const Colour &foreColour) :
EditBox(parent, rect, font, maxChars, style, text, backColour, foreColour)
{
m_tca = tca;
}
void SimpleEditBox::TextChanged()
{
(*m_tca)(this);
}
GroupBox::GroupBox(Window *parent, Rect rect, const char *caption, Font *font, Colour &foreColour, Colour &backColour) :
Window(parent, rect), m_foreColour(foreColour), m_backColour(backColour)
{
m_caption = caption? strcpy(m_caption = new char[strlen(caption) + 1], caption): NULL;
m_font = font? new Font(*font): NULL;
}
void GroupBox::Exposed(DrawingSurface &DS, const Rect &invRect)
{
DS.Rectangle(invRect, Pen(), Brush(m_backColour));
Rect clientRect = ClientRect();
DS.Rectangle(Rect(clientRect.left, clientRect.top + 1 + m_font->TextHeight() / 2, clientRect.right - 1, clientRect.bottom - 1),
Pen(m_foreColour, 0), Brush(m_backColour));
DS.Text(m_caption, clientRect.TopLeft() + Point(m_font->TextWidth("M"), 0), *m_font, m_foreColour, DrawingSurface::left,
DrawingSurface::top, DrawingSurface::opaque, m_backColour);
}
GroupBox::~GroupBox()
{
delete [] m_caption;
delete m_font;
}
// Labels ...
static WNDPROC s_oldLabelProc = NULL;
static LRESULT CALLBACK NewLabelProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
Window *w = (Window *)GetWindowLong(hWnd, GWL_USERDATA);
LRESULT lRes;
if (w && message != WM_PAINT && StdMessageProcessing(&lRes, w, hWnd, message, wParam, lParam))
return lRes;
return CallWindowProc(s_oldLabelProc, hWnd, message, wParam, lParam);
}
Label::Label(Window *parent, Rect rect, const char *text, TextAlignment ta, const Font *font,
const Colour &backColour, const Colour &foreColour)
{
ControlData *cd = new ControlData;
m_windowData = cd;
HWND hWndParent = parent->m_windowData->hWnd;
m_parent = parent;
memset(cd, 0, sizeof(ControlData));
cd->hWnd = CreateWindow("STATIC", text, WS_CHILD | WS_VISIBLE |
(ta == TA_centre? SS_CENTER: ta == TA_right? SS_RIGHT: SS_LEFT),
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
hWndParent, 0, g_hInst, NULL);
SendMessage(cd->hWnd, WM_SETFONT, font? (LPARAM)CloneFont((HFONT)font->m_fontData):
SendMessage(hWndParent, WM_GETFONT, 0, 0), 0);
cd->backBrush = CreateSolidBrush(&backColour? CVTCLR(backColour): GetSysColor(COLOR_3DFACE));
cd->foreColour = &foreColour? CVTCLR(foreColour): GetSysColor(COLOR_WINDOWTEXT);
SetWindowLong(cd->hWnd, GWL_USERDATA, (LONG)this);
WNDPROC lp = (WNDPROC)SetWindowLong(cd->hWnd, GWL_WNDPROC, (LONG)NewLabelProc);
if (!s_oldLabelProc) s_oldLabelProc = lp;
}
Label::Label(Window *parent, Point pt, const Bitmap &bm)
{
ControlData *cd = new ControlData;
m_windowData = cd;
m_parent = parent;
memset(cd, 0, sizeof(ControlData));
cd->hWnd = CreateWindow("STATIC", "", WS_CHILD | WS_VISIBLE | SS_BITMAP,
pt.x, pt.y, 0, 0, parent->m_windowData->hWnd, 0, g_hInst, NULL);
cd->backBrush = CreateSolidBrush(GetSysColor(COLOR_3DFACE));
cd->foreColour = GetSysColor(COLOR_WINDOWTEXT);
SendMessage(cd->hWnd, STM_SETIMAGE, IMAGE_BITMAP,
(LPARAM)CloneBitmap(bm.m_bitmapData->hBitmap));
SetWindowLong(cd->hWnd, GWL_USERDATA, (LONG)this);
WNDPROC lp = (WNDPROC)SetWindowLong(cd->hWnd, GWL_WNDPROC, (LONG)NewLabelProc);
if (!s_oldLabelProc) s_oldLabelProc = lp;
}
Label::~Label()
{
HBITMAP hbm = (HBITMAP)SendMessage(m_windowData->hWnd, STM_GETIMAGE, IMAGE_BITMAP, 0);
if (hbm) DeleteObject(hbm);
HBRUSH hBr = ((ControlData *)m_windowData)->backBrush;
if (hBr) DeleteObject(hBr);
}
void Label::SetImage(const Bitmap &bm)
{
HBITMAP hbm = (HBITMAP)SendMessage(m_windowData->hWnd, STM_GETIMAGE, IMAGE_BITMAP, 0);
if (hbm) DeleteObject(hbm);
SendMessage(m_windowData->hWnd, STM_SETIMAGE, IMAGE_BITMAP,
(LPARAM)CloneBitmap(bm.m_bitmapData->hBitmap));
}
/* List boxes ...
static WNDPROC s_oldListProc = NULL;
static LRESULT CALLBACK NewListProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
Window *w = (Window *)GetWindowLong(hWnd, GWL_USERDATA);
LRESULT lRes = 0;
if (w && message != WM_PAINT && StdMessageProcessing(&lRes, w, hWnd, message, wParam, lParam))
return lRes;
return CallWindowProc(s_oldListProc, hWnd, message, wParam, lParam);
}
ListBox::ListBox(Window *parent, Rect rect, int nCols)
{
ControlData *cd = new ControlData;
m_windowData = cd;
HWND hWndParent = parent->m_windowData->hWnd;
m_parent = parent;
memset(cd, 0, sizeof(ControlData));
cd->hWnd = CreateWindow("LISTBOX", "", WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | LBS_USETABSTOPS |
LBS_NOINTEGRALHEIGHT | WS_VSCROLL,
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
hWndParent, 0, g_hInst, NULL);
SendMessage(cd->hWnd, WM_SETFONT, SendMessage(hWndParent, WM_GETFONT, 0, 0), 0);
cd->backBrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
cd->foreColour = GetSysColor(COLOR_WINDOWTEXT);
m_nCols = nCols;
m_minWidth = new int[2 * nCols];
m_tabPos = m_minWidth + nCols;
memset(m_minWidth, 0, 2 * nCols * sizeof(int));
SetWindowLong(cd->hWnd, GWL_USERDATA, (LONG)this);
WNDPROC lp = (WNDPROC)SetWindowLong(cd->hWnd, GWL_WNDPROC, (LONG)NewListProc);
if (!s_oldListProc) s_oldListProc = lp;
}
ListBox::~ListBox()
{
delete m_minWidth;
DeleteObject(((ControlData *)m_windowData)->backBrush);
}
/* Widens a list box, if necessary, to accommodate multi-column text whose
tab positions have been set by a call to SetColWidths()
Returns the new list box width in pixels ...
int ListBox::AutoWidth(int minWidth)
{
RECT rectW, rectC;
int ww;
HWND hWnd = m_windowData->hWnd;
GetWindowRect1(hWnd, &rectW);
GetClientRect(hWnd, &rectC);
ww = m_tabPos[m_nCols - 1] + rectW.right - rectW.left - rectC.right;
if (minWidth > ww) ww = minWidth;
MoveWindow(hWnd, rectW.left, rectW.top, ww, rectW.bottom - rectW.top, TRUE);
return ww;
}
void ListBox::Clear()
{
g_hWndNuu = m_windowData->hWnd;
SendMessage(g_hWndNuu, LB_RESETCONTENT, 0, 0);
g_hWndNuu = NULL;
}
void ListBox::Delete(int idx)
{
g_hWndNuu = m_windowData->hWnd;
SendMessage(m_windowData->hWnd, LB_DELETESTRING, idx, 0);
g_hWndNuu = NULL;
}
int ListBox::Insert(const char *buff)
{
g_hWndNuu = m_windowData->hWnd;
LRESULT lRes = SendMessage(m_windowData->hWnd, LB_ADDSTRING, 0, (LPARAM)buff);
g_hWndNuu = NULL;
return lRes;
}
int ListBox::Insert(int idx, const char *buff)
{
g_hWndNuu = m_windowData->hWnd;
LRESULT lRes = SendMessage(m_windowData->hWnd, LB_INSERTSTRING, idx, (LPARAM)buff);
g_hWndNuu = NULL;
return lRes;
}
Rect ListBox::ItemRect(int idx) const
{
RECT iRect;
SendMessage(m_windowData->hWnd, LB_GETITEMRECT, idx, (LPARAM)&iRect);
return Rect(iRect.left, iRect.top, iRect.right, iRect.bottom);
}
int ListBox::GetText(char *text, int idx) const
{
if (idx < 0) idx = ListIndex();
LRESULT lRes = SendMessage(m_windowData->hWnd, LB_GETTEXTLEN, idx, 0);
int n = lRes == LB_ERR? 0: lRes;
if (text) SendMessage(m_windowData->hWnd, LB_GETTEXT, idx, (LPARAM)text);
return n;
}
int ListBox::GetText(char *text) const
{
return GetText(text, ListIndex());
}
int ListBox::ItemHeight() const
{
return SendMessage(m_windowData->hWnd, LB_GETITEMHEIGHT, 0, 0);
}
int ListBox::ListCount() const
{
return SendMessage(m_windowData->hWnd, LB_GETCOUNT, 0, 0);
}
int ListBox::ListIndex() const
{
return SendMessage(m_windowData->hWnd, LB_GETCURSEL, 0, 0);
}
void ListBox::ListIndexChanged() {}
/* m_tabPos[] = tab stops (offsets from left in pixels) --
m_tabPos[0] is the tab position of the second column. m_tabPos[m_nCols - 1]
is the window width required to accomodate all the text
m_minWidth[] (pixels) can be set to > 0 to guarantee minimum column widths
void ListBox::SetColWidths()
{
int i, j, nBuff = 0, n = ListCount();
char *ptr, *ptr1;
AutomaticArray(int, wid, m_nCols)
memset(wid, 0, m_nCols * sizeof(int));
SIZE siz;
HDC hDC = CreateIC("DISPLAY", NULL, NULL, NULL);
HWND hWnd = m_windowData->hWnd;
SelectObject(hDC, (HFONT)SendMessage(hWnd, WM_GETFONT, 0, 0));
for (i = nBuff = 0; i < n; i++)
if ((j = GetText(NULL, i)) > nBuff) nBuff = j;
AutomaticArray(char, buff, nBuff + 1)
for (i = 0; i < n; i++)
{
GetText(buff, i);
for (ptr = ptr1 = buff, j = 0; *ptr1 && j < m_nCols; ptr = ptr1 + 1, j++)
{
ptr1 = strchr(ptr, '\t');
if (!ptr1) ptr1 = ptr + strlen(ptr);
GetTextExtentPoint32(hDC, ptr, ptr1 - ptr, &siz);
if (siz.cx > wid[j]) wid[j] = siz.cx;
}
}
m_tabPos[0] = max(wid[0], m_minWidth[0]) + 4;
for (i = 1; i < m_nCols; i++)
m_tabPos[i] = max(wid[i], m_minWidth[i]) + 4 + m_tabPos[i - 1];
DeleteDC(hDC);
SetTabStops();
}
void ListBox::ListIndex(int idx)
{
SendMessage(g_hWndNuu = m_windowData->hWnd, LB_SETCURSEL, idx, 0);
g_hWndNuu = NULL;
}
int ListBox::MatchString(const char *text) const
{
return (int)SendMessage(m_windowData->hWnd, LB_FINDSTRINGEXACT, (WPARAM)-1, (LPARAM)text);
}
/* Sets up tab stops in list box based on information given in
m_tabPos[] array
void ListBox::SetTabStops()
{
Rect rect = ((ModelessDialog *)m_parent)->DlgToPixel(Rect(0, 0, 2100, 0));
AutomaticArray(int, tp, m_nCols - 1)
for (int i = 0; i < m_nCols - 1; i++)
tp[i] = m_tabPos[i] * 2100 / rect.right;
SendMessage(m_windowData->hWnd, LB_SETTABSTOPS, m_nCols - 1, (LPARAM)tp);
}
void ListBox::SetText(int idx, const char *text)
{
g_hWndNuu = m_windowData->hWnd;
int i, n = ListCount();
if (idx < 0)
SendMessage(g_hWndNuu, LB_INSERTSTRING, (WPARAM)-1, (LPARAM)text);
else if (idx >= n)
{
for (i = idx; i < n; i++)
SendMessage(g_hWndNuu, LB_ADDSTRING, 0, (LPARAM)"");
SendMessage(g_hWndNuu, LB_ADDSTRING, 0, (LPARAM)text);
}
else
{
SendMessage(g_hWndNuu, LB_DELETESTRING, idx, 0);
SendMessage(g_hWndNuu, LB_INSERTSTRING, idx, (LPARAM)text);
ListIndex(idx);
}
g_hWndNuu = NULL;
}
void ListBox::SetText(int idx, const char *text, int nText)
{
char *buff = (char *)_alloca(nText + 1);
memcpy(buff, text, nText);
buff[nText] = '\0';
SetText(idx, buff);
}
void ListBox::SetText(const char *text)
{
int i = ListIndex();
SetText(i == -1? ListCount(): i, text);
}
void ListBox::SetText(const char *text, int nText)
{
char *buff = (char *)_alloca(nText + 1);
memcpy(buff, text, nText);
buff[nText] = '\0';
SetText(buff);
}
void ListBox::SetTopIndex(int idx)
{
g_hWndNuu = m_windowData->hWnd;
SendMessage(g_hWndNuu, LB_SETTOPINDEX, idx, 0);
g_hWndNuu = NULL;
}
HWND g_floatingEdit = NULL;
int g_floatEdColNo = -1;
void ListBox::Edit(int col)
{
if (col < 0)
{
if (g_floatingEdit && IsWindowVisible(g_floatingEdit))
{
if (col == -1)
{
int nText = GetWindowTextLength(g_floatingEdit);
char *text = (char *)alloca(nText + 1);
GetWindowText(g_floatingEdit, text, nText + 1);
SetText(g_floatEdColNo, text);
}
ShowWindow(g_floatingEdit, SW_HIDE);
g_floatEdColNo = -1;
}
SetFocus();
}
else
{
g_hWndNuu = m_windowData->hWnd;
RECT rect;
SendMessage(g_hWndNuu, LB_GETITEMRECT, (WPARAM)ListIndex(), (LPARAM)&rect);
// MapWindowPoints(g_hWndNuu, hwnddlg, (LPPOINT)&rect, 2);
char *text = (char *)alloca(GetText(NULL, col) + 1);
GetText(text, g_floatEdColNo = col);
if (!g_floatingEdit)
g_floatingEdit = CreateWindow("EDIT", text, WS_POPUP | WS_VISIBLE | WS_BORDER,
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
NULL, 0, g_hInst, NULL);
else
{
MoveWindow(g_floatingEdit, rect.left + m_tabPos[col] - 1, rect.top - 3,
m_tabPos[col + 1] - m_tabPos[col], rect.bottom - rect.top + 7, FALSE);
::SetWindowText(g_floatingEdit, text);
}
SendMessage(g_floatingEdit, EM_SETSEL, 0, -1);
// SetFocus(g_floatingEdit);
ShowWindow(g_floatingEdit, SW_SHOW);
}
}
int ListBox::EditCol() const {return g_floatEdColNo;}
bool ListBox::EditMode() const {return g_floatEdColNo != -1;} */
| [
"[email protected]"
] | [
[
[
1,
822
]
]
] |
e9209580d1acbcdf9484c0f44ca31cc44eff17ae | 40b507c2dde13d14bb75ee1b3c16b4f3f82912d1 | /core/CDataPack.h | d04cca51487b15747308e53172dd94823cd4626d | [] | no_license | Nephyrin/-furry-octo-nemesis | 5da2ef75883ebc4040e359a6679da64ad8848020 | dd441c39bd74eda2b9857540dcac1d98706de1de | refs/heads/master | 2016-09-06T01:12:49.611637 | 2008-09-14T08:42:28 | 2008-09-14T08:42:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,455 | h | /**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_SOURCEMOD_CDATAPACK_H_
#define _INCLUDE_SOURCEMOD_CDATAPACK_H_
#include <IDataPack.h>
using namespace SourceMod;
class CDataPack : public IDataPack
{
public:
CDataPack();
~CDataPack();
public: //IDataReader
void Reset() const;
size_t GetPosition() const;
bool SetPosition(size_t pos) const;
cell_t ReadCell() const;
float ReadFloat() const;
bool IsReadable(size_t bytes) const;
const char *ReadString(size_t *len) const;
void *GetMemory() const;
void *ReadMemory(size_t *size) const;
public: //IDataPack
void ResetSize();
void PackCell(cell_t cell);
void PackFloat(float val);
void PackString(const char *string);
size_t CreateMemory(size_t size, void **addr);
public:
void Initialize();
private:
void CheckSize(size_t sizetype);
private:
char *m_pBase;
mutable char *m_curptr;
size_t m_capacity;
size_t m_size;
};
#endif //_INCLUDE_SOURCEMOD_CDATAPACK_H_
| [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
],
[
31,
71
]
],
[
[
2,
3
],
[
6,
10
],
[
12,
15
],
[
17,
18
],
[
20,
30
]
],
[
[
4,
5
],
[
11,
11
],
[
16,
16
],
[
19,
19
]
]
] |
c01cee44223f7b8ef91a0de8dd2cf18d0616ca95 | 3970f1a70df104f46443480d1ba86e246d8f3b22 | /imebra/src/imebra/src/dataHandlerDateTimeBase.cpp | 634c6a98640a9fbdd247bf0240199b348bd1953e | [] | no_license | zhan2016/vimrid | 9f8ea8a6eb98153300e6f8c1264b2c042c23ee22 | 28ae31d57b77df883be3b869f6b64695df441edb | refs/heads/master | 2021-01-20T16:24:36.247136 | 2009-07-28T18:32:31 | 2009-07-28T18:32:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,209 | cpp | /*
0.0.46
Imebra: a C++ dicom library.
Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 by Paolo Brandoli
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU AFFERO GENERAL PUBLIC LICENSE Version 3 for more details.
You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3
along with this program; If not, see http://www.gnu.org/licenses/
-------------------
If you want to use Imebra commercially then you have to buy the commercial
license available at http://puntoexe.com
After you buy the commercial license then you can use Imebra according
to the terms described in the Imebra Commercial License Version 1.
A copy of the Imebra Commercial License Version 1 is available in the
documentation pages.
Imebra is available at http://puntoexe.com
The author can be contacted by email at [email protected] or by mail at
the following address:
Paolo Brandoli
Preglov trg 6
1000 Ljubljana
Slovenia
*/
/*! \file dataHandlerDateTimeBase.cpp
\brief Implementation of the base class for the date/time handlers.
*/
#include "../../base/include/exception.h"
#include "../include/dataHandlerDateTimeBase.h"
#include <time.h>
#include <stdlib.h>
#include <sstream>
#include <iomanip>
namespace puntoexe
{
namespace imebra
{
namespace handlers
{
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
//
// dataHandlerDateTimeBase
//
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Returns a long integer representing the date/time (UTC)
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
imbxInt32 dataHandlerDateTimeBase::getSignedLong()
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::getSignedLong");
#ifdef _WIN32_WCE
return -1;
#else
imbxInt32 year, month, day, hour, minutes, seconds, nanoseconds, offsetHours, offsetMinutes;
getDate(&year, &month, &day, &hour, &minutes, &seconds, &nanoseconds, &offsetHours, &offsetMinutes);
tm timeStructure;
timeStructure.tm_isdst= -1;
timeStructure.tm_wday= 0;
timeStructure.tm_yday= 0;
timeStructure.tm_year = year;
timeStructure.tm_mon = month-1;
timeStructure.tm_mday = day;
timeStructure.tm_hour = hour;
timeStructure.tm_min = minutes;
timeStructure.tm_sec = seconds;
return (imbxInt32)mktime(&timeStructure);
#endif
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Cast getSignedLong to unsigned long
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
imbxUint32 dataHandlerDateTimeBase::getUnsignedLong()
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::getUnsignedLong");
return (imbxUint32)getSignedLong();
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Cast getSignedLong to double
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
double dataHandlerDateTimeBase::getDouble()
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::getDouble");
return (double)getSignedLong();
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Set the date as a signed long (from time_t)
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
void dataHandlerDateTimeBase::setSignedLong(imbxInt32 value)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::setSignedLong");
#ifdef _WIN32_WCE
return;
#else
tm* timeStructure = localtime((time_t*)&value);
imbxInt32 year = timeStructure->tm_year;
imbxInt32 month = timeStructure->tm_mon + 1;
imbxInt32 day = timeStructure->tm_mday;
imbxInt32 hour = timeStructure->tm_hour;
imbxInt32 minutes = timeStructure->tm_min;
imbxInt32 seconds = timeStructure->tm_sec;
setDate(year, month, day, hour, minutes, seconds, 0, 0, 0);
#endif
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Set the date as a long (from time_t)
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
void dataHandlerDateTimeBase::setUnsignedLong(imbxUint32 value)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::setUnsignedLong");
setSignedLong((imbxInt32)value);
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Set the date as a double (from time_t)
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
void dataHandlerDateTimeBase::setDouble(double value)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::setDouble");
setSignedLong((imbxInt32)value);
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Return the separator
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
wchar_t dataHandlerDateTimeBase::getSeparator()
{
return 0;
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Parse a date string
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
void dataHandlerDateTimeBase::parseDate(
std::wstring dateString,
imbxInt32* pYear,
imbxInt32* pMonth,
imbxInt32* pDay)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::parseDate");
if(dateString.size()<8)
dateString.resize(8, L'0');
std::wstring dateYear=dateString.substr(0, 4);
std::wstring dateMonth=dateString.substr(4, 2);
std::wstring dateDay=dateString.substr(6, 2);
std::wistringstream yearStream(dateYear);
yearStream >> (*pYear);
std::wistringstream monthStream(dateMonth);
monthStream >> (*pMonth);
std::wistringstream dayStream(dateDay);
dayStream >> (*pDay);
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Build a date string
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
std::wstring dataHandlerDateTimeBase::buildDate(
imbxUint32 year,
imbxUint32 month,
imbxUint32 day)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::buildDate");
if((year < 0) || (year > 9999) || (month < 1) || (month>12) || (day<1) || (day>31))
{
year = month = day = 0;
}
std::wostringstream dateStream;
dateStream << std::setfill(L'0');
dateStream << std::setw(4) << year;
dateStream << std::setw(2) << month;
dateStream << std::setw(2) << day;
return dateStream.str();
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Parse a time string
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
void dataHandlerDateTimeBase::parseTime(
std::wstring timeString,
imbxInt32* pHour,
imbxInt32* pMinutes,
imbxInt32* pSeconds,
imbxInt32* pNanoseconds,
imbxInt32* pOffsetHours,
imbxInt32* pOffsetMinutes)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::parseTime");
if(timeString.size() < 6)
{
timeString.resize(6, L'0');
}
if(timeString.size() < 7)
{
timeString += L'.';
}
if(timeString.size() < 13)
{
timeString.resize(13, L'0');
}
if(timeString.size() < 14)
{
timeString += L'+';
}
if(timeString.size() < 18)
{
timeString.resize(18, L'0');
}
std::wstring timeHour = timeString.substr(0, 2);
std::wstring timeMinutes = timeString.substr(2, 2);
std::wstring timeSeconds = timeString.substr(4, 2);
std::wstring timeNanoseconds = timeString.substr(7, 6);
std::wstring timeOffsetHours = timeString.substr(13, 3);
std::wstring timeOffsetMinutes = timeString.substr(16, 2);
std::wistringstream hourStream(timeHour);
hourStream >> (*pHour);
std::wistringstream minutesStream(timeMinutes);
minutesStream >> (*pMinutes);
std::wistringstream secondsStream(timeSeconds);
secondsStream >> (*pSeconds);
std::wistringstream nanosecondsStream(timeNanoseconds);
nanosecondsStream >> (*pNanoseconds);
std::wistringstream offsetHoursStream(timeOffsetHours);
offsetHoursStream >> (*pOffsetHours);
std::wistringstream offsetMinutesStream(timeOffsetMinutes);
offsetMinutesStream >> (*pOffsetMinutes);
if(*pOffsetHours < 0)
{
*pOffsetMinutes= - *pOffsetMinutes;
}
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Build the time string
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
std::wstring dataHandlerDateTimeBase::buildTime(
imbxInt32 hour,
imbxInt32 minutes,
imbxInt32 seconds,
imbxInt32 nanoseconds,
imbxInt32 offsetHours,
imbxInt32 offsetMinutes
)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::buildTime");
if(
(hour < 0)
|| (hour >= 24)
|| (minutes < 0)
|| (minutes >= 60)
|| (seconds <0)
|| (seconds >= 60)
|| (nanoseconds < 0)
|| (nanoseconds > 999999)
|| (offsetHours < -12)
|| (offsetHours > 12)
|| (offsetMinutes < -59)
|| (offsetMinutes > 59))
{
hour = minutes = seconds = nanoseconds = offsetHours = offsetMinutes = 0;
}
bool bMinus=offsetHours < 0;
std::wostringstream timeStream;
timeStream << std::setfill(L'0');
timeStream << std::setw(2) << hour;
timeStream << std::setw(2) << minutes;
timeStream << std::setw(2) << seconds;
timeStream << std::setw(1) << L".";
timeStream << std::setw(6) << nanoseconds;
timeStream << std::setw(1) << (bMinus ? L"-" : L"+");
timeStream << std::setw(2) << labs(offsetHours);
timeStream << std::setw(2) << labs(offsetMinutes);
return timeStream.str();
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Split several parts of a string
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
void dataHandlerDateTimeBase::split(std::wstring timeString, std::wstring separators, std::vector<std::wstring> *pComponents)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::split");
for(size_t sepPos = timeString.find_first_of(separators); sepPos != timeString.npos; sepPos = timeString.find_first_of(separators))
{
std::wstring left = timeString.substr(0, sepPos);
std::wstring right = timeString.substr(++sepPos);
pComponents->push_back(left);
timeString = right;
}
pComponents->push_back(timeString);
PUNTOEXE_FUNCTION_END();
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
// Add the specified char to the left of a string until
// its length reaches the desidered value
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
std::wstring dataHandlerDateTimeBase::padLeft(std::wstring source, std::wstring fillChar, size_t length)
{
PUNTOEXE_FUNCTION_START(L"dataHandlerDateTimeBase::padLeft");
while(source.size() < length)
{
source.insert(0, fillChar);
}
return source;
PUNTOEXE_FUNCTION_END();
}
} // namespace handlers
} // namespace imebra
} // namespace puntoexe
| [
"[email protected]"
] | [
[
[
1,
493
]
]
] |
b491299cbedacb945e47814f267754c25a3008f5 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/wheel/WheelAnimalController/src/AllColorProcess.cpp | 48ccb3eeda45f584908323e5b2bb23ca4891716e | [] | no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,079 | cpp | #include "WheelAnimalControllerStableHeaders.h"
#include "AllColorProcess.h"
#include "RotateAnimation.h"
using namespace Orz;
/////////////////////////////////预旋转过程/////////////////////////////////////////////
ColorProRun::ColorProRun(boost::shared_ptr<WheelAnimalSceneObj> scene, boost::shared_ptr<ColorChange> cc):_time(0.f),_scene(scene),_cc(cc),_ProRunMusicIsEnd(false)
{
std::cout<<"ColorProRun is Start!!!!!!!!!"<<std::endl;
_allColorProRunMusic = ISoundManager::getSingleton().createPlayer("Pre_1.wav", true);
_allColorProRunMusic->load();
_allColorProRunMusic->play(1);
//_as = scene->getSceneAnimation(SCENE_ANIMATION_0);
//_as->setEnabled(true);
//_as->setLoop(false);
}
bool ColorProRun::update(TimeType interval)
{
_update2enable();
//_as->addTime(interval);
//bool ret = _cc->getRise()->update(interval);
bool isPlayingMusic = _allColorProRunMusic->playing();
if( isPlayingMusic == false && _allColorProRunMusic != NULL && _ProRunMusicIsEnd == false)
{
_allColorProRunMusic->unload();
ISoundManager::getSingleton().quickPlay("Pre_2.wav");
_ProRunMusicIsEnd = true;
}
_time += interval;
if(_time > 7.5f)
return false;
/*if(!_as->hasEnded() || ret || !_ProRunMusicIsEnd)
return true;
return false;*/
return true;
}
ColorProRun::~ColorProRun(void)
{
}
void ColorProRun::clear(void)
{
//_as->setEnabled(true);
//_as->setTimePosition(0.f);
_scene->clearLight();
}
void ColorProRun::enable(void)
{
_scene->clearLight();
_scene->addLight(WheelEnum::Red);
_scene->addLight(WheelEnum::Green);
_scene->addLight(WheelEnum::Yellow);
_scene->addLight(WheelEnum::Blue);
_scene->addLight(WheelEnum::DeepBlue);
}
//////////////////////////////////旋转过程//////////////////////////////////////////////////
ColorGameRotate::ColorGameRotate( boost::shared_ptr<WheelAnimalSceneObj> scene, boost::shared_ptr<ColorChange> cc,
boost::shared_ptr<RotateAnimation> needle,
boost::shared_ptr<RotateAnimation> rotate,
int winner,
float nAngle,
float rAngle
):
_scene(scene), _cc(cc), _needle(needle), _rotate(rotate),_color(WinData::getInstance().getLightColor()),_winner(winner),_isContinue(false)
{
_as = scene->getSceneAnimation(SCENE_ANIMATION_0);
_as->setEnabled(true);
_as->setLoop(false);
_needle->play(RotateAnimation::getStartAll(needle->getAngle(), nAngle),15.f);
_rotate->play(RotateAnimation::getStartAll(_rotate->getAngle(), rAngle),20.f);
}
void ColorGameRotate::clear(void)
{
if( _allColorGameRotateMusic)
_allColorGameRotateMusic->unload();
for(int i =0; i<24; ++i)
{
_scene->getAnimal(i)->play(WheelEnum::ACTION1);
}
_as->setEnabled(true);
_as->setTimePosition(0.f);
//_needle->reset();
//_rotate->reset();
}
ColorGameRotate::~ColorGameRotate(void)
{
}
void ColorGameRotate::enable(void)
{
_allColorGameRotateMusic = ISoundManager::getSingleton().createPlayer("Win_1.wav", true);
_allColorGameRotateMusic->load();
_allColorGameRotateMusic->play(0);
_allColorGameRotateMusic->setVolume(0.7f);
for(int i =0; i<24; ++i)
{
_scene->getAnimal(i)->play(WheelEnum::ACTION2);
}
}
bool ColorGameRotate::update(TimeType interval)
{
_update2enable();
_as->addTime(interval);
if(_isContinue == false)
{
bool ret = _cc->getRise(50.0f)->update(interval);
if(!_as->hasEnded() || ret )
{
return true;
}
else
{
_isContinue = true;
}
}
if(_isContinue == true)
{
bool a = _needle->update(interval);
bool b = _rotate->update(interval);
if( b||a )
return true;
else
{
_cc->stop(_color);
return false;
}
}
return true;
}
///////////////////////////////////显示胜利者////////////////////////////////////////////////
ColorShowWinner::ColorShowWinner( boost::shared_ptr<WheelAnimalSceneObj> scene, ObjectLightsPtr objLights ,int winner, int offset):
_scene(scene),
_offset(offset),
_n(0),
_playanimtion(false),
_color(WinData::getInstance().getLightColor()),
_objLights(objLights),
_winner(winner)
{
}
ColorShowWinner::~ColorShowWinner(void)
{
}
void ColorShowWinner::clear(void)
{
_scene->clearLight();
_animation = _scene->getSceneAnimation(SCENE_ANIMATION_0);
_animation->setEnabled(true);
_animation->setTimePosition(0.f);
if(_winnerAnim)
_winnerAnim->reset();
_winner = -1;
_playanimtion = false;
_n = 0;
std::vector<int>::iterator it;
for(it = _ns.begin(); it != _ns.end(); ++it)
{
_scene->showBaseLight(*it, _color,false);
}
_ns.clear();
}
void ColorShowWinner::enable(void)
{
switch( _color )
{
case 0:
ISoundManager::getSingleton().quickPlay("color_r.wav");
break;
case 1:
ISoundManager::getSingleton().quickPlay("color_y.wav");
break;
case 2:
ISoundManager::getSingleton().quickPlay("color_g.wav");
break;
}
_scene->clearLight();
_scene->addLight(_color);
_scene->addLight(_color);
_scene->addLight(_color);
_scene->addLight(WheelEnum::DeepBlue);
}
bool ColorShowWinner::update(TimeType interval)
{
_update2enable();
if(_playanimtion)
{
if(!_winnerAnim->update(interval))
{
_playanimtion = false;
}
return true;
}
if(_n >= 24)
return false;
if(_objLights->getLights()[(_n+_offset+24)%24] == _color)
{
int winner = (_n+_winner)%24;
if(_scene->getAnimal(winner)->getType().second != WheelEnum::KING )
{
ISoundManager::getSingleton().quickPlay("Poniter.wav");
_winnerAnim.reset();
_winnerAnim.reset(new WinnerAnimationNoMove("test", _scene->getBase(winner)));
_scene->showBaseLight(winner, _color);
_ns.push_back(winner);
_winnerAnim->play();
_playanimtion = true;
}
}
_n++;
return true;
}
///////////////////////////////////播放送颜色的动作////////////////////////////////////////////////
ColorPlayAnimation::ColorPlayAnimation():_time(0.f)
{
}
ColorPlayAnimation::~ColorPlayAnimation(void)
{
}
void ColorPlayAnimation::enable(void)
{
_time = 0.f;
}
bool ColorPlayAnimation::update(Orz::TimeType interval)
{
_update2enable();
_time+= interval;
if(_time >=3.0)
return false;
return true;
}
void ColorPlayAnimation::clear(void)
{
}
////////////////////////////////////////////////////////////////////////
ColorProcess5::ColorProcess5():_time(0.f)
{
}
ColorProcess5::~ColorProcess5(void)
{
}
void ColorProcess5::enable(void)
{
_time = 0.f;
}
bool ColorProcess5::update(Orz::TimeType interval)
{
return false;
}
void ColorProcess5::clear(void)
{
}
///////////////////////////////////送颜色的工厂////////////////////////////////////////////////
ProcessFactoryAllColor::ProcessFactoryAllColor(
boost::shared_ptr<WheelAnimalSceneObj> scene,
boost::shared_ptr<ColorChange> cc,
boost::shared_ptr<RotateAnimation> needle,
boost::shared_ptr<RotateAnimation> rotate,
ObjectLightsPtr objLights
):ProcessFactory(scene, objLights),_cc(cc),
_needle(needle),_rotate(rotate)//,_color(color)
{
}
ProcessFactoryAllColor::~ProcessFactoryAllColor(void)
{
}
Process0Ptr ProcessFactoryAllColor::createProcess0(void)
{
return Process0Ptr();
}
ProcessPtr ProcessFactoryAllColor::createProcess1(void)
{
return ProcessPtr(new ColorProRun(_scene, _cc));
}
ProcessPtr ProcessFactoryAllColor::createProcess2(void)
{
return ProcessPtr(new ColorGameRotate(_scene, _cc, _needle, _rotate, _winner, _nAngle, _rAngle));
}
ProcessPtr ProcessFactoryAllColor::createProcess3(void)
{
return ProcessPtr(new ColorShowWinner(_scene, _objLights, _winner, _offset));
}
ProcessPtr ProcessFactoryAllColor::createProcess4(void)
{
return ProcessPtr(new ColorPlayAnimation());
}
//
//ProcessPtr ProcessFactoryAllColor::createProcess5(void)
//{
// return ProcessPtr(new ColorProcess5());
//
//} | [
"[email protected]"
] | [
[
[
1,
387
]
]
] |
076ee19878254eeec7da854b54745811134c1a02 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/graph/test/johnson-test.cpp | 3018c0f431257f454abecaec572371be6d0a25fb | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Artistic-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,767 | cpp | //=======================================================================
// Copyright 2002 Indiana University.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
/* Expected Output
0 1 2 3 4 5 6 7 8 9
0 0 99 111 123 103 107 125 105 111 123
1 99 0 12 24 4 8 26 6 12 24
2 111 12 0 12 16 20 24 18 24 26
3 123 24 12 0 28 30 12 30 26 14
4 103 4 16 28 0 4 22 2 8 20
5 107 8 20 30 4 0 18 6 4 16
6 125 26 24 12 22 18 0 24 14 2
7 105 6 18 30 2 6 24 0 10 22
8 111 12 24 26 8 4 14 10 0 12
9 123 24 26 14 20 16 2 22 12 0
*/
#include <boost/config.hpp>
#include <fstream>
#include <iostream>
#include <vector>
#include <iomanip>
#include <boost/property_map.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/johnson_all_pairs_shortest.hpp>
int main()
{
using namespace boost;
typedef adjacency_list<vecS, vecS, undirectedS, no_property,
property< edge_weight_t, int,
property< edge_weight2_t, int > > > Graph;
const int V = 10;
typedef std::pair < int, int >Edge;
Edge edge_array[] =
{ Edge(0,1), Edge(1,2), Edge(2,3), Edge(1,4), Edge(2,5), Edge(3,6),
Edge(4,5), Edge(5,6), Edge(4,7), Edge(5,8), Edge(6,9), Edge(7,8),
Edge(8,9)
};
const std::size_t E = sizeof(edge_array) / sizeof(Edge);
Graph g(edge_array, edge_array + E, V);
property_map < Graph, edge_weight_t >::type w = get(edge_weight, g);
int weights[] = { 99, 12, 12, 4, 99, 12, 4, 99, 2, 4, 2, 99, 12 };
int *wp = weights;
graph_traits < Graph >::edge_iterator e, e_end;
for (boost::tie(e, e_end) = edges(g); e != e_end; ++e)
w[*e] = *wp++;
std::vector < int >d(V, (std::numeric_limits < int >::max)());
int D[V][V];
johnson_all_pairs_shortest_paths(g, D, distance_map(&d[0]));
std::cout << std::setw(5) <<" ";
for (int k = 0; k < 10; ++k)
std::cout << std::setw(5) << k ;
std::cout << std::endl;
for (int i = 0; i < 10; ++i) {
std::cout <<std::setw(5) << i ;
for (int j = 0; j < 10; ++j) {
std::cout << std::setw(5) << D[i][j] ;
}
std::cout << std::endl;
}
return 0;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
79
]
]
] |
b0e36928c315c320ba9cd2de168464e44721c7e3 | 12ea67a9bd20cbeed3ed839e036187e3d5437504 | /winxgui/Tools/Dev/include/kscomm/text/script_error_report.h | e115b6627435820086d7373086b539de001ca8a3 | [] | no_license | cnsuhao/winxgui | e0025edec44b9c93e13a6c2884692da3773f9103 | 348bb48994f56bf55e96e040d561ec25642d0e46 | refs/heads/master | 2021-05-28T21:33:54.407837 | 2008-09-13T19:43:38 | 2008-09-13T19:43:38 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,196 | h | /* -------------------------------------------------------------------------
// 文件名 : text/script_error_report.h
// 创建者 : 许式伟
// 创建时间 : 5/5/2003 12:35:54 AM
// 功能描述 :
//
// $Id: script_error_report.h,v 1.2 2006/06/10 05:37:09 xushiwei Exp $
// -----------------------------------------------------------------------*/
#ifndef __KFC_TEXT_SCRIPT_ERROR_REPORT_H__
#define __KFC_TEXT_SCRIPT_ERROR_REPORT_H__
#ifndef __KFC_TEXT_SCRIPT_DEBUG_H__
#include "script_debug.h"
#endif
_TEXT_SCRIPT_BEGIN
// -------------------------------------------------------------------------
// log file
class DefaultLog : public MultiLog<2>
{
public:
DefaultLog()
{
m_log[0].Open(stderr);
m_log[1].Open("_ErrorLog_.txt");
}
};
template <class Unused>
class KScriptLogT
{
public:
static DefaultLog log;
};
template <class Unused>
DefaultLog KScriptLogT<Unused>::log;
typedef KScriptLogT<void> KScriptLog;
// -------------------------------------------------------------------------
template <class _Archive, class _String>
class KScriptErrorReport : public KScriptLog
{
public:
typedef _String String;
typedef _Archive Archive;
typedef typename _Archive::char_type char_type;
typedef typename _Archive::pos_type pos_type;
static const char_type cint[];
static const char_type csymbol[];
static const char_type csymbol_or_all[];
static const char_type cstring[];
static const char_type blank[];
static const char_type quomark[];
enum error_type
{
error_except = 0,
error_unexcept = 1,
};
public:
KScriptErrorReport()
{
_error_type = error_except;
_error_pos = 0;
}
STDMETHODIMP_(void) SetContext(Archive& src, const String& context)
{
_pos = src.tell();
_context = context;
}
STDMETHODIMP_(void) Except(Archive& src, const char_type* szMsg)
{
if (_error_pos < _pos)
{
_error_type = error_except;
_error_pos = _pos;
_error_context = _context;
_error_msg = szMsg;
}
else if (_error_pos == _pos && _error_context != _context)
{
_error_type = error_unexcept;
}
}
STDMETHODIMP_(int) ErrorLine(Archive& src) const
{
int line_no = 1;
src.seek(0);
for (pos_type pos = 0; pos <= _error_pos; ++pos)
{
switch ( src.get() )
{
case '\n':
++line_no;
}
}
return line_no;
}
STDMETHODIMP_(void) ReportError(Archive& src)
{
int errline = ErrorLine(src);
if (_error_type == error_except)
{
const char_type* context = _error_context.c_str();
if (_error_msg)
log.Print("Line(%d) Error: '%s(%s)' is excepted.\n", errline, context, _error_msg);
else
log.Print("Line(%d) Error: '%s' is excepted.\n", errline, context);
}
else
{
src.unget();
log.Print("Line(%d) Error: unexcepted character '%c'.\n", errline, src.get());
}
}
protected:
pos_type _error_pos, _pos;
error_type _error_type;
const char_type* _error_msg;
String _error_context;
String _context;
};
// -------------------------------------------------------------------------
#define ERROR_REPORT_CONST_STRING \
template <class _Archive, class _String> \
const typename KScriptErrorReport<_Archive, _String>::char_type \
KScriptErrorReport<_Archive, _String>::
ERROR_REPORT_CONST_STRING cint[] = { 'i', 'n', 't', 'c', 'o', 'n', 's', 't', '\0' };
ERROR_REPORT_CONST_STRING csymbol[] = { 's', 'y', 'm', 'b', 'o', 'l', '\0' };
ERROR_REPORT_CONST_STRING csymbol_or_all[] = { 's', 'y', 'm', 'b', 'o', 'l', ' ', 'o', 'r', ' ', '*', '\0' };
ERROR_REPORT_CONST_STRING cstring[] = { 'c', 'o', 'n', 's', 't', ' ', 's', 't', 'r', 'i', 'n', 'g', '\0' };
ERROR_REPORT_CONST_STRING blank[] = { 'b', 'l', 'a', 'n', 'k', '\0' };
ERROR_REPORT_CONST_STRING quomark[] = { 'q', 'u', 'o', 'm', 'a', 'r', 'k', '\0' };
// -------------------------------------------------------------------------
// $Log: script_error_report.h,v $
// Revision 1.2 2006/06/10 05:37:09 xushiwei
// 支持多个Log终端同时输出: stderr, file("_ErrorLog_.txt")
//
_TEXT_SCRIPT_END
#endif /* __KFC_TEXT_SCRIPT_ERROR_REPORT_H__ */
| [
"[email protected]@86f14454-5125-0410-a45d-e989635d7e98"
] | [
[
[
1,
154
]
]
] |
a0292acc2a66a85cf46c3d80498a2fba4a772ad9 | b83c990328347a0a2130716fd99788c49c29621e | /include/boost/signals2/detail/tracked_objects_visitor.hpp | d3f1649568680de54362fb1592896c1747d975ff | [] | no_license | SpliFF/mingwlibs | c6249fbb13abd74ee9c16e0a049c88b27bd357cf | 12d1369c9c1c2cc342f66c51d045b95c811ff90c | refs/heads/master | 2021-01-18T03:51:51.198506 | 2010-06-13T15:13:20 | 2010-06-13T15:13:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,244 | hpp | // Boost.Signals2 library
// Copyright Frank Mori Hess 2007-2008.
// Copyright Timmo Stange 2007.
// Copyright Douglas Gregor 2001-2004. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// For more information, see http://www.boost.org
#ifndef BOOST_SIGNALS2_TRACKED_OBJECTS_VISITOR_HPP
#define BOOST_SIGNALS2_TRACKED_OBJECTS_VISITOR_HPP
#include <boost/mpl/bool.hpp>
#include <boost/ref.hpp>
#include <boost/signals2/detail/signals_common.hpp>
#include <boost/signals2/slot_base.hpp>
#include <boost/signals2/trackable.hpp>
#include <boost/type_traits.hpp>
#include <boost/utility/addressof.hpp>
namespace boost
{
namespace signals2
{
namespace detail
{
// Visitor to collect tracked objects from a bound function.
class tracked_objects_visitor
{
public:
tracked_objects_visitor(slot_base *slot) : slot_(slot)
{}
template<typename T>
void operator()(const T& t) const
{
m_visit_reference_wrapper(t, mpl::bool_<is_reference_wrapper<T>::value>());
}
private:
template<typename T>
void m_visit_reference_wrapper(const reference_wrapper<T> &t, const mpl::bool_<true> &) const
{
m_visit_pointer(t.get_pointer(), mpl::bool_<true>());
}
template<typename T>
void m_visit_reference_wrapper(const T &t, const mpl::bool_<false> &) const
{
m_visit_pointer(t, mpl::bool_<is_pointer<T>::value>());
}
template<typename T>
void m_visit_pointer(const T &t, const mpl::bool_<true> &) const
{
m_visit_not_function_pointer(t, mpl::bool_<!is_function<typename remove_pointer<T>::type>::value>());
}
template<typename T>
void m_visit_pointer(const T &t, const mpl::bool_<false> &) const
{
m_visit_pointer(addressof(t), mpl::bool_<true>());
}
template<typename T>
void m_visit_not_function_pointer(const T *t, const mpl::bool_<true> &) const
{
m_visit_signal(t, mpl::bool_<is_signal<T>::value>());
}
template<typename T>
void m_visit_not_function_pointer(const T &t, const mpl::bool_<false> &) const
{}
template<typename T>
void m_visit_signal(const T *signal, const mpl::bool_<true> &) const
{
if(signal)
slot_->track_signal(*signal);
}
template<typename T>
void m_visit_signal(const T &t, const mpl::bool_<false> &) const
{
add_if_trackable(t);
}
void add_if_trackable(const trackable *trackable) const
{
if(trackable)
slot_->_tracked_objects.push_back(trackable->get_shared_ptr());
}
void add_if_trackable(const void *trackable) const {}
mutable slot_base * slot_;
};
} // end namespace detail
} // end namespace signals2
} // end namespace boost
#endif // BOOST_SIGNALS2_TRACKED_OBJECTS_VISITOR_HPP
| [
"[email protected]"
] | [
[
[
1,
96
]
]
] |
bb16581ab885233c060f6b074e9130e77606ed79 | 03f442e60a836172561ef833ae7eb7e7ed434d49 | /Sudoku/Node.cpp | 415b0116771fa0f5af45f7c0f35a9505792f0760 | [] | no_license | wooodblr/sudoku-xiu | b72bed616e437e8ee734bf2b039c3572ad6887d3 | f76d8106d62d422733552eeab675840d8a5e7f20 | refs/heads/master | 2020-04-06T03:40:36.806144 | 2011-04-12T13:44:45 | 2011-04-12T13:44:45 | 42,170,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,761 | cpp | #include "StdAfx.h"
#include "Node.h"
using namespace std;
CNode::CNode(void)
{
for(int i = 0;i < 9;i ++)
{
m_bNum[i] = true;
}
m_len = 9;
}
CNode::CNode(const int num)
{
for(int i = 0;i < 9;i ++)
{
this->m_bNum[i] = false;
}
m_len = 1;
m_data = num;
}
CNode::~CNode(void)
{
}
//whether the node has the num
bool CNode::hasNum(const int num)
{
return m_bNum[num - 1];
}
//Add the num to the node, if it already has, return false, else true
bool CNode::addNum(const int num)
{
if(this->m_bNum[num - 1])
{
return false;
}
else
{
if(m_len == 1 && m_data == num)
{
return false;
}
else if(m_len == 1)
{
m_bNum[m_data - 1] = true;
m_bNum[num - 1] = true;
m_len ++;
return true;
}
else
{
this->m_bNum[num - 1] = true;
m_len ++;
return true;
}
}
}
int CNode::getLen() const
{
return m_len;
}
bool CNode::removeNum(const int num)
{
if(this->m_bNum[num - 1])
{
this->m_bNum[num - 1] = false;
m_len --;
if(m_len == 1)
{
//Has only one num, number confirmed.
for(int i = 0;i < 9;i ++)
{
if(this->m_bNum[i])
{
m_data = i + 1;
this->m_bNum[i] = false;
//len = 0;
return true;
}
}
}
return true;
}
else
{
return false;
}
}
//Known the node has only one num, number confirmed
void CNode::setNum(const int num)
{
for(int i = 0;i < 9;i ++)
{
this->m_bNum[i] = false;
}
m_data = num;
m_len = 1;
}
const int CNode::getData()
{
return m_data;
}
const int CNode::getRow()
{
return m_row;
}
const int CNode::getCol()
{
return m_col;
}
void CNode::setLoc(int col, int row)
{
m_row = row;
m_col = col;
} | [
"[email protected]"
] | [
[
[
1,
128
]
]
] |
ba24483f7d0a25f059c11166670073e8da6f2839 | cfa1c9f0d1e0bef25f48586d19395b5658752f5b | /Proj_2/PhysicsManager.h | 1e9f7158b8eb89fd1fbd597d2c506ce2be8cf697 | [] | no_license | gemini14/AirBall | de9c9a9368bb58d7f7c8fe243a900b11d0596227 | 5d41d3f2c5282f50e7074010f7c1d3b5a804be77 | refs/heads/master | 2021-03-12T21:42:26.819173 | 2011-05-11T08:10:51 | 2011-05-11T08:10:51 | 1,732,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,067 | h | #ifndef PHYSICSMANAGER_H
#define PHYSICSMANAGER_H
#include <memory>
#include <boost/noncopyable.hpp>
#include <irrlicht.h>
#include "EnumsConstants.h"
namespace Tuatara
{
struct Physics_Manager;
class SoundSystem;
class PhysicsManager : boost::noncopyable
{
private:
std::shared_ptr<Physics_Manager> physics;
public:
PhysicsManager();
~PhysicsManager();
void CreateBlock( const float& x, const float& y, const float& z);
void CreateBall( const float& entryX, const float& entryY, const float& entryZ, SoundSystem *sound );
void CreatePhantom( const float& x, const float& y, const float& z, const Direction& dir,
const int& strength, bool isVent = true );
bool StepSimulation( float timeDelta = 0 );
void ApplyImpulseToBall( Direction dir, const float& x = 0, const float& y = 0, const float& z = 0 );
irr::core::vector3df GetBallPosition() const;
bool GetBallRotation( irr::core::vector3df& rotationVector ) const;
irr::core::vector3df GetBallVelocity() const;
};
}
#endif | [
"devnull@localhost"
] | [
[
[
1,
43
]
]
] |
2509bca1f088f33a2ec7bffc17bded4efb42ec98 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osg/TexGenNode | 8025fc432633c3f91137ffa656b2f22dd6cb8df0 | [] | no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,412 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#ifndef OSG_TexGenNode
#define OSG_TexGenNode 1
#include <osg/Group>
#include <osg/TexGen>
namespace osg {
/** Node for defining the position of TexGen in the scene. */
class OSG_EXPORT TexGenNode : public Group
{
public:
TexGenNode();
TexGenNode(TexGen* texgen);
TexGenNode(const TexGenNode& tgb, const CopyOp& copyop=CopyOp::SHALLOW_COPY);
META_Node(osg, TexGenNode);
enum ReferenceFrame
{
RELATIVE_RF,
ABSOLUTE_RF
};
/** Set the TexGenNode's ReferenceFrame, either to be relative to its
* parent reference frame. */
void setReferenceFrame(ReferenceFrame rf);
/** Ge thte TexGenNode's ReferenceFrame.*/
ReferenceFrame getReferenceFrame() const { return _referenceFrame; }
/** Set the texture unit that this TexGenNode is associated with.*/
void setTextureUnit(unsigned int textureUnit) { _textureUnit = textureUnit; }
unsigned int getTextureUnit() const { return _textureUnit; }
/** Set the TexGen. */
void setTexGen(TexGen* texgen);
/** Get the TexGen. */
inline TexGen* getTexGen() { return _texgen.get(); }
/** Get the const TexGen. */
inline const TexGen* getTexGen() const { return _texgen.get(); }
/** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/
virtual void setThreadSafeRefUnref(bool threadSafe);
protected:
virtual ~TexGenNode();
unsigned int _textureUnit;
osg::ref_ptr<TexGen> _texgen;
ReferenceFrame _referenceFrame;
};
}
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] | [
[
[
1,
78
]
]
] |
|
fe6257b62fc68ef0a86484a0fa647b1e92874c8f | 967868cbef4914f2bade9ef8f6c300eb5d14bc57 | /Object/Object.hpp | 095b5e4c180af27fe13b7dd28d66bc8f5c0a8aef | [] | no_license | saminigod/baseclasses-001 | 159c80d40f69954797f1c695682074b469027ac6 | 381c27f72583e0401e59eb19260c70ee68f9a64c | refs/heads/master | 2023-04-29T13:34:02.754963 | 2009-10-29T11:22:46 | 2009-10-29T11:22:46 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,161 | hpp | /*
© Vestris Inc., Geneva, Switzerland
http://www.vestris.com, 1994-1999 All Rights Reserved
______________________________________________
written by Serge Huber - [email protected]
and Daniel Doubrovkine - [email protected]
*/
#ifndef BASE_OBJECT_HPP
#define BASE_OBJECT_HPP
#include <platform/include.hpp>
#include <platform/debug.hpp>
#include <Object/Handler.hpp>
class CObject {
BASE_GUARD(m_ClassGuard);
public:
inline CObject(void) BASE_GUARD_INIT_FN(m_ClassGuard) {
}
inline CObject(const CObject& /* Object */) BASE_GUARD_INIT_FN(m_ClassGuard) {
}
virtual ~CObject(void) {
BASE_GUARD_CHECK(m_ClassGuard);
}
virtual CObject& operator=(const CObject&) {
return * this;
}
virtual bool operator<(const CObject& Object) const { if (&Object < this) return true; else return false; }
virtual bool operator>(const CObject& Object) const { if (&Object > this) return true; else return false; }
virtual bool operator<=(const CObject& Object) const { if (&Object <= this) return true; else return false; }
virtual bool operator>=(const CObject& Object) const { if (&Object >= this) return true; else return false; }
virtual bool operator!=(const CObject& Object) const { if (&Object != this) return true; else return false; }
virtual bool operator==(const CObject &Object) const { if (&Object == this) return true; else return false; }
virtual ostream& operator<<(ostream& Stream) const { return Stream; }
friend ostream& operator<<(ostream&, const CObject&);
virtual istream& operator>>(istream& Stream) { return Stream; }
friend istream& operator>>(istream&, CObject&);
friend ostream& operator<<(ostream& Stream, const CObject * Object);
friend istream& operator>>(istream& Stream, CObject * Object);
#ifdef _WIN32
static void ShowLastError(void) { CHandler::ShowLastError(); }
#endif
static void * __object_new(size_t stAllocateBlock);
static void __object_delete(void * pvMem);
};
inline ostream& operator<<(ostream& Stream, const CObject& Object) { return Object.operator<<(Stream); }
inline istream& operator>>(istream& Stream, CObject& Object) { return Object.operator>>(Stream); }
inline ostream& operator<<(ostream& Stream, const CObject * Object) { return Object->operator<<(Stream); }
inline istream& operator>>(istream& Stream, CObject * Object) { return Object->operator>>(Stream); }
#ifdef _UNIX
void * operator new( size_t stAllocateBlock );
void * operator new[](size_t stAllocateBlock);
void operator delete[](void * pvMem);
void operator delete(void * pvMem);
#else
inline void * operator new( size_t stAllocateBlock ) { return CObject :: __object_new(stAllocateBlock); }
inline void * operator new[]( size_t stAllocateBlock ) { return CObject :: __object_new(stAllocateBlock); }
inline void operator delete[](void * pvMem) { CObject :: __object_delete(pvMem); }
inline void operator delete(void * pvMem) { CObject :: __object_delete(pvMem); }
#endif
#endif
| [
"[email protected]"
] | [
[
[
1,
77
]
]
] |
9d7170c2c0f51e994ca76b6673206f91b24c310b | bfcc0f6ef5b3ec68365971fd2e7d32f4abd054ed | /kguidb.cpp | 9c8bc31608342fb3a42f97b9e80a4f8e511029fe | [] | no_license | cnsuhao/kgui-1 | d0a7d1e11cc5c15d098114051fabf6218f26fb96 | ea304953c7f5579487769258b55f34a1c680e3ed | refs/heads/master | 2021-05-28T22:52:18.733717 | 2011-03-10T03:10:47 | 2011-03-10T03:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,393 | cpp | /**********************************************************************************/
/* kGUI - kguidb.cpp */
/* */
/* Programmed by Kevin Pickell */
/* */
/* http://code.google.com/p/kgui/ */
/* */
/* kGUI is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU Lesser General Public License as published by */
/* the Free Software Foundation; version 2. */
/* */
/* kGUI is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* http://www.gnu.org/licenses/lgpl.txt */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with kGUI; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* */
/**********************************************************************************/
/*! @file kguidb.cpp
@brief These are classes for attaching to a mysql database. As well as the usual
queries, they can also load and save records and generate the sql strings to
send to the database based on only the fields that have changed. */
/*! @todo Handle different database encodings UTF-8 etc. */
/*! @todo Handle database disconnect errors more gracefully. */
#include "kgui.h"
#include "kguidb.h"
kGUIDbCommand::kGUIDbCommand(kGUIDb *db,const char *command,...)
{
kGUIString fcommand;
const char *errormsg;
va_list args;
va_start(args, command);
fcommand.AVSprintf(command,args);
va_end(args);
mysql_query(db->GetConn(),fcommand.GetString());
if(db->GetTrace())
db->GetTrace()->ASprintf("->%s\n",fcommand.GetString());
errormsg=mysql_error(db->GetConn());
if(errormsg[0])
assert(false,errormsg);
}
kGUIDbQuery::kGUIDbQuery(kGUIDb *db,const char *query,...)
{
int i;
int nf;
kGUIString fquery;
const char *errormsg;
va_list args;
/* for performance analysis */
db->IncNumQueries();
va_start(args, query);
fquery.AVSprintf(query,args);
va_end(args);
if(db->GetTrace())
db->GetTrace()->ASprintf("->%s\n",fquery.GetString());
tryagain:;
mysql_query(db->GetConn(),fquery.GetString());
m_res_set = mysql_store_result(db->GetConn());
errormsg=mysql_error(db->GetConn());
if(errormsg[0])
{
if(!strcmp(errormsg,"Lost connection to MySQL server during query"))
{
/* try to re-connect! */
db->ReConnect();
goto tryagain;
}
else if(!strcmp(errormsg,"Server shutdown in progress") || !strcmp(errormsg,"MySQL server has gone away"))
{
/* hmmm, not sure what to do here! */
return;
}
else
assert(false,errormsg);
}
assert(m_res_set!=0,"Error, no result set!");
/* use a hash table for field->index conversion */
m_fi.Init(8,sizeof(int));
nf=GetNumFields();
for(i=0;i<nf;++i)
m_fi.Add(GetFieldName(i),&i);
}
unsigned int kGUIDbQuery::GetIndex(const char *fieldname)
{
unsigned int *ip;
ip=(unsigned int *)m_fi.Find(fieldname);
assert(ip!=0,"Field not found!");
return(ip[0]);
}
kGUIDb::kGUIDb()
{
m_conn=0;
m_isconnected=false;
m_lockschanged=false;
m_lockedtables.Init(8,sizeof(int));
m_numqueries=0;
m_trace=0;
}
kGUIDb::~kGUIDb()
{
// assert(m_numlocked==0,"Error locked tables left in list!" );
UpdateLocks();
if(m_conn)
Close();
}
/* this is called if the connection is lost, it will try and re-connect automatically */
void kGUIDb::ReConnect(void)
{
if(!mysql_real_connect(m_conn,m_servername.GetString(),m_username.GetString(),m_password.GetString(),m_dbname.GetString(),0,NULL,0))
m_isconnected=false;
else
m_isconnected=true;
}
void kGUIDb::Connect(const char *servername,const char *dbname,const char *username,const char *password)
{
m_servername.SetString(servername);
m_dbname.SetString(dbname);
m_username.SetString(username);
m_password.SetString(password);
m_conn = mysql_init(NULL);
if(!mysql_real_connect(m_conn,servername,username,password,dbname,0,NULL,0))
{
m_isconnected=false;
// char errorstring[256];
// sprintf(errorstring,"Failed to connect to database: Error: %s\n",mysql_error(m_conn));
// printf("%s",errorstring);
// return;
}
else
{
MYSQL_RES *res;
int z=0;
const char **row;
m_isconnected=true;
/* add all tablenames to a hashtable with a locked count of 0 */
res=mysql_list_tables(m_conn,0); /* get list of tablenames */
/* populate table */
while ((row = (const char **)mysql_fetch_row(res)) != NULL)
m_lockedtables.Add(row[0],&z); /* add tablename to locked list */
mysql_free_result(res);
}
}
/* increment lock table count for this table */
void kGUIDb::LockTable(const char *name)
{
int *lockcount;
lockcount=(int *)m_lockedtables.Find(name);
if(!lockcount)
{
int z=0;
/* table must have been created since connecting to DB */
m_lockedtables.Add(name,&z); /* add tablename to locked list */
lockcount=(int *)m_lockedtables.Find(name);
}
assert(lockcount!=0,"table not found in database!");
/* only set changed flag if count went from 0 to 1 */
if(!lockcount[0])
m_lockschanged=true;
++lockcount[0];
}
void kGUIDb::UnLockTable(const char *name)
{
int *lockcount;
lockcount=(int *)m_lockedtables.Find(name);
assert(lockcount!=0,"table not found in database!");
/* only set changed flag if count went from 1 to 0 */
--lockcount[0];
if(!lockcount[0])
m_lockschanged=true;
}
void kGUIDb::UpdateLocks(void)
{
int i,numtables;
HashEntry *he;
int *lcount;
kGUIString ls;
int numlocked;
kGUIDbCommand *c;
if(m_lockschanged==false)
return;
c=new kGUIDbCommand(this,"UNLOCK TABLES;");
delete c;
numlocked=0;
numtables=m_lockedtables.GetNum();
he=m_lockedtables.GetFirst();
ls.SetString("LOCK TABLES ");
for(i=0;i<numtables;++i)
{
lcount=(int *)(he->m_data); /* get data pointer */
if(lcount[0])
{
if(numlocked)
ls.Append(", ");
ls.ASprintf("%s WRITE",he->m_string);
++numlocked;
}
he=he->GetNext();
}
if(numlocked)
{
ls.Append(";");
c=new kGUIDbCommand(this,ls.GetString());
delete c;
}
m_lockschanged=false;
}
/* since this field might contain quotes, c/r, l/f etc, it needs to be encoded */
void kGUIDb::EncodeField(kGUIString *os,kGUIString *ns)
{
#if 1
char temp[65536];
assert(os->GetLen()<32767,"Buffer overflow is possible!");
mysql_real_escape_string(m_conn,temp,os->GetString(),os->GetLen());
ns->SetString(temp);
ns->Trim(TRIM_SPACE);
#else
ns->SetString(os->GetString());
ns->Trim();
ns->Replace("'","''");
#endif
}
/* read tables and return array of names */
int kGUIDb::ReadTables(kGUIString **names)
{
MYSQL_RES *res_set;
int i,num;
MYSQL_ROW row;
res_set=mysql_list_tables(GetConn(), 0);
num=(int)mysql_num_rows(res_set);
if(!num)
names[0]=0;
else
{
names[0]=new kGUIString[num];
/* populate table */
for(i=0;i<num;++i)
{
row=mysql_fetch_row(res_set);
names[0][i].SetString(row[0]);
}
}
mysql_free_result(res_set);
return(num);
}
void kGUIDb::Close(void)
{
mysql_close(m_conn);
m_conn=0;
}
kGUIDBRecord::kGUIDBRecord(kGUIDb *db)
{
m_db=db;
m_numfields=0;
m_numentries=0;
m_fieldnames.Init(12,4);
m_numprikeyfields=0;
m_prikey.Init(4,2);
m_ce=0;
m_locked=false;
}
kGUIDBRecord::kGUIDBRecord()
{
m_db=0; /* must be defined later */
m_numfields=0;
m_numentries=0;
m_fieldnames.Init(12,4);
m_numprikeyfields=0;
m_prikey.Init(4,2);
m_ce=0;
m_locked=false;
}
void kGUIDBRecord::LockTable(void)
{
if(m_locked==false)
{
m_db->LockTable(m_tablename.GetString());
m_db->UpdateLocks();
m_locked=true;
}
}
void kGUIDBRecord::UnLockTable(void)
{
if(m_locked==true)
{
m_db->UnLockTable(m_tablename.GetString());
m_db->UpdateLocks();
m_locked=false;
}
}
int kGUIDBRecord::NextKey(void)
{
int last;
kGUIDbQuery *q;
LockTable();
m_db->UpdateLocks();
q=new kGUIDbQuery(m_db,"SELECT %s from %s ORDER BY %s DESC LIMIT 0,1",m_keyname.GetString(),m_tablename.GetString(),m_keyname.GetString());
if(q->GetNumRows())
last=atoi(q->GetRow()[0])+1;
else
last=0;
delete q;
return(last);
}
void kGUIDBRecord::PurgeEntries(void)
{
unsigned int i;
kGUIDBRecordEntry *re;
for(i=0;i<m_numentries;++i)
{
re=m_entries.GetEntry(i);
delete re;
}
m_numentries=0;
}
kGUIDBRecord::~kGUIDBRecord()
{
PurgeEntries();
// if(m_fieldnames)
// {
// delete []m_fieldnames;
// m_fieldnames=0;
// }
m_numfields=0;
}
void kGUIDBRecord::GetFieldNames(kGUIDbQuery *q)
{
unsigned int i;
unsigned int n=q->GetNumFields();
#if 1
m_numprikeyfields=0;
m_numfields=n;
for(i=0;i<n;++i)
{
m_fieldnames.GetEntryPtr(i)->SetString(q->GetFieldName(i));
if((q->GetFieldFlags(i)&PRI_KEY_FLAG)==PRI_KEY_FLAG)
m_prikey.SetEntry(m_numprikeyfields++,i);
}
#else
if(m_numfields!=n)
{
if(m_fieldnames)
delete []m_fieldnames;
m_fieldnames=new kGUIString[n];
m_numfields=n;
}
for(i=0;i<n;++i)
m_fieldnames[i].SetString(q->GetFieldName(i));
#endif
}
void kGUIDBRecord::New(const char *tablename,const char *keyname)
{
kGUIDbQuery *q;
m_unique=true;
m_tablename.SetString(tablename);
m_keyname.SetString(keyname);
/* do a query to just get all the field names */
q=new kGUIDbQuery(m_db,"SELECT * from %s LIMIT 0,0",tablename);
GetFieldNames(q);
delete q;
if(m_numentries)
PurgeEntries();
m_entries.Alloc(1);
AddEntry(); /* 1 entry only */
m_ce->m_new=true;
}
void kGUIDBRecord::NewGroup(const char *tablename,const char *keyname)
{
kGUIDbQuery *q;
m_unique=false;
m_tablename.SetString(tablename);
if(keyname)
m_keyname.SetString(keyname);
else
m_keyname.Clear();
/* do a query to just get all the field names */
q=new kGUIDbQuery(m_db,"SELECT * from %s LIMIT 0,0",tablename);
GetFieldNames(q);
delete q;
if(m_numentries)
PurgeEntries();
m_entries.SetGrow(true);
}
void kGUIDBRecord::AddEntry(void)
{
kGUIDBRecordEntry *re;
re=new kGUIDBRecordEntry(m_numfields);
m_entries.SetEntry(m_numentries++,re);
re->m_new=true;
m_ce=re; /* this is the current entry */
}
/* one and only 1 record should be found, any more/less is an error */
void kGUIDBRecord::Load(const char *tablename,kGUIDbQuery *q)
{
assert(Loadz(tablename,q),"Error loading record!");
}
/* only 1 or zero is valid, more than 1 is an error */
bool kGUIDBRecord::Loadz(const char *tablename,kGUIDbQuery *q)
{
m_unique=false;
m_keyname.Clear();
m_key.Clear();
LoadGroup(tablename,q);
assert(m_numentries<2,"Error: Too many matching records, use LoadGroup");
return(m_numentries==1);
}
void kGUIDBRecord::Load(const char *tablename,kGUIDbQuery *q,const char **row)
{
m_unique=false;
m_keyname.Clear();
m_key.Clear();
m_tablename.SetString(tablename);
LoadQ(q,row);
}
bool kGUIDBRecord::Load(const char *tablename,const char *keyname,const char *key)
{
kGUIDbQuery *q;
m_unique=true;
q=new kGUIDbQuery(m_db,"SELECT * from %s WHERE %s='%s'",tablename,keyname,key);
assert(q->GetNumRows()<2,"Error num matches>1");
m_tablename.SetString(tablename);
m_keyname.SetString(keyname);
m_key.SetString(key);
if(!q->GetNumRows())
{
delete q;
if(m_numentries)
PurgeEntries();
m_numentries=0;
m_ce=0;
return(false);
}
LoadQ(q,q->GetRow());
delete q;
return(true);
}
void kGUIDBRecord::LoadQ(kGUIDbQuery *q,const char **row)
{
unsigned int i;
unsigned int n;
kGUIDBRecordEntry *re;
assert(row!=0,"No data!");
n=q->GetNumFields();
if(m_numentries)
PurgeEntries();
GetFieldNames(q);
m_numentries=1;
m_entries.Alloc(1);
re=new kGUIDBRecordEntry(n);
m_ce=re;
m_entries.SetEntry(0,re);
re->m_new=false;
for(i=0;i<n;++i)
{
re->m_fieldvalues[i].SetString(row[i]);
re->m_newfieldvalues[i].SetString(row[i]);
}
}
void kGUIDBRecord::LoadGroup(const char *tablename,const char *keyname,const char *key,const char *sort)
{
kGUIDbQuery *q;
m_keyname.SetString(keyname);
if(key)
m_key.SetString(key);
m_unique=false;
if(strlen(keyname) && key)
{
if(sort)
q=new kGUIDbQuery(m_db,"SELECT * from %s WHERE %s='%s' ORDER BY %s",tablename,keyname,key,sort);
else
q=new kGUIDbQuery(m_db,"SELECT * from %s WHERE %s='%s'",tablename,keyname,key);
}
else
q=new kGUIDbQuery(m_db,"SELECT * from %s",tablename);
LoadGroup(tablename,q);
delete q;
}
bool kGUIDBRecord::CompareGroup(kGUIDbQuery *q)
{
unsigned int i;
unsigned int j;
unsigned int ne;
unsigned int nf;
const char **row;
kGUIDBRecordEntry *re;
nf=q->GetNumFields();
if(m_numfields!=nf)
return(false); /* different! */
ne=q->GetNumRows();
if(m_numentries!=ne)
return(false); /* different! */
for(i=0;i<ne;++i)
{
re=m_entries.GetEntry(i);
row=q->GetRow();
for(j=0;j<nf;++j)
{
if(strcmp(re->m_fieldvalues[j].GetString(),row[j]))
{
q->SeekRow(0);
return(false);
}
}
}
q->SeekRow(0);
return(true); /* same! */
}
void kGUIDBRecord::LoadGroup(const char *tablename,kGUIDbQuery *q)
{
unsigned int i;
unsigned int n;
unsigned int j;
const char **row;
kGUIDBRecordEntry *re;
m_tablename.SetString(tablename);
m_unique=false;
n=q->GetNumFields();
GetFieldNames(q);
#if 0
if(m_numfields!=n)
{
if(m_fieldnames)
delete []m_fieldnames;
m_fieldnames=new kGUIString[n];
m_numfields=n;
for(i=0;i<n;++i)
m_fieldnames[i].SetString(q->GetFieldName(i));
}
#endif
if(m_numentries)
PurgeEntries();
m_numentries=q->GetNumRows();
m_entries.Alloc(m_numentries);
m_entries.SetGrow(true);
m_entries.SetGrowSize(32);
j=0;
while((row = q->GetRow()) != NULL)
{
re=new kGUIDBRecordEntry(n);
m_entries.SetEntry(j++,re);
re->m_new=false;
for(i=0;i<n;++i)
{
re->m_fieldvalues[i].SetString(row[i]);
re->m_newfieldvalues[i].SetString(row[i]);
}
}
if(m_numentries)
SelectEntry(0); /* default to first entry is selected */
else
m_ce=0; /* no current entry! */
}
void kGUIDBRecord::LoadTable(kGUITableObj *table)
{
unsigned int i;
kGUIDBRecordEntry *re;
kGUITableRowObj *newrow;
kGUIDBTableRowObj *newrowdb;
table->DeleteChildren();
for(i=0;i<m_numentries;++i)
{
re=m_entries.GetEntry(i);
newrow=table->AddNewRow();
newrowdb=static_cast<kGUIDBTableRowObj *>(newrow);
m_ce=re;
newrowdb->SetRE(re);
newrowdb->LoadTableEntry(this);
}
}
/* does this record have any pending changes to write? */
bool kGUIDBRecord::GetChanged(void)
{
unsigned int e;
unsigned int i;
kGUIDBRecordEntry *re;
for(e=0;e<m_numentries;++e)
{
re=m_entries.GetEntry(e);
if(re->m_delete==true)
return(true);
if(re->m_new==true)
return(true);
for(i=0;i<m_numfields;++i)
{
if(strcmp(re->m_newfieldvalues[i].GetString(),re->m_fieldvalues[i].GetString()))
return(true); /* changed */
}
}
return(false);
}
/* this is mainly for debugging, it generates a string */
/* that shows differences between the current record and */
bool kGUIDBRecord::GetDiff(kGUIString *diff)
{
unsigned int i;
bool changed;
kGUIDBRecordEntry *re;
diff->Clear();
changed=false;
re=m_ce;
for(i=0;i<m_numfields;++i)
{
if(strcmp(re->m_newfieldvalues[i].GetString(),re->m_fieldvalues[i].GetString()))
{
if(changed==true)
diff->Append(", ");
diff->ASprintf("%s ('%s'<>'%s')",GetFieldName(i),re->m_newfieldvalues[i].GetString(),re->m_fieldvalues[i].GetString());
changed=true;
}
}
return(changed);
}
bool kGUIDBRecord::CompareTable(kGUITableObj *table)
{
unsigned int i;
unsigned int f;
kGUIObj *gobj;
kGUIDBTableRowObj *row;
kGUIDBRecordEntry *re;
kGUIDBRecordEntry tempentry(m_numfields);
/* set the deleted flag on all entries at first */
for(i=0;i<m_numentries;++i)
{
re=m_entries.GetEntry(i);
re->m_changed=true;
}
/* now iterate through the table and update all */
/* records and reset the delete flag on them */
for(i=0;i<table->GetNumChildren(0);++i)
{
gobj=table->GetChild(0,i);
row=static_cast<kGUIDBTableRowObj *>(gobj);
if(!row->GetRE())
return(true); /* changed, this is a new record */
/* copy fields incase not all fields are updated */
for(f=0;f<m_numfields;++f)
tempentry.m_newfieldvalues[f].SetString(m_ce->m_fieldvalues[f].GetString());
m_ce=&tempentry; /* set current row to this one */
row->SaveTableEntry(this); /* save fields from table to this temp one */
/* compare values in tempentry to last one */
m_ce=row->GetRE();
for(f=0;f<m_numfields;++f)
{
if(strcmp(m_ce->m_newfieldvalues[f].GetString(),tempentry.m_newfieldvalues[f].GetString()))
return(true); /* different */
}
m_ce->m_changed=false;
}
/* have any entries not been referenced? */
for(i=0;i<m_numentries;++i)
{
re=m_entries.GetEntry(i);
if(re->m_changed==true)
return(true);
}
return(false); /* same */
}
void kGUIDBRecord::FlagAllEntriesForDelete(void)
{
unsigned int i;
kGUIDBRecordEntry *re;
/* set the deleted flag on all entries at first */
for(i=0;i<m_numentries;++i)
{
re=m_entries.GetEntry(i);
re->m_delete=true;
}
}
bool kGUIDBRecord::SaveTable(kGUITableObj *table)
{
unsigned int i;
kGUIObj *gobj;
kGUIDBTableRowObj *row;
kGUIDBRecordEntry *re;
FlagAllEntriesForDelete();
/* now iterate through the table and update all */
/* records and reset the delete flag on them */
for(i=0;i<table->GetNumChildren(0);++i)
{
gobj=table->GetChild(0,i);
row=static_cast<kGUIDBTableRowObj *>(gobj);
if(row->GetRE())
m_ce=row->GetRE(); /* set current row to this one */
else
{
/* allocate a new record entry to put this into */
re=new kGUIDBRecordEntry(m_numfields);
m_entries.SetEntry(m_numentries++,re);
re->m_new=true;
m_ce=re;
row->SetRE(m_ce);
}
row->SaveTableEntry(this);
}
return(Save());
}
unsigned int kGUIDBRecord::GetIndex(const char *fieldname)
{
unsigned int i;
for(i=0;i<m_numfields;++i)
{
if(!stricmp(GetFieldName(i),fieldname))
return(i);
}
assert(false,"Field not found error!");
return(0);
}
const char *kGUIDBRecord::GetField(const char *fieldname)
{
return m_ce->m_newfieldvalues[GetIndex(fieldname)].GetString();
}
void kGUIDBRecord::SetField(const char *fieldname,const char *value)
{
int i=GetIndex(fieldname);
m_ce->m_newfieldvalues[i].SetString(value);
m_ce->m_newfieldvalues[i].Trim(TRIM_SPACE); /* remove leading and trailing spaces */
m_ce->m_delete=false;
}
void kGUIDBRecord::SetField(const char *fieldname,int val)
{
int i=GetIndex(fieldname);
m_ce->m_newfieldvalues[i].Sprintf("%d",val);
m_ce->m_newfieldvalues[i].Trim(TRIM_SPACE); /* remove leading and trailing spaces */
m_ce->m_delete=false;
}
void kGUIDBRecord::SetField(const char *fieldname,const char *format,int val)
{
int i=GetIndex(fieldname);
m_ce->m_newfieldvalues[i].Sprintf(format,val);
m_ce->m_newfieldvalues[i].Trim(TRIM_SPACE); /* remove leading and trailing spaces */
m_ce->m_delete=false;
}
void kGUIDBRecord::SetField(const char *fieldname,const char *format,double val)
{
int i=GetIndex(fieldname);
m_ce->m_newfieldvalues[i].Sprintf(format,val);
m_ce->m_newfieldvalues[i].Trim(TRIM_SPACE); /* remove leading and trailing spaces */
m_ce->m_delete=false;
}
bool kGUIDBRecord::Save(void)
{
unsigned int i;
unsigned int e;
int numchanged;
bool changed;
bool where;
bool uselimit;
kGUIString update;
kGUIString field;
kGUIDBRecordEntry *re;
const char *errormsg;
assert(m_tablename.GetLen()!=0,"Name not defined for table, call SetTableName(name)!");
/* locate using old key */
/* make sure all fields at the same as before changed */
/* if any are diffent, then return changed by other user error code, unlock table */
/* update fields that are different */
/* unlock table */
update.Alloc(8192);
field.Alloc(1024);
for(e=0;e<m_numentries;++e)
{
re=m_entries.GetEntry(e);
if(re->m_delete==true)
{
uselimit=true;
where=true;
changed=true;
update.SetString("DELETE FROM ");
update.Append(m_tablename.GetString());
}
else if(re->m_new==true)
{
where=false;
uselimit=false;
update.SetString("INSERT ");
update.Append(m_tablename.GetString());
update.Append(" SET ");
changed=false;
for(i=0;i<m_numfields;++i)
{
if(changed==true)
update.Append(", ");
update.Append(GetFieldName(i));
update.Append("='");
m_db->EncodeField(&re->m_newfieldvalues[i],&field);
update.Append(field.GetString());
update.Append("'");
changed=true;
}
}
else /* update an existing record */
{
update.SetString("UPDATE ");
update.Append(m_tablename.GetString());
where=true;
uselimit=true;
update.Append(" SET ");
changed=false;
for(i=0;i<m_numfields;++i)
{
if(strcmp(re->m_newfieldvalues[i].GetString(),re->m_fieldvalues[i].GetString()))
{
if(changed==true)
update.Append(", ");
update.Append(GetFieldName(i));
update.Append("='");
m_db->EncodeField(&re->m_newfieldvalues[i],&field);
update.Append(field.GetString());
update.Append("'");
changed=true;
}
}
}
if(changed==true)
{
/* does this table have a unique primary key? */
if(where==true)
{
update.Append(" WHERE ");
if(m_numprikeyfields)
{
unsigned int f;
for(i=0;i<m_numprikeyfields;++i)
{
f=m_prikey.GetEntry(i);
if(i)
update.Append("AND ");
update.Append(GetFieldName(f));
update.Append("='");
m_db->EncodeField(&re->m_fieldvalues[f],&field);
update.Append(field.GetString());
update.Append("' ");
}
}
#if 0
if(m_unique==true)
{
update.Append(m_keyname.GetString());
update.Append("='");
update.Append(m_key.GetString());
update.Append("'");
}
#endif
else
{
for(i=0;i<m_numfields;++i)
{
if(i)
update.Append("AND ");
update.Append(GetFieldName(i));
update.Append("='");
m_db->EncodeField(&re->m_fieldvalues[i],&field);
update.Append(field.GetString());
update.Append("' ");
}
}
}
/* this is necessary as there could be multiple matches */
if(uselimit==true)
update.Append(" LIMIT 1");
/* lock table */
LockTable();
m_db->UpdateLocks();
mysql_query(m_db->GetConn(),update.GetString());
if(m_db->GetTrace())
m_db->GetTrace()->ASprintf("->%s\n",update.GetString());
errormsg=mysql_error(m_db->GetConn());
if(errormsg[0])
assert(false,errormsg);
numchanged=(int)mysql_affected_rows(m_db->GetConn());
assert(numchanged==1,"Error,number of records changed should have been one!");
/* fields were sucessfully written, copy new fields over previous ones */
/* hmmm, deleted entries? */
for(i=0;i<m_numfields;++i)
{
re->m_new=false;
if(strcmp(re->m_newfieldvalues[i].GetString(),re->m_fieldvalues[i].GetString()))
re->m_fieldvalues[i].SetString(re->m_newfieldvalues[i].GetString());
}
/* remove lock from this table */
UnLockTable();
m_db->UpdateLocks();
}
}
/* delete all entries that are flagged for deletion */
i=0;
for(e=0;e<m_numentries;++e)
{
re=m_entries.GetEntry(e-i);
if(re->m_delete)
{
delete re;
m_entries.DeleteEntry(e-i);
++i; /* ajust for scrolling entries */
}
}
m_numentries-=i; /* update number of entries */
return(true); /* ok! */
}
/*******************************************/
/* list all of the tables in this database */
/*******************************************/
kGUIDbTablesListRowObj::kGUIDbTablesListRowObj(kGUIDb *dbobj)
{
SetRowHeight(20);
m_objptrs[0]=&m_text;
m_dbobj=dbobj;
m_text.SetEventHandler(this,& CALLBACKNAME(NameEvent));
}
/* save tablename */
void kGUIDbTablesListRowObj::NameEvent(kGUIEvent *event)
{
switch(event->GetEvent())
{
case EVENT_ENTER:
/* save before name */
break;
case EVENT_AFTERUPDATE:
/* after name */
break;
}
}
kGUIDbTablesListWindowObj::kGUIDbTablesListWindowObj(kGUIDb *dbobj)
{
MYSQL *conn;
MYSQL_RES *res_set;
MYSQL_ROW row;
m_dbobj=dbobj;
SetEventHandler(this,CALLBACKNAME(WindowEvent));
SetTitle("Database tables");
SetPos(50,50);
SetSize(600,500);
m_def.SetPos(25,10);
m_def.SetSize(150,20);
m_def.SetString("Design View");
m_def.SetEventHandler(this,CALLBACKNAME(Design));
AddObject(&m_def);
m_data.SetPos(200,10);
m_data.SetSize(150,20);
m_data.SetString("Data View");
m_data.SetEventHandler(this,CALLBACKNAME(Data));
AddObject(&m_data);
m_newtable.SetPos(400,10);
m_newtable.SetSize(150,20);
m_newtable.SetString("New Table");
m_newtable.SetEventHandler(this,CALLBACKNAME(NewTable));
AddObject(&m_newtable);
m_table.SetPos(0,50);
m_table.SetSize(400,400);
m_table.SetNumCols(1);
m_table.SetColTitle(0,"Name");
m_table.SetColWidth(0,200);
m_table.SetEventHandler(this,&CALLBACKNAME(WindowEvent));
m_table.SetAllowAddNewRow(true);
AddObject(&m_table);
conn=dbobj->GetConn();
res_set=mysql_list_tables(conn, 0);
/* populate table */
while ((row = mysql_fetch_row(res_set)) != NULL)
{
kGUIDbTablesListRowObj *robj=new kGUIDbTablesListRowObj(dbobj);
robj->SetName(row[0]);
m_table.AddRow(robj);
}
mysql_free_result(res_set);
/* automatically calculate */
//m_table.CalculateColWidths();
kGUI::AddWindow(this);
}
void kGUIDbTablesListWindowObj::WindowEvent(kGUIEvent *event)
{
switch(event->GetEvent())
{
case EVENT_CLOSE:
m_table.DeleteChildren();
delete this;
break;
case EVENT_ADDROW:
{
kGUIDbTablesListRowObj *row;
row=new kGUIDbTablesListRowObj(m_dbobj);
m_table.AddRow(row);
}
break;
}
}
void kGUIDbTablesListWindowObj::Data(kGUIEvent *event)
{
kGUIDbTableDataWindowObj *w;
kGUIDbTablesListRowObj *row;
if(event->GetEvent()==EVENT_PRESSED)
{
if(m_table.GetNumChildren())
{
row=static_cast<kGUIDbTablesListRowObj *>(m_table.GetCursorRowObj());
if(row)
w=new kGUIDbTableDataWindowObj(m_dbobj,row->GetName());
}
}
}
void kGUIDbTablesListWindowObj::Design(kGUIEvent *event)
{
kGUIDbTableDefWindowObj *w;
kGUIDbTablesListRowObj *row;
if(event->GetEvent()==EVENT_PRESSED)
{
if(m_table.GetNumChildren())
{
row=static_cast<kGUIDbTablesListRowObj *>(m_table.GetCursorRowObj());
if(row)
w=new kGUIDbTableDefWindowObj(m_dbobj,row->GetName());
}
}
}
/*****************************************/
/* Show the data currently in this table */
/*****************************************/
kGUIDbTableDataRowObj::kGUIDbTableDataRowObj(int num,const int *coltypes,const char **row)
{
int i;
SetRowHeight(20);
m_num=num;
m_objptrs=new kGUIObj *[num];
for(i=0;i<num;++i)
{
if(coltypes[i]==0)
{
kGUIInputBoxObj *tobj;
tobj=new kGUIInputBoxObj;
tobj->SetString(row[i]);
m_objptrs[i]=tobj;
}
else
{
kGUITickBoxObj *tbobj;
tbobj=new kGUITickBoxObj;
tbobj->SetSelected(row[i][0]=='1');
m_objptrs[i]=tbobj;
}
}
}
kGUIDbTableDataRowObj::~kGUIDbTableDataRowObj()
{
int i;
for(i=0;i<m_num;++i)
delete m_objptrs[i];
delete []m_objptrs;
}
kGUIDbTableDataWindowObj::kGUIDbTableDataWindowObj(kGUIDb *dbobj,const char *tablename)
{
kGUIDbQuery *q;
const char **row;
unsigned int i;
unsigned int numfields;
int *coltypes;
SetEventHandler(this,CALLBACKNAME(WindowEvent));
SetTitle(tablename);
SetPos(50,50);
SetSize(800,500);
m_table.SetPos(0,0);
m_table.SetSize(700,400);
kGUI::SetMouseCursor(MOUSECURSOR_BUSY);
q=new kGUIDbQuery(dbobj,"SELECT * FROM %s",tablename);
numfields=q->GetNumFields();
m_table.SetNumCols(numfields);
for(i=0;i<numfields;++i)
{
m_table.SetColTitle(i,q->GetFieldName(i));
m_table.SetColWidth(i,200);
}
/* build a table of field types for display */
coltypes=new int[numfields];
for(i=0;i<numfields;++i)
{
if(q->GetFieldType(i)==MYSQL_TYPE_TINY && q->GetFieldLength(i)==1)
coltypes[i]=1;
else
coltypes[i]=0;
}
/* populate table */
while ((row = q->GetRow()) != NULL)
{
kGUIDbTableDataRowObj *robj=new kGUIDbTableDataRowObj(numfields,coltypes,row);
m_table.AddRow(robj);
}
/* automatically calculate */
m_table.CalculateColWidths();
delete q;
delete []coltypes;
AddObject(&m_table);
kGUI::AddWindow(this);
kGUI::SetMouseCursor(MOUSECURSOR_DEFAULT);
}
void kGUIDbTableDataWindowObj::WindowEvent(kGUIEvent *event)
{
switch(event->GetEvent())
{
case EVENT_CLOSE:
m_table.DeleteChildren();
delete this;
break;
}
}
/*****************************************/
/* Show the fields currently in this table */
/*****************************************/
typedef struct
{
int num;
const char *name;
int size;
}SQLTYPES_DEF;
SQLTYPES_DEF sqltypes[]={
{MYSQL_TYPE_DECIMAL,"decimal",0},
{MYSQL_TYPE_TINY,"tiny",0},
{MYSQL_TYPE_SHORT,"short",0},
{MYSQL_TYPE_LONG,"long",0},
{MYSQL_TYPE_FLOAT,"float",0},
{MYSQL_TYPE_DOUBLE,"double",0},
{MYSQL_TYPE_NULL,"null",0},
{MYSQL_TYPE_TIMESTAMP,"timestamp",0},
{MYSQL_TYPE_LONGLONG,"longlong",0},
{MYSQL_TYPE_INT24,"int24",0},
{MYSQL_TYPE_DATE,"date",0},
{MYSQL_TYPE_TIME,"time",0},
{MYSQL_TYPE_DATETIME,"datetime",0},
{MYSQL_TYPE_YEAR,"year",0},
{MYSQL_TYPE_NEWDATE,"newdate",0},
{MYSQL_TYPE_VARCHAR,"varchar",1},
{MYSQL_TYPE_BIT,"bit",0},
{MYSQL_TYPE_NEWDECIMAL,"newdecimal",0},
{MYSQL_TYPE_ENUM,"enum",0},
{MYSQL_TYPE_SET,"set",0},
{MYSQL_TYPE_TINY_BLOB,"tinyblob",0},
{MYSQL_TYPE_MEDIUM_BLOB,"mediumblob",0},
{MYSQL_TYPE_LONG_BLOB,"longblob",0},
{MYSQL_TYPE_BLOB,"blob",0},
{MYSQL_TYPE_VAR_STRING,"varstring",1},
{MYSQL_TYPE_STRING,"string",0},
{MYSQL_TYPE_GEOMETRY,"geometry",0}};
/* assert if type not in list */
int kGUIDbTableDefRowObj::GetSqlTypeIndex(int type)
{
unsigned int i;
for(i=0;i<sizeof(sqltypes)/sizeof(SQLTYPES_DEF);++i)
{
if(type==sqltypes[i].num)
return(i);
}
passert(false,"Unknown SQL type! %d\n",type);
return(-1); /* never gets here, but stop compiler from complaining... */
}
kGUIDbTableDefRowObj::kGUIDbTableDefRowObj(kGUIDbTableDefWindowObj *parent,const char *name,int type,int length,int maxlength,bool prikey,bool indexed)
{
unsigned int i;
m_parent=parent;
m_name.SetString(name);
m_name.SetEventHandler(this,CALLBACKNAME(ChangeNameorType));
m_oldname.SetString(name);
m_type.SetNumEntries(sizeof(sqltypes)/sizeof(SQLTYPES_DEF));
for(i=0;i<sizeof(sqltypes)/sizeof(SQLTYPES_DEF);++i)
m_type.SetEntry(i,sqltypes[i].name,sqltypes[i].num);
m_type.SetSelection(type);
m_oldtype=m_type.GetSelection();
m_type.SetEventHandler(this,CALLBACKNAME(ChangeNameorType));
m_length.SetInt(length);
m_maxlength.SetInt(maxlength);
m_prikey.SetSelected(prikey);
m_prikey.SetEventHandler(this,CALLBACKNAME(ChangePriKey));
m_indexed.SetSelected(indexed);
m_indexed.SetEventHandler(this,CALLBACKNAME(ChangeIndexed));
m_objptrs[0]=&m_name;
m_objptrs[1]=&m_type;
m_objptrs[2]=&m_length;
m_objptrs[3]=&m_maxlength;
m_objptrs[4]=&m_prikey;
m_objptrs[5]=&m_indexed;
SetRowHeight(20);
}
void kGUIDbTableDefRowObj::ChangeNameorType(kGUIEvent *event)
{
if(event->GetEvent()==EVENT_AFTERUPDATE)
{
kGUIDbCommand *q;
int typeindex;
typeindex=GetSqlTypeIndex(m_type.GetSelection());
if(sqltypes[typeindex].size)
q=new kGUIDbCommand(m_parent->GetDB(),"ALTER TABLE %s CHANGE %s %s %s(%d);",m_parent->GetTableName(),m_oldname.GetString(),m_name.GetString(),sqltypes[typeindex].name,m_length.GetInt());
else
q=new kGUIDbCommand(m_parent->GetDB(),"ALTER TABLE %s CHANGE %s %s %s;",m_parent->GetTableName(),m_oldname.GetString(),m_name.GetString(),sqltypes[typeindex].name);
delete q;
m_oldname.SetString(m_name.GetString());
m_oldtype=m_type.GetSelection();
}
}
void kGUIDbTableDefRowObj::ChangePriKey(kGUIEvent *event)
{
if(event->GetEvent()==EVENT_AFTERUPDATE)
{
kGUIDbCommand *q;
if(m_prikey.GetSelected()==true)
q=new kGUIDbCommand(m_parent->GetDB(),"ALTER TABLE %s ADD PRIMARY KEY(%s);",m_parent->GetTableName(),m_name.GetString());
else
{
// drops all primary keys, not sure how to just drop one????
q=new kGUIDbCommand(m_parent->GetDB(),"ALTER TABLE %s DROP PRIMARY KEY;",m_parent->GetTableName(),m_name.GetString());
}
delete q;
}
}
void kGUIDbTableDefRowObj::ChangeIndexed(kGUIEvent *event)
{
if(event->GetEvent()==EVENT_AFTERUPDATE)
{
kGUIDbCommand *q;
if(m_indexed.GetSelected()==true)
q=new kGUIDbCommand(m_parent->GetDB(),"ALTER TABLE %s ADD INDEX(%s);",m_parent->GetTableName(),m_name.GetString());
else
q=new kGUIDbCommand(m_parent->GetDB(),"ALTER TABLE %s DROP INDEX %s;",m_parent->GetTableName(),m_name.GetString());
delete q;
}
}
kGUIDbTableDefWindowObj::kGUIDbTableDefWindowObj(kGUIDb *dbobj,const char *tablename)
{
kGUIDbQuery *q;
unsigned int i;
unsigned int numfields;
int *maxlengths;
const char **row;
const int tdcwidths[]={200,200,200,200,100,100};
const char *tdcnames[]={"Field Name","Field Type","Field Length","Current Max Length","PriKey","Indexed"};
SetEventHandler(this,CALLBACKNAME(WindowEvent));
m_db=dbobj;
m_name.SetString(tablename);
SetTitle(tablename);
SetPos(50,50);
SetSize(800,500);
m_table.SetPos(0,0);
m_table.SetSize(700,400);
kGUI::SetMouseCursor(MOUSECURSOR_BUSY);
/* scan whole table because we show the max used length for each field */
q=new kGUIDbQuery(dbobj,"SELECT * FROM %s",tablename);
m_table.SetNumCols(6);
for(i=0;i<6;++i)
{
m_table.SetColTitle(i,tdcnames[i]);
m_table.SetColWidth(i,tdcwidths[i]);
}
numfields=q->GetNumFields();
maxlengths=new int[numfields];
for(i=0;i<numfields;++i)
maxlengths[i]=0;
/* calculate current maximum used field lengths */
while ((row = q->GetRow()) != NULL)
{
for(i=0;i<numfields;++i)
{
if(row[i]) /* null for undefined text type */
{
int l=(int)strlen(row[i]);
if(l>maxlengths[i])
maxlengths[i]=l;
}
}
}
for(i=0;i<numfields;++i)
{
unsigned int flags=q->GetFieldFlags(i);
kGUIDbTableDefRowObj *robj=new kGUIDbTableDefRowObj(this,q->GetFieldName(i),q->GetFieldType(i),q->GetFieldLength(i),maxlengths[i],(flags&PRI_KEY_FLAG)==PRI_KEY_FLAG,(flags&MULTIPLE_KEY_FLAG)==MULTIPLE_KEY_FLAG);
m_table.AddRow(robj);
}
/* automatically calculate */
m_table.CalculateColWidths();
delete q;
delete maxlengths;
m_table.SetAllowAddNewRow(true);
m_table.SetEventHandler(this,CALLBACKNAME(WindowEvent));
AddObject(&m_table);
kGUI::AddWindow(this);
kGUI::SetMouseCursor(MOUSECURSOR_DEFAULT);
}
void kGUIDbTableDefWindowObj::WindowEvent(kGUIEvent *event)
{
switch(event->GetEvent())
{
case EVENT_CLOSE:
m_table.DeleteChildren();
delete this;
break;
case EVENT_ADDROW:
{
unsigned int i;
kGUIDbTableDefRowObj *row;
bool exists;
int index;
kGUIString name;
index=0;
do
{
exists=false;
if(!index)
name.SetString("field");
else
name.Sprintf("field%d",index);
++index;
/* check to see if this field name already exists */
for(i=0;i<m_table.GetNumChildren();++i)
{
row=static_cast<kGUIDbTableDefRowObj *>(m_table.GetChild(i));
if(!stricmp(row->GetName(),name.GetString()))
{
exists=true;
break;
}
}
}while(exists);
//add field
kGUIDbCommand *q;
//ALTER TABLE t1 CHANGE oldname newname newtype;
q=new kGUIDbCommand(GetDB(),"ALTER TABLE %s ADD COLUMN %s %s;",GetTableName(),name.GetString(),sqltypes[row->GetSqlTypeIndex(MYSQL_TYPE_LONG)].name);
delete q;
row=new kGUIDbTableDefRowObj(this,name.GetString(),row->GetSqlTypeIndex(MYSQL_TYPE_LONG),4,4,false,false);
m_table.AddRow(row);
}
break;
}
}
void kGUIDbTablesListWindowObj::NewTable(kGUIEvent *event)
{
if(event->GetEvent()==EVENT_PRESSED)
{
kGUIInputBoxReq *gn;
gn=new kGUIInputBoxReq(this,CALLBACKNAME(NewTable2),"New Table Name?");
}
}
void kGUIDbTablesListWindowObj::NewTable2(kGUIString *s,int closebutton)
{
if(s->GetLen())
{
kGUIDbCommand *c;
MYSQL_RES *res_set;
MYSQL_ROW row;
c=new kGUIDbCommand(m_dbobj,"CREATE TABLE %s (id INT);",s->GetString());
m_table.DeleteChildren();
/* repopulate the table */
res_set=mysql_list_tables(m_dbobj->GetConn(), 0);
/* populate table */
while ((row = mysql_fetch_row(res_set)) != NULL)
{
kGUIDbTablesListRowObj *robj=new kGUIDbTablesListRowObj(m_dbobj);
robj->SetName(row[0]);
m_table.AddRow(robj);
}
mysql_free_result(res_set);
/* automatically calculate */
m_table.CalculateColWidths();
}
}
/* this is in the database code as it generates today's date as a string */
/* in the database's native date format */
void kGUIDb::DateToString(kGUIDate *date,kGUIString *s)
{
s->Sprintf("%04d-%02d-%02d",date->GetYear(),date->GetMonth(),date->GetDay());
}
void kGUIDb::StringToDate(const char *s,kGUIDate *date)
{
int d,m,y;
y=atoi(s);
m=atoi(s+5);
d=atoi(s+8);
date->Set(d,m,y);
}
/* convert true/false from database to boolean true/false */
bool atob(const char *p)
{
if(!stricmp(p,"true"))
return(true);
if(!stricmp(p,"false"))
return(false);
if(p[0]=='1')
return(true);
return(false);
}
/* convert boolean true/false to string "0","1" */
const char *btoa(bool b)
{
static const char *btoastrings[2]={"0","1"};
if(b==true)
return btoastrings[1];
else
return btoastrings[0];
}
| [
"[email protected]@4b35e2fd-144d-0410-91a6-811dcd9ab31d"
] | [
[
[
1,
1642
]
]
] |
306ea4d6c08cda80e160aca1c090ed0844f0e8fd | a04058c189ce651b85f363c51f6c718eeb254229 | /Src/Forms/FlightsMainForm.hpp | c599bed052701e383260ee5edef34b95dd4842bc | [] | no_license | kjk/moriarty-palm | 090f42f61497ecf9cc232491c7f5351412fba1f3 | a83570063700f26c3553d5f331968af7dd8ff869 | refs/heads/master | 2016-09-05T19:04:53.233536 | 2006-04-04T06:51:31 | 2006-04-04T06:51:31 | 18,799 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,058 | hpp | #ifndef _FLIGHTS_MAIN_FORM_HPP__
#define _FLIGHTS_MAIN_FORM_HPP__
#include "MoriartyForm.hpp"
#include <FormObject.hpp>
#include <TextRenderer.hpp>
#include "HyperlinkHandler.hpp"
#include <PopupMenu.hpp>
class FlightsMainForm: public MoriartyForm {
TextRenderer textRenderer_;
Control doneButton_;
Control searchButton_;
Control updateButton_;
ScrollBar scrollBar_;
ArsLexis::String updateString_;
public:
explicit FlightsMainForm(MoriartyApplication& app);
~FlightsMainForm();
void handleSearch();
void handleUpdateButton();
void showMain();
private:
void readUdf();
void handleControlSelect(const EventType& data);
void handleLookupFinished(const EventType& event);
protected:
void attachControls();
bool handleOpen();
void resize(const ArsRectangle& screenBounds);
bool handleEvent(EventType& event);
bool handleMenuCommand(UInt16 itemId);
};
#endif | [
"andrzejc@a75a507b-23da-0310-9e0c-b29376b93a3c"
] | [
[
[
1,
54
]
]
] |
c168fd70a332742fdfdb24f4a253030219a90272 | bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2 | /Open GL Basic Engine/source/glutFramework/glutFramework/playGame.cpp | 1feb5237ccb708a5c41d2b1d6dfb1a533ee8e7a4 | [] | no_license | CorwinJV/rvbgame | 0f2723ed3a4c1a368fc3bac69052091d2d87de77 | a4fc13ed95bd3e5a03e3c6ecff633fe37718314b | refs/heads/master | 2021-01-01T06:49:33.445550 | 2009-11-03T23:14:39 | 2009-11-03T23:14:39 | 32,131,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,412 | cpp | #include "playGame.h"
#include "GameStateManager.h"
#include <sstream>
#include <string>
bool playGame::Update()
{
// get the game state
curState = gamePlay->getCurState();
// level variables
int levelCounter;
string tempString;
int tempInt;
bool inGameStatus;
// see if the robot is at the end square
if((gamePlay->robotAtEndSquare())&& (curState == GB_EXECUTION))
{
curState = GB_VICTORYDANCE;
}
// Update mInterface all the time
mInterface.Update();
compass->Update();
if(GameVars->getCurrentLevel() <= GameVars->numTutorialLevels)
{
skipMenu->Update();
}
int maxLevel;
switch(curState)
{
case GB_LOGICVIEW:
inGameStatus = true;
GameVars->setInGame(inGameStatus);
gameSaved = false;
pregameRunning = false;
gamePlay->update();
gamePlay->mapScroll();
break;
case GB_EXECUTION:
inGameStatus = true;
GameVars->setInGame(inGameStatus);
if(!finishNow && !finishing)
{
gameSaved = false;
gamePlay->update();
gamePlay->mapScroll();
}
break;
case GB_PREGAME:
inGameStatus = true;
GameVars->setInGame(inGameStatus);
gameSaved = false;
if(pregameRunning)
{
timer = clock();
if(timer > (startTime + 5000))
{
pregameRunning = false;
GameVars->commandsProcessed = 0;
GameVars->totalCommandsProcessed = 0;
gamePlay->setState(GB_LOGICVIEW);
}
}
else
{
startTime = clock();
timer = clock();
pregameRunning = true;
}
break;
case GB_ROBOTDIED:
inGameStatus = true;
GameVars->setInGame(inGameStatus);
gameSaved = false;
doneDead = false;
if(pregameRunning)
{
timer = clock();
if(timer > (startTime + 5000))
{
pregameRunning = false;
doneDead = true;
}
}
else
{
startTime = clock();
timer = clock();
pregameRunning = true;
}
break;
case GB_VIEWSCORE:
inGameStatus = false;
GameVars->setInGame(inGameStatus);
//save the game for the player, if it hasn't been saved yet
finishNow = false;
if(!gameSaved)
{
GameVars->updatePlayerFile();
// GameVars->PM->saveProfile();
gameSaved = true;
}
//Get the number of bytes user started the level off with and subtract number remaining
playerScore = GameVars->getTotalScore();
// eventually we will implement an equation here to calculate the score based off percentage
// of points used for the level score
myMenu->Update();
break;
case GB_FINISHED:
inGameStatus = false;
GameVars->setInGame(inGameStatus);
//gamePlay->~gameBoard();
mInterface.ClearExecutionList();
mInterface.ResetExecutionMode();
levelCounter = GameVars->getCurrentLevel();
levelCounter++;
maxLevel = GameVars->getMaxLevel();
if(levelCounter < (GameVars->getMaxLevel()))
{
delete gamePlay;
// in with the new
gamePlay = new gameBoard();
tempString = GameVars->getFilename(levelCounter);
//tempInt = GameVars->getCurrentLevel();
gamePlay->LoadGameMapFromFile(tempString);
mInterface.GetCurrentMapLogicBank();
mInterface.GetCurrentLevelBytes();
GameVars->commandsProcessed = 0;
GameVars->totalCommandsProcessed = 0;
curState = GB_PREGAME;
GameVars->didYouKnowI++;
if(GameVars->didYouKnowI == GameVars->didYouKnow.end())
{
GameVars->didYouKnowI = GameVars->didYouKnow.begin();
}
}
else
{
curState = GB_YOUWIN;
levelCounter;
}
GameVars->setLevel(levelCounter);
if(levelCounter > GameVars->getPlayerMaxLevel())
{
GameVars->setPlayerMaxLevel(levelCounter);
}
//=====================================================
// Register the gameBoard callback with the interface!
mInterface.SetExecuteHandler(BE::CreateFunctionPointer3R(gamePlay, &gameBoard::interfaceHasFiredExecuteOrder));
mInterface.SetAbortHandler(BE::CreateFunctionPointer0R(gamePlay, &gameBoard::interfaceHasFiredAbortOrder));
mInterface.SetResetHandler(BE::CreateFunctionPointer0R(gamePlay, &gameBoard::interfaceHasFiredResetOrder));
mInterface.SetHelpHandler(BE::CreateFunctionPointer0R(this, &playGame::launchHelpState));
mInterface.SetSpeedUpHandler(BE::CreateFunctionPointer0R(this, &playGame::speedUp));
mInterface.SetSlowDownHandler(BE::CreateFunctionPointer0R(this, &playGame::slowDown));
gamePlay->SetInterfaceAdvanceHandler(BE::CreateFunctionPointer2R(&mInterface, &LogicInterface::CommandAdvanced));
gamePlay->SetInterfaceReprogramHandler(BE::CreateFunctionPointer0R(&mInterface, &LogicInterface::ReprogramReached));
gamePlay->SetInterfaceClearExecutionListHandler(BE::CreateFunctionPointer0R(&mInterface, &LogicInterface::ClearExecutionList));
gamePlay->setState(curState);
pregameRunning = false;
break;
case GB_YOUWIN:
// upload score onto server (when it gets implemented)
break;
case GB_VICTORYDANCE:
if(!finishing)
{
startTime = clock();
spintimer = clock();
spintimerStart = clock();
finishing = true;
}
timer = clock();
if(timer > startTime + 2000)
{
finishing = false;
finishNow = true;
curState = GB_VIEWSCORE;
gamePlay->setState(curState);
GameVars->totalCommandsProcessed += GameVars->commandsProcessed;
double scoreToAdd = 0;
int bytesUsed = GameVars->getBytesUsed();
int bytesAvail = GameVars->getCurrentLevelBytes();
// happy magical scoring stuff yay
// for the time being, we're going to add a 10% bonus per level
// such that at level 1 you get 110% score, level 2 you get 120%
// and so on and so on capping out at roughly 250% at 15 levels
// so bust out those subroutines on the higher levels for maximum scorage yay!
// score bonus is only applied to the memory used portion of the scoring
// function, the default of 200 base is always default of 200 base so yeah there
// for shitz n gigglez i'm having it give only 25% bonus on tutorial levels
// you won't get a whole lot of points on the tutorials
double levelmultiplier = 0.0;
if(GameVars->getCurrentLevel() > GameVars->numTutorialLevels)
{ // if we're in a normal level, do this
levelmultiplier = GameVars->getCurrentLevel() - GameVars->numTutorialLevels;
levelmultiplier *= 0.1; // here's our 10%
levelmultiplier += 1;
}
else
{
levelmultiplier = 0.25; // 25% for tutorial levels, suck it tutorials
}
scoreToAdd = ((100 - (((double)bytesUsed/(double)bytesAvail)*100)) * 10)*levelmultiplier + 200;
//scoreToAdd *= (double)GameVars->getCurrentLevel() * 0.1;
// sends in your score for the level just completed to be compared against previous attempts
GameVars->setLevelScore(scoreToAdd);
// Get the level score from the level just completed, and add it up with all previous levels completed
GameVars->setTotalScore(GameVars->getLevelScore() + GameVars->getTotalScore());
}
spintimer = clock();
if(spintimer > spintimerStart + 200)
{
gamePlay->spinRobot();
spintimerStart = clock();
}
break;
default:
break;
}
if((!gamePlay->getRobotAlive()) && doneDead)
{
mInterface.AbortButtonClick();
doneDead = false;
gamePlay->setState(GB_LOGICVIEW);
}
// ask the gameboard is a reprogrammable square was hit, if so we need to make a popup screen!
if(gamePlay->getReprogramHit())
{
gamePlay->setReprogramHit(false);
GSM->addGameState<clickOKState>();
}
return true;
}
bool playGame::Draw()
{
GameBoardState curState;
curState = gamePlay->getCurState();
string tempString;
int offsetAmt = 0;
std::stringstream painInTheAss;
//clock_t startTime;
int tempInt;
oglTexture2D fadeToBlack;
int textspacing = 30;
int speed = gamePlay->getProcessSpeed();
int viewscoretext = backgroundImage->mY+50;
// did you know stuffs
int tY = 600;
int tYspace = 20;
int tAmt = 0;
vector<string*> didYouKnowParsed;
vector<string*>::iterator dykItr;
switch(curState)
{
case GB_LOGICVIEW:
glClearColor(0, 0, 0, 0);
gamePlay->draw();
if(GameVars->getCurrentLevel() <= GameVars->numTutorialLevels)
{
skipMenu->Draw();
}
mInterface.Draw();
drawLevelInfo();
compass->Draw();
// display starting speed
glColor3ub(0, 0, 0);
GameVars->fontArial12.drawText(258, 650, "Speed: ");
painInTheAss.str("");
painInTheAss << (1100 - speed) << " MHZ";
tempString += painInTheAss.str();
GameVars->fontDigital12.drawText(258, 670, tempString);
break;
case GB_EXECUTION:
glClearColor(0, 0, 0, 0);
gamePlay->draw();
mInterface.Draw();
drawLevelInfo();
compass->Draw();
// display current speed
glColor3ub(0, 0, 0);
GameVars->fontArial12.drawText(258, 650, "Speed: ");
painInTheAss.str("");
painInTheAss << (1100 - speed) << " MHZ";
tempString += painInTheAss.str();
GameVars->fontDigital12.drawText(258, 670, tempString);
break;
break;
case GB_PREGAME:
if(currentStatus == Passive) // waiting for click ok to continue to finish...
{
startTime = clock();
timer = clock();
pregameRunning = true;
gamePlay->setState(GB_PREGAME);
}
clearBackground();
logoImage->drawImage();
backgroundImage->drawImage();
glColor3ub(0, 0, 0);
// player name
tempString = "Player Name: ";
tempString += GameVars->PM->getPlayerName();
GameVars->fontArial24.drawText(preGameTextOffsetX, preGameTextOffsetY + offsetAmt*preGameTextSpacing, tempString);
offsetAmt++;
// level name
tempInt = GameVars->getCurrentLevel();
tempString = GameVars->getLevelName(tempInt);
offsetAmt += GameVars->fontArial24.drawText(preGameTextOffsetX, preGameTextOffsetY + offsetAmt*preGameTextSpacing, tempString, 48);
// level description
offsetAmt += GameVars->fontArial18.drawText(preGameTextOffsetX, preGameTextOffsetY + offsetAmt*preGameTextSpacing, GameVars->getDesc(tempInt), 48);
// bytes available
tempString = "Bytes Available: ";
painInTheAss.str("");
tempInt = GameVars->getCurrentLevelBytes();
painInTheAss << tempInt;
tempString += painInTheAss.str();
GameVars->fontArial18.drawText(preGameTextOffsetX, preGameTextOffsetY + offsetAmt*preGameTextSpacing, tempString);
offsetAmt++;
// did you know
GameVars->fontArial16.drawText(preGameTextOffsetX, tY+ (tAmt*tYspace), "Did You Know:");
tAmt++;
GameVars->parseMeIntoRows(&didYouKnowParsed, (*GameVars->didYouKnowI), 56, true);
dykItr = didYouKnowParsed.begin();
for(;dykItr < didYouKnowParsed.end(); dykItr++)
{
GameVars->fontArial16.drawText(preGameTextOffsetX, tY+ (tAmt*tYspace), (*dykItr)->c_str());
tAmt++;
}
break;
case GB_ROBOTDIED:
// gl shit that may or may not be needed for font stuff, we shall find out shortly
clearBackground();
//glutSwapBuffers();
//glEnable(GL_TEXTURE_2D);
//glEnable(GL_BLEND);
/*glColor3ub(255, 0, 0);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);*/
// player name
//GameVars->fontDigital200.drawText(150 + rand()%15, 250 + rand()%15, "YOU DIED");
youDiedImage->mX = rand()%15;
youDiedImage->mY = rand()%15;
youDiedImage->drawImage();
break;
case GB_VIEWSCORE:
clearBackground();
logoImage->drawImage();
backgroundImage->drawImage();
if(myMenu != NULL)
myMenu->Draw();
glColor3ub(0, 0, 0);
//
// level name
tempString = "Congratulations! Level Complete!";
GameVars->fontArial32.drawText(150, viewscoretext+ offsetAmt*textspacing, tempString);
offsetAmt++;
offsetAmt++;
offsetAmt++;
// level name
tempInt = GameVars->getCurrentLevel();
tempString = GameVars->getLevelName(tempInt);
offsetAmt += GameVars->fontArial18.drawText(200, viewscoretext+ offsetAmt*textspacing, tempString, 45);
// level description
tempString = GameVars->getDesc(tempInt);
// description
offsetAmt += GameVars->fontArial18.drawText(200, viewscoretext+ offsetAmt*textspacing, tempString, 45);
offsetAmt++;
painInTheAss.str("");
// bytes used
tempString = "";
tempString = "BYTES USED: ";
tempInt = GameVars->getBytesUsed(); // this should get the bytes used value
painInTheAss.str("");
painInTheAss << tempInt;
tempString += painInTheAss.str();
GameVars->fontArial24.drawText(200, viewscoretext+ offsetAmt*textspacing, tempString);
offsetAmt++;
// commands used
tempString = "";
tempString = "COMMANDS PROCESSED: ";
tempInt = GameVars->totalCommandsProcessed;
painInTheAss.str("");
painInTheAss << tempInt;
tempString += painInTheAss.str();
GameVars->fontArial24.drawText(200, viewscoretext+ offsetAmt*textspacing, tempString);
offsetAmt++;
// level score
tempString = "";
tempString = "YOUR LEVEL SCORE: ";
tempInt = GameVars->getLevelScore();
painInTheAss.str("");
painInTheAss << tempInt;
tempString += painInTheAss.str();
GameVars->fontArial24.drawText(200, viewscoretext+ offsetAmt*textspacing, tempString);
offsetAmt++;
// TOTAL SCORE
tempString = "";
tempString = "YOUR TOTAL SCORE: ";
tempInt = GameVars->getTotalScore();
painInTheAss.str("");
painInTheAss << tempInt;
tempString += painInTheAss.str();
GameVars->fontArial24.drawText(200, viewscoretext+ offsetAmt*textspacing, tempString);
offsetAmt++;
if(myMenu != NULL)
myMenu->Draw();
//mInterface.Draw();
break;
case GB_FINISHED:
//gamePlay->draw();
//mInterface.Draw();
break;
case GB_YOUWIN:
doEndGameDraw();
break;
default:
break;
}
return false;
}
bool playGame::initialize()
{
finishNow = false;
finishing = false;
string tempString;
int playerCurrentLevel;
youDiedImage = new oglTexture2D();
youDiedImage->loadImage("youdied.png", 1024,768);
doneDead = false;
gamePlay = new gameBoard();
//check to see if a level has been specified (initialized to -1)
playerCurrentLevel = GameVars->getLevelSpecified();
if(playerCurrentLevel < 0)
{
//if a level has not been specified, set to max level
playerCurrentLevel = GameVars->getPlayerMaxLevel();
}
// debug brute force of level
// abcxyz
// playerCurrentLevel = 0;
GameVars->setLevel(playerCurrentLevel);
GameVars->setLevelSpecified(-1);
tempString = GameVars->getFilename(playerCurrentLevel);
gamePlay->LoadGameMapFromFile(tempString);
//gamePlay->LoadGameMapFromFile(levelList[GameVars->getCurrentLevel()]->getFile());
mInterface.GetCurrentMapLogicBank();
mInterface.GetCurrentLevelBytes();
//=====================================================
// Register the gameBoard callback with the interface!
mInterface.SetExecuteHandler(BE::CreateFunctionPointer3R(gamePlay, &gameBoard::interfaceHasFiredExecuteOrder));
mInterface.SetAbortHandler(BE::CreateFunctionPointer0R(gamePlay, &gameBoard::interfaceHasFiredAbortOrder));
mInterface.SetResetHandler(BE::CreateFunctionPointer0R(gamePlay, &gameBoard::interfaceHasFiredResetOrder));
mInterface.SetHelpHandler(BE::CreateFunctionPointer0R(this, &playGame::launchHelpState));
mInterface.SetSpeedUpHandler(BE::CreateFunctionPointer0R(this, &playGame::speedUp));
mInterface.SetSlowDownHandler(BE::CreateFunctionPointer0R(this, &playGame::slowDown));
gamePlay->SetInterfaceAdvanceHandler(BE::CreateFunctionPointer2R(&mInterface, &LogicInterface::CommandAdvanced));
gamePlay->SetInterfaceReprogramHandler(BE::CreateFunctionPointer0R(&mInterface, &LogicInterface::ReprogramReached));
gamePlay->SetInterfaceClearExecutionListHandler(BE::CreateFunctionPointer0R(&mInterface, &LogicInterface::ClearExecutionList));
gamePlay->setState(GB_PREGAME);
pregameRunning = false;
gameSaved = false;
//display a menu that shows info and contains advance, replay level and exit buttons
blackImage = new oglTexture2D();
blackImage->loadImage("black.png", 373, 75);
// skip tutorial level button
skipMenu = new MenuSys(5, 440, 200, 75, "blank.png", None, false);
skipMenu->addButton("buttons\\skipthistutorial.png", "buttons\\skipthistutorialhover.png", "buttons\\skipthistutorialhover.png", CreateFunctionPointer0R(this, &playGame::advance), 30, 535, 200, 40);
myMenu = new MenuSys(250, 50, "blank.png", None);
myMenu->addButton("buttons\\advance.png", "buttons\\advancehover.png", "buttons\\advancehover.png", CreateFunctionPointer0R(this, &playGame::advance));
myMenu->setLastButtonDimensions(100, 50);
myMenu->setLastButtonPosition(350, backgroundImage->mY+backgroundImage->dY - 60);
myMenu->addButton("buttons\\exit.png", "buttons\\exithover.png", "buttons\\exithover.png", CreateFunctionPointer0R(this, &playGame::exitGame));
myMenu->setLastButtonDimensions(100, 50);
myMenu->setLastButtonPosition(600, backgroundImage->mY+backgroundImage->dY - 60);
myMenu->addButton("buttons\\replaylevel.png", "buttons\\replaylevelhover.png", "buttons\\replaylevelhover.png", CreateFunctionPointer0R(this, &playGame::replayLevel));
myMenu->setLastButtonDimensions(100, 50);
myMenu->setLastButtonPosition(475, backgroundImage->mY+backgroundImage->dY - 60);
// compass stuff
compassOffsetX = 763;
compassOffsetY = 580;
compass = new MenuSys(compassOffsetX, compassOffsetY, "blank.png", None, true);
// rotate map left
compass->addButton("compass\\rotateleftnormal.png", "compass\\rotatelefthover.png", "compass\\rotatelefthover.png", CreateFunctionPointer0R(this, &playGame::rotatemapleft));
compass->setLastButtonDimensions(37, 25);
compass->setLastButtonPosition(compassOffsetX+6, compassOffsetY+5);
// zoom out
compass->addButton("compass\\zoomoutnormal.png", "compass\\zoomouthover.png", "compass\\zoomouthover.png", CreateFunctionPointer0R(this, &playGame::zoomout));
compass->setLastButtonDimensions(35, 25);
compass->setLastButtonPosition(compassOffsetX+6+37, compassOffsetY+5);
// zoom in
compass->addButton("compass\\zoominnormal.png", "compass\\zoominhover.png", "compass\\zoominhover.png", CreateFunctionPointer0R(this, &playGame::zoomin));
compass->setLastButtonDimensions(36, 25);
compass->setLastButtonPosition(compassOffsetX + 6 + 37 + 35, compassOffsetY+5);
// zoom in
compass->addButton("compass\\rotaterightnormal.png", "compass\\rotaterighthover.png", "compass\\rotaterighthover.png", CreateFunctionPointer0R(this, &playGame::rotatemapright));
compass->setLastButtonDimensions(38, 25);
compass->setLastButtonPosition(compassOffsetX + 6 + 37 + 35 + 36, compassOffsetY+5);
////////////////////////////////
// up left
compass->addButton("compass\\upleftnormal.png", "compass\\uplefthover.png", "compass\\uplefthover.png", CreateFunctionPointer0R(this, &playGame::panupleft));
compass->setLastButtonDimensions(48, 45);
compass->setLastButtonPosition(compassOffsetX+3, compassOffsetY+30+3);
// up
compass->addButton("compass\\upnormal.png", "compass\\uphover.png", "compass\\uphover.png", CreateFunctionPointer0R(this, &playGame::panup));
compass->setLastButtonDimensions(51, 48);
compass->setLastButtonPosition(compassOffsetX+48+3, compassOffsetY+30);
// up right
compass->addButton("compass\\uprightnormal.png", "compass\\uprighthover.png", "compass\\uprighthover.png", CreateFunctionPointer0R(this, &playGame::panupright));
compass->setLastButtonDimensions(49, 45);
compass->setLastButtonPosition(compassOffsetX+48+51+3, compassOffsetY+30+3);
///////////////////////////////
// left
compass->addButton("compass\\leftnormal.png", "compass\\lefthover.png", "compass\\lefthover.png", CreateFunctionPointer0R(this, &playGame::panleft));
compass->setLastButtonDimensions(51, 47);
compass->setLastButtonPosition(compassOffsetX, compassOffsetY+33+48-3);
// center
compass->addButton("compass\\center.png", "compass\\centerhover.png", "compass\\centerhover.png", CreateFunctionPointer0R(this, &playGame::center));
compass->setLastButtonDimensions(51, 47);
compass->setLastButtonPosition(compassOffsetX+51, compassOffsetY+33+48-3);
// right
compass->addButton("compass\\rightnormal.png", "compass\\righthover.png", "compass\\righthover.png", CreateFunctionPointer0R(this, &playGame::panright));
compass->setLastButtonDimensions(52, 47);
compass->setLastButtonPosition(compassOffsetX+51+51, compassOffsetY+33+48-3);
//////////////////////////////////
// down left
compass->addButton("compass\\downleftnormal.png", "compass\\downlefthover.png", "compass\\downlefthover.png", CreateFunctionPointer0R(this, &playGame::pandownleft));
compass->setLastButtonDimensions(48, 46);
compass->setLastButtonPosition(compassOffsetX+3, compassOffsetY+33+48+47-3);
// down
compass->addButton("compass\\downnormal.png", "compass\\downhover.png", "compass\\downhover.png", CreateFunctionPointer0R(this, &playGame::pandown));
compass->setLastButtonDimensions(51, 49);
compass->setLastButtonPosition(compassOffsetX+48+3, compassOffsetY+33+48+47-3);
// down right
compass->addButton("compass\\downrightnormal.png", "compass\\downrighthover.png", "compass\\downrighthover.png", CreateFunctionPointer0R(this, &playGame::pandownright));
compass->setLastButtonDimensions(49, 46);
compass->setLastButtonPosition(compassOffsetX+48+51+3, compassOffsetY+33+48+47-3);
// pregame textinfo
preGameTextOffsetX = 150;
preGameTextOffsetY = 250;
preGameTextSpacing = 45;
preGameTitleDescSpacing = 18;
Update();
return true;
}
bool playGame::panleft() { gamePlay->panleft(); return true;}
bool playGame::panright() { gamePlay->panright(); return true;}
bool playGame::panup() { gamePlay->panup(); return true;}
bool playGame::pandown() { gamePlay->pandown(); return true;}
bool playGame::panupleft() { gamePlay->panupleft(); return true;}
bool playGame::panupright() { gamePlay->panupright(); return true;}
bool playGame::pandownleft() { gamePlay->pandownleft();return true;}
bool playGame::pandownright() { gamePlay->pandownright();return true;}
bool playGame::zoomout() { gamePlay->zoomout(); return true;}
bool playGame::zoomin() { gamePlay->zoomin(); return true;}
bool playGame::center()
{
gamePlay->center();
gamePlay->resetZoom();
return true;
}
bool playGame::rotatemapleft() { gamePlay->rotateMapLeft(); return true;}
bool playGame::rotatemapright() { gamePlay->rotateMapRight(); return true;}
void playGame::processMouse(int x, int y)
{
switch(curState)
{
case GB_LOGICVIEW:
case GB_EXECUTION:
case GB_FINISHED:
case GB_VIEWSCORE:
gamePlay->processMouse(x, y);
mInterface.processMouse(x, y);
compass->processMouse(x, y);
if(myMenu != NULL)
myMenu->processMouse(x, y);
skipMenu->processMouse(x,y);
break;
case GB_PREGAME:
case GB_ROBOTDIED:
break;
default:
break;
}
}
void playGame::processMouseClick(int button, int state, int x, int y)
{
switch(curState)
{
case GB_LOGICVIEW:
case GB_EXECUTION:
case GB_FINISHED:
case GB_VIEWSCORE:
gamePlay->processMouseClick(button, state, x, y);
mInterface.processMouseClick(button, state, x, y);
compass->processMouseClick(button, state, x, y);
if(curState == GB_VIEWSCORE)
{
if(myMenu != NULL)
myMenu->processMouseClick(button, state, x, y);
}
skipMenu->processMouseClick(button, state, x, y);
break;
case GB_PREGAME:
case GB_ROBOTDIED:
break;
default:
break;
}
}
void playGame::keyboardInput(unsigned char c, int x, int y)
{
switch(c)
{
case ',':
case '<':
slowDown();
break;
case '.':
case '>':
speedUp();
break;
}
switch(curState)
{
case GB_LOGICVIEW:
case GB_EXECUTION:
switch(c)
{
case 27:
GSM->addGameState<PauseGameState>();
this->setStatus(Passive);
break;
default:
break;
}
gamePlay->keyboardInput(c, x, y);
break;
case GB_PREGAME:
switch(c)
{
case 27:
gamePlay->setState(GB_LOGICVIEW);
//doneDead = false;
break;
default:
break;
}
break;
case GB_ROBOTDIED:
switch(c)
{
case 27:
gamePlay->setState(GB_LOGICVIEW);
doneDead = true;
break;
default:
break;
}
break;
case GB_YOUWIN:
switch(c)
{
case 27:
this->setStatus(DeleteMe);
GSM->addGameState<MainMenuState>();
break;
default:
break;
}
break;
default:
break;
}
}
playGame::~playGame()
{
//below is memory management that may or may not work, we'll see (Oscar)
vector<levelData*>::iterator itr = levelList.end();
for (; itr != levelList.begin(); itr--)
{
delete(*itr);
levelList.erase(itr);
}
}
bool playGame::advance()
{
// sets the game state to finished to allow advancement through mini state manager
curState = GB_FINISHED;
gamePlay->setState(curState);
return true;
}
bool playGame::exitGame()
{
//delete this state while creating a Main Menu State
GSM->addGameState<MainMenuState>();
this->setStatus(DeleteMe);
return true;
}
bool playGame::replayLevel()
{
// reset the state to pregame of the current level
curState = GB_PREGAME;
gamePlay->setState(curState);
// reset the map for a fresh start for the replay
gamePlay->resetMap();
GameVars->updatePlayerFile();
// is there a way to clear the instruction list?
// find/use same code as when user clicks clear button on interface
////////////////////
// complete and total map reset
mInterface.ClearExecutionList();
mInterface.ResetExecutionMode();
delete gamePlay;
gamePlay = new gameBoard();
int levelCounter = GameVars->getCurrentLevel();
string tempString;
tempString = GameVars->getFilename(GameVars->getCurrentLevel());
gamePlay->LoadGameMapFromFile(tempString);
mInterface.GetCurrentMapLogicBank();
mInterface.GetCurrentLevelBytes();
GameVars->commandsProcessed = 0;
GameVars->totalCommandsProcessed = 0;
curState = GB_PREGAME;
GameVars->didYouKnowI++;
if(GameVars->didYouKnowI == GameVars->didYouKnow.end())
{
GameVars->didYouKnowI = GameVars->didYouKnow.begin();
}
//=====================================================
// Register the gameBoard callback with the interface!
mInterface.SetExecuteHandler(BE::CreateFunctionPointer3R(gamePlay, &gameBoard::interfaceHasFiredExecuteOrder));
mInterface.SetAbortHandler(BE::CreateFunctionPointer0R(gamePlay, &gameBoard::interfaceHasFiredAbortOrder));
mInterface.SetResetHandler(BE::CreateFunctionPointer0R(gamePlay, &gameBoard::interfaceHasFiredResetOrder));
mInterface.SetHelpHandler(BE::CreateFunctionPointer0R(this, &playGame::launchHelpState));
mInterface.SetSpeedUpHandler(BE::CreateFunctionPointer0R(this, &playGame::speedUp));
mInterface.SetSlowDownHandler(BE::CreateFunctionPointer0R(this, &playGame::slowDown));
gamePlay->SetInterfaceAdvanceHandler(BE::CreateFunctionPointer2R(&mInterface, &LogicInterface::CommandAdvanced));
gamePlay->SetInterfaceReprogramHandler(BE::CreateFunctionPointer0R(&mInterface, &LogicInterface::ReprogramReached));
gamePlay->SetInterfaceClearExecutionListHandler(BE::CreateFunctionPointer0R(&mInterface, &LogicInterface::ClearExecutionList));
return true;
}
void playGame::doEndGameDraw()
{
if(endGamePics.size() == 0)
{
// load in alot of pictures
int numPics = 45;
oglTexture2D* tempPic;
for(int x = 0; x < numPics; x++)
{
string filename;
stringstream filenumber;
// build a variable filename
filenumber.clear();
filenumber << x;
filename = "ending\\frames\\ending00";
filename += filenumber.str();
filename += ".png";
tempPic = new oglTexture2D;
tempPic->loadImage(filename, 1024, 768);
endGamePics.push_back(tempPic);
}
endGameAnimation = endGamePics.begin();
}
else
{
// iterate through the pictures drawing them
(*endGameAnimation)->drawImage(0, 0);
glColor3ub(0, 0, 0);
GameVars->fontArial24.drawText(200, 80, "We apologize for the crappy ending,");
GameVars->fontArial24.drawText(200, 120, "we needed to save space.");
GameVars->fontArial24.drawText(200, 160, "Press ESC to return to the main menu.");
endGameAnimation++;
if(endGameAnimation == endGamePics.end())
endGameAnimation = endGamePics.begin();
timer = clock();
startTime = clock();
while(timer < startTime + 50)
{
timer = clock();
}
}
}
void playGame::drawLevelInfo()
{
string tempString;
int playerCurrentLevel;
int textOffsetX = 10;
int textOffsetY = 10;
int textSpacing = 20;
int offsetAmt = 0;
blackImage->mX = 0;
blackImage->mY = 0;
blackImage->drawImageFaded(0.75, 1024, 85);
glColor3ub(255, 0, 0);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
//this wont work if we're coming in out of a level select
playerCurrentLevel = GameVars->getCurrentLevel();
stringstream levelNumText;
levelNumText << "Level " << playerCurrentLevel << " - " << GameVars->getLevelName(playerCurrentLevel);
offsetAmt += GameVars->fontArialRed14.drawText(textOffsetX, textOffsetY + offsetAmt*textSpacing, levelNumText.str(), 87);
// description
tempString = GameVars->getDesc(playerCurrentLevel);
offsetAmt += GameVars->fontArialRed14.drawText(textOffsetX, textOffsetY + offsetAmt*textSpacing, tempString, 87);
}
bool playGame::launchHelpState()
{
GSM->addGameState<helpScreenState>();
return true;
}
bool playGame::speedUp()
{
// get the current game speed
int speed = gamePlay->getProcessSpeed();
//speed up the process time by lowering the timer
// make sure it doesn't get so fast the user can't tell what's going on
if(speed >= 200)
{
speed -= 100;
}
else if(speed == 100)
{
speed = 50;
}
else if(speed == 50)
{
speed = 25;
}
else if(speed == 25)
{
speed = 10;
}
// set the speed to the newly altered value
gamePlay->setProcessSpeed(speed);
return true;
}
bool playGame::slowDown()
{
// get the current game speed
int speed = gamePlay->getProcessSpeed();
//slow down the process time by raising the timer
if(speed == 10)
{
speed = 25;
}
else if (speed == 25)
{
speed = 50;
}
else if(speed == 50)
{
speed = 100;
}
else
{
speed += 100;
}
// make sure it doesn't get too slow
if(speed > 1000)
{
speed = 1000;
}
// set the speed to the newly altered value
gamePlay->setProcessSpeed(speed);
return true;
}
| [
"corwin.j@5457d560-9b84-11de-b17c-2fd642447241"
] | [
[
[
1,
1001
]
]
] |
b2d7af7196a9d18018d454db6018be40acc76fb1 | d6e0f648d63055d6576de917de8d6f0f3fcb2989 | /dac/win/src/qtservice.cpp | 297472e3dbb6e73cc693e7971d991b360e9c5b7c | [] | no_license | lgosha/ssd | 9b4a0ade234dd192ef30274377787edf1244b365 | 0b97a39fd7edabca44c4ac19178a5c626d1efea3 | refs/heads/master | 2020-05-19T12:41:32.060017 | 2011-09-27T12:43:06 | 2011-09-27T12:43:06 | 2,428,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,846 | cpp | /****************************************************************************
**
** This file is part of a Qt Solutions component.
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third
** Party Software they are using.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
****************************************************************************/
#include "qtservice.h"
#include "qtservice_p.h"
#include <QtCore/QCoreApplication>
#include <stdio.h>
#include <QtCore/QTimer>
#include <QtCore/QVector>
#include <QtCore/QProcess>
#if defined(QTSERVICE_DEBUG)
#include <QDebug>
#include <QtCore/QFile>
#include <QtCore/QTime>
#include <QtCore/QMutex>
#if defined(Q_OS_WIN32)
#include <qt_windows.h>
#else
#include <unistd.h>
#include <stdlib.h>
#endif
static QFile* f = 0;
static void qtServiceCloseDebugLog()
{
if (!f)
return;
QString ps(QTime::currentTime().toString("HH:mm:ss.zzz ") + QLatin1String("--- DEBUG LOG CLOSED ---\n\n"));
f->write(ps.toAscii());
f->flush();
f->close();
delete f;
f = 0;
}
void qtServiceLogDebug(QtMsgType type, const char* msg)
{
static QMutex mutex;
QMutexLocker locker(&mutex);
QString s(QTime::currentTime().toString("HH:mm:ss.zzz "));
s += QString("[%1] ").arg(
#if defined(Q_OS_WIN32)
GetCurrentProcessId());
#else
getpid());
#endif
if (!f) {
#if defined(Q_OS_WIN32)
f = new QFile("c:/service-debuglog.txt");
#else
f = new QFile("/tmp/service-debuglog.txt");
#endif
if (!f->open(QIODevice::WriteOnly | QIODevice::Append)) {
delete f;
f = 0;
return;
}
QString ps(QLatin1String("\n") + s + QLatin1String("--- DEBUG LOG OPENED ---\n"));
f->write(ps.toAscii());
}
switch (type) {
case QtWarningMsg:
s += QLatin1String("WARNING: ");
break;
case QtCriticalMsg:
s += QLatin1String("CRITICAL: ");
break;
case QtFatalMsg:
s+= QLatin1String("FATAL: ");
break;
case QtDebugMsg:
s += QLatin1String("DEBUG: ");
break;
default:
// Nothing
break;
}
s += msg;
s += QLatin1String("\n");
f->write(s.toAscii());
f->flush();
if (type == QtFatalMsg) {
qtServiceCloseDebugLog();
exit(1);
}
}
#endif
/*!
\class QtServiceController
\brief The QtServiceController class allows you to control
services from separate applications.
QtServiceController provides a collection of functions that lets
you install and run a service controlling its execution, as well
as query its status.
In order to run a service, the service must be installed in the
system's service database using the install() function. The system
will start the service depending on the specified StartupType; it
can either be started during system startup, or when a process
starts it manually.
Once a service is installed, the service can be run and controlled
manually using the start(), stop(), pause(), resume() or
sendCommand() functions. You can at any time query for the
service's status using the isInstalled() and isRunning()
functions, or you can query its properties using the
serviceDescription(), serviceFilePath(), serviceName() and
startupType() functions. For example:
\code
MyService service; \\ which inherits QtService
QString serviceFilePath;
QtServiceController controller(service.serviceName());
if (controller.install(serviceFilePath))
controller.start()
if (controller.isRunning())
QMessageBox::information(this, tr("Service Status"),
tr("The %1 service is started").arg(controller.serviceName()));
...
controller.stop();
controller.uninstall();
}
\endcode
An instance of the service controller can only control one single
service. To control several services within one application, you
must create en equal number of service controllers.
The QtServiceController destructor neither stops nor uninstalls
the associated service. To stop a service the stop() function must
be called explicitly. To uninstall a service, you can use the
uninstall() function.
\sa QtServiceBase, QtService
*/
/*!
\enum QtServiceController::StartupType
This enum describes when a service should be started.
\value AutoStartup The service is started during system startup.
\value ManualStartup The service must be started manually by a process.
\warning The \a StartupType enum is ignored under UNIX-like
systems. A service, or daemon, can only be started manually on such
systems with current implementation.
\sa startupType()
*/
/*!
Creates a controller object for the service with the given
\a name.
*/
QtServiceController::QtServiceController(const QString &name)
: d_ptr(new QtServiceControllerPrivate())
{
Q_D(QtServiceController);
d->q_ptr = this;
d->serviceName = name;
}
/*!
Destroys the service controller. This neither stops nor uninstalls
the controlled service.
To stop a service the stop() function must be called
explicitly. To uninstall a service, you can use the uninstall()
function.
\sa stop(), QtServiceController::uninstall()
*/
QtServiceController::~QtServiceController()
{
delete d_ptr;
}
/*!
\fn bool QtServiceController::isInstalled() const
Returns true if the service is installed; otherwise returns false.
On Windows it uses the system's service control manager.
On Unix it checks configuration written to QSettings::SystemScope
using "QtSoftware" as organization name.
\sa install()
*/
/*!
\fn bool QtServiceController::isRunning() const
Returns true if the service is running; otherwise returns false. A
service must be installed before it can be run using a controller.
\sa start(), isInstalled()
*/
/*!
Returns the name of the controlled service.
\sa QtServiceController(), serviceDescription()
*/
QString QtServiceController::serviceName() const
{
Q_D(const QtServiceController);
return d->serviceName;
}
/*!
\fn QString QtServiceController::serviceDescription() const
Returns the description of the controlled service.
\sa install(), serviceName()
*/
/*!
\fn QtServiceController::StartupType QtServiceController::startupType() const
Returns the startup type of the controlled service.
\sa install(), serviceName()
*/
/*!
\fn QString QtServiceController::serviceFilePath() const
Returns the file path to the controlled service.
\sa install(), serviceName()
*/
/*!
Installs the service with the given \a serviceFilePath
and returns true if the service is installed
successfully; otherwise returns false.
On Windows service is installed in the system's service control manager with the given
\a account and \a password.
On Unix service configuration is written to QSettings::SystemScope
using "QtSoftware" as organization name. \a account and \a password
arguments are ignored.
\warning Due to the different implementations of how services (daemons)
are installed on various UNIX-like systems, this method doesn't
integrate the service into the system's startup scripts.
\sa uninstall(), start()
*/
bool QtServiceController::install(const QString &serviceFilePath, const QString &account,
const QString &password)
{
QStringList arguments;
arguments << QLatin1String("-i");
arguments << account;
arguments << password;
return (QProcess::execute(serviceFilePath, arguments) == 0);
}
/*!
\fn bool QtServiceController::uninstall()
Uninstalls the service and returns true if successful; otherwise returns false.
On Windows service is uninstalled using the system's service control manager.
On Unix service configuration is cleared using QSettings::SystemScope
with "QtSoftware" as organization name.
\sa install()
*/
/*!
\fn bool QtServiceController::start(const QStringList &arguments)
Starts the installed service passing the given \a arguments to the
service. A service must be installed before a controller can run it.
Returns true if the service could be started; otherwise returns
false.
\sa install(), stop()
*/
/*!
\overload
Starts the installed service without passing any arguments to the service.
*/
bool QtServiceController::start()
{
return start(QStringList());
}
/*!
\fn bool QtServiceController::stop()
Requests the running service to stop. The service will call the
QtServiceBase::stop() implementation unless the service's state
is QtServiceBase::CannotBeStopped. This function does nothing if
the service is not running.
Returns true if a running service was successfully stopped;
otherwise false.
\sa start(), QtServiceBase::stop(), QtServiceBase::ServiceFlags
*/
/*!
\fn bool QtServiceController::pause()
Requests the running service to pause. If the service's state is
QtServiceBase::CanBeSuspended, the service will call the
QtServiceBase::pause() implementation. The function does nothing
if the service is not running.
Returns true if a running service was successfully paused;
otherwise returns false.
\sa resume(), QtServiceBase::pause(), QtServiceBase::ServiceFlags
*/
/*!
\fn bool QtServiceController::resume()
Requests the running service to continue. If the service's state
is QtServiceBase::CanBeSuspended, the service will call the
QtServiceBase::resume() implementation. This function does nothing
if the service is not running.
Returns true if a running service was successfully resumed;
otherwise returns false.
\sa pause(), QtServiceBase::resume(), QtServiceBase::ServiceFlags
*/
/*!
\fn bool QtServiceController::sendCommand(int code)
Sends the user command \a code to the service. The service will
call the QtServiceBase::processCommand() implementation. This
function does nothing if the service is not running.
Returns true if the request was sent to a running service;
otherwise returns false.
\sa QtServiceBase::processCommand()
*/
class QtServiceStarter : public QObject
{
Q_OBJECT
public:
QtServiceStarter(QtServiceBasePrivate *service)
: QObject(), d_ptr(service) {}
public slots:
void slotStart()
{
d_ptr->startService();
}
private:
QtServiceBasePrivate *d_ptr;
};
#include "qtservice.moc"
QtServiceBase *QtServiceBasePrivate::instance = 0;
QtServiceBasePrivate::QtServiceBasePrivate(const QString &name)
: startupType(QtServiceController::ManualStartup), serviceFlags(0), controller(name)
{
}
QtServiceBasePrivate::~QtServiceBasePrivate()
{
}
void QtServiceBasePrivate::startService()
{
q_ptr->start();
}
int QtServiceBasePrivate::run(bool asService, const QStringList &argList)
{
int argc = argList.size();
QVector<char *> argv(argc);
QList<QByteArray> argvData;
for (int i = 0; i < argc; ++i)
argvData.append(argList.at(i).toLocal8Bit());
for (int i = 0; i < argc; ++i)
argv[i] = argvData[i].data();
if (asService && !sysInit())
return -1;
q_ptr->createApplication(argc, argv.data());
QCoreApplication *app = QCoreApplication::instance();
if (!app)
return -1;
if (asService)
sysSetPath();
QtServiceStarter starter(this);
QTimer::singleShot(0, &starter, SLOT(slotStart()));
int res = q_ptr->executeApplication();
delete app;
if (asService)
sysCleanup();
return res;
}
/*!
\class QtServiceBase
\brief The QtServiceBase class provides an API for implementing
Windows services and Unix daemons.
A Windows service or Unix daemon (a "service"), is a program that
runs "in the background" independently of whether a user is logged
in or not. A service is often set up to start when the machine
boots up, and will typically run continuously as long as the
machine is on.
Services are usually non-interactive console applications. User
interaction, if required, is usually implemented in a separate,
normal GUI application that communicates with the service through
an IPC channel. For simple communication,
QtServiceController::sendCommand() and QtService::processCommand()
may be used, possibly in combination with a shared settings
file. For more complex, interactive communication, a custom IPC
channel should be used, e.g. based on Qt's networking classes. (In
certain circumstances, a service may provide a GUI itself,
ref. the "interactive" example documentation).
Typically, you will create a service by subclassing the QtService
template class which inherits QtServiceBase and allows you to
create a service for a particular application type.
The Windows implementation uses the NT Service Control Manager,
and the application can be controlled through the system
administration tools. Services are usually launched using the
system account, which requires that all DLLs that the service
executable depends on (i.e. Qt), are located in the same directory
as the service, or in a system path.
On Unix a service is implemented as a daemon.
You can retrieve the service's description, state, and startup
type using the serviceDescription(), serviceFlags() and
startupType() functions respectively. The service's state is
decribed by the ServiceFlag enum. The mentioned properites can
also be set using the corresponding set functions. In addition you
can retrieve the service's name using the serviceName() function.
Several of QtServiceBase's protected functions are called on
requests from the QtServiceController class:
\list
\o start()
\o pause()
\o processCommand()
\o resume()
\o stop()
\endlist
You can control any given service using an instance of the
QtServiceController class which also allows you to control
services from separate applications. The mentioned functions are
all virtual and won't do anything unless they are
reimplemented. You can reimplement these functions to pause and
resume the service's execution, as well as process user commands
and perform additional clean-ups before shutting down.
QtServiceBase also provides the static instance() function which
returns a pointer to an application's QtServiceBase instance. In
addition, a service can report events to the system's event log
using the logMessage() function. The MessageType enum describes
the different types of messages a service reports.
The implementation of a service application's main function
typically creates an service object derived by subclassing the
QtService template class. Then the main function will call this
service's exec() function, and return the result of that call. For
example:
\code
int main(int argc, char **argv)
{
MyService service(argc, argv);
return service.exec();
}
\endcode
When the exec() function is called, it will parse the service
specific arguments passed in \c argv, perform the required
actions, and return.
\target serviceSpecificArguments
The following arguments are recognized as service specific:
\table
\header \i Short \i Long \i Explanation
\row \i -i \i -install \i Install the service.
\row \i -u \i -uninstall \i Uninstall the service.
\row \i -e \i -exec
\i Execute the service as a standalone application (useful for debug purposes).
This is a blocking call, the service will be executed like a normal application.
In this mode you will not be able to communicate with the service from the contoller.
\row \i -t \i -terminate \i Stop the service.
\row \i -p \i -pause \i Pause the service.
\row \i -r \i -resume \i Resume a paused service.
\row \i -c \e{cmd} \i -command \e{cmd}
\i Send the user defined command code \e{cmd} to the service application.
\row \i -v \i -version \i Display version and status information.
\endtable
If \e none of the arguments is recognized as service specific,
exec() will first call the createApplication() function, then
executeApplication() and finally the start() function. In the end,
exec() returns while the service continues in its own process
waiting for commands from the service controller.
\sa QtService, QtServiceController
*/
/*!
\enum QtServiceBase::MessageType
This enum describes the different types of messages a service
reports to the system log.
\value Success An operation has succeeded, e.g. the service
is started.
\value Error An operation failed, e.g. the service failed to start.
\value Warning An operation caused a warning that might require user
interaction.
\value Information Any type of usually non-critical information.
*/
/*!
\enum QtServiceBase::ServiceFlag
This enum describes the different states of a service.
\value Default The service can be stopped, but not suspended.
\value CanBeSuspended The service can be suspended.
\value CannotBeStopped The service cannot be stopped.
*/
/*!
Creates a service instance called \a name. The \a argc and \a argv
parameters are parsed after the exec() function has been
called. Then they are passed to the application's constructor.
The application type is determined by the QtService subclass.
The service is neither installed nor started. The name must not
contain any backslashes or be longer than 255 characters. In
addition, the name must be unique in the system's service
database.
\sa exec(), start(), QtServiceController::install()
*/
QtServiceBase::QtServiceBase(int argc, char **argv, const QString &name)
{
#if defined(QTSERVICE_DEBUG)
qInstallMsgHandler(qtServiceLogDebug);
qAddPostRoutine(qtServiceCloseDebugLog);
#endif
Q_ASSERT(!QtServiceBasePrivate::instance);
QtServiceBasePrivate::instance = this;
QString nm(name);
if (nm.length() > 255) {
qWarning("QtService: 'name' is longer than 255 characters.");
nm.truncate(255);
}
if (nm.contains('\\')) {
qWarning("QtService: 'name' contains backslashes '\\'.");
nm.replace((QChar)'\\', (QChar)'\0');
}
d_ptr = new QtServiceBasePrivate(nm);
d_ptr->q_ptr = this;
d_ptr->serviceFlags = 0;
d_ptr->sysd = 0;
for (int i = 0; i < argc; ++i)
d_ptr->args.append(QString::fromLocal8Bit(argv[i]));
}
/*!
Destroys the service object. This neither stops nor uninstalls the
service.
To stop a service the stop() function must be called
explicitly. To uninstall a service, you can use the
QtServiceController::uninstall() function.
\sa stop(), QtServiceController::uninstall()
*/
QtServiceBase::~QtServiceBase()
{
delete d_ptr;
QtServiceBasePrivate::instance = 0;
}
/*!
Returns the name of the service.
\sa QtServiceBase(), serviceDescription()
*/
QString QtServiceBase::serviceName() const
{
return d_ptr->controller.serviceName();
}
/*!
Returns the description of the service.
\sa setServiceDescription(), serviceName()
*/
QString QtServiceBase::serviceDescription() const
{
return d_ptr->serviceDescription;
}
/*!
Sets the description of the service to the given \a description.
\sa serviceDescription()
*/
void QtServiceBase::setServiceDescription(const QString &description)
{
d_ptr->serviceDescription = description;
}
/*!
Returns the service's startup type.
\sa QtServiceController::StartupType, setStartupType()
*/
QtServiceController::StartupType QtServiceBase::startupType() const
{
return d_ptr->startupType;
}
/*!
Sets the service's startup type to the given \a type.
\sa QtServiceController::StartupType, startupType()
*/
void QtServiceBase::setStartupType(QtServiceController::StartupType type)
{
d_ptr->startupType = type;
}
/*!
Returns the service's state which is decribed using the
ServiceFlag enum.
\sa ServiceFlags, setServiceFlags()
*/
QtServiceBase::ServiceFlags QtServiceBase::serviceFlags() const
{
return d_ptr->serviceFlags;
}
/*!
\fn void QtServiceBase::setServiceFlags(ServiceFlags flags)
Sets the service's state to the state described by the given \a
flags.
\sa ServiceFlags, serviceFlags()
*/
/*!
Executes the service.
When the exec() function is called, it will parse the \l
{serviceSpecificArguments} {service specific arguments} passed in
\c argv, perform the required actions, and exit.
If none of the arguments is recognized as service specific, exec()
will first call the createApplication() function, then executeApplication() and
finally the start() function. In the end, exec()
returns while the service continues in its own process waiting for
commands from the service controller.
\sa QtServiceController
*/
int QtServiceBase::exec()
{
if (d_ptr->args.size() > 1) {
QString a = d_ptr->args.at(1);
if (a == QLatin1String("-i") || a == QLatin1String("-install")) {
if (!d_ptr->controller.isInstalled()) {
QString account;
QString password;
QString dir;
QString conf = "dac.xml";
if (d_ptr->args.size() > 2) {
dir = d_ptr->args.at(2);
}
if (d_ptr->args.size() > 3) {
conf = d_ptr->args.at(3);
}
else {
fprintf(stderr, "The service %s could not be installed, no directory\n", serviceName().toLatin1().constData());
return -1;
}
if (!d_ptr->install(account, password, dir, conf)) {
fprintf(stderr, "The service %s could not be installed\n", serviceName().toLatin1().constData());
return -1;
} else {
printf("The service %s has been installed under: %s\n",
serviceName().toLatin1().constData(), d_ptr->filePath().toLatin1().constData());
}
} else {
fprintf(stderr, "The service %s is already installed\n", serviceName().toLatin1().constData());
}
return 0;
} else if (a == QLatin1String("-u") || a == QLatin1String("-uninstall")) {
if (d_ptr->controller.isInstalled()) {
if (!d_ptr->controller.uninstall()) {
fprintf(stderr, "The service %s could not be uninstalled\n", serviceName().toLatin1().constData());
return -1;
} else {
printf("The service %s has been uninstalled.\n",
serviceName().toLatin1().constData());
}
} else {
fprintf(stderr, "The service %s is not installed\n", serviceName().toLatin1().constData());
}
return 0;
} else if (a == QLatin1String("-v") || a == QLatin1String("-version")) {
printf("The service\n"
"\t%s\n\t%s\n\n", serviceName().toLatin1().constData(), d_ptr->args.at(0).toLatin1().constData());
printf("is %s", (d_ptr->controller.isInstalled() ? "installed" : "not installed"));
printf(" and %s\n\n", (d_ptr->controller.isRunning() ? "running" : "not running"));
return 0;
} else if (a == QLatin1String("-t") || a == QLatin1String("-terminate")) {
if (!d_ptr->controller.stop())
qErrnoWarning("The service could not be stopped.");
return 0;
} else if (a == QLatin1String("-p") || a == QLatin1String("-pause")) {
d_ptr->controller.pause();
return 0;
} else if (a == QLatin1String("-r") || a == QLatin1String("-resume")) {
d_ptr->controller.resume();
return 0;
} else if (a == QLatin1String("-c") || a == QLatin1String("-command")) {
int code = 0;
if (d_ptr->args.size() > 2)
code = d_ptr->args.at(2).toInt();
d_ptr->controller.sendCommand(code);
return 0;
} else if (a == QLatin1String("-h") || a == QLatin1String("-help")) {
printf("\n%s -[i|u|e|t|c|v|h]\n"
"\t-i(nstall) dir\t: Install the service.\n"
"\t-u(ninstall)\t: Uninstall the service.\n"
"\t-t(erminate)\t: Stop the service.\n"
"\t-c(ommand) num\t: Send command code num to the service.\n"
"\t-v(ersion)\t: Print version and status information.\n"
"\t-h(elp) \t: Show this help.\n"
"\tNo arguments\t: Start the service.\n",
d_ptr->args.at(0).toLatin1().constData());
return 0;
}
}
#if defined(Q_OS_UNIX)
if (::getenv("QTSERVICE_RUN")) {
// Means we're the detached, real service process.
int ec = d_ptr->run(true, d_ptr->args);
if (ec == -1)
qErrnoWarning("The service failed to run.");
return ec;
}
#endif
if (!d_ptr->start()) {
fprintf(stderr, "The service %s could not start\n", serviceName().toLatin1().constData());
return -4;
}
return 0;
}
/*!
\fn void QtServiceBase::logMessage(const QString &message, MessageType type,
int id, uint category, const QByteArray &data)
Reports a message of the given \a type with the given \a message
to the local system event log. The message identifier \a id and
the message \a category are user defined values. The \a data
parameter can contain arbitrary binary data.
Message strings for \a id and \a category must be provided by a
message file, which must be registered in the system registry.
Refer to the MSDN for more information about how to do this on
Windows.
\sa MessageType
*/
/*!
Returns a pointer to the current application's QtServiceBase
instance.
*/
QtServiceBase *QtServiceBase::instance()
{
return QtServiceBasePrivate::instance;
}
/*!
\fn void QtServiceBase::start()
This function must be implemented in QtServiceBase subclasses in
order to perform the service's work. Usually you create some main
object on the heap which is the heart of your service.
The function is only called when no service specific arguments
were passed to the service constructor, and is called by exec()
after it has called the executeApplication() function.
Note that you \e don't need to create an application object or
call its exec() function explicitly.
\sa exec(), stop(), QtServiceController::start()
*/
/*!
Reimplement this function to perform additional cleanups before
shutting down (for example deleting a main object if it was
created in the start() function).
This function is called in reply to controller requests. The
default implementation does nothing.
\sa start(), QtServiceController::stop()
*/
void QtServiceBase::stop()
{
}
/*!
Reimplement this function to pause the service's execution (for
example to stop a polling timer, or to ignore socket notifiers).
This function is called in reply to controller requests. The
default implementation does nothing.
\sa resume(), QtServiceController::pause()
*/
void QtServiceBase::pause()
{
}
/*!
Reimplement this function to continue the service after a call to
pause().
This function is called in reply to controller requests. The
default implementation does nothing.
\sa pause(), QtServiceController::resume()
*/
void QtServiceBase::resume()
{
}
/*!
Reimplement this function to process the user command \a code.
This function is called in reply to controller requests. The
default implementation does nothing.
\sa QtServiceController::sendCommand()
*/
void QtServiceBase::processCommand(int /*code*/)
{
}
/*!
\fn void QtServiceBase::createApplication(int &argc, char **argv)
Creates the application object using the \a argc and \a argv
parameters.
This function is only called when no \l
{serviceSpecificArguments}{service specific arguments} were
passed to the service constructor, and is called by exec() before
it calls the executeApplication() and start() functions.
The createApplication() function is implemented in QtService, but
you might want to reimplement it, for example, if the chosen
application type's constructor needs additional arguments.
\sa exec(), QtService
*/
/*!
\fn int QtServiceBase::executeApplication()
Executes the application previously created with the
createApplication() function.
This function is only called when no \l
{serviceSpecificArguments}{service specific arguments} were
passed to the service constructor, and is called by exec() after
it has called the createApplication() function and before start() function.
This function is implemented in QtService.
\sa exec(), createApplication()
*/
/*!
\class QtService
\brief The QtService is a convenient template class that allows
you to create a service for a particular application type.
A Windows service or Unix daemon (a "service"), is a program that
runs "in the background" independently of whether a user is logged
in or not. A service is often set up to start when the machine
boots up, and will typically run continuously as long as the
machine is on.
Services are usually non-interactive console applications. User
interaction, if required, is usually implemented in a separate,
normal GUI application that communicates with the service through
an IPC channel. For simple communication,
QtServiceController::sendCommand() and QtService::processCommand()
may be used, possibly in combination with a shared settings file. For
more complex, interactive communication, a custom IPC channel
should be used, e.g. based on Qt's networking classes. (In certain
circumstances, a service may provide a GUI itself, ref. the
"interactive" example documentation).
\bold{Note:} On Unix systems, this class relies on facilities
provided by the QtNetwork module, provided as part of the
\l{Qt Open Source Edition} and certain \l{Qt Commercial Editions}.
The QtService class functionality is inherited from QtServiceBase,
but in addition the QtService class binds an instance of
QtServiceBase with an application type.
Typically, you will create a service by subclassing the QtService
template class. For example:
\code
class MyService : public QtService<QApplication>
{
public:
MyService(int argc, char **argv);
~MyService();
protected:
void start();
void stop();
void pause();
void resume();
void processCommand(int code);
};
\endcode
The application type can be QCoreApplication for services without
GUI, QApplication for services with GUI or you can use your own
custom application type.
You must reimplement the QtServiceBase::start() function to
perform the service's work. Usually you create some main object on
the heap which is the heart of your service.
In addition, you might want to reimplement the
QtServiceBase::pause(), QtServiceBase::processCommand(),
QtServiceBase::resume() and QtServiceBase::stop() to intervene the
service's process on controller requests. You can control any
given service using an instance of the QtServiceController class
which also allows you to control services from separate
applications. The mentioned functions are all virtual and won't do
anything unless they are reimplemented.
Your custom service is typically instantiated in the application's
main function. Then the main function will call your service's
exec() function, and return the result of that call. For example:
\code
int main(int argc, char **argv)
{
MyService service(argc, argv);
return service.exec();
}
\endcode
When the exec() function is called, it will parse the \l
{serviceSpecificArguments} {service specific arguments} passed in
\c argv, perform the required actions, and exit.
If none of the arguments is recognized as service specific, exec()
will first call the createApplication() function, then executeApplication() and
finally the start() function. In the end, exec()
returns while the service continues in its own process waiting for
commands from the service controller.
\sa QtServiceBase, QtServiceController
*/
/*!
\fn QtService::QtService(int argc, char **argv, const QString &name)
Constructs a QtService object called \a name. The \a argc and \a
argv parameters are parsed after the exec() function has been
called. Then they are passed to the application's constructor.
There can only be one QtService object in a process.
\sa QtServiceBase()
*/
/*!
\fn QtService::~QtService()
Destroys the service object.
*/
/*!
\fn Application *QtService::application() const
Returns a pointer to the application object.
*/
/*!
\fn void QtService::createApplication(int &argc, char **argv)
Creates application object of type Application passing \a argc and
\a argv to its constructor.
\reimp
*/
/*!
\fn int QtService::executeApplication()
\reimp
*/
| [
"[email protected]"
] | [
[
[
1,
1119
]
]
] |
a9df9099347555c81670b74ed1a2916b3f4d9ea6 | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /_代码统计专用文件夹/C++Primer中文版(第4版)/第十章 关联容器/20090210_习题10.1_pair对象的应用_参考答案版.cpp | 0124281ca03af555e44647e82236a4848cf241ec | [] | no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | #include <iostream>
#include <utility> //NOTICE!
#include <string>
#include <vector>
using namespace std;
int main()
{
pair<string, int> sipr;
string str;
int ival;
vector< pair<string, int> > pvec;
cout << "Enter a string and an integer(Ctrl+Z to end):"
<< endl;
while (cin >> str >> ival) {
sipr = make_pair(str, ival);
pvec.push_back(sipr);
}
return 0;
} | [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
] | [
[
[
1,
22
]
]
] |
fa39c07e7de21df5ed0651f99e5bf3322350689f | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Shared/include/TileMapHandler.h | a104535f10b507bd0bd23c86ad3b20727f801e9f | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,461 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TILE_MAPHANDLER_H
#define TILE_MAPHANDLER_H
#include "MC2SimpleString.h"
#include "TileMapConfig.h"
#include "TileMapHandlerTypes.h"
#include <map>
#include <set>
#include <vector>
#include <list>
#include "TileMapToolkit.h"
#include "MapPlotter.h"
#include "MC2BoundingBox.h"
#include "MapProjection.h"
#include "LangTypes.h"
#include "PixelBox.h"
#include "OverlapDetector.h"
#include "MovementHelper.h"
#include "TileMap.h"
#include "MapMovingInterface.h"
#include "MapDrawingInterface.h"
#include "BitmapMovementHelper.h"
#include "CopyrightHandler.h"
class InterpolationDebugInfo {
public:
MC2Coordinate coord;
int timeDiffMillis;
};
typedef std::vector<InterpolationDebugInfo> InterpolationDebugVector;
using namespace isab;
namespace isab {
class PlotterAdapter3d;
}
class DBufRequester;
class BitBuffer;
class TileMapFormatDesc;
class ClickInfo;
class CoordsArg;
class TileMapUtil;
class TileMap;
class TileMapParams;
class TileMapCoord;
class TilePrimitiveFeature;
class DBufRequestListener;
class TransformMatrix;
class FileDBufRequester;
class RouteID;
class MC2Coordinate;
class MC2Point;
class PositionInterpolator;
class TileMapTextHandler;
class UserDefinedFeature;
class DirectedPolygon;
class TileMapEventListener;
class TileMapTextSettings;
class TileMapLayerInfoVector;
class TileMapContainer;
class TileCategory;
class TMKTimingInfo;
class TileMapHandlerReleaseChecker;
class TileMapInfoCallback;
class TileMapEvent;
class isab::PlotterAdapter3d;
class InterpolationCallback;
struct Settings3D;
/**
* Class for returning information about clicked items.
*/
class TileMapHandlerClickResult : public ClickInfo {
public:
TileMapHandlerClickResult() : m_clickedFeature(NULL),
m_selectionOutline(NULL),
m_distance(MAX_UINT32) {}
/**
* Returns the name of the clicked feature, if a
* feature in the map has been clicked.
*/
inline const char* getName() const {
return m_name.c_str();
}
/**
* Returns the server string to use when getting more information
* about an item when a feature in the map has been clicked.
*/
inline const char* getServerString() const {
return m_serverString.c_str();
}
/**
* Returns the feature clicked, if any. Probably already owned
* by the caller of the method. NULL if a feature in the map
* was clicked.
*/
inline UserDefinedFeature* getClickedUserFeature() const {
return m_clickedFeature;
}
/// Returns the outline feature. Must not be deleted.
inline UserDefinedFeature* getOutlineFeature() const {
return m_selectionOutline;
}
inline int32 getDistance() const {
return m_distance;
}
inline bool shouldHighlight() const {
return getOutlineFeature() != NULL;
}
private:
friend class TileMapHandler;
MC2SimpleString m_name;
MC2SimpleString m_serverString;
UserDefinedFeature* m_clickedFeature;
UserDefinedFeature* m_selectionOutline;
uint32 m_distance;
};
#include "TileMapGarbage.h"
#include "TileFeature.h"
/**
* Cross-platform TileMap getter and drawer.
* No platform dependand code should be here, only
* in the drivers, e.g. XXXMapPlotter.
*/
class TileMapHandler : public MapProjection,
public TileMapTimerListener,
public TileMapIdleListener,
public MapMovingInterface,
public MapDrawingInterface {
public:
/**
* Creates a new TileMapHandler plotting on the supplied
* MapPlotter and requesting from the supplied requester.
* @param plotter The MapPlotter.
* @param requester DBufRequester to use.
* @param platform The toolkit for the platform.
* @param eventListener
*/
TileMapHandler(MapPlotter* plotter,
DBufRequester* requester,
TileMapToolkit* platform,
TileMapEventListener* eventListener = NULL );
/**
* The destructor.
*/
virtual ~TileMapHandler();
/**
* Tells the TileMapHandler that it is time to redraw
* the screen.
*/
void repaint(uint32 maxTimeMillis);
/**
* Called when a timer expires.
*/
void timerExpired(uint32 id);
/**
* Called when the system is a bit idle.
*/
void runIdleTask(uint32 id);
/**
* Sets automatic selection highlighting on/off.
*/
void setHighlight( bool onoff );
/**
* Sets highlight point. MC2Point(-1, -1) means auto-center.
*/
void setHighlightPoint( const MC2Point& hightlightPoint );
/**
* Sets new text settings in the text handler.
*/
void setTextSettings( const TileMapTextSettings& settings );
/**
* Sets the current route id to show in the map.
* @param routeID Route to show.
*/
void setRouteID(const RouteID& routeID);
/**
* Gets the current route id that is shown in the map.
* @return Current route id
*/
const RouteID* getRouteID() const;
/**
* Removes the route id from the TileMapHandler.
* @see setRouteID.
*/
void clearRouteID();
/**
* Set the language for the maps
* using the LangTypes::language_t type.
*/
void setLanguage( LangTypes::language_t lang );
/**
* Returns the lanugage.
*/
LangTypes::language_t getLanguage() const { return m_lang; }
/**
* Set the language for the maps using the nav2 lang type.
*/
void setNav2Language( uint32 nav2Lang );
/**
* Set the language using the specified iso639 string.
* The string can consist of two or three letters and must be
* NULL terminated.
* @param isoStr The string, containing two or three letters.
* @return The language as iso639 that was set to MapLib.
*/
const char* setLanguageAsISO639( const char* isoStr );
/**
* Returns all information possible at the same time.
* More efficient than calling getNameForFeatureAt followed
* by getSelectionOutline etc.
*
* @param highlightable [Optional] If set to true, only
* highlightable features will be
* processed. Default is that
* all feature types are processed.
* @param infoCallback [Optional] Callback that will be called
* when a missing string map is received.
*/
void getInfoForFeatureAt( TileMapHandlerClickResult& res,
const MC2Point& point,
bool highlightable = false,
TileMapInfoCallback* infoCallback= NULL );
/**
* Returns the name for an item at the specified point.
* @deprecated Use getInfoForFeatureAt instead.
* @param point The coordinate to look at.
* @param distance Set to the distance to the found item in pixels
* if not NULL.
*/
const char* getNameForFeatureAt(const MC2Point& point,
uint32* distance = NULL );
/**
* Puts most probably only one id string to identify the
* object at the given coordinate.
* @deprecated Use getInfoForFeatureAt instead.
* @param strings The strings are put here. Send them to the server.
* @return The number of items found.
*/
int getServerIDStringForFeaturesAt( std::vector<MC2SimpleString>& strings,
const MC2Point& point );
/**
* Set the user defined features that should be drawn after
* the map.
*/
void setUserDefinedFeatures( std::vector<UserDefinedFeature*>* features );
/**
* Returns the poi categories or NULL if not loaded yet.
* Must _not_ be saved since the vector can disappear
* anytime after you have left your calling method.
*/
const std::vector<const TileCategory*>* getCategories() const;
/**
* Synchronizes the layer info between the local copy
* and the copy of the ui.
* @return True if the info was updated and may need to be
* re-displayed.
*/
bool updateLayerInfo( TileMapLayerInfoVector& info );
/**
* Enable or disable a category with the specified id.
* Will not work correctly until getCategories returns non-NULL.
* @param id The id of the parameter to disable/enable.
* @param enabled True/false.
* @return True if the category id was found.
*/
bool setCategoryEnabled( int id, bool enabled );
/**
* Sets tracking mode on or off.
* On (true) means that all of the map is drawn at once, including the
* edges of the streets and that the texts are moved with the map
* to be updated correctly later.
*/
//void setTrackingMode( bool on );
/**
* Returns the layer id:s and descriptions. If the vector is NULL
* it means that the layers and descriptions have not arrived
* yet, try again later. The ids are the ids to use when
* choosing which layers to display.
*/
const TileMapLayerInfoVector* getLayerIDsAndDescriptions() const;
/**
* Returns the detail level for the layer.
* FOR DEBUG!
*/
uint32 getDetailLevelForLayer(uint32 layerID) const;
void setInterpolationDebugInfo( InterpolationDebugVector v );
/**
* Returns the total map size for the maps loaded so far.
* Only for DEBUG!.
*/
uint32 getTotalMapSize() const;
void drawPoint( MC2Coordinate center,
unsigned int color,
unsigned int size);
void drawPoint( MC2Point center,
unsigned int color,
unsigned int size);
/**
* Dups the sizes of the maps to mc2dbg.
* Only for DEBUG!.
*/
void dumpMapSizes() const;
/**
* Requests that the screen should be repainted soon.
*/
void requestRepaint();
/**
* Requests that the display should be repainted now.
*/
void repaintNow() {
repaint(0);
}
/**
* Sends the signal that we are ready to move to an
* interpolated position, if available. Typically called
* after drawing.
*/
void requestPositionInterpolation();
/**
* Called when the position interpolation request timer has
* expired.
*/
void positionInterpolationTimerExpired();
/**
* Puts the dimensions of the displayed map in the
* variables.
*/
PixelBox getMapSizePixels() const;
/**
* Set the position of the copyright string of the map.
* @param pos The left baseline position of the copyright string.
*/
void setCopyrightPos( const MC2Point& pos );
/**
* Set if to show copyright string.
*/
void showCopyright( bool show );
template<class VECTOR> void getAllRequesters( VECTOR& dest ) {
if ( m_requester ) {
m_requester->getAllRequesters( dest );
}
}
/// @return If MapLib is initialized or not.
bool isInitialized() const;
// -- Implementation of MapMovingInterface - all is repeated...
void setMovementMode( bool moving ) {
setMoving( moving );
}
/**
* Yet another interface to clicking.
* Returns a reference to info for the feature at the specified
* position on the screen.
* @param point The point on the screen where
* the info should be found.
* @param onlyPois True if only poi info should be returned.
*/
const ClickInfo&
getInfoForFeatureAt( const MC2Point& point,
bool onlyPois,
TileMapInfoCallback* infoCallback = NULL );
const MC2Coordinate& getCenter() const;
void transform( MC2Point& point,
const MC2Coordinate& coord ) const;
void inverseTransform( MC2Coordinate& coord,
const MC2Point& point ) const;
void setCenter( const MC2Coordinate& newCenter );
void setPoint(const MC2Coordinate& newCoord,
const MC2Point& screenPoint );
/**
* Sets the specified point on the screen to the
* specified coordinate and rotate around that point.
*
* This method call result in the same thing as below,
* but more efficiently implemented:
*
* setPoint( newCoord, screenPoint );
* setAngle( angleDegrees, screenPoint );
*
*
* @param newCoord The new coordinate to move the specified
* point to.
* @param screenPoint The point on the screen to set to the
* specified coordinate.
* @param angle The angle in degrees to rotate around
* the screenPoint.
*/
void setPoint(const MC2Coordinate& newCoord,
const MC2Point& screenPoint,
double angleDegrees );
inline void move( int deltaX, int deltaY ) {
MapProjection::move( deltaX, deltaY );
}
void setAngle(double angleDegrees);
void setAngle( double angleDegrees,
const MC2Point& rotationPoint );
/**
* Rotates the display the supplied number of degrees.
*/
void rotateLeftDeg(int nbrDeg);
inline double getAngle() const {
return MapProjection::getAngle();
}
inline double setScale( double scale ) {
return MapProjection::setDPICorrectedScale( scale );
}
inline double getScale() const {
return MapProjection::getDPICorrectedScale();
}
double zoom( double factor );
double zoom( double factor,
const MC2Coordinate& zoomCoord,
const MC2Point& zoomPoint );
void setPixelBox( const MC2Point& oneCorner,
const MC2Point& otherCorner );
void setWorldBox( const MC2Coordinate& oneCorner,
const MC2Coordinate& otherCorner );
bool canHandleScreenAsBitmap() const;
void moveBitmap(int deltaX, int deltaY);
void setPointBitmap( const MC2Point& screenPoint );
void setBitmapDragPoint( const MC2Point& dragPoint );
void zoomBitmapAtPoint( double factor,
const MC2Point& screenPoint );
void zoomBitmapAtCenter( double factor );
protected:
/**
* Called by tranformmatrix to tell TileMapHandler that
* the matrix has been updated.
*/
void matrixUpdated();
public:
/**
* Adds an event listener to be called when new categories
* are available and if cache info needs update.
*/
void addEventListener( TileMapEventListener* listener );
/**
* Removes an event listener.
*/
void removeEventListener( TileMapEventListener* listener );
/**
* Sends a TileMapEvent to all listeners.
*/
void sendEvent( const TileMapEvent& event );
/* returns true if the specified layer is already visible,
else false. FIXME: Un-inline this function */
bool isLayerVisible(int layerNo) {
return m_layersToDisplay.find( layerNo ) != m_layersToDisplay.end();
}
/**
* sets the specified layer for display if it is not getting displayed,
* else sets it to not be displayed.
*/
void toggleLayerToDisplay(int layerNo);
/**
* Get's a reference to the screen coords for the feature.
* To be used by the textplacement.
*/
VectorProxy<MC2Point>& getScreenCoords( TileMap& tileMap,
TilePrimitiveFeature& feature );
/**
* Get the outer pixel width of the polyline.
*/
uint32 getPolylineOuterPixelWidth(
const TilePrimitiveFeature& prim ) const;
/**
* Set the pixelbox for the progress indicator text.
*/
void setProgressIndicatorBox( const PixelBox& box );
/**
* @return The DBufRequestListener.
*/
DBufRequestListener* getDBufRequestListener() const;
/**
* @return the interpolation hint consumer, which in our case
* is the position interpolator.
*/
PositionInterpolator* getPositionInterpolator();
/**
* Sets the callback that will receive new position related
* information from the interpolation, when available.
*/
void setInterpolationCallback( InterpolationCallback* callback );
/**
* Clears the callback previously set with setInterpolationCallback.
*/
void clearInterpolationCallback( InterpolationCallback* callback );
/**
* True if we are currently interpolating positions
*/
bool getInterpolatingPositions() const;
/**
* Sets if we should interpolate positions or not.
*
*/
void setInterpolatingPositions( bool enabled );
/**
* Set timing info to display or null.
*/
void setTMKTimingInfo( const TMKTimingInfo* info ) {
m_tmkTimingInfo = info;
}
/**
* Sets the bbox and sets routeID if route param str.
*
* @param paramString The tilemap param string.
*/
void setBBoxFromParamStr( const MC2SimpleString& paramString );
/**
* Get the next point that contains a feature that could be
* highlighted.
* @param point [IN] The point to be set to the next highlightable
* feature.
* @return True if a highlightable feature was found and thus
* if the point was updated. False otherwise.
*/
bool getNextHighlightPoint( MC2Point& point );
/**
* Set if the map is moving or not.
*/
void setMoving( bool moving );
/**
* Set if to detect movement by self, or by someone using the
* setMoving method.
*/
void setDetectMovementBySelf( bool detectSelf );
/**
* Turns the night mode on or off.
**/
void setNightModeL( bool aOn );
/// Temporary method that returns the 3D settings for modification.
Settings3D& getSettings3D();
/**
* Turns 3d mode on or off.
*/
void set3dMode( bool on );
/**
* Turns outlines on in 3d mode.
*/
void setOutlinesIn3dEnabled( bool enabled );
/**
* True if in 3d mode, false if not.
*/
bool get3dMode( );
/**
* True if in outlines are enabled in 3d mode, false if not.
*/
bool getOutlinesIn3dEnabled( ) const;
/**
* Sets the horizon height that is displayed
* when map is displayed in 3d.
* @param height The height of the horizon.
*/
void setHorizonHeight( uint32 height );
/**
* Get the ACP mode setting. True if ACP enabled, false if not.
*/
bool isACPModeEnabled() const;
/**
* Set the ACP mode setting. True if ACP enabled, false if not.
*/
void setACPModeEnabled( bool enable );
private:
friend class TileMapHandlerReleaseChecker;
/// Easiest way to solve this right now
friend class MapLib;
/// Easiest way to solve this right now
friend class MapLibInternal;
/// For use in MapLib.
DBufRequester* getInternalRequester() {
return m_requester;
}
/**
* Converts a bit map desc from the server to a bitmap name.
*/
MC2SimpleString bitMapDescToBitMapName(const MC2SimpleString& desc);
/**
* Converts a bit map name to a desc to use when requesting from
* the server.
*/
MC2SimpleString bitMapNameToDesc( const MC2SimpleString& name );
/**
* Gets a bitmap from the internal storage and returns it if
* it is there. If it is not there, the function will add it to
* the queue of buffers to be fetched from the server and return
* NULL.
*/
isab::BitMap* getOrRequestBitMap( const MC2SimpleString& name,
bool shouldScale = false );
/**
* Request the cached TMFDs ([Dd]XXX, [Dd]YYY).
*/
void requestCachedTMFD();
/**
* Requests the desc from cache or by requesting it from
* the requester.
* @param desc DataBuffer to send for.
* @param reqType The type of source that the desc may be requested
* from. Default is both cache or internet.
* @return True if the buffer was found in the cache.
*/
bool requestFromCacheOrForReal(
const MC2SimpleString& desc,
const DBufRequester::request_t& reqType =
DBufRequester::cacheOrInternet );
/**
* Clear coordinates for the feature.
*/
inline void clearCoords( TilePrimitiveFeature& feat );
/**
* Prepares the coordinates of the feature to work with
* the current screen.
*/
inline int prepareCoordinates(TileMap& tileMap,
TilePrimitiveFeature& feat,
const MC2BoundingBox& bbox);
/**
* Plots a feature containing polyline stuff.
* @param color The color in rrggbb.
* @param lineWidth Line width in pixels.
* @return Number of coordinates drawn.
*/
inline int plotPolyLines(const TilePrimitiveFeature& feat,
uint32 color,
int lineWidth );
/**
* Plots a polygon.
* @return Number of coordinates drawn.
*/
inline int plotPolygon(const MC2BoundingBox& bbox,
TileMap& tilemap,
const TilePrimitiveFeature& feat,
uint32 color );
/**
* Called by dataBufferReceived when the BitBuffer
* contains a tileMap.
* @param removeFromCache [OUT] Descs that are to be removed
* from the cache.
* @return True if everything was ok. False if the map contained
* unknown features and therefore the mapdesc should be
* rerequested.
*/
inline bool tileMapReceived(const MC2SimpleString& descr,
BitBuffer& buffer,
std::vector<TileMapParams>& removeFromCache );
/**
* Get which maps to plot.
* @param maps [Out] The maps to plot.
* @return True if the outparameter contains the maps to plot.
* False if m_mapVector should be used instead.
*/
bool getWhichMapsToPlot( std::vector<TileMap*>& maps );
/**
* @return If the feature is within the current scale.
*/
int checkScale( const TilePrimitiveFeature& feature ) const;
/**
* Draw the progess indicator.
*/
void drawProgressIndicator();
/**
* Plots the maps that we have already.
*/
void plotWhatWeGot( );
/**
* Plots the maps in a certain bounding box only.
*/
void plotWhatWeGotInBBox( const MC2BoundingBox& bbox,
int skipOutLines,
int lowQualityDrawing,
int& nbrFeatures,
int& nbrDrawn );
/**
* Draws the debug strings if enabled.
*/
void drawDebugStrings();
void drawDebugText( const char* text,
const MC2Point& position );
/**
* Draws interpolation related information.
*/
void drawInterpolationDebugInfo();
/**
* Get the inner pixel width of the polyline.
*/
inline uint32 getPolylineInnerPixelWidth(
const TilePrimitiveFeature& prim ) const;
/**
* Plots a polygon or line feature.
* @return The number of coordinates plotted.
*/
inline int plotPolygonOrLineFeature( const MC2BoundingBox& bbox,
TileMap& tilemap,
const TilePrimitiveFeature& prim,
int pass,
int moving );
/**
* Converts the coordinates in the CoordArg of primWithCoordArg
* to screen coordinates.
* @return True if there were coordinates in the feature and they
* were inside the bbox.
*/
inline bool getXYFromCoordArg(
const TilePrimitiveFeature& primWithCoordArg,
const MC2BoundingBox& bbox,
int& x,
int& y ) const;
/**
* Plots a bitmap feature. Must have one coordinate.
*/
inline int plotBitMapFeature( TileMap& curMap,
TilePrimitiveFeature& prim,
const MC2BoundingBox& bbox,
int pass,
int moving );
/**
* Plots a circle feature. Must have one coordinate.
*/
inline int plotCircleFeature( TilePrimitiveFeature& prim,
const MC2BoundingBox& bbox,
int pass,
int moving );
int plotBBox( const MC2BoundingBox& bbox,
const MC2BoundingBox& screenBBox );
/**
* Plots a feature.
*/
inline int plotPrimitive( TileMap& curMap,
TilePrimitiveFeature& prim,
const MC2BoundingBox& bbox,
int pass,
int moving );
/**
* Returns true if one of the coordinates in coords
* is inside the boundingbox.
*/
inline static bool coordsInside(const CoordsArg& coords,
const MC2BoundingBox& bbox);
/**
* Returns true if the map with the given description
* is loaded.
*/
inline bool haveMap(const MC2SimpleString& desc) const;
/**
* Returns a pointer to the map with the given description
* or NULL if not loaded yet.
*/
inline TileMap* getMap(const MC2SimpleString& desc) const;
/**
* Returns true if new parameters have been created.
* @param oldParamsUpdated [Out] If the old params also
* were updated.
*/
bool getNewParams( bool& oldParamsUpdated );
/**
* Updates the parameters so that they are ok for the
* current display etc.
*/
void updateParams();
/**
* Debug method. Dumps the params.
*/
void dumpParams();
/**
* Checks the cache for the existance of the descr
* and then calls dataBufferReceived if the requested
* data was in a cache.
* @param descr Descr to request.
* @return True if the buffer was in cache.
*/
bool requestFromCacheAndCreate(const MC2SimpleString& descr);
/**
* Requests maxNbr maps or other buffers.
*/
void requestMaps(int maxNbr);
// -- Geometry
/**
* Returns the distance from the coordinate coord to the
* line described by the coordinates linefirst and
* lineSecond.
*/
static int64 sqDistanceCoordToLine(const TileMapCoord& coord,
const TileMapCoord& lineFirst,
const TileMapCoord& lineSecond,
float cosF );
/**
* Returns the minimum distance from a coordinate to
* a primitive.
*/
static int64 getMinSQDist(TileMap& tileMap,
const TileMapCoord& coord,
const TilePrimitiveFeature& prim,
float cosLat);
/**
* Returns the closest feature and map for the given point.
* @param primType [Optional] Default (MAX_INT32) is that
* all primitive types are processed,
* but setting the param to a specific primitive
* type (e.g. TilePrimitiveFeature::bitmap)
* will lead to that only that primitive
* type will be processed.
*/
std::pair<const TileMap*, const TilePrimitiveFeature*>
getFeatureAt(const MC2Point& points, uint32* distance = NULL,
int32 primType = MAX_INT32 );
/**
* Get name for feature.
*
* @param theMap The map.
* @param theFeature The feature to get the name of.
* @param infoCallback [Optional] Callback that will be called
* when the possibly missing string map is
* received.
*/
const char* getNameForFeature(
const TileMap& theMap,
const TilePrimitiveFeature& theFeature,
TileMapInfoCallback* infoCallback = NULL );
/**
* Returns the first primitive that is inside a polygon.
* Goes through the levels top down.
*/
std::pair<const TileMap*, const TilePrimitiveFeature*> getFirstInside(
const TileMapCoord& coord) const;
/**
* Get the bitmap's pixelbox. The method is not forgiving if
* submitting a non bitmap feature.
*/
PixelBox getPixelBoxForBitMap(
const TilePrimitiveFeature& bitmap ) const;
/**
* Returns the closest feature or null.
* @param primType MAX_INT32 means that
* all primitive types are processed,
* but setting the param to a specific primitive
* type (e.g. TilePrimitiveFeature::bitmap)
* will lead to that only that primitive
* type will be processed.
*/
inline const TilePrimitiveFeature*
getClosest(TileMap& tileMap,
const MC2Point& point,
const MC2Coordinate& coord,
TileMap::primVect_t::const_iterator begin,
TileMap::primVect_t::const_iterator end,
int64& mindist,
int primType ) const;
/// Plot the copyright string.
void plotCopyrightString( const char* copyrightString );
/// Plot the last copyright string.
void plotLastCopyrightString();
/// Force that the map is really redrawn from scratch on next repaint.
void forceRedrawOnNextRepaint();
// -- Variables
/**
* The MapPlotter can plot stuff, e.g. maps.
*/
MapPlotter* m_plotter;
/**
* Points to the 2d plotter, normal map plotter.
*/
MapPlotter* m_plotter2d;
/**
* Pointer to the 3d plotter.
*/
PlotterAdapter3d* m_plotter3d;
/**
* The DBufRequester can request BitBuffers from
* server or e.g. a file using a string as key.
*/
DBufRequester* m_requester;
/**
* The current platform.
*/
TileMapToolkit* m_toolkit;
/**
* The MapFormatDescription.
*/
TileMapFormatDesc* m_mapFormatDesc;
/**
* The current databufferlistener.
*/
DBufRequestListener* m_dataBufferListener;
/**
* The text handler.
*/
TileMapTextHandler* m_textHandler;
/**
* The id of the timer of the textHandler.
*/
uint32 m_textHandlerIdleID;
/**
* If == 0 we are not painting.
*/
int m_painting;
/**
* Callback to use when databuffer is received.
* Will release the buffer back to the requester.
* @param descr The received descr.
* @param dataBuffer The received dataBuffer.
* @param requestMore True if another buffer should be reuqested.
*/
void dataBufferReceived(const MC2SimpleString& descr,
BitBuffer* dataBuffer,
bool requestMore = true);
/**
* Requests a idle object if the text handler wants one
* @return True if the text handler wants to run.
*/
bool requestTextHandlerIdle();
/// Draws the texts from the TileMapTextHandler.
void drawTexts();
/// Draws one UserDefinedFeature and updates the coords of it
inline void drawOneUserDefinedFeature( UserDefinedFeature& userFeat );
/// Draws the user defined features if there are any.
void drawUserDefinedFeatures();
/// Plots some debug on the screen.
void printDebugStrings(const std::vector<MC2SimpleString>& strings,
const MC2Point& pos );
void printDebugStrings(const std::vector<MC2SimpleString>& strings);
/// Get the center point of the screen.
MC2Point getCenterPoint() const;
/**
* Get 2D point from screen point, i.e. a point for map projection usage.
*/
MC2Point getPoint2D( const MC2Point& screenPoint ) const;
MC2Pointf getPoint2Df( const MC2Point& screenPoint ) const;
/// Draw fps debug info.
void drawFps();
/// Update the copyright handler with data from tmfd.
void updateCopyrightHandler( const TileMapFormatDesc& tmfd );
/// Pointer to the outline feature
DirectedPolygon* m_outlinePolygon;
/**
* Time when the stuff was repainted last time.
*/
uint32 m_lastRepaintTime;
/// Type of the map where we store our bitmaps.
typedef std::map<MC2SimpleString, isab::BitMap*> bitMapMap_t;
/**
* Map containing the bitmaps for e.g. pois.
* The leading 'B' has been removed and also the extension.
*/
bitMapMap_t m_bitMaps;
/**
* Structure that encapsulates additional data related
* to an image request.
*/
struct ImageRequest {
bool shouldScale;
};
/**
* Map containing the bitmaps needed.
* The leading 'B' has been removed.
*/
std::map<MC2SimpleString, ImageRequest> m_neededBitMaps;
/**
* True if gzipped maps should be used.
*/
bool m_useGzip;
/**
* The id of the repaint timer if a repaint timer
* has been requested. Else 0.
*/
uint32 m_repaintTimerRequested;
/**
* The id of the detail repaint timer if a detail repaint timer
* has been requested. Else 0. Used for filling in missing details
* after a while of non-movement.
*/
uint32 m_detailRepaintTimerRequested;
/**
* The id of the position interpolation request timer.
*/
uint32 m_positionInterpolationRequested;
/**
* The callback that will receive new information from
* the interpolator, when available.
*/
InterpolationCallback* m_interpolationCallback;
/**
* True if there has been time for the detail repaint timer
* to run.
*/
int m_detailRepaintTimerHasBeenRun;
/**
* The id of a timer that will repaint the screen
* after the last received map in a batch.
*/
uint32 m_repaintAfterMapReceptionTimer;
/// Timer that handles re-requests of maps that have not arrived.
uint32 m_rerequestTimer;
/// Time for the re-request timer
uint32 m_rerequestTimerValue;
enum {
/// Minimum value for the re-request timer
c_minRerequestTimerValue = 7500,
/// Maximum value for the re-requsst timer.If above, it will be shut down
c_maxRerequestTimerValue = 5*60*1000,
};
/// True if the transformmatrix has changed since the last draw.
int m_matrixChangedSinceDraw;
/**
* The current detaillevel.
*/
int m_detailLevel;
/// Set of layers to display (e.g. map, route, pois)
std::set<int> m_layersToDisplay;
/// The route id or NULL.
RouteID* m_routeID;
/// The current language
LangTypes::language_t m_lang;
/// The overlap detector for bitmaps.
OverlapDetector<PixelBox> m_overlapDetector;
/// The current scale index.
int m_scaleIndex;
/// Random characters to put in request for DXXX
MC2SimpleString m_randChars;
/// List of debug printouts, a character in first and a time in second.
std::list<std::pair<char, uint32> > m_drawTimes;
/// Pointer to the list of user defined features.
std::vector<UserDefinedFeature*>* m_userDefinedFeatures;
MC2Coordinate m_lastInterpolatedCenter;
/// The garbage collector.
TileMapGarbage<TileMap> m_garbage;
/// The maps.
TileMapContainer* m_tileMapCont;
/// True if tracking mode is on
int m_trackingModeOn;
/// Set of features that are disabled for drawing.
std::set<int32> m_disabledParentTypes;
/// Event listener to inform e.g. when DXXX has arrived
std::vector<TileMapEventListener*> m_eventListeners;
/// True if highlight should be shown.
int m_showHighlight;
/// Highlight point
MC2Point m_highlightPoint;
/// This class should be able to call the Handler when DB is recv.
friend class TileMapHandlerDefaultDBListener;
/// This class needs the m_mapFormatDesc
friend class TileMapHandlerDBBufRequester;
/// Screen coords for the currently drawn feature.
std::vector<MC2Point> m_realScreenCoords;
VectorProxy<MC2Point> m_screenCoords;
/// The bitbuffer of the last loaded DXXX ( or null )
BitBuffer* m_dxxBuffer;
/// True if the crc for the DXXX has been received
int m_descCRCReceived;
/// Server's version of the crc
uint32 m_serverDescCRC;
/// The pixel box that the progress indicator text should be drawn into.
PixelBox m_progressIndicatorBox;
/// Current timing info from TileMapKeyHandler
const TMKTimingInfo* m_tmkTimingInfo;
/// True if a map has arrived since the map was repainted
bool m_mapArrivedSinceRepaint;
/// True if the outlines were drawn last time
bool m_outlinesDrawnLastTime;
/// Screen size the last time the screen was drawn
isab::Rectangle m_lastScreenSize;
/// Movement helper.
MovementHelper m_movementHelper;
/// Copyright string position.
MC2Point m_copyrightPos;
/// Release checker
TileMapHandlerReleaseChecker* m_releaseChecker;
/// If to show copyright.
bool m_showCopyright;
/// If in night mode.
bool m_nightMode;
/// If in 3d mode
bool m_3dOn;
/// If we should interpolate positions
bool m_interpolatingPositions;
/// If true, draw outlines in 3d mode.
bool m_outlinesIn3dEnabled;
/// The height of the horizon
uint32 m_horizonHeight;
/// Clickinfo to return.
TileMapHandlerClickResult* m_clickInfo;
/**
* Keeps track if we requested a string map due to a call of
* getNameForFeature.
*
* first is the string map desc that we are waiting for.
* second is the callback class that should be called once this desc
* is received. If NULL then we are not waiting for any info strings.
*/
std::pair<MC2SimpleString, TileMapInfoCallback*> m_waitingForInfoString;
/**
* The bitmap mover helper class.
*/
BitmapMovementHelper m_bitmapMover;
/**
* The copyright handler.
*/
CopyrightHandler m_copyrightHandler;
/**
* How many times the requesting maps parts of requestMaps()
* have been entered.
*/
int m_inRequestingMaps;
/// Used for getCenter() which returns a Coord reference.
MC2Coordinate m_tmpCoord;
/// Time since last redraw, used to calculate fps.
uint32 m_lastDrawTimeStamp;
/**
* The ACP mode setting. True if ACP enabled, false if not.
*/
bool m_acpModeEnabled;
/**
* An interpolator that can be used to smooth out position
* changes.
*/
PositionInterpolator* m_posInterpolator;
};
#endif // TILE_MAPHANDLER_H
| [
"[email protected]"
] | [
[
[
1,
1384
]
]
] |
4f94ccd657b45744b07594a80c129af2ef16ad24 | 50dc193d6b274aa7918e35c5dc96682d63b226b3 | /lab2/Lab1.cpp | 056f85dd82dea6f488d9def8434c4dfc0c3675ea | [] | no_license | Ryuho/CPE476 | d4a77277b6ee7bfbd93c9f0b090f31c775442eb7 | cc60e8516dff69cec279ac2e55b30e26466763bf | refs/heads/master | 2021-01-13T02:15:22.798497 | 2011-02-07T03:43:54 | 2011-02-07T03:43:54 | 1,261,991 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,021 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <GL/glut.h>
#include <GL/gl.h>
#include <math.h>
#include "SDL.h"
#include "MyVector.h"
#include "GameObject.h"
#include <string.h>
using namespace std;
#define FLT_MIN 1.1754E-38F
#define FLT_MAX 1.1754E+38F
SDL_Surface* screen = NULL;
SDL_Surface* subScreen = NULL;
//constants
const int _windowWidth = 1080;
const int _windowHeight = 780;
const unsigned winPoints = 30;
const float gameOverTime = 600.0;
const int totalEnemyCount = 1000;
Uint8* _keys;
//Mesh Vars
float cx, cy, cz;
float max_x, max_y, max_z, min_x, min_y, min_z;
float max_extent;
//Mouse Movement Vars
int mouseX = 0;
int mouseY = 0;
//CameraVars
float ang_x = 0.0;
float ang_y = 0.0;
float ang_z = 0.0;
float pos_x = 0.0;
float pos_y = 0.0;
float pos_z = 0.0;
float rightPlane, leftPlane, top, bottom, near, far;
//Game Vars
vector<GameObject> gameObjects;
//DisplayList Vars
GLuint DLid;
GLuint createDL(void);
//FPS Vars
unsigned frame = 0;
unsigned FPStime,timebase=0;
char FPSDisplay [11];
char ObjectDisplay[15];
//Points value
unsigned points = 0;
char PointsDisplay [11];
//seconds elapsed
unsigned seconds = 0;
char SecondsDisplay [11];
//game over
char GameOverDisplay [11];
//used for delta time
unsigned now = 0;
unsigned then = 0;
unsigned dt = 0;
//used for delta time
unsigned nowObj = 0;
unsigned thenObj = 0;
unsigned dtObj = 0;
//constants
float MOVE_DELTA = -0.002f;
float MOUSE_DELTA = 0.001f;
//enemy count
int eCount = 0;
// used for frucstrum
float lt[3];
float rt[3];
//bool to cull or not
bool cullToggle = false;
bool drawingMiniMap = false;
//GL light vars
GLfloat light_pos[4] = {0, 0, 1.5, 1.0};
GLfloat light_amb[4] = {0.6, 0.6, 0.6, 1.0};
GLfloat light_diff[4] = {0.6, 0.6, 0.6, 1.0};
GLfloat light_spec[4] = {0.8, 0.8, 0.8, 1.0};
GameObject player;
//Materials
typedef struct materialStruct {
GLfloat ambient[4];
GLfloat diffuse[4];
GLfloat specular[4];
GLfloat shininess[1];
} materialStruct;
materialStruct RedFlat = {
{0.3, 0.0, 0.0, 1.0},
{0.9, 0.0, 0.0, 1.0},
{0.0, 0.0, 0.0, 1.0},
{0.0}
};
materialStruct GreenFlat = {
{0.0, 0.3, 0.0, 1.0},
{0.0, 0.9, 0.0, 1.0},
{0.0, 0.0, 0.0, 1.0},
{0.0}
};
materialStruct BlueFlat = {
{0.0, 0.0, 0.3, 1.0},
{0.0, 0.0, 0.9, 1.0},
{0.0, 0.0, 0.0, 1.0},
{0.0}
};
/**an example of a simple data structure to store a 4x4 matrix */
GLfloat ProjectionMatrix[4][4] = {
{1.0, 0.0, 0.0, 0.0},
{0.0, 1.0, 0.0, 0.0},
{0.0, 0.0, 1.0, 0.0},
{0.0, 0.0, 0.0, 1.0}
};
GLfloat ModelViewMatrix[4][4] = {
{1.0, 0.0, 0.0, 0.0},
{0.0, 1.0, 0.0, 0.0},
{0.0, 0.0, 1.0, 0.0},
{0.0, 0.0, 0.0, 1.0}
};
GLfloat ProjectionTimesModelview[4][4] = {
{1.0, 0.0, 0.0, 0.0},
{0.0, 1.0, 0.0, 0.0},
{0.0, 0.0, 1.0, 0.0},
{0.0, 0.0, 0.0, 1.0}
};
//TODO define objects to store 1) vertices 2) faces - be sure you understand the file format
typedef struct vertice{
float x;
float y;
float z;
float normX;
float normY;
float normZ;
} vertice;
typedef struct triangle {
int one;
int two;
int three;
float normX;
float normY;
float normZ;
float centX;
float centY;
float centZ;
} triangle;
vertice center;
vector<vertice> verts;
vector<triangle> faces;
MyVector myVects;
//forward declarations of functions
void readLine(char* str);
void readStream(istream& is);
void setMaterial(materialStruct materials) {
glMaterialfv(GL_FRONT, GL_AMBIENT, materials.ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, materials.diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, materials.specular);
glMaterialfv(GL_FRONT, GL_SHININESS, materials.shininess);
}
//open the file for reading
void ReadFile(char* filename) {
printf("Reading coordinates from %s\n", filename);
ifstream in_f(filename);
if (!in_f) {
printf("Could not open file %s\n", filename);
} else {
readStream(in_f);
}
}
void faceNorms()
{
for(int index = 0; index < faces.size();index++)
{
faces[index].normX = (verts[faces[index].three].x + verts[faces[index].two].x + verts[faces[index].one].x);
faces[index].normY = (verts[faces[index].three].y + verts[faces[index].two].y + verts[faces[index].one].y);
faces[index].normZ = (verts[faces[index].three].z + verts[faces[index].two].z + verts[faces[index].one].z);
float mag = sqrt(pow(faces[index].normX,2)+pow(faces[index].normY,2)+pow(faces[index].normZ,2));
faces[index].normX /= mag;
faces[index].normY /= mag;
faces[index].normZ /= mag;
}
}
void set_default_lt_rt()
{
lt[0] = pos_x - 5 * sin(ang_y - M_PI / 6.0f);
lt[1] = 9.0f;
lt[2] = pos_z - 5 * cos(ang_y - M_PI / 6.0f);
rt[0] = pos_x - 5 * sin(ang_y + M_PI / 6.0f);
rt[1] = 9.0f;
rt[2] = pos_z - 5 * cos(ang_y + M_PI / 6.0f);
}
//process the input stream from the file
void readStream(istream& is)
{
char str[256];
for (;is;) {
is >> ws;
is.get(str,sizeof(str));
if (!is) break;
is.ignore(9999,'\n');
readLine(str);
}
}
//process each line of input save vertices and faces appropriately
void readLine(char* str) {
int indx = 0, vi;
float x, y, z;
float r, g, b;
int mat;
if (str[0]=='#') return;
//read a vertex or face
if (str[0]=='V' && !strncmp(str,"Vertex ",7)) {
if (sscanf(str,"Vertex %d %g %g %g",&vi,&x,&y,&z) !=4)
{
printf("an error occurred in reading vertices\n");
#ifdef _DEBUG
exit(EXIT_FAILURE);
#endif
}
//TODO allocate an object to store the vertex or face
//store the vertex in a collection
vertice tempVert;
tempVert.x = x;
tempVert.y = y;
tempVert.z = z;
tempVert.normX = 0;
tempVert.normY = 0;
tempVert.normZ = 0;
verts.push_back(tempVert);
//This code is house keeping to display in center of the scene
cx += x;
cy += y;
cz += z;
if (x > max_x) max_x = x; if (x < min_x) min_x = x;
if (y > max_y) max_y = y; if (y < min_y) min_y = y;
if (z > max_z) max_z = z; if (z < min_z) min_z = z;
} else if (str[0]=='F' && !strncmp(str,"Face ",5)) {
triangle tempTri;
//TODO allocate an object to store the vertex or face
char* s=str+4;
int fi=-1;
for (int t_i = 0;;t_i++) {
while (*s && isspace(*s)) s++;
//if we reach the end of the line break out of the loop
if (!*s) break;
//save the position of the current character
char* beg=s;
//advance to next space
while (*s && isdigit(*s)) s++;
//covert the character to an integer
int j=atoi(beg);
//the first number we encounter will be the face index, don't store it
if (fi<0) { fi=j; continue; }
//otherwise process the digit we've grabbed in j as a vertex index
//the first number will be the face id the following are vertex ids
if (t_i == 1){
tempTri.one = j-1;
//TODO store the first vertex in your face object
}else if (t_i == 2){
tempTri.two = j -1 ;
//TODO store the second vertex in your face object
}else if (t_i == 3)
tempTri.three = j-1;
//TODO store the third vertex in your face object
//if there is more data to process break out
if (*s =='{') break;
}
//possibly process colors if the mesh has colors
if (*s && *s =='{'){
char *s1 = s+1;
cout << "trying to parse color " << !strncmp(s1,"rgb",3) << endl;
//if we're reading off a color
if (!strncmp(s1,"rgb=",4)) {
//grab the values of the string
if (sscanf(s1,"rgb=(%g %g %g) matid=%d",&r,&g,&b,&mat)!=4)
{
printf("error during reading rgb values\n");
#ifdef _DEBUG
exit(EXIT_FAILURE);
#endif
}
}
}
//store the triangle read in to your face collection
faces.push_back(tempTri);
//calcNormals(faces.size()-1);
}
faceNorms();
}
//A simple routine that prints the first three vertices and faces to test that you successfully stored the data your data structures....
void printFirstThree() {
for(int i = 0;i < 3; i++){
cout << verts[i].x << " " << verts[i].y << " " << verts[i].z << endl;
cout << "Faces " << verts[faces[i].one].x << " " << verts[faces[i].one].y << " " << verts[faces[i].one].z << endl;
}
cout << "Should be very first X " << verts[faces[0].one].x << endl;
}
void drawTria(int index) {
glBegin(GL_TRIANGLES);
glNormal3f(faces[index].normX,faces[index].normY ,faces[index].normZ);
glVertex3f(verts[faces[index].one].x,verts[faces[index].one].y,verts[faces[index].one].z);
glVertex3f(verts[faces[index].two].x,verts[faces[index].two].y,verts[faces[index].two].z);
glVertex3f(verts[faces[index].three].x,verts[faces[index].three].y,verts[faces[index].three].z);
glEnd();
}
void drawBunny(void){
for(unsigned int j = 0; j < faces.size(); j++) {
drawTria(j);
}
}
GLuint createDL() {
GLuint bunnyDL;
bunnyDL = glGenLists(1);
glNewList(bunnyDL,GL_COMPILE);
drawBunny();
glEndList();
return(bunnyDL);
}
void renderBitmapString(float x, float y, float z, char *string)
{
char *c;
glRasterPos3f(x, y,z);
for (c=string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
}
void drawWireFramePlane()
{
glPushMatrix(); {
// Draw Grid
setMaterial(BlueFlat);
glBegin(GL_LINES); {
for (float i = -8.0; i <= 8.0f; i += 1) {
glVertex3f(i, 0, -8.0f);
glVertex3f(i, 0, 8.0f);
glVertex3f(-8.0f, 0, i);
glVertex3f(8.0f, 0, i);
glVertex3f(i, 0, -4.0f);
glVertex3f(i, 0, 4.0f);
glVertex3f(-4.0f, 0, i);
glVertex3f(4.0f, 0, i);
}
}
glEnd();
}
glPopMatrix();
}
void setOrthographicProjection() {
// switch to projection mode
glMatrixMode(GL_PROJECTION);
// save previous matrix which contains the
//settings for the perspective projection
glPushMatrix();
// reset matrix
glLoadIdentity();
// set a 2D orthographic projection
gluOrtho2D(0, _windowWidth, 0, _windowHeight);
// invert the y axis, down is positive
glScalef(1, -1, 1);
// mover the origin from the bottom left corner
// to the upper left corner
glTranslatef(0, -_windowHeight, 0);
glMatrixMode(GL_MODELVIEW);
}
void resetPerspectiveProjection() {
// set the current matrix to GL_PROJECTION
glMatrixMode(GL_PROJECTION);
// restore previous settings
glPopMatrix();
// get back to GL_MODELVIEW matrix
glMatrixMode(GL_MODELVIEW);
}
void drawStats()
{
glPushMatrix();
frame++;
FPStime=glutGet(GLUT_ELAPSED_TIME);
if (FPStime - timebase > 1000) {
sprintf(FPSDisplay,"FPS:%4.2f",frame*1000.0/(FPStime-timebase));
sprintf(PointsDisplay,"H:%d",points);
timebase = FPStime;
frame = 0;
}
sprintf(SecondsDisplay,"%.2f sec",((float)seconds)/1000.0);
sprintf(ObjectDisplay,"# of objs: %d",gameObjects.size());
glColor3f(1.0, 0.0, 0.0);
glLoadIdentity();
setOrthographicProjection();
if(winPoints <= points){
sprintf(GameOverDisplay,"You Won!!");
//printf("Game Over!!\n");
renderBitmapString(_windowWidth/2-30,_windowHeight/2,0,GameOverDisplay);
if(gameOverTime+5.0 <= ((float)seconds)/1000.0){
exit(0);
}
}
else if(gameOverTime <= ((float)seconds)/1000.0){
sprintf(GameOverDisplay,"Game Over!!");
//printf("Game Over!!\n");
renderBitmapString(_windowWidth/2-50,_windowHeight/2,0,GameOverDisplay);
if(gameOverTime+5.0 <= ((float)seconds)/1000.0){
exit(0);
}
}
else{
renderBitmapString(1,15,0,FPSDisplay);
renderBitmapString(1,35,0,PointsDisplay);
renderBitmapString(1,55,0,SecondsDisplay);
renderBitmapString(1,75,0,ObjectDisplay);
}
resetPerspectiveProjection();
glPopMatrix();
}
void initViewFrustum()
{
glGetFloatv(GL_PROJECTION_MATRIX, *ProjectionMatrix);
glGetFloatv(GL_MODELVIEW_MATRIX, *ModelViewMatrix);
//Do Projection * ModelView
/*ma00*mb00 + ma01*mb10 + ma02*mb20 + ma03*mb30 ma00*mb01 + ma01*mb11 + ma02*mb21 + ma03*mb31 ma00*mb02 + ma01*mb12 + ma02*mb22 + ma03*mb32 ma00*mb03 + ma01*mb13 + ma02*mb23 + ma03*mb33
ma10*mb00 + ma11*mb10 + ma12*mb20 + ma13*mb30 ma10*mb01 + ma11*mb11 + ma12*mb21 + ma13*mb31 ma10*mb02 + ma11*mb12 + ma12*mb22 + ma13*mb32 ma10*mb03 + ma11*mb13 + ma12*mb23 + ma13*mb33
ma20*mb00 + ma21*mb10 + ma22*mb20 + ma23*mb30 ma20*mb01 + ma21*mb11 + ma22*mb21 + ma23*mb31 ma20*mb02 + ma21*mb12 + ma22*mb22 + ma23*mb32 ma20*mb03 + ma21*mb13 + ma22*mb23 + ma23*mb33
ma30*mb00 + ma31*mb10 + ma32*mb20 + ma33*mb30 ma30*mb01 + ma31*mb11 + ma32*mb21 + ma33*mb31 ma30*mb02 + ma31*mb12 + ma32*mb22 + ma33*mb32 ma30*mb03 + ma31*mb13 + ma32*mb23 + ma33*mb33*/
for(int i = 0; i < 4; i++)
{
ProjectionTimesModelview[i][0] = ProjectionMatrix[0][i] * ModelViewMatrix[0][0] + ProjectionMatrix[1][i] * ModelViewMatrix[0][1] + ProjectionMatrix[2][i] * ModelViewMatrix[0][2] + ProjectionMatrix[3][i] * ModelViewMatrix[0][3];
}
for(int i = 0; i < 4; i++)
{
ProjectionTimesModelview[i][1] = ProjectionMatrix[0][i] * ModelViewMatrix[1][0] + ProjectionMatrix[1][i] * ModelViewMatrix[1][1] + ProjectionMatrix[2][i] * ModelViewMatrix[1][2] + ProjectionMatrix[3][i] * ModelViewMatrix[1][3];
}
for(int i = 0; i < 4; i++)
{
ProjectionTimesModelview[i][2] = ProjectionMatrix[0][i] * ModelViewMatrix[2][0] + ProjectionMatrix[1][i] * ModelViewMatrix[2][1] + ProjectionMatrix[2][i] * ModelViewMatrix[2][2] + ProjectionMatrix[3][i] * ModelViewMatrix[2][3];
}
for(int i = 0; i < 4; i++)
{
ProjectionTimesModelview[i][3] = ProjectionMatrix[0][i] * ModelViewMatrix[3][0] + ProjectionMatrix[1][i] * ModelViewMatrix[3][1] + ProjectionMatrix[2][i] * ModelViewMatrix[3][2] + ProjectionMatrix[3][i] * ModelViewMatrix[3][3];
}
//Test Against Known Point then normalize!!
//float right, left, top, bottom, near, far;
float pointX = pos_x + -sin(ang_y);
float pointY = pos_y + sin(ang_x);
float pointZ = pos_z + -cos(ang_y);
//printf("x,y,z=%.2f\t%.2f\t%.2f| ang_x,ang_y=%.2f\t%.2f\n", pos_x, pos_y, pos_z, ang_x,ang_y);
//printf("point=%.2f\t%.2f\t%.2f\n", pointX, pointY, pointZ);
//glTranslatef(pointX, pointY, pointZ);
//glutSolidTeapot(0.1);
//glTranslatef(-pointX, -pointY, -pointZ);
rightPlane = (ProjectionTimesModelview[3][0]-ProjectionTimesModelview[0][0]) * pointX + (ProjectionTimesModelview[3][1]-ProjectionTimesModelview[0][1]) * pointY + (ProjectionTimesModelview[3][2]-ProjectionTimesModelview[0][2]) * pointZ + (ProjectionTimesModelview[3][3]-ProjectionTimesModelview[0][3]);
leftPlane = (ProjectionTimesModelview[0][0]+ProjectionTimesModelview[3][0]) * pointX + (ProjectionTimesModelview[0][1]+ProjectionTimesModelview[3][1]) * pointY + (ProjectionTimesModelview[0][2]+ProjectionTimesModelview[3][2]) * pointZ + (ProjectionTimesModelview[0][3]+ProjectionTimesModelview[3][3]);
bottom = (ProjectionTimesModelview[1][0]+ProjectionTimesModelview[3][0]) * pointX + (ProjectionTimesModelview[1][1]+ProjectionTimesModelview[3][1]) * pointY + (ProjectionTimesModelview[1][2]+ProjectionTimesModelview[3][2]) * pointZ + (ProjectionTimesModelview[1][3]+ProjectionTimesModelview[3][3]);
top = (ProjectionTimesModelview[3][0]-ProjectionTimesModelview[1][0]) * pointX + (ProjectionTimesModelview[3][1]-ProjectionTimesModelview[1][1]) * pointY + (ProjectionTimesModelview[3][2]-ProjectionTimesModelview[1][2]) * pointZ + (ProjectionTimesModelview[3][3]-ProjectionTimesModelview[1][3]);
far = (ProjectionTimesModelview[3][0]-ProjectionTimesModelview[2][0]) * pointX + (ProjectionTimesModelview[3][1]-ProjectionTimesModelview[2][1]) * pointY + (ProjectionTimesModelview[3][2]-ProjectionTimesModelview[2][2]) * pointZ + (ProjectionTimesModelview[3][3]-ProjectionTimesModelview[2][3]);
near = (ProjectionTimesModelview[2][0]+ProjectionTimesModelview[3][0]) * pointX + (ProjectionTimesModelview[2][1]+ProjectionTimesModelview[3][1]) * pointY + (ProjectionTimesModelview[2][2]+ProjectionTimesModelview[3][2]) * pointZ + (ProjectionTimesModelview[2][3]+ProjectionTimesModelview[3][3]);
if( rightPlane < 0 ||
leftPlane < 0 ||
top < 0 ||
bottom < 0 ||
far < 0 ||
near < 0 ){
cout << "the reference point became outside of the view angle, this should never happen!!!" << endl;
exit(0);
}
}
int culled(int index)
{
float rightTestObject, leftTestObject, topTestObject, bottomTestObject, nearTestObject, farTestObject;
rightTestObject = (ProjectionTimesModelview[3][0]-ProjectionTimesModelview[0][0]) * gameObjects[index].position.endX + (ProjectionTimesModelview[3][1]-ProjectionTimesModelview[0][1]) * gameObjects[index].position.endY + (ProjectionTimesModelview[3][2]-ProjectionTimesModelview[0][2]) * gameObjects[index].position.endZ + (ProjectionTimesModelview[3][3]-ProjectionTimesModelview[0][3]);
if(rightTestObject < 0)
{//cout << "right object failed" << rightTestObject << endl;
return 0;
}
leftTestObject = (ProjectionTimesModelview[0][0]+ProjectionTimesModelview[3][0]) * gameObjects[index].position.endX + (ProjectionTimesModelview[0][1]+ProjectionTimesModelview[3][1]) * gameObjects[index].position.endY + (ProjectionTimesModelview[0][2]+ProjectionTimesModelview[3][2]) * gameObjects[index].position.endZ + (ProjectionTimesModelview[0][3]+ProjectionTimesModelview[3][3]);
if(leftTestObject < 0)
{//cout << "left object failed " << leftTestObject << endl;
return 0;
}
topTestObject = (ProjectionTimesModelview[1][0]+ProjectionTimesModelview[3][0])/top * gameObjects[index].position.endX + (ProjectionTimesModelview[1][1]+ProjectionTimesModelview[3][1])/top * gameObjects[index].position.endY + (ProjectionTimesModelview[1][2]+ProjectionTimesModelview[3][2])/top * gameObjects[index].position.endZ + (ProjectionTimesModelview[1][3]+ProjectionTimesModelview[3][3])/top;
if(topTestObject < 0)
{
//cout << "top object failed " << topTestObject << endl;
return 0;
}
bottomTestObject = (ProjectionTimesModelview[3][0]-ProjectionTimesModelview[1][0])/bottom * gameObjects[index].position.endX + (ProjectionTimesModelview[3][1]-ProjectionTimesModelview[1][1])/bottom * gameObjects[index].position.endY + (ProjectionTimesModelview[3][2]-ProjectionTimesModelview[1][2])/bottom * gameObjects[index].position.endZ + (ProjectionTimesModelview[3][3]-ProjectionTimesModelview[1][3])/bottom;
if(bottomTestObject < 0)
{//cout << "bottom object failed " << bottomTestObject << endl;
return 0;
}
nearTestObject = (ProjectionTimesModelview[2][0]+ProjectionTimesModelview[3][0])/near * gameObjects[index].position.endX + (ProjectionTimesModelview[2][1]+ProjectionTimesModelview[3][1])/near * gameObjects[index].position.endY + (ProjectionTimesModelview[2][2]+ProjectionTimesModelview[3][2])/near * gameObjects[index].position.endZ + (ProjectionTimesModelview[2][3]+ProjectionTimesModelview[3][3])/near;
if(nearTestObject < 0)
{//cout << "near object failed " << nearTestObject << endl;
return 0;
}
farTestObject = (ProjectionTimesModelview[3][0]-ProjectionTimesModelview[2][0])/far * gameObjects[index].position.endX + (ProjectionTimesModelview[3][1]-ProjectionTimesModelview[2][1])/far * gameObjects[index].position.endY + (ProjectionTimesModelview[3][2]-ProjectionTimesModelview[2][2])/far * gameObjects[index].position.endZ + (ProjectionTimesModelview[3][3]-ProjectionTimesModelview[2][3])/far;
if(farTestObject < 0)
{//cout << "far object failed " << farTestObject << endl;
return 0;
}
//cout << rightTestObject << " " << leftTestObject << " " << topTestObject << " " << bottomTestObject << " " << farTestObject << " " << nearTestObject << endl;
//cout << "Passed all the test!" << endl;
return 1;
}
void drawGameObjects()
{
glPushMatrix();
for(int i = 0;i < gameObjects.size();i++)
{//cout << gameObjects.size() << endl;
glPushMatrix();
//glColor3f(gameObjects[i].R, gameObjects[i].G, gameObjects[i].B);
if(gameObjects[i].alive){
setMaterial(GreenFlat);
}
else{
setMaterial(RedFlat);
}
glTranslatef(gameObjects[i].position.endX,gameObjects[i].position.endY,gameObjects[i].position.endZ);
if (gameObjects[i].id > 9000)
{
glPushMatrix();
setMaterial(BlueFlat);
glTranslatef(0, 0.28f, 0);
glutSolidCube(0.5);
glPopMatrix();
}
else
{
if(!cullToggle){
glCallList(DLid);
}
else if(culled(i)){
glCallList(DLid);
}
/*else if (gameObjects[i].position.endX >= 0){
glCallList(DLid);
}*/
}
glPopMatrix();
}
glPopMatrix();
}
void drawMiniMap()
{
drawingMiniMap = true;
glPushMatrix();
/* Set the viewport to 3/4 of the way across the screen on the bottom.
* It should take up the bottom right corner of the screen.
*/
glViewport (_windowWidth*0.75, _windowHeight*0.75, _windowWidth/4, _windowHeight/4);
//glMatrixMode (GL_PROJECTION); /* Select The Projection Matrix */
glLoadIdentity (); /* Reset The Projection Matrix */
/* Set Up Ortho Mode To Fit 1/4 The Screen (Size Of A Viewport) */
//gluOrtho2D(0, GW/2, GH/2, 0);
//useOrtho();
glPushMatrix(); {
glRotatef(90, 1, 0, 0);
glTranslatef(0, -5.0f, 0);
// Draw a solid sphere that signifies you
//glColor3f(0, 1, 0);
glutSolidSphere(0.25f, 5, 5);
// Draw actual scene
glEnable(GL_LIGHTING);
glPushMatrix(); {
glTranslatef(-pos_x, 0, -pos_z);
drawWireFramePlane();
drawGameObjects();
}
glPopMatrix();
glDisable(GL_LIGHTING);
/* broken for now...
// Draw neat blended viewing frustum
glEnable(GL_BLEND);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_ALWAYS, 0.01);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix(); {
glColor4f(1, 0, 0, 0.5f);
glBegin(GL_TRIANGLES);
glVertex3f(pos_x,pos_y,pos_z);
glVertex3f(lt[0], lt[1], lt[2]);
glVertex3f(rt[0], rt[1], rt[2]);
glEnd();
}
glPopMatrix();
glDisable(GL_BLEND);
glDisable(GL_ALPHA_TEST);
*/
}
glPopMatrix();
glEnable(GL_LIGHTING);
SDL_GL_SwapBuffers();
drawingMiniMap = false;
}
void setCameraMode(int width, int height) // reshape the window when it's moved or resized
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90,(float)width/(float)height,0.1,15);
glMatrixMode(GL_MODELVIEW);
glViewport(0, 0, width, height);
}
GLvoid DrawScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
initViewFrustum();
glLoadIdentity();
glRotatef(360.0f - (ang_x * (180.0f / M_PI)), 1, 0, 0);
glRotatef(360.0f - (ang_y * (180.0f / M_PI)), 0, 1, 0);
glTranslatef(-pos_x, -pos_y, -pos_z);
glPointSize(3.0);
glBegin(GL_POINTS);
glColor3f(1.0,0,0);
glVertex3f(pos_x, pos_y, pos_z);
glEnd();
// Loop to draw the main viewport and the minimap
for (int loop = 0; loop < 2; loop++)
{
// Draw the main screen
if(loop == 0)
{
drawWireFramePlane();
drawGameObjects();
drawStats();
}
if(loop == 1)
{
drawMiniMap();
setCameraMode(_windowWidth, _windowHeight);
}
}
SDL_GL_SwapBuffers();
}
GLboolean CheckKeys(int dt)
{
bool moved = false;
if (_keys[SDLK_ESCAPE])
{
return true;
}
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
if (_keys[SDLK_s]) {
x += -MOVE_DELTA * sin(ang_y);
z += -MOVE_DELTA * cos(ang_y);
y += MOVE_DELTA * sin(ang_x);
moved = true;
}
if (_keys[SDLK_w]) {
x += MOVE_DELTA * sin(ang_y);
z += MOVE_DELTA * cos(ang_y);
y += -MOVE_DELTA * sin(ang_x);
moved = true;
}
if (_keys[SDLK_d]) {
x += -MOVE_DELTA * cos(ang_y);
z += MOVE_DELTA * sin(ang_y);
moved = true;
}
if (_keys[SDLK_a]) {
x += MOVE_DELTA * cos(ang_y);
z += -MOVE_DELTA * sin(ang_y);
moved = true;
}
if(_keys[SDLK_KP_PLUS]){
MOVE_DELTA += -0.0002f;
}
if(_keys[SDLK_KP_MINUS]){
MOVE_DELTA -= -0.0002f;
}
if(moved)
{
//increment the amount of (speed * time) = distance
pos_x += x * dt;
pos_y += y * dt;
pos_z += z * dt;
player.position.endX = pos_x;
player.position.endY = pos_y;
player.position.endZ = pos_z;
if (pos_y < 0.0f)
{
pos_y = 0.0f;
}
}
//check for collison with game objects
int objIndex = player.collidingWithObjects(gameObjects);
while(objIndex != -1 && gameObjects[objIndex].id <= 9000)
{
cout << "Player collided with #" << objIndex << "!" << endl;
//gameObjects.erase (gameObjects.begin()+objIndex);
gameObjects[objIndex].alive = false;
gameObjects[objIndex].R = 0.5;
gameObjects[objIndex].B = 0.0;
points++;
objIndex = player.collidingWithObjects(gameObjects);
}
if(_keys[SDLK_HOME]){
pos_x = 0;
pos_y = 0;
pos_z = 0;
ang_x = 0;
ang_y = 0;
ang_z = 0;
}
set_default_lt_rt();
return false;
}
float randWrap(float min, float max)
{
return min+((max-min)*rand()/(RAND_MAX));
}
Uint32 spawnGameObj(Uint32 interval, void *param)
{
if(gameObjects.size() < totalEnemyCount)
{
gameObjects.push_back(GameObject(eCount,MyVector(0.0f,0.0f,0.0f,randWrap(-4.0,4.0),-.03f,randWrap(-4.0,4.0)),
MyVector(0.0f,0.0f,0.0f,randWrap(-4.0,4.0),0.0,randWrap(-4.0,4.0)), randWrap(0.001,0.004),-.07f,0.f,-.07f,.07f,.17f,.07f));
eCount++;
}
return interval;
}
Uint32 gameObjStep(Uint32 interval, void *param)
{
nowObj = glutGet(GLUT_ELAPSED_TIME);
dtObj = nowObj - thenObj;
for(int i = 0; i < gameObjects.size();i++)
{
gameObjects[i].step(dtObj,&gameObjects);
}
thenObj = glutGet(GLUT_ELAPSED_TIME);
return interval;
}
void pos_light() {
//set the light's position
glMatrixMode(GL_MODELVIEW);
glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
glLightfv(GL_LIGHT1, GL_POSITION, light_pos);
glLightfv(GL_LIGHT2, GL_POSITION, light_pos);
glLightfv(GL_LIGHT3, GL_POSITION, light_pos);
}
void glInit()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHT0);
//set up the diffuse, ambient and specular components for the light
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diff);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_amb);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_spec);
//specify our lighting model as 1 normal per face
glShadeModel(GL_FLAT);
glEnable(GL_LIGHTING);
pos_light();
}
int main(int argc, char *argv[])
{
//Initialization
glutInit(&argc, argv);
max_x = max_y = max_z = FLT_MIN;
min_x = min_y = min_z = FLT_MAX;
cx =cy = cz = 0;
max_extent = 1.0;
player = GameObject(-1, MyVector(0.f,0.f,0.f,0.f,0.f,0.f), MyVector(0.f,0.f,0.f,0.f,0.f,0.f),0,-0.1f,-0.1f,0.f,0.1f,0.1f,0.1f);
//player.setBoundingBox(-0.1, -0.1, 0, 0.1, 0.1, 0.1);
//SDL INITIALIZATIONS
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
cout << "Unable to initialize SDL: " << SDL_GetError() << endl;
exit(1);
}
screen = SDL_SetVideoMode(_windowWidth, _windowHeight, 0, SDL_OPENGL );
//subScreen = SDL_SetVideoMode(800, 600, 0, SDL_OPENGL);
if (screen == NULL)
{
cout << "Unable to create OpenGL scene: " << SDL_GetError() << endl;
exit(2);
}
glClearColor( 1.0, 1.0 ,1.0, 1);
void *param;
//TIMER CODE
srand(time(NULL));
SDL_Init(SDL_INIT_TIMER);
SDL_AddTimer(Uint32 (100), spawnGameObj, param);
SDL_AddTimer(Uint32 (10), gameObjStep, param);
gameObjects.push_back(GameObject(9001,MyVector(0.0f,0.0f,0.0f,randWrap(-8.0,8.0),-.03f,randWrap(-8.0,8.0)),
MyVector(0.0f,0.0f,0.0f,0.0f,0.0f,0.0f), 0,-.17f,0.f,-.25f,.25f,.25f,.25f));
gameObjects.push_back(GameObject(9002,MyVector(0.0f,0.0f,0.0f,randWrap(-8.0,8.0),-.03f,randWrap(-8.0,8.0)),
MyVector(0.0f,0.0f,0.0f,0.0f,0.0f,0.0f), 0,-.17f,0.f,-.25f,.25f,.25f,.25f));
gameObjects.push_back(GameObject(9003,MyVector(0.0f,0.0f,0.0f,randWrap(-8.0,8.0),-.03f,randWrap(-8.0,8.0)),
MyVector(0.0f,0.0f,0.0f,0.0f,0.0f,0.0f), 0,-.17f,0.f,-.25f,.25f,.25f,.25f));
gameObjects.push_back(GameObject(9004,MyVector(0.0f,0.0f,0.0f,randWrap(-8.0,8.0),-.03f,randWrap(-8.0,8.0)),
MyVector(0.0f,0.0f,0.0f,0.0f,0.0f,0.0f), 0,-.17f,0.f,-.25f,.25f,.25f,.25f));
gameObjects.push_back(GameObject(9005,MyVector(0.0f,0.0f,0.0f,randWrap(-8.0,8.0),-.03f,randWrap(-8.0,8.0)),
MyVector(0.0f,0.0f,0.0f,0.0f,0.0f,0.0f), 0,-.17f,0.f,-.25f,.25f,.25f,.25f));
//(int _id, MyVector _position, MyVector _direction, float _velocity,float llx, float lly, float llz, float urx, float ury, float urz)
//ENDTIMER CODE
setCameraMode(_windowWidth, _windowHeight);
//////////////////////////////Mesh Initialize Code//////
//make sure a file to read is specified
if (argc > 1) {
cout << "file " << argv[1] << endl;
//read-in the mesh file specified
ReadFile(argv[1]);
//only for debugging
printFirstThree();
//once the file is parsed find out the maximum extent to center and scale mesh
max_extent = max_x - min_x;
if (max_y - min_y > max_extent) max_extent = max_y - min_y;
cout << "max_extent " << max_extent << " max_x " << max_x << " min_x " << min_x << endl;
cout << "max_y " << max_y << " min_y " << min_y << " max_z " << max_z << " min_z " << min_z << endl;
center.x = 0;
center.y = 0;
center.z = 1;
//TODO divide by the number of vertices you read in!!!
center.x = cx/verts.size();
center.y = cy/verts.size();
center.z = cz/verts.size();
cout << "center " << center.x << " " << center.y << " " << center.z << endl;
cout << "scale by " << 1.0/(float)max_extent << endl;
}
else
{
cout << "format is: meshparser filename" << endl;
}
//////////////////////////////End Mesh Code////////////
// Set window title
SDL_WM_SetCaption("Lab1", 0);
SDL_ShowCursor(SDL_DISABLE);
then = glutGet(GLUT_ELAPSED_TIME);
_keys = SDL_GetKeyState(NULL);
now = glutGet(GLUT_ELAPSED_TIME);
nowObj = glutGet(GLUT_ELAPSED_TIME);
dt = now - then;
dtObj = nowObj - thenObj;
int running = 1;
DLid = createDL();
glInit();
while (running)
{
DrawScene();
SDL_Event event;
float mouseButtonDown = 0;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT){
running = 0;
}
if(event.type == SDL_MOUSEMOTION){
mouseX = event.motion.xrel;
mouseY = event.motion.yrel;
ang_y -= mouseX * MOUSE_DELTA;
ang_x -= mouseY * MOUSE_DELTA;
if(ang_x <= -(M_PI/2.0))
{
ang_x = -(M_PI/2.0);
}
if(ang_x >= (M_PI/2.0))
{
ang_x = (M_PI/2.0);
}
SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
SDL_WarpMouse(_windowWidth/2, _windowHeight/2);
SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);
}
if(event.type == SDL_MOUSEBUTTONDOWN)
{
printf("Mouse button %d pressed at (%d,%d)\n",event.button.button, event.button.x, event.button.y);
mouseButtonDown = 1;
cullToggle = !cullToggle;
}
if (event.type == SDL_MOUSEBUTTONUP)
{
printf("The mouse is up\n");
mouseButtonDown = 0;
}
_keys = SDL_GetKeyState(NULL);
}
now = glutGet(GLUT_ELAPSED_TIME);
dt = now - then;
seconds += dt;
if (CheckKeys(dt)){
running = 0;
}
then = glutGet(GLUT_ELAPSED_TIME);
}
SDL_Quit();
return 0;
}
| [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
7
],
[
9,
21
],
[
24,
26
],
[
29,
37
],
[
40,
46
],
[
48,
57
],
[
60,
97
],
[
99,
116
],
[
121,
123
],
[
127,
130
],
[
134,
134
],
[
136,
188
],
[
190,
341
],
[
343,
350
],
[
352,
352
],
[
354,
355
],
[
360,
360
],
[
366,
390
],
[
392,
393
],
[
395,
395
],
[
400,
409
],
[
411,
440
],
[
442,
443
],
[
446,
446
],
[
449,
449
],
[
453,
517
],
[
527,
527
],
[
529,
529
],
[
531,
531
],
[
533,
533
],
[
535,
535
],
[
549,
553
],
[
555,
555
],
[
558,
558
],
[
562,
563
],
[
565,
565
],
[
569,
569
],
[
571,
571
],
[
573,
573
],
[
579,
579
],
[
585,
585
],
[
589,
589
],
[
591,
592
],
[
595,
599
],
[
601,
609
],
[
612,
665
],
[
668,
673
],
[
675,
691
],
[
693,
701
],
[
703,
704
],
[
707,
710
],
[
714,
714
],
[
716,
718
],
[
722,
731
],
[
735,
741
],
[
744,
745
],
[
747,
747
],
[
749,
749
],
[
751,
760
],
[
762,
767
],
[
769,
773
],
[
775,
779
],
[
781,
830
],
[
833,
834
],
[
836,
852
],
[
854,
888
],
[
896,
898
],
[
900,
906
],
[
909,
912
],
[
914,
915
],
[
917,
937
],
[
940,
940
],
[
966,
967
],
[
971,
971
],
[
973,
977
],
[
979,
984
],
[
986,
986
],
[
988,
990
],
[
992,
992
],
[
994,
994
],
[
1001,
1001
],
[
1003,
1014
],
[
1016,
1018
],
[
1024,
1024
],
[
1035,
1036
],
[
1039,
1040
],
[
1043,
1043
],
[
1046,
1046
]
],
[
[
8,
8
],
[
22,
23
],
[
27,
28
],
[
38,
39
],
[
47,
47
],
[
58,
59
],
[
98,
98
],
[
342,
342
],
[
351,
351
],
[
353,
353
],
[
356,
359
],
[
361,
365
],
[
391,
391
],
[
396,
399
],
[
410,
410
],
[
441,
441
],
[
444,
445
],
[
447,
448
],
[
450,
452
],
[
518,
526
],
[
528,
528
],
[
530,
530
],
[
532,
532
],
[
534,
534
],
[
536,
548
],
[
554,
554
],
[
556,
557
],
[
559,
561
],
[
564,
564
],
[
566,
568
],
[
570,
570
],
[
572,
572
],
[
574,
578
],
[
580,
584
],
[
586,
588
],
[
590,
590
],
[
593,
594
],
[
600,
600
],
[
611,
611
],
[
666,
667
],
[
674,
674
],
[
692,
692
],
[
702,
702
],
[
705,
706
],
[
711,
713
],
[
715,
715
],
[
719,
721
],
[
732,
734
],
[
742,
743
],
[
746,
746
],
[
748,
748
],
[
750,
750
],
[
761,
761
],
[
768,
768
],
[
774,
774
],
[
780,
780
],
[
831,
832
],
[
835,
835
],
[
853,
853
],
[
889,
895
],
[
899,
899
],
[
907,
908
],
[
913,
913
],
[
916,
916
],
[
938,
939
],
[
941,
965
],
[
968,
970
],
[
972,
972
],
[
978,
978
],
[
985,
985
],
[
987,
987
],
[
991,
991
],
[
993,
993
],
[
995,
1000
],
[
1002,
1002
],
[
1015,
1015
],
[
1019,
1023
],
[
1025,
1034
],
[
1037,
1038
],
[
1041,
1042
],
[
1044,
1045
]
],
[
[
117,
120
],
[
124,
126
],
[
131,
133
],
[
135,
135
],
[
189,
189
],
[
394,
394
],
[
610,
610
]
]
] |
74fb2745298a1054688ebf2e49f566e39197aae2 | 4d3983366ea8a2886629d9a39536f0cd05edd001 | /src/main/config.cpp | 05ae8a0e7c3d6aed3a1710f7c96fffcae83de654 | [] | no_license | clteng5316/rodents | 033a06d5ad11928425a40203a497ea95e98ce290 | 7be0702d0ad61d9a07295029ba77d853b87aba64 | refs/heads/master | 2021-01-10T13:05:13.757715 | 2009-08-07T14:46:13 | 2009-08-07T14:46:13 | 36,857,795 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,690 | cpp | // config.cpp
#include "stdafx.h"
#include "sq.hpp"
#include "win32.hpp"
//================================================================================
extern SQInteger get_hotkeys(sq::VM v);
extern SQInteger set_hotkeys(sq::VM v);
extern void set_full_row_select(bool value);
extern void set_gridlines(bool value);
extern void set_show_hidden_files(bool value);
extern void set_folderview_flag(int value);
extern bool navigation_pane;
extern bool detail_pane;
extern bool preview_pane;
extern bool gridlines;
extern bool loop_cursor;
extern bool show_hidden_files;
extern int floating_preview;
extern int folderview_flag;
extern int folderview_mode;
extern WCHAR navigation_sound[MAX_PATH];
namespace
{
template < bool* Var > SQInteger get_bool(sq::VM v) { v.push(*Var); return 1; }
template < bool* Var > SQInteger set_bool(sq::VM v) { *Var = v.get<bool>(2); return 0; }
template < int* Var > SQInteger get_int(sq::VM v) { v.push(*Var); return 1; }
template < int* Var > SQInteger set_int(sq::VM v) { *Var = v.get<int>(2); return 0; }
template < PWSTR Var > SQInteger get_str(sq::VM v) { v.push(Var); return 1; }
template < PWSTR Var > SQInteger set_str(sq::VM v) { wcscpy_s(Var, MAX_PATH, v.get<PCWSTR>(2)); return 0; }
}
//================================================================================
#define def_bool(name) \
do { \
__if_exists (get_##name) { v.def(L"get_"_SC(#name), get_##name ); } \
__if_not_exists(get_##name) { v.def(L"get_"_SC(#name), get_bool<&name>); } \
__if_exists (set_##name) { v.def(L"set_"_SC(#name), set_##name ); } \
__if_not_exists(set_##name) { v.def(L"set_"_SC(#name), set_bool<&name>); } \
} while (0)
#define def_int(name) \
do { \
__if_exists (get_##name) { v.def(L"get_"_SC(#name), get_##name ); } \
__if_not_exists(get_##name) { v.def(L"get_"_SC(#name), get_int<&name>); } \
__if_exists (set_##name) { v.def(L"set_"_SC(#name), set_##name ); } \
__if_not_exists(set_##name) { v.def(L"set_"_SC(#name), set_int<&name>); } \
} while (0)
#define def_str(name) \
do { \
__if_exists (get_##name) { v.def(L"get_"_SC(#name), get_##name ); } \
__if_not_exists(get_##name) { v.def(L"get_"_SC(#name), get_str<name>); } \
__if_exists (set_##name) { v.def(L"set_"_SC(#name), set_##name ); } \
__if_not_exists(set_##name) { v.def(L"set_"_SC(#name), set_str<name>); } \
} while (0)
SQInteger def_config(sq::VM v)
{
// 環境依存の設定パラメータを初期化する。
if (WINDOWS_VERSION < WINDOWS_VISTA)
{
folderview_flag = 0;
detail_pane = false;
navigation_pane = false;
preview_pane = false;
}
// 環境依存の設定
SHELLFLAGSTATE sh;
SHGetSettings(&sh, SSF_SHOWALLOBJECTS);
show_hidden_files = (sh.fShowAllObjects != 0);
// object から派生する無名クラスを作成する。
sq_pushroottable(v);
sq::push(v, L"object");
sq_rawget(v, -2);
sq_newclass(v, SQTrue);
// 無名クラスにグローバル変数ハンドラを登録する。
def_bool(navigation_pane);
def_bool(detail_pane);
def_bool(preview_pane);
def_bool(gridlines);
def_bool(loop_cursor);
def_bool(show_hidden_files);
def_int(floating_preview);
def_int(folderview_flag);
def_int(folderview_mode);
def_str(navigation_sound);
v.def(L"get_keymap", get_hotkeys);
v.def(L"set_keymap", set_hotkeys);
// グローバル変数 config を作成する。
v.push(L"config");
SQ_VERIFY( sq_createinstance(v, -2) );
v.newslot(-5);
// 無名クラスは登録する必要がない。root と共に取り除く。
v.pop(2);
return 1;
}
| [
"itagaki.takahiro@fad0b036-4cad-11de-8d8d-752d95cf3e3c"
] | [
[
[
1,
112
]
]
] |
c37c49685a86446ee13d620967a86eb800ca0696 | ca99bc050dbc58be61a92e04f2a80a4b83cb6000 | /Game/src/Entities/EntityManager.h | 08613b88dde5f2bf25906fee40fc4679a82f38a1 | [] | no_license | NicolasBeaudrot/angry-tux | e26c619346c63a468ad3711de786e94f5b78a2f1 | 5a8259f57ba59db9071158a775948d06e424a9a8 | refs/heads/master | 2021-01-06T20:41:23.705460 | 2011-04-14T18:28:04 | 2011-04-14T18:28:04 | 32,141,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,745 | h | /*
Copyright (C) 2010 Nicolas Beaudrot
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ENTITYMANAGER_H
#define ENTITYMANAGER_H
#include "../Utilities/Config.h"
#include "../Utilities/Algorithm.h"
#include "Texture.h"
#include "Obstacle.h"
#include "Bar.h"
#include "Bear.h"
#include "Tux.h"
#include "Canon.h"
#include <Box2D/Box2D.h>
#include <vector>
class EntityManager : public CSingleton<EntityManager>
{
public:
void init(sf::RenderWindow* app
,b2World* world);
void loadTexture(int layer_position
,std::string str_class
,sf::Vector2i position
,std::string path_texture
,sf::Vector2i dimension
,float angle
,bool repeat_x
,bool repeat_y
,std::string color);
void loadBar (sf::Vector2i position
,std::string path_texture
,sf::Vector2i dimension
,float angle
,int type);
void loadBear (sf::Vector2i position
,std::string path_texture
,int size
,int score);
void loadTux (sf::Vector2i position
,std::string path_texture
,int type);
void mousePressedMoving(sf::Vector2f firstPosition, sf::Vector2f secondPosition);
void mouseReleased(sf::Vector2f firstPosition, sf::Vector2f secondPosition, float time_elapse);
void render();
void stop();
protected:
private:
EntityManager();
~EntityManager();
friend class CSingleton<EntityManager>;
std::multimap<int, Texture*> _arrTexture;
std::vector<Bar*> _arrBar;
std::vector<Bear*> _arrBear;
std::vector<Tux*> _arrTux;
sf::RenderWindow* _app;
b2World* _world;
int _layer_count;
Tux* _currentTux;
Canon* _canon;
};
#endif // ENTITYMANAGER_H
| [
"nicolas.beaudrot@43db0318-7ac6-f280-19a0-2e79116859ad"
] | [
[
[
1,
85
]
]
] |
a5fb7942c7aaa1e8cebcf8e8ef01971400cdfe9c | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/C++/练习/Visual C++程序设计与应用教程/Li2_1/Li2_1View.cpp | fe286519db27946e3d2e24786beee66a871b8fe0 | [] | no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,462 | cpp | // Li2_1View.cpp : CLi2_1View 类的实现
//
#include "stdafx.h"
#include "Li2_1.h"
#include "Li2_1Doc.h"
#include "Li2_1View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CLi2_1View
IMPLEMENT_DYNCREATE(CLi2_1View, CView)
BEGIN_MESSAGE_MAP(CLi2_1View, CView)
// 标准打印命令
ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview)
ON_WM_RBUTTONDOWN()
ON_COMMAND(ID_FILE_OPEN, &CLi2_1View::OnFileOpen)
ON_COMMAND(ID_32771, &CLi2_1View::OnCompute)
ON_WM_CHAR()
ON_WM_KEYDOWN()
END_MESSAGE_MAP()
// CLi2_1View 构造/析构
CLi2_1View::CLi2_1View()
: x(0)
, y(0)
, m_string(_T(""))
{
// TODO: 在此处添加构造代码
x = 50;
y = 50;
m_string.Empty();
}
CLi2_1View::~CLi2_1View()
{
}
BOOL CLi2_1View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return CView::PreCreateWindow(cs);
}
// CLi2_1View 绘制
void CLi2_1View::OnDraw(CDC* pDC)
{
CLi2_1Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
pDC->TextOutW(x,y-15,L"可以输入文本,移动文本");
pDC->TextOutW(x,y,m_string);
}
// CLi2_1View 打印
BOOL CLi2_1View::OnPreparePrinting(CPrintInfo* pInfo)
{
// 默认准备
return DoPreparePrinting(pInfo);
}
void CLi2_1View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 添加额外的打印前进行的初始化过程
}
void CLi2_1View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 添加打印后进行的清理过程
}
// CLi2_1View 诊断
#ifdef _DEBUG
void CLi2_1View::AssertValid() const
{
CView::AssertValid();
}
void CLi2_1View::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CLi2_1Doc* CLi2_1View::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CLi2_1Doc)));
return (CLi2_1Doc*)m_pDocument;
}
#endif //_DEBUG
// CLi2_1View 消息处理程序
void CLi2_1View::OnRButtonDown(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
MessageBox(L"鼠标右键被按下!",L"恭喜你!",MB_ICONEXCLAMATION|MB_OK);
CView::OnRButtonDown(nFlags, point);
}
void CLi2_1View::OnFileOpen()
{
// TODO: 在此添加命令处理程序代码
MessageBox(L"打开菜单被单击!",L"恭喜你!",MB_ICONQUESTION|MB_OK);
}
void CLi2_1View::OnCompute()
{
// TODO: 在此添加命令处理程序代码
CClientDC pDC(this);
int sum=0;
for(int i=1;i<=200;i++){
sum+=i*i*i;
}
CString str;
str.Format(L"和是: %d",sum);
m_string = L"1到200的立方"+str;
pDC.TextOut(x,y,m_string);
}
void CLi2_1View::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
m_string += (TCHAR)nChar;
Invalidate();
CView::OnChar(nChar, nRepCnt, nFlags);
}
void CLi2_1View::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
switch (nChar)
{
case VK_LEFT:
x-=10;
break;
case VK_RIGHT:
x+=10;
break;
case VK_UP:
y-=10;
break;
case VK_DOWN:
y+=10;
}
Invalidate();
CView::OnKeyDown(nChar, nRepCnt, nFlags);
}
| [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
] | [
[
[
1,
167
]
]
] |
174e5a38f381c97dedbc5a25fdf7e23e48d3b3d2 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/test/src/cpp_main.cpp | 6f3868c5179cdc0096ad5b57cb74bc7e8510c74e | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | cpp | // (C) Copyright Gennadiy Rozental 2005.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile: cpp_main.cpp,v $
//
// Version : $Revision: 1.17 $
//
// Description : forwarding source
// ***************************************************************************
#define BOOST_TEST_SOURCE
#include <boost/test/impl/cpp_main.ipp>
// ***************************************************************************
// Revision History :
//
// $Log: cpp_main.cpp,v $
// Revision 1.17 2005/03/22 07:18:39 rogeeff
// no message
//
// Revision 1.16 2005/01/22 19:26:35 rogeeff
// implementation moved into headers section to eliminate dependency of included/minimal component on src directory
//
// ***************************************************************************
// EOF
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
30
]
]
] |
b1a36288f38c7a9c10a41fe5f8c4acbcaac42096 | f7682efd1b53576a60beea5fe905d7cc9d21d5f4 | /inflate/inflate/inflate.cpp | e56d57d47dbc4478d9beb8f7e689afaa151d16da | [] | no_license | douglasguo/eclipselu | 696c36526918258690438e2fe62b76e7230ecb13 | 19529f0ae778a5ccd2f92d57a27c83aebf845b9a | refs/heads/master | 2016-09-06T18:37:05.105486 | 2010-05-14T06:32:41 | 2010-05-14T06:32:41 | 39,516,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | cpp | /*
ID: eclipse5
PROG: inflate
LANG: C++
*/
#include <cstdio>
const int maxn = 10000;
int M,N;
int p[maxn],m[maxn];
int f[maxn];
void init()
{
int i;
scanf("%d%d",&M,&N);
for (i=0;i<N;i++)
scanf("%d%d",&p[i],&m[i]);
}
void dp()
{
int i,j;
for (i=0;i<=M;i++)
f[i]=0;
for (i=0;i<N;i++)
for (j=m[i];j<=M;j++)
if (f[j]<f[j-m[i]]+p[i])
f[j]=f[j-m[i]]+p[i];
printf("%d\n",f[M]);
}
int main()
{
freopen("inflate.in","r",stdin);
freopen("inflate.out","w",stdout);
init();
dp();
return 0;
} | [
"eclipselu@bf7c4ae8-0690-11df-8158-c7cbc0dd6240"
] | [
[
[
1,
43
]
]
] |
b8d6f3b22e86901cbd8269b0bc84e91d79c94c11 | 1cc5720e245ca0d8083b0f12806a5c8b13b5cf98 | /v3/partials/395/c.cpp | 898ee82c2e5bf05574518d12543e4f8c56d75ae1 | [] | no_license | Emerson21/uva-problems | 399d82d93b563e3018921eaff12ca545415fd782 | 3079bdd1cd17087cf54b08c60e2d52dbd0118556 | refs/heads/master | 2021-01-18T09:12:23.069387 | 2010-12-15T00:38:34 | 2010-12-15T00:38:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,914 | cpp | #include <iostream>
#include <stdio.h>
using namespace std;
char lines[10][10];
char s[5];
int hor[10];
int ver[10];
int diag[10][10];
int odiag[10][10];
int p;
char car(int i) {
return 'A' + i;
}
void possivel(int y,int x,int dy, int dx, int t) {
int py=y,px=x;
for(int i=0;i!=t;i++) {
py += dy;
px += dx;
if(py<0 || py==8) return;
if(px<0 || px==8) return;
if(lines[py][px]!='.' && lines[py][px]!=s[0]) {
// nao pode
return;
}
}
if(lines[py][px]==s[0]) {
// nao pode
return;
}
cout << car(y) << (x+1) << "-" << car(py) << (px+1) << endl;
p++;
}
void tenta(int y,int x) {
cout << "comeca em " << y << "," << x << endl;
possivel(y,x,-1,-1,diag[y][x]);
possivel(y,x,-1,0,ver[x]);
possivel(y,x,0,-1,hor[x]);
possivel(y,x,0,1,hor[x]);
possivel(y,x,1,0,ver[x]);
possivel(y,x,1,1,diag[y][x]);
possivel(y,x,-1,1,odiag[y][x]);
possivel(y,x,1,-1,odiag[y][x]);
}
void sh(int y) {
hor[y] = 0;
for(int i=0;i!=8;i++) {
if(lines[y][i]!='.') hor[y]++;
}
}
void sv(int x) {
ver[x] = 0;
for(int i=0;i!=8;i++) {
if(lines[i][x]!='.') ver[x]++;
}
}
void sd(int y,int x) {
diag[y][x] = 0;
for(int i=-8;i<=8;i++) {
if(y+i<0 || x+i<0 || y+i>=8 || x+i>=8) continue;
if(lines[y+i][x+i]!='.') diag[y][x]++;
}
odiag[y][x] = 0;
for(int i=-8;i<=8;i++) {
if(y+i<0 || x+i<0 || y+i>=8 || x+i>=8) continue;
if(lines[y+i][x-i]!='.') odiag[y][x]++;
}
}
int main() {
int t = 0;
while((cin >> lines[0])) {
if(t++) cout << endl;
for(int i=1;i!=8;i++) cin >> lines[i];
cin >> s;
p = 0;
for(int i=0;i!=8;i++) {
sh(i); sv(i);
for(int j=0;j!=8;j++) {
sd(i,j);
}
}
for(int i=0;i!=8;i++) {
for(int j=0;j!=8;j++) {
if(lines[i][j]==s[0]) tenta(i,j);
}
}
if(!p) {
cout << "No moves are possible" << endl;
}
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
107
]
]
] |
726033eb7166c7314a6b25f629a67e244c44ecd1 | 188058ec6dbe8b1a74bf584ecfa7843be560d2e5 | /FLVGServer/RelayPropertyPage1.cpp | 94cb9ceb313306461fd251234401250825759ffd | [] | no_license | mason105/red5cpp | 636e82c660942e2b39c4bfebc63175c8539f7df0 | fcf1152cb0a31560af397f24a46b8402e854536e | refs/heads/master | 2021-01-10T07:21:31.412996 | 2007-08-23T06:29:17 | 2007-08-23T06:29:17 | 36,223,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,227 | cpp | // RelayPropertyPage1.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "RelayPropertyPage1.h"
#include "RelayPropertySheet.h"
#include "MRLRecentFileList.h"
#include "SysInfo.h"
#include "SysUtils.h"
#include <sstream>
using namespace std;
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CRelayPropertyPage1, CXTMainPropertyPage)
IMPLEMENT_DYNCREATE(CRelayPropertyPage2, CXTMainPropertyPage)
IMPLEMENT_DYNCREATE(CRelayPropertyPage3, CXTMainPropertyPage)
/////////////////////////////////////////////////////////////////////////////
// CRelayPropertyPage1 property page
CRelayPropertyPage1::CRelayPropertyPage1() : CXTMainPropertyPage(CRelayPropertyPage1::IDD)
{
static long lcount = 0;
//{{AFX_DATA_INIT(CRelayPropertyPage1)
m_nType = 0;
m_strInput = _T("");
//}}AFX_DATA_INIT
m_strName.Format("Noname_%d", lcount++);
m_pMRU = NULL;
}
CRelayPropertyPage1::~CRelayPropertyPage1()
{
if(m_pMRU)
{
m_pMRU->WriteList();
delete m_pMRU;
}
}
void CRelayPropertyPage1::DoDataExchange(CDataExchange* pDX)
{
CXTMainPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CRelayPropertyPage1)
DDX_Control(pDX, IDC_EDIT_NAME, m_editName);
DDX_Control(pDX, IDC_COMBO_TYPE, m_comboType);
DDX_Control(pDX, IDC_COMBO_INPUT, m_comboInput);
DDX_CBIndex(pDX, IDC_COMBO_TYPE, m_nType);
DDX_CBString(pDX, IDC_COMBO_INPUT, m_strInput);
DDX_Text(pDX, IDC_EDIT_NAME, m_strName);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CRelayPropertyPage1, CXTMainPropertyPage)
//{{AFX_MSG_MAP(CRelayPropertyPage1)
ON_CBN_SELCHANGE(IDC_COMBO_TYPE, OnSelchangeComboType)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CRelayPropertyPage2 property page
CRelayPropertyPage2::CRelayPropertyPage2() : CXTMainPropertyPage(CRelayPropertyPage2::IDD)
{
static DWORD dwRTSPBasePort = 5000;
//{{AFX_DATA_INIT(CNewSourcePropertyPage2)
m_dwNetPort = 6789;
m_strNetAddress = ("234.0.0.1");
m_dwNetRTSPPort = dwRTSPBasePort ++;
m_strMifaceAddress = _T("");
//}}AFX_DATA_INIT
}
CRelayPropertyPage2::~CRelayPropertyPage2()
{
}
void CRelayPropertyPage2::DoDataExchange(CDataExchange* pDX)
{
CXTMainPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CRelayPropertyPage2)
DDX_Control(pDX, IDC_EDIT_NETRTSPPORT, m_editNetRTSPPort);
DDX_Control(pDX, IDC_EDIT_MIFACEADDRESS, m_comboMifaceAddress);
DDX_Control(pDX, IDC_EDIT_NETPORT, m_editNetPort);
DDX_Control(pDX, IDC_EDIT_NETADDRESS, m_editNetAddress);
DDX_Control(pDX, IDC_COMBO_NETPROTOCOL, m_comboNetProtocol);
DDX_Control(pDX, IDC_COMBO_ENCAPSULATIONMETHOD, m_comboEncapsulationMethod);
DDX_Text(pDX, IDC_EDIT_NETPORT, m_dwNetPort);
DDX_Text(pDX, IDC_EDIT_NETADDRESS, m_strNetAddress);
DDX_Text(pDX, IDC_EDIT_NETRTSPPORT, m_dwNetRTSPPort);
DDX_CBString(pDX, IDC_EDIT_MIFACEADDRESS, m_strMifaceAddress);
DDX_CBString(pDX, IDC_COMBO_NETPROTOCOL, m_strNetProctol);
DDX_CBString(pDX, IDC_COMBO_ENCAPSULATIONMETHOD, m_strEncapsulationMethod);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CRelayPropertyPage2, CXTMainPropertyPage)
//{{AFX_MSG_MAP(CRelayPropertyPage2)
ON_CBN_SELCHANGE(IDC_COMBO_NETPROTOCOL, OnSelchangeComboNetprotocol)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL CRelayPropertyPage1::OnSetActive()
{
UpdateCtrl();
return CXTMainPropertyPage::OnSetActive();
}
BOOL CRelayPropertyPage2::OnSetActive()
{
CRelayPropertySheet* pParent=(CRelayPropertySheet*)GetParent();
pParent->SetWizardButtons(PSWIZB_FINISH | PSWIZB_BACK);
return CXTMainPropertyPage::OnSetActive();
}
void CRelayPropertyPage1::UpdateCtrl()
{
UpdateData();
CRelayPropertySheet *pParent = (CRelayPropertySheet*)GetParent();
ASSERT(pParent);
pParent->SetWizardButtons(PSWIZB_NEXT);
}
void CRelayPropertyPage1::OnSelchangeComboType()
{
UpdateCtrl();
}
void CRelayPropertyPage2::OnSelchangeComboNetprotocol()
{
UpdateData();
m_comboEncapsulationMethod.ResetContent();
CString strText;
GetDlgItem(IDC_COMBO_NETPROTOCOL)->GetWindowText(strText);
if(strText == "rtp")
{
m_comboEncapsulationMethod.AddString("ts");
GetDlgItem(IDC_EDIT_NETADDRESS)->EnableWindow(TRUE);
GetDlgItem(IDC_EDIT_NETADDRESS)->SetWindowText("234.0.0.1");
GetDlgItem(IDC_EDIT_NETRTSPPORT)->EnableWindow(FALSE);
GetDlgItem(IDC_EDIT_MIFACEADDRESS)->EnableWindow(TRUE);
SocketInfo sockInfo;
for(list_string::iterator it = sockInfo.m_strlistIPAddress.begin();
it != sockInfo.m_strlistIPAddress.end(); it ++)
{
((CXTFlatComboBox*)GetDlgItem(IDC_EDIT_MIFACEADDRESS))->AddString((*it).c_str());
}
GetDlgItem(IDC_EDIT_MIFACEADDRESS)->SetWindowText(sockInfo.getIPAddress().c_str());
}
else if(strText == "http")
{
m_comboEncapsulationMethod.AddString("asf");
m_comboEncapsulationMethod.AddString("ts");
GetDlgItem(IDC_EDIT_NETADDRESS)->SetWindowText("");
GetDlgItem(IDC_EDIT_NETADDRESS)->EnableWindow(FALSE);
GetDlgItem(IDC_EDIT_NETRTSPPORT)->EnableWindow(FALSE);
GetDlgItem(IDC_EDIT_MIFACEADDRESS)->EnableWindow(FALSE);
GetDlgItem(IDC_EDIT_MIFACEADDRESS)->SetWindowText("");
}
else if(strText == "mmsh")
{
m_comboEncapsulationMethod.AddString("asfh");
m_comboEncapsulationMethod.AddString("ts");
GetDlgItem(IDC_EDIT_NETADDRESS)->SetWindowText("");
GetDlgItem(IDC_EDIT_NETADDRESS)->EnableWindow(FALSE);
GetDlgItem(IDC_EDIT_NETRTSPPORT)->EnableWindow(FALSE);
GetDlgItem(IDC_EDIT_MIFACEADDRESS)->EnableWindow(FALSE);
GetDlgItem(IDC_EDIT_MIFACEADDRESS)->SetWindowText("");
}
else if(strText == "rtsp")
{
m_comboEncapsulationMethod.AddString("es");
GetDlgItem(IDC_EDIT_NETADDRESS)->SetWindowText("");
GetDlgItem(IDC_EDIT_NETADDRESS)->EnableWindow(FALSE);
GetDlgItem(IDC_EDIT_NETRTSPPORT)->EnableWindow(TRUE);
GetDlgItem(IDC_EDIT_MIFACEADDRESS)->SetWindowText("");
GetDlgItem(IDC_EDIT_MIFACEADDRESS)->EnableWindow(FALSE);
}
else
{
ASSERT(0);
return ;
}
m_comboEncapsulationMethod.SetCurSel(0);
}
BOOL CRelayPropertyPage2::OnInitDialog()
{
CXTMainPropertyPage::OnInitDialog();
OnSelchangeComboNetprotocol();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
BOOL CRelayPropertyPage2::OnWizardFinish()
{
CXTMainPropertyPage::UpdateData();
return CXTMainPropertyPage::OnWizardFinish();
}
BOOL CRelayPropertyPage1::OnWizardFinish()
{
CXTMainPropertyPage::UpdateData();
if(m_pMRU)
m_pMRU->Add(m_strInput);
return CXTMainPropertyPage::OnWizardFinish();
}
LRESULT CRelayPropertyPage1::OnWizardNext()
{
CXTMainPropertyPage::UpdateData();
if(m_pMRU)
m_pMRU->Add(m_strInput);
if(m_nType == 0)
return IDD_PROPPAGE2;
else
return IDD_PROPPAGE3;
// return CXTMainPropertyPage::OnWizardNext();
}
BOOL CRelayPropertyPage1::OnInitDialog()
{
CXTMainPropertyPage::OnInitDialog();
{
CString strTmp;
m_pMRU = new CMRLRecentFileList(1, MRL_MRURegKey, MRL_MRUValueFormat, 10);
m_pMRU->ReadList();
if(m_pMRU->GetSize())
{
for ( int i = 0; i < m_pMRU->GetSize(); i++ )
{
if ( (*m_pMRU)[i].GetLength() > 0 )
{
m_comboInput.AddString((LPSTR)(LPCSTR)(*m_pMRU)[i]);
}
}
}
if(m_comboInput.GetCount())
m_comboInput.SetCurSel(0);
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
//////////////////////////////////////////////////////////////////////////
void IDtoStr(char* id, char *str)
{
str[0] = 0;
for(int i=0; i<16; i++)
{
char tmp[8];
unsigned char ipb = id[i];
sprintf(tmp,"%02X",ipb);
strcat(str,tmp);
}
}
void IDfromStr(char* id, const char *str)
{
if (strlen(str) < 32)
return;
char buf[8];
buf[2] = 0;
for(int i=0; i<16; i++)
{
buf[0] = str[i*2];
buf[1] = str[i*2+1];
id[i] = (unsigned char)strtoul(buf,NULL,16);
}
}
CRelayPropertyPage3::CRelayPropertyPage3() : CXTMainPropertyPage(CRelayPropertyPage3::IDD)
{
//{{AFX_DATA_INIT(CRelayPropertyPage3)
m_dwWebRelayBitrate = 0;
m_strWebSourceType = "TS";
//}}AFX_DATA_INIT
static char id[16];
memset(id, 0, 16);
id[0] = 1;
char str[64];
IDtoStr(id, str);
m_strWebRelayID.Format("%s", str);
id[15] ++;
}
CRelayPropertyPage3::~CRelayPropertyPage3()
{
}
void CRelayPropertyPage3::DoDataExchange(CDataExchange* pDX)
{
CXTMainPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CRelayPropertyPage3)
DDX_Control(pDX, IDC_COMBO_WebSOURCETYPE, m_comboWebSourceType);
DDX_Control(pDX, IDC_EDIT_WebRELAYID, m_editWebRelayID);
DDX_Control(pDX, IDC_EDIT_DESCRIPTION, m_editDescription);
DDX_Control(pDX, IDC_EDIT_BITRATE, m_editWebRelayBitrate);
DDX_CBString(pDX, IDC_COMBO_WebSOURCETYPE, m_strWebSourceType);
DDX_Text(pDX, IDC_EDIT_DESCRIPTION, m_strWebDescription);
DDX_Text(pDX, IDC_EDIT_WebRELAYID, m_strWebRelayID);
DDX_Text(pDX, IDC_EDIT_BITRATE, m_dwWebRelayBitrate);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CRelayPropertyPage3, CXTMainPropertyPage)
//{{AFX_MSG_MAP(CRelayPropertyPage3)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL CRelayPropertyPage3::OnSetActive()
{
CRelayPropertySheet* pParent=(CRelayPropertySheet*)GetParent();
pParent->SetWizardButtons(PSWIZB_FINISH | PSWIZB_BACK);
return CXTMainPropertyPage::OnSetActive();
}
BOOL CRelayPropertyPage3::OnWizardFinish()
{
CXTMainPropertyPage::UpdateData();
return CXTMainPropertyPage::OnWizardFinish();
}
BOOL CRelayPropertyPage3::OnInitDialog()
{
CXTMainPropertyPage::OnInitDialog();
m_editWebRelayID.SetLimitText(32);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
LRESULT CRelayPropertyPage2::OnWizardBack()
{
return IDD_PROPPAGE1;
return CXTMainPropertyPage::OnWizardBack();
}
LRESULT CRelayPropertyPage3::OnWizardBack()
{
return IDD_PROPPAGE1;
return CXTMainPropertyPage::OnWizardBack();
}
| [
"soaris@46205fef-a337-0410-8429-7db05d171fc8"
] | [
[
[
1,
373
]
]
] |
dd9248d7c8a92df0173a196a96ee9d230a29730b | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_1_006.cpp | 8fd71721f2bd66d488f6d6bc785872976667b7f7 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 992 | cpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2006 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// Tests the correctness of parameter replacement, if the parameter is
// adjacent to an operator '##'.
#define CONCAT(a, b) PRIMITIVE_CONCAT(a, b)
#define PRIMITIVE_CONCAT(a, b) a ## b
//R #line 18 "t_1_006.cpp"
//R 123
CONCAT(1, PRIMITIVE_CONCAT(2, 3))
//R #line 21 "t_1_006.cpp"
//R 123
CONCAT(1, CONCAT(2, 3))
// E t_1_006.cpp(23): error: pasting the following two tokens does not give a valid preprocessing token: "1" and "CONCAT"
//R #line 25 "t_1_006.cpp"
//R 1 CONCAT(2, 3)
PRIMITIVE_CONCAT(1, CONCAT(2, 3))
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
25
]
]
] |
e5bda893b47b999bf3a5ad7b7601b1aec9a49d2a | b22c254d7670522ec2caa61c998f8741b1da9388 | /NewClient/main.cpp | 8f57b0f0c4561c8aa6b2e68d253cb68be80c4af9 | [] | no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,200 | cpp | /*
------------------------[ Lbanet Source ]-------------------------
Copyright (C) 2009
Author: Vivien Delage [Rincevent_123]
Email : [email protected]
-------------------------------[ GNU License ]-------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------------
*/
#if defined(NDEBUG)
#if defined(_MSC_VER)
#include "SDL.h"
#else
#include "SDL/SDL.h"
#endif
#endif
#include "LbaNetEngine.h"
#include "UserAllocatorHandler.h"
#include "ConnectionHandler.h"
#include "chatclient.h"
#include "LogHandler.h"
#include "InternalWorkpile.h"
#include "gameclient.h"
#include <iostream>
int main( int argc, char **argv )
{
LogHandler::getInstance()->Init("LBAClient.log");
// init memory allocator
UserAllocatorHandler::getInstance()->Initialize();
// set up connection class
ConnectionHandler* ConH = new ConnectionHandler("Zoidcom.log");
// set up chat client
ChatClient* Chatcl = new ChatClient(InternalWorkpile::getInstance(),
InternalWorkpile::getInstance(), 30, 200,
InternalWorkpile::getInstance());
// set up game client
GameClient* Gamecl = new GameClient(30, 200);
// start main thread engine
LbaNetEngine engine(Chatcl, Gamecl);
engine.run();
//disconnect from servers
Chatcl->CloseConnection();
Gamecl->CloseConnection();
delete Chatcl;
delete Gamecl;
delete ConH;
return 0;
}
//TODO
// integrate with database
// add friend stuff
// add + for chatbox
// remove channel button | [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] | [
[
[
1,
89
]
]
] |
4aac386532bbee7bcaf6afc3198349eb61bf081c | c4001da8f012dfbc46fef0d9c11f8412f4ad9c6f | /allegro/demos/a5teroids/src/Enemy.cpp | 3b075d4bc2114574a1d5cb75a07a9e7085d7a97a | [
"Zlib",
"BSD-3-Clause"
] | permissive | sesc4mt/mvcdecoder | 4602fdfe42ab39706cfa3c749282782ca9da73c9 | 742a5c0d9cad43f0b01aa6e9169d96a286458e72 | refs/heads/master | 2021-01-01T17:56:47.666505 | 2010-11-02T12:36:52 | 2010-11-02T12:36:52 | 40,896,775 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 734 | cpp | #include "a5teroids.hpp"
Enemy::~Enemy()
{
}
/*
void createEnemy(char *id, lua_State *luaState)
{
Enemy *enemy;
if (!strcmp(id, "la")) {
enemy = new LargeAsteroid();
}
else if (!strcmp(id, "ma")) {
enemy = new MediumAsteroid();
}
else if (!strcmp(id, "ufo")) {
enemy = new UFO();
}
else { // Small Asteroid default
enemy = new SmallAsteroid();
}
enemy->init(luaState);
entities.push_back(enemy);
lua_pushstring(luaState, "powerup");
lua_gettable(luaState, -2);
if (lua_isnumber(luaState, -1)) {
int poweruptype = (int)lua_tonumber(luaState, -1);
enemy->setPowerUp(poweruptype);
}
lua_pop(luaState, 1);
}
*/
| [
"edwardtoday@34199c9c-95aa-5eba-f35a-9ba8a8a04cd7"
] | [
[
[
1,
37
]
]
] |
31b7321fb2e09b771dc2133497f30ecea7809847 | bdb1e38df8bf74ac0df4209a77ddea841045349e | /CapsuleSortor/Version 1.0 -2.0/CapsuleSortor-10-11-15/ToolSrc/TLogManager.h | 1b2d74e8fa122898801a666fe15e14e9a385ffc4 | [] | no_license | Strongc/my001project | e0754f23c7818df964289dc07890e29144393432 | 07d6e31b9d4708d2ef691d9bedccbb818ea6b121 | refs/heads/master | 2021-01-19T07:02:29.673281 | 2010-12-17T03:10:52 | 2010-12-17T03:10:52 | 49,062,858 | 0 | 1 | null | 2016-01-05T11:53:07 | 2016-01-05T11:53:07 | null | UTF-8 | C++ | false | false | 556 | h | #ifndef TLOGMANAGER_H
#define TLOGMANAGER_H
#pragma warning(disable: 4786)
#pragma once
#ifdef _AFXDLL
#include "afx.h"
#else
#include "windows.h"
#endif
#include "TTimeDiff.h"
#include <list>
#include <utility>
#include <string>
typedef std::pair<double, std::string > Node;
class TLogManager
{
public:
TLogManager();
~TLogManager();
void AddInfo(const char* info);
void Save();
private:
std::string Time2String(SYSTEMTIME &time);
private:
std::list<Node> m_dataSet;
TTimeDiff m_timeCount;
};
#endif
| [
"vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e"
] | [
[
[
1,
35
]
]
] |
3bc8c8492ece070e2782289bc9ef5e252e65b5a6 | 867f5533667cce30d0743d5bea6b0c083c073386 | /jingxian-network/src/jingxian/networks/networking.cpp | aa268213def77dbfd93231a858ee04056db1983b | [] | no_license | mei-rune/jingxian-project | 32804e0fa82f3f9a38f79e9a99c4645b9256e889 | 47bc7a2cb51fa0d85279f46207f6d7bea57f9e19 | refs/heads/master | 2022-08-12T18:43:37.139637 | 2009-12-11T09:30:04 | 2009-12-11T09:30:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,892 | cpp | # include "pro_config.h"
# include <vector>
# include "jingxian/networks/networking.h"
_jingxian_begin
namespace networking
{
static LPFN_TRANSMITFILE __transmitfile;
static LPFN_ACCEPTEX __acceptex;
static LPFN_TRANSMITPACKETS __transmitpackets;
static LPFN_CONNECTEX __connectex;
static LPFN_DISCONNECTEX __disconnectex;
static LPFN_GETACCEPTEXSOCKADDRS __getacceptexsockaddrs;
bool set_option(SOCKET sock,
int level,
int option,
void *optval,
int optlen)
{
return (SOCKET_ERROR != setsockopt(sock, level,
option, (char *) optval, optlen));
}
bool get_option(SOCKET sock,
int level,
int option,
void *optval,
int *optlen)
{
return (SOCKET_ERROR != getsockopt(sock, level,
option, (char *) optval, optlen));
}
bool enable(SOCKET sock, int value)
{
u_long nonblock = 1;
return (0 ==::ioctlsocket(sock,
value,
&nonblock));
}
bool disable(SOCKET sock, int value)
{
u_long nonblock = 0;
return (0 == ioctlsocket(sock,
value,
&nonblock));
}
bool poll(SOCKET sock, const TIMEVAL& time_val, int mode)
{
fd_set socket_set;
FD_ZERO(&socket_set);
FD_SET(sock, &socket_set);
return (1 == ::select(0, (mode & select_read) ? &socket_set : NULL
, (mode & select_write) ? &socket_set : NULL
, (mode & select_error) ? &socket_set : NULL
, &time_val));
}
bool isReadable(SOCKET sock)
{
TIMEVAL time_val;
time_val.tv_sec = 0;
time_val.tv_usec = 0;
return poll(sock, time_val, select_read);
}
bool isWritable(SOCKET sock)
{
TIMEVAL time_val;
time_val.tv_sec = 0;
time_val.tv_usec = 0;
return poll(sock, time_val, select_write);
}
void setBlocking(SOCKET sock, bool val)
{
if (val)
enable(sock, FIONBIO);
else
disable(sock, FIONBIO);
}
bool send_n(SOCKET sock, const char* buf, size_t length)
{
do
{
#pragma warning(disable: 4267)
int n = ::send(sock, buf, length, 0);
#pragma warning(default: 4267)
if (0 >= n)
return false;
length -= n;
buf += n;
}
while (0 < length);
return true;
}
bool recv_n(SOCKET sock, char* buf, size_t length)
{
do
{
#pragma warning(disable: 4267)
int n = ::recv(sock, buf, length, 0);
#pragma warning(default: 4267)
if (0 >= n)
return false;
length -= n;
buf += n;
}
while (0 < length);
return true;
}
bool sendv_n(SOCKET sock, const io_mem_buf* wsaBuf, size_t size)
{
std::vector<io_mem_buf> buf(wsaBuf, wsaBuf + size);
io_mem_buf* p = &buf[0];
do
{
DWORD numberOfBytesSent = 0;
#pragma warning(disable: 4267)
if (SOCKET_ERROR == ::WSASend(sock, p, size, &numberOfBytesSent, 0, 0 , 0))
#pragma warning(default: 4267)
return false;
do
{
if (numberOfBytesSent < p->len)
{
p->len -= numberOfBytesSent;
p->buf = p->buf + numberOfBytesSent;
break;
}
numberOfBytesSent -= p->len;
++ p;
-- size;
}
while (0 < numberOfBytesSent);
}
while (0 < size);
return true;
}
bool recvv_n(SOCKET sock, io_mem_buf* wsaBuf, size_t size)
{
io_mem_buf* p = wsaBuf;
do
{
DWORD numberOfBytesRecvd = 0;
#pragma warning(disable: 4267)
if (SOCKET_ERROR == ::WSARecv(sock, p, size, &numberOfBytesRecvd, 0, 0 , 0))
#pragma warning(default: 4267)
return false;
do
{
if (numberOfBytesRecvd < p->len)
{
p->len -= numberOfBytesRecvd;
p->buf = p->buf + numberOfBytesRecvd;
break;
}
numberOfBytesRecvd -= p->len;
++ p;
-- size;
}
while (0 < numberOfBytesRecvd);
}
while (0 < size);
return true;
}
bool initializeScket()
{
WSADATA wsaData;
if (0 != WSAStartup(MAKEWORD(2, 2), &wsaData))
return false;
if (LOBYTE(wsaData.wVersion) != 2 ||
HIBYTE(wsaData.wVersion) != 2)
{
WSACleanup();
return false;
}
SOCKET cliSock = ::socket(AF_INET , SOCK_STREAM, IPPROTO_TCP);
GUID GuidConnectEx = WSAID_CONNECTEX;
GUID GuidDisconnectEx = WSAID_DISCONNECTEX;
GUID GuidGetAcceptExSockAddrs = WSAID_GETACCEPTEXSOCKADDRS;
GUID GuidAcceptEx = WSAID_ACCEPTEX;
GUID GuidTransmitFile = WSAID_TRANSMITFILE;
GUID GuidTransmitPackets = WSAID_TRANSMITPACKETS;
DWORD dwBytes = 0;
if (SOCKET_ERROR == WSAIoctl(cliSock,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&GuidConnectEx,
sizeof(GuidConnectEx),
&__connectex,
sizeof(__connectex),
&dwBytes,
NULL,
NULL))
{
__connectex = NULL;
}
dwBytes = 0;
if (SOCKET_ERROR == WSAIoctl(cliSock,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&GuidDisconnectEx,
sizeof(GuidDisconnectEx),
&__disconnectex,
sizeof(__disconnectex),
&dwBytes,
NULL,
NULL))
{
__disconnectex = NULL;
}
dwBytes = 0;
if (SOCKET_ERROR == WSAIoctl(cliSock,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&GuidTransmitFile,
sizeof(GuidTransmitFile),
&__transmitfile,
sizeof(__transmitfile),
&dwBytes,
NULL,
NULL))
{
__transmitfile = NULL;
}
dwBytes = 0;
if (SOCKET_ERROR == WSAIoctl(cliSock,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&GuidAcceptEx,
sizeof(GuidAcceptEx),
&__acceptex,
sizeof(__acceptex),
&dwBytes,
NULL,
NULL))
{
__acceptex = NULL;
}
dwBytes = 0;
if (SOCKET_ERROR == WSAIoctl(cliSock,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&GuidTransmitPackets,
sizeof(GuidTransmitPackets),
&__transmitpackets,
sizeof(__transmitpackets),
&dwBytes,
NULL,
NULL))
{
__transmitpackets = NULL;
}
dwBytes = 0;
if (SOCKET_ERROR == WSAIoctl(cliSock,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&GuidGetAcceptExSockAddrs,
sizeof(GuidGetAcceptExSockAddrs),
&__getacceptexsockaddrs,
sizeof(__getacceptexsockaddrs),
&dwBytes,
NULL,
NULL))
{
__getacceptexsockaddrs = NULL;
}
closesocket(cliSock);
return true;
}
void shutdownSocket()
{
WSACleanup();
}
bool transmitFile(SOCKET hSocket,
HANDLE hFile,
DWORD nNumberOfBytesToWrite,
DWORD nNumberOfBytesPerSend,
LPOVERLAPPED lpOverlapped,
LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers,
DWORD dwFlags)
{
return TRUE == __transmitfile(hSocket
, hFile
, nNumberOfBytesToWrite
, nNumberOfBytesPerSend
, lpOverlapped
, lpTransmitBuffers
, dwFlags);
}
bool acceptEx(SOCKET sListenSocket,
SOCKET sAcceptSocket,
PVOID lpOutputBuffer,
DWORD dwReceiveDataLength,
DWORD dwLocalAddressLength,
DWORD dwRemoteAddressLength,
LPDWORD lpdwBytesReceived,
LPOVERLAPPED lpOverlapped)
{
return TRUE == __acceptex(sListenSocket,
sAcceptSocket,
lpOutputBuffer,
dwReceiveDataLength,
dwLocalAddressLength,
dwRemoteAddressLength,
lpdwBytesReceived,
lpOverlapped);
}
bool transmitPackets(SOCKET hSocket,
LPTRANSMIT_PACKETS_ELEMENT lpPacketArray,
DWORD nElementCount,
DWORD nSendSize,
LPOVERLAPPED lpOverlapped,
DWORD dwFlags)
{
return TRUE == __transmitpackets(hSocket,
lpPacketArray,
nElementCount,
nSendSize,
lpOverlapped,
dwFlags);
}
bool connectEx(SOCKET s,
const struct sockaddr* name,
int namelen,
PVOID lpSendBuffer,
DWORD dwSendDataLength,
LPDWORD lpdwBytesSent,
LPOVERLAPPED lpOverlapped)
{
return TRUE == __connectex(s,
name,
namelen,
lpSendBuffer,
dwSendDataLength,
lpdwBytesSent,
lpOverlapped);
}
bool disconnectEx(SOCKET hSocket,
LPOVERLAPPED lpOverlapped,
DWORD dwFlags,
DWORD reserved)
{
return TRUE == __disconnectex(hSocket,
lpOverlapped,
dwFlags,
reserved);
}
void getAcceptExSockaddrs(PVOID lpOutputBuffer,
DWORD dwReceiveDataLength,
DWORD dwLocalAddressLength,
DWORD dwRemoteAddressLength,
LPSOCKADDR* LocalSockaddr,
LPINT LocalSockaddrLength,
LPSOCKADDR* RemoteSockaddr,
LPINT RemoteSockaddrLength)
{
__getacceptexsockaddrs(lpOutputBuffer,
dwReceiveDataLength,
dwLocalAddressLength,
dwRemoteAddressLength,
LocalSockaddr,
LocalSockaddrLength,
RemoteSockaddr,
RemoteSockaddrLength);
}
bool stringToAddress(const tchar* host
, struct sockaddr* addr
, int* len)
{
memset(addr, 0, *len);
addr->sa_family = AF_INET;
const tchar* begin = string_traits<tchar>::strstr(host, _T("://"));
if (null_ptr != begin)
{
if (begin != host && _T('6') == *(begin - 1))
addr->sa_family = AF_INET6;
begin += 3;
}
else
{
begin = host;
}
return (SOCKET_ERROR != ::WSAStringToAddress((LPTSTR)begin
, addr->sa_family
, 0
, addr
, len));
}
tstring fetchAddr(const tchar* host)
{
const tchar* begin = string_traits<tchar>::strstr(host, _T("://"));
if (null_ptr == begin)
begin = host;
else
begin += 3;
const tchar* end = string_traits<tchar>::strchr(begin, _T(':'));
if (null_ptr == end)
return begin;
return tstring(begin, end);
}
const tchar* fetchPort(const tchar* host)
{
const tchar* end = string_traits<tchar>::strrchr(host, _T(':'));
if (null_ptr == end)
return 0;
return ++end;
}
bool addressToString(struct sockaddr* addr
, int len
, const tchar* schema
, tstring& host)
{
host = (null_ptr == schema) ? _T("tcp") : schema;
host += (addr->sa_family == AF_INET6) ? _T("6://") : _T("://");
size_t prefix = host.size();
host.resize(256);
DWORD addressLength = static_cast<DWORD>(host.size() - prefix);
if (SOCKET_ERROR == ::WSAAddressToString(addr
, len
, NULL
, (LPTSTR)host.c_str() + prefix
, &addressLength))
return false;
host.resize(addressLength + prefix - 1);
return true;
}
}
_jingxian_end | [
"runner.mei@0dd8077a-353d-11de-b438-597f59cd7555"
] | [
[
[
1,
479
]
]
] |
c53327761b5ccfa7b7ba3a4cd55e32530408c77a | 6629f18d84dc8d5a310b95fedbf5be178b00da92 | /SDK-2008-05-27/foobar2000/SDK/filesystem.h | b56b9d3f28316e28aa59c9165a44ada54252d152 | [] | no_license | thenfour/WMircP | 317f7b36526ebf8061753469b10f164838a0a045 | ad6f4d1599fade2ae4e25656a95211e1ca70db31 | refs/heads/master | 2021-01-01T17:42:20.670266 | 2008-07-11T03:10:48 | 2008-07-11T03:10:48 | 16,931,152 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,511 | h | class file_info;
//! Contains various I/O related structures and interfaces.
namespace foobar2000_io
{
//! Type used for file size related variables.
typedef t_uint64 t_filesize;
//! Type used for file size related variables when signed value is needed.
typedef t_int64 t_sfilesize;
//! Type used for file timestamp related variables. 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601; 0 for invalid/unknown time.
typedef t_uint64 t_filetimestamp;
//! Invalid/unknown file timestamp constant. Also see: t_filetimestamp.
const t_filetimestamp filetimestamp_invalid = 0;
//! Invalid/unknown file size constant. Also see: t_filesize.
static const t_filesize filesize_invalid = (t_filesize)(~0);
static const t_filetimestamp filetimestamp_1second_increment = 10000000;
//! Generic I/O error. Root class for I/O failure exception. See relevant default message for description of each derived exception class.
PFC_DECLARE_EXCEPTION(exception_io, pfc::exception,"I/O error");
//! Object not found.
PFC_DECLARE_EXCEPTION(exception_io_not_found, exception_io,"Object not found");
//! Access denied.
PFC_DECLARE_EXCEPTION(exception_io_denied, exception_io,"Access denied");
//! Unsupported format or corrupted file (unexpected data encountered).
PFC_DECLARE_EXCEPTION(exception_io_data, exception_io,"Unsupported format or corrupted file");
//! Unsupported format or corrupted file (truncation encountered).
PFC_DECLARE_EXCEPTION(exception_io_data_truncation, exception_io_data,"Unsupported format or corrupted file");
//! Unsupported format (a subclass of "unsupported format or corrupted file" exception).
PFC_DECLARE_EXCEPTION(exception_io_unsupported_format, exception_io_data,"Unsupported file format");
//! Object is remote, while specific operation is supported only for local objects.
PFC_DECLARE_EXCEPTION(exception_io_object_is_remote, exception_io,"This operation is not supported on remote objects");
//! Sharing violation.
PFC_DECLARE_EXCEPTION(exception_io_sharing_violation, exception_io,"Sharing violation");
//! Device full.
PFC_DECLARE_EXCEPTION(exception_io_device_full, exception_io,"Device full");
//! Attempt to seek outside valid range.
PFC_DECLARE_EXCEPTION(exception_io_seek_out_of_range, exception_io,"Seek offset out of range");
//! This operation requires a seekable object.
PFC_DECLARE_EXCEPTION(exception_io_object_not_seekable, exception_io,"Object is not seekable");
//! This operation requires an object with known length.
PFC_DECLARE_EXCEPTION(exception_io_no_length, exception_io,"Length of object is unknown");
//! Invalid path.
PFC_DECLARE_EXCEPTION(exception_io_no_handler_for_path, exception_io,"Invalid path");
//! Object already exists.
PFC_DECLARE_EXCEPTION(exception_io_already_exists, exception_io,"Object already exists");
//! Pipe error.
PFC_DECLARE_EXCEPTION(exception_io_no_data, exception_io,"The process receiving or sending data has terminated");
//! Network not reachable.
PFC_DECLARE_EXCEPTION(exception_io_network_not_reachable,exception_io,"Network not reachable");
//! Media is write protected.
PFC_DECLARE_EXCEPTION(exception_io_write_protected, exception_io_denied,"The media is write protected");
//! File is corrupted. This indicates filesystem call failure, not actual invalid data being read by the app.
PFC_DECLARE_EXCEPTION(exception_io_file_corrupted, exception_io,"The file is corrupted");
//! The disc required for requested operation is not available.
PFC_DECLARE_EXCEPTION(exception_io_disk_change, exception_io,"Disc not available");
//! The directory is not empty.
PFC_DECLARE_EXCEPTION(exception_io_directory_not_empty, exception_io,"Directory not empty");
//! Stores file stats (size and timestamp).
struct t_filestats {
//! Size of the file.
t_filesize m_size;
//! Time of last file modification.
t_filetimestamp m_timestamp;
inline bool operator==(const t_filestats & param) const {return m_size == param.m_size && m_timestamp == param.m_timestamp;}
inline bool operator!=(const t_filestats & param) const {return m_size != param.m_size || m_timestamp != param.m_timestamp;}
};
//! Invalid/unknown file stats constant. See: t_filestats.
static const t_filestats filestats_invalid = {filesize_invalid,filetimestamp_invalid};
#ifdef _WIN32
void exception_io_from_win32(DWORD p_code);
#define WIN32_IO_OP(X) {SetLastError(NO_ERROR); if (!(X)) exception_io_from_win32(GetLastError());}
#endif
//! Generic interface to read data from a nonseekable stream. Also see: stream_writer, file. \n
//! Error handling: all methods may throw exception_io or one of derivatives on failure; exception_aborted when abort_callback is signaled.
class NOVTABLE stream_reader {
public:
//! Attempts to reads specified number of bytes from the stream.
//! @param p_buffer Receives data being read. Must have at least p_bytes bytes of space allocated.
//! @param p_bytes Number of bytes to read.
//! @param p_abort abort_callback object signaling user aborting the operation.
//! @returns Number of bytes actually read. May be less than requested when EOF was reached.
virtual t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) = 0;
//! Reads specified number of bytes from the stream. If requested amount of bytes can't be read (e.g. EOF), throws exception_io_data_truncation.
//! @param p_buffer Receives data being read. Must have at least p_bytes bytes of space allocated.
//! @param p_bytes Number of bytes to read.
//! @param p_abort abort_callback object signaling user aborting the operation.
virtual void read_object(void * p_buffer,t_size p_bytes,abort_callback & p_abort);
//! Attempts to skip specified number of bytes in the stream.
//! @param p_bytes Number of bytes to skip.
//! @param p_abort abort_callback object signaling user aborting the operation.
//! @returns Number of bytes actually skipped, May be less than requested when EOF was reached.
virtual t_filesize skip(t_filesize p_bytes,abort_callback & p_abort);
//! Skips specified number of bytes in the stream. If requested amount of bytes can't be skipped (e.g. EOF), throws exception_io_data_truncation.
//! @param p_bytes Number of bytes to skip.
//! @param p_abort abort_callback object signaling user aborting the operation.
virtual void skip_object(t_filesize p_bytes,abort_callback & p_abort);
//! Helper template built around read_object. Reads single raw object from the stream.
//! @param p_object Receives object read from the stream on success.
//! @param p_abort abort_callback object signaling user aborting the operation.
template<typename T> inline void read_object_t(T& p_object,abort_callback & p_abort) {pfc::assert_raw_type<T>(); read_object(&p_object,sizeof(p_object),p_abort);}
//! Helper template built around read_object. Reads single raw object from the stream; corrects byte order assuming stream uses little endian order.
//! @param p_object Receives object read from the stream on success.
//! @param p_abort abort_callback object signaling user aborting the operation.
template<typename T> inline void read_lendian_t(T& p_object,abort_callback & p_abort) {read_object_t(p_object,p_abort); byte_order::order_le_to_native_t(p_object);}
//! Helper template built around read_object. Reads single raw object from the stream; corrects byte order assuming stream uses big endian order.
//! @param p_object Receives object read from the stream on success.
//! @param p_abort abort_callback object signaling user aborting the operation.
template<typename T> inline void read_bendian_t(T& p_object,abort_callback & p_abort) {read_object_t(p_object,p_abort); byte_order::order_be_to_native_t(p_object);}
//! Helper function; reads a string (with a 32-bit header indicating length in bytes followed by UTF-8 encoded data without a null terminator).
void read_string(pfc::string_base & p_out,abort_callback & p_abort);
//! Helper function; alternate way of storing strings; assumes string takes space up to end of stream.
void read_string_raw(pfc::string_base & p_out,abort_callback & p_abort);
//! Helper function; reads a string (with a 32-bit header indicating length in bytes followed by UTF-8 encoded data without a null terminator).
pfc::string read_string(abort_callback & p_abort);
//! Helper function; reads a string of specified length from the stream.
void read_string_ex(pfc::string_base & p_out,t_size p_bytes,abort_callback & p_abort);
//! Helper function; reads a string of specified length from the stream.
pfc::string read_string_ex(t_size p_len,abort_callback & p_abort);
protected:
stream_reader() {}
~stream_reader() {}
};
//! Generic interface to write data to a nonseekable stream. Also see: stream_reader, file. \n
//! Error handling: all methods may throw exception_io or one of derivatives on failure; exception_aborted when abort_callback is signaled.
class NOVTABLE stream_writer {
public:
//! Writes specified number of bytes from specified buffer to the stream.
//! @param p_buffer Buffer with data to write. Must contain at least p_bytes bytes.
//! @param p_bytes Number of bytes to write.
//! @param p_abort abort_callback object signaling user aborting the operation.
virtual void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) = 0;
//! Helper. Same as write(), provided for consistency.
inline void write_object(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {write(p_buffer,p_bytes,p_abort);}
//! Helper template. Writes single raw object to the stream.
//! @param p_object Object to write.
//! @param p_abort abort_callback object signaling user aborting the operation.
template<typename T> inline void write_object_t(const T & p_object, abort_callback & p_abort) {pfc::assert_raw_type<T>(); write_object(&p_object,sizeof(p_object),p_abort);}
//! Helper template. Writes single raw object to the stream; corrects byte order assuming stream uses little endian order.
//! @param p_object Object to write.
//! @param p_abort abort_callback object signaling user aborting the operation.
template<typename T> inline void write_lendian_t(const T & p_object, abort_callback & p_abort) {T temp = p_object; byte_order::order_native_to_le_t(temp); write_object_t(temp,p_abort);}
//! Helper template. Writes single raw object to the stream; corrects byte order assuming stream uses big endian order.
//! @param p_object Object to write.
//! @param p_abort abort_callback object signaling user aborting the operation.
template<typename T> inline void write_bendian_t(const T & p_object, abort_callback & p_abort) {T temp = p_object; byte_order::order_native_to_be_t(temp); write_object_t(temp,p_abort);}
//! Helper function; writes string (with 32-bit header indicating length in bytes followed by UTF-8 encoded data without null terminator).
void write_string(const char * p_string,abort_callback & p_abort);
void write_string(const char * p_string,t_size p_len,abort_callback & p_abort);
template<typename T>
void write_string(const T& val,abort_callback & p_abort) {write_string(pfc::stringToPtr(val),p_abort);}
//! Helper function; writes raw string to the stream, with no length info or null terminators.
void write_string_raw(const char * p_string,abort_callback & p_abort);
protected:
stream_writer() {}
~stream_writer() {}
};
//! A class providing abstraction for an open file object, with reading/writing/seeking methods. See also: stream_reader, stream_writer (which it inherits read/write methods from). \n
//! Error handling: all methods may throw exception_io or one of derivatives on failure; exception_aborted when abort_callback is signaled.
class NOVTABLE file : public service_base, public stream_reader, public stream_writer {
public:
//! Seeking mode constants. Note: these are purposedly defined to same values as standard C SEEK_* constants
enum t_seek_mode {
//! Seek relative to beginning of file (same as seeking to absolute offset).
seek_from_beginning = 0,
//! Seek relative to current position.
seek_from_current = 1,
//! Seek relative to end of file.
seek_from_eof = 2,
};
//! Retrieves size of the file.
//! @param p_abort abort_callback object signaling user aborting the operation.
//! @returns File size on success; filesize_invalid if unknown (nonseekable stream etc).
virtual t_filesize get_size(abort_callback & p_abort) = 0;
//! Retrieves read/write cursor position in the file. In case of non-seekable stream, this should return number of bytes read so far since open/reopen call.
//! @param p_abort abort_callback object signaling user aborting the operation.
//! @returns Read/write cursor position
virtual t_filesize get_position(abort_callback & p_abort) = 0;
//! Resizes file to specified size in bytes.
//! @param p_abort abort_callback object signaling user aborting the operation.
virtual void resize(t_filesize p_size,abort_callback & p_abort) = 0;
//! Sets read/write cursor position to specific offset.
//! @param p_position position to seek to.
//! @param p_abort abort_callback object signaling user aborting the operation.
virtual void seek(t_filesize p_position,abort_callback & p_abort) = 0;
//! Sets read/write cursor position to specific offset; extended form allowing seeking relative to current position or to end of file.
//! @param p_position Position to seek to; interpretation of this value depends on p_mode parameter.
//! @param p_mode Seeking mode; see t_seek_mode enum values for further description.
//! @param p_abort abort_callback object signaling user aborting the operation.
virtual void seek_ex(t_sfilesize p_position,t_seek_mode p_mode,abort_callback & p_abort);
//! Returns whether the file is seekable or not. If can_seek() returns false, all seek() or seek_ex() calls will fail; reopen() is still usable on nonseekable streams.
virtual bool can_seek() = 0;
//! Retrieves mime type of the file.
//! @param p_out Receives content type string on success.
virtual bool get_content_type(pfc::string_base & p_out) = 0;
//! Hint, returns whether the file is already fully buffered into memory.
virtual bool is_in_memory() {return false;}
//! Optional, called by owner thread before sleeping.
//! @param p_abort abort_callback object signaling user aborting the operation.
virtual void on_idle(abort_callback & p_abort) {}
//! Retrieves last modification time of the file.
//! @param p_abort abort_callback object signaling user aborting the operation.
//! @returns Last modification time o fthe file; filetimestamp_invalid if N/A.
virtual t_filetimestamp get_timestamp(abort_callback & p_abort) {return filetimestamp_invalid;}
//! Resets non-seekable stream, or seeks to zero on seekable file.
//! @param p_abort abort_callback object signaling user aborting the operation.
virtual void reopen(abort_callback & p_abort) = 0;
//! Indicates whether the file is a remote resource and non-sequential access may be slowed down by lag. This is typically returns to true on non-seekable sources but may also return true on seekable sources indicating that seeking is supported but will be relatively slow.
virtual bool is_remote() = 0;
//! Retrieves file stats structure. Usese get_size() and get_timestamp().
t_filestats get_stats(abort_callback & p_abort);
//! Returns whether read/write cursor position is at the end of file.
bool is_eof(abort_callback & p_abort);
//! Truncates file to specified size (while preserving read/write cursor position if possible); uses set_eof().
void truncate(t_filesize p_position,abort_callback & p_abort);
//! Truncates the file at current read/write cursor position.
void set_eof(abort_callback & p_abort) {resize(get_position(p_abort),p_abort);}
//! Helper; retrieves size of the file. If size is not available (get_size() returns filesize_invalid), throws exception_io_no_length.
t_filesize get_size_ex(abort_callback & p_abort);
//! Helper; retrieves amount of bytes between read/write cursor position and end of file. Fails when length can't be determined.
t_filesize get_remaining(abort_callback & p_abort);
//! Helper; throws exception_io_object_not_seekable if file is not seekable.
void ensure_seekable();
//! Helper; throws exception_io_object_is_remote if the file is remote.
void ensure_local();
//! Helper; transfers specified number of bytes between streams.
//! @returns number of bytes actually transferred. May be less than requested if e.g. EOF is reached.
static t_filesize g_transfer(stream_reader * src,stream_writer * dst,t_filesize bytes,abort_callback & p_abort);
//! Helper; transfers specified number of bytes between streams. Throws exception if requested number of bytes could not be read (EOF).
static void g_transfer_object(stream_reader * src,stream_writer * dst,t_filesize bytes,abort_callback & p_abort);
//! Helper; transfers entire file content from one file to another, erasing previous content.
static void g_transfer_file(const service_ptr_t<file> & p_from,const service_ptr_t<file> & p_to,abort_callback & p_abort);
//! Helper; improved performance over g_transfer on streams (avoids disk fragmentation when transferring large blocks).
static t_filesize g_transfer(service_ptr_t<file> p_src,service_ptr_t<file> p_dst,t_filesize p_bytes,abort_callback & p_abort);
//! Helper; improved performance over g_transfer_file on streams (avoids disk fragmentation when transferring large blocks).
static void g_transfer_object(service_ptr_t<file> p_src,service_ptr_t<file> p_dst,t_filesize p_bytes,abort_callback & p_abort);
t_filesize skip(t_filesize p_bytes,abort_callback & p_abort);
FB2K_MAKE_SERVICE_INTERFACE(file,service_base);
};
typedef service_ptr_t<file> file_ptr;
//! Special hack for shoutcast metadata nonsense handling. Documentme.
class file_dynamicinfo : public file {
public:
//! Retrieves "static" info that doesn't change in the middle of stream, such as station names etc. Returns true on success; false when static info is not available.
virtual bool get_static_info(class file_info & p_out) = 0;
//! Returns whether dynamic info is available on this stream or not.
virtual bool is_dynamic_info_enabled()=0;
//! Retrieves dynamic stream info (e.g. online stream track titles). Returns true on success, false when info has not changed since last call.
virtual bool get_dynamic_info(class file_info & p_out) = 0;
FB2K_MAKE_SERVICE_INTERFACE(file_dynamicinfo,file);
};
//! Implementation helper - contains dummy implementations of methods that modify the file
template<typename t_base> class file_readonly_t : public t_base {
public:
void resize(t_filesize p_size,abort_callback & p_abort) {throw exception_io_denied();}
void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {throw exception_io_denied();}
};
typedef file_readonly_t<file> file_readonly;
class filesystem;
class NOVTABLE directory_callback {
public:
//! @returns true to continue enumeration, false to abort.
virtual bool on_entry(filesystem * p_owner,abort_callback & p_abort,const char * p_url,bool p_is_subdirectory,const t_filestats & p_stats)=0;
};
//! Entrypoint service for all filesystem operations.\n
//! Implementation: standard implementations for local filesystem etc are provided by core.\n
//! Instantiation: use static helper functions rather than calling filesystem interface methods directly, e.g. filesystem::g_open() to open a file.
class NOVTABLE filesystem : public service_base {
public:
//! Enumeration specifying how to open a file. See: filesystem::open(), filesystem::g_open().
enum t_open_mode {
//! Opens an existing file for reading; if the file does not exist, the operation will fail.
open_mode_read,
//! Opens an existing file for writing; if the file does not exist, the operation will fail.
open_mode_write_existing,
//! Opens a new file for writing; if the file exists, its contents will be wiped.
open_mode_write_new,
};
virtual bool get_canonical_path(const char * p_path,pfc::string_base & p_out)=0;
virtual bool is_our_path(const char * p_path)=0;
virtual bool get_display_path(const char * p_path,pfc::string_base & p_out)=0;
virtual void open(service_ptr_t<file> & p_out,const char * p_path, t_open_mode p_mode,abort_callback & p_abort)=0;
virtual void remove(const char * p_path,abort_callback & p_abort)=0;
virtual void move(const char * p_src,const char * p_dst,abort_callback & p_abort)=0;
//! Queries whether a file at specified path belonging to this filesystem is a remove object or not.
virtual bool is_remote(const char * p_src) = 0;
//! Retrieves stats of a file at specified path.
virtual void get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort) = 0;
virtual bool relative_path_create(const char * file_path,const char * playlist_path,pfc::string_base & out) {return false;}
virtual bool relative_path_parse(const char * relative_path,const char * playlist_path,pfc::string_base & out) {return false;}
//! Creates a directory.
virtual void create_directory(const char * p_path,abort_callback & p_abort) = 0;
virtual void list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort)=0;
//! Hint; returns whether this filesystem supports mime types. \n
//! When this returns false, all file::get_content_type() calls on files opened thru this filesystem implementation will return false; otherwise, file::get_content_type() calls may return true depending on the file.
virtual bool supports_content_types() = 0;
static void g_get_canonical_path(const char * path,pfc::string_base & out);
static void g_get_display_path(const char * path,pfc::string_base & out);
static bool g_get_interface(service_ptr_t<filesystem> & p_out,const char * path);//path is AFTER get_canonical_path
static bool g_is_remote(const char * p_path);//path is AFTER get_canonical_path
static bool g_is_recognized_and_remote(const char * p_path);//path is AFTER get_canonical_path
static bool g_is_remote_safe(const char * p_path) {return g_is_recognized_and_remote(p_path);}
static bool g_is_remote_or_unrecognized(const char * p_path);
static bool g_is_recognized_path(const char * p_path);
//! Opens file at specified path, with specified access privileges.
static void g_open(service_ptr_t<file> & p_out,const char * p_path,t_open_mode p_mode,abort_callback & p_abort);
//! Attempts to open file at specified path; if the operation fails with sharing violation error, keeps retrying (with short sleep period between retries) for specified amount of time.
static void g_open_timeout(service_ptr_t<file> & p_out,const char * p_path,t_open_mode p_mode,double p_timeout,abort_callback & p_abort);
static void g_open_write_new(service_ptr_t<file> & p_out,const char * p_path,abort_callback & p_abort);
static void g_open_read(service_ptr_t<file> & p_out,const char * path,abort_callback & p_abort) {return g_open(p_out,path,open_mode_read,p_abort);}
static void g_open_precache(service_ptr_t<file> & p_out,const char * path,abort_callback & p_abort);//open only for precaching data (eg. will fail on http etc)
static bool g_exists(const char * p_path,abort_callback & p_abort);
static bool g_exists_writeable(const char * p_path,abort_callback & p_abort);
//! Removes file at specified path.
static void g_remove(const char * p_path,abort_callback & p_abort);
//! Attempts to remove file at specified path; if the operation fails with a sharing violation error, keeps retrying (with short sleep period between retries) for specified amount of time.
static void g_remove_timeout(const char * p_path,double p_timeout,abort_callback & p_abort);
//! Moves file from one path to another.
static void g_move(const char * p_src,const char * p_dst,abort_callback & p_abort);
//! Attempts to move file from one path to another; if the operation fails with a sharing violation error, keeps retrying (with short sleep period between retries) for specified amount of time.
static void g_move_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort);
static void g_copy(const char * p_src,const char * p_dst,abort_callback & p_abort);//needs canonical path
static void g_copy_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort);//needs canonical path
static void g_copy_directory(const char * p_src,const char * p_dst,abort_callback & p_abort);//needs canonical path
static void g_get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort);
static bool g_relative_path_create(const char * p_file_path,const char * p_playlist_path,pfc::string_base & out);
static bool g_relative_path_parse(const char * p_relative_path,const char * p_playlist_path,pfc::string_base & out);
static void g_create_directory(const char * p_path,abort_callback & p_abort);
//! If for some bloody reason you ever need stream io compatibility, use this, INSTEAD of calling fopen() on the path string you've got; will only work with file:// (and not with http://, unpack:// or whatever)
static FILE * streamio_open(const char * p_path,const char * p_flags);
static void g_open_temp(service_ptr_t<file> & p_out,abort_callback & p_abort);
static void g_open_tempmem(service_ptr_t<file> & p_out,abort_callback & p_abort);
static void g_list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort);// path must be canonical
static bool g_is_valid_directory(const char * path,abort_callback & p_abort);
static bool g_is_empty_directory(const char * path,abort_callback & p_abort);
FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(filesystem);
};
class directory_callback_impl : public directory_callback
{
struct t_entry
{
pfc::string_simple m_path;
t_filestats m_stats;
t_entry(const char * p_path, const t_filestats & p_stats) : m_path(p_path), m_stats(p_stats) {}
};
pfc::list_t<pfc::rcptr_t<t_entry> > m_data;
bool m_recur;
static int sortfunc(const pfc::rcptr_t<const t_entry> & p1, const pfc::rcptr_t<const t_entry> & p2) {return stricmp_utf8(p1->m_path,p2->m_path);}
public:
bool on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats);
directory_callback_impl(bool p_recur) : m_recur(p_recur) {}
t_size get_count() {return m_data.get_count();}
const char * operator[](t_size n) const {return m_data[n]->m_path;}
const char * get_item(t_size n) const {return m_data[n]->m_path;}
const t_filestats & get_item_stats(t_size n) const {return m_data[n]->m_stats;}
void sort() {m_data.sort_t(sortfunc);}
};
class archive;
class NOVTABLE archive_callback : public abort_callback {
public:
virtual bool on_entry(archive * owner,const char * url,const t_filestats & p_stats,const service_ptr_t<file> & p_reader) = 0;
};
//! Interface for archive reader services. When implementing, derive from archive_impl rather than from deriving from archive directly.
class NOVTABLE archive : public filesystem {
public:
virtual void archive_list(const char * p_path,const service_ptr_t<file> & p_reader,archive_callback & p_callback,bool p_want_readers) = 0;
FB2K_MAKE_SERVICE_INTERFACE(archive,filesystem);
};
//! Root class for archive implementations. Derive from this instead of from archive directly.
class NOVTABLE archive_impl : public archive {
private:
//do not override these
bool get_canonical_path(const char * path,pfc::string_base & out);
bool is_our_path(const char * path);
bool get_display_path(const char * path,pfc::string_base & out);
void remove(const char * path,abort_callback & p_abort);
void move(const char * src,const char * dst,abort_callback & p_abort);
bool is_remote(const char * src);
bool relative_path_create(const char * file_path,const char * playlist_path,pfc::string_base & out);
bool relative_path_parse(const char * relative_path,const char * playlist_path,pfc::string_base & out);
void open(service_ptr_t<file> & p_out,const char * path, t_open_mode mode,abort_callback & p_abort);
void create_directory(const char * path,abort_callback &);
void list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort);
void get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort);
protected:
//override these
virtual const char * get_archive_type()=0;//eg. "zip", must be lowercase
virtual t_filestats get_stats_in_archive(const char * p_archive,const char * p_file,abort_callback & p_abort) = 0;
virtual void open_archive(service_ptr_t<file> & p_out,const char * archive,const char * file, abort_callback & p_abort)=0;//opens for reading
public:
//override these
virtual void archive_list(const char * path,const service_ptr_t<file> & p_reader,archive_callback & p_out,bool p_want_readers)=0;
static bool g_parse_unpack_path(const char * path,pfc::string8 & archive,pfc::string8 & file);
static void g_make_unpack_path(pfc::string_base & path,const char * archive,const char * file,const char * name);
void make_unpack_path(pfc::string_base & path,const char * archive,const char * file);
};
template<typename T>
class archive_factory_t : public service_factory_single_t<T> {};
t_filetimestamp filetimestamp_from_system_timer();
void generate_temp_location_for_file(pfc::string_base & p_out, const char * p_origpath,const char * p_extension,const char * p_magic);
static file_ptr fileOpen(const char * p_path,filesystem::t_open_mode p_mode,abort_callback & p_abort,double p_timeout) {
file_ptr temp; filesystem::g_open_timeout(temp,p_path,p_mode,p_timeout,p_abort); PFC_ASSERT(temp.is_valid()); return temp;
}
static file_ptr fileOpenReadExisting(const char * p_path,abort_callback & p_abort,double p_timeout = 0) {
return fileOpen(p_path,filesystem::open_mode_read,p_abort,p_timeout);
}
static file_ptr fileOpenWriteExisting(const char * p_path,abort_callback & p_abort,double p_timeout = 0) {
return fileOpen(p_path,filesystem::open_mode_write_existing,p_abort,p_timeout);
}
static file_ptr fileOpenWriteNew(const char * p_path,abort_callback & p_abort,double p_timeout = 0) {
return fileOpen(p_path,filesystem::open_mode_write_new,p_abort,p_timeout);
}
template<typename t_list>
class directory_callback_retrieveList : public directory_callback {
public:
directory_callback_retrieveList(t_list & p_list,bool p_getFiles,bool p_getSubDirectories) : m_list(p_list), m_getFiles(p_getFiles), m_getSubDirectories(p_getSubDirectories) {}
bool on_entry(filesystem * p_owner,abort_callback & p_abort,const char * p_url,bool p_is_subdirectory,const t_filestats & p_stats) {
p_abort.check();
if (p_is_subdirectory ? m_getSubDirectories : m_getFiles) {
m_list.add_item(p_url);
}
return true;
}
private:
const bool m_getSubDirectories;
const bool m_getFiles;
t_list & m_list;
};
template<typename t_list>
class directory_callback_retrieveListEx : public directory_callback {
public:
directory_callback_retrieveListEx(t_list & p_files, t_list & p_directories) : m_files(p_files), m_directories(p_directories) {}
bool on_entry(filesystem * p_owner,abort_callback & p_abort,const char * p_url,bool p_is_subdirectory,const t_filestats & p_stats) {
p_abort.check();
if (p_is_subdirectory) m_directories += p_url;
else m_files += p_url;
return true;
}
private:
t_list & m_files;
t_list & m_directories;
};
template<typename t_list> class directory_callback_retrieveListRecur : public directory_callback {
public:
directory_callback_retrieveListRecur(t_list & p_list) : m_list(p_list) {}
bool on_entry(filesystem * owner,abort_callback & p_abort,const char * path, bool isSubdir, const t_filestats&) {
if (isSubdir) {
try { owner->list_directory(path,*this,p_abort); } catch(exception_io) {}
} else {
m_list.add_item(path);
}
return true;
}
private:
t_list & m_list;
};
template<typename t_list>
static void listFiles(const char * p_path,t_list & p_out,abort_callback & p_abort) {
directory_callback_retrieveList<t_list> callback(p_out,true,false);
filesystem::g_list_directory(p_path,callback,p_abort);
}
template<typename t_list>
static void listDirectories(const char * p_path,t_list & p_out,abort_callback & p_abort) {
directory_callback_retrieveList<t_list> callback(p_out,false,true);
filesystem::g_list_directory(p_path,callback,p_abort);
}
template<typename t_list>
static void listFilesAndDirectories(const char * p_path,t_list & p_files,t_list & p_directories,abort_callback & p_abort) {
directory_callback_retrieveListEx<t_list> callback(p_files,p_directories);
filesystem::g_list_directory(p_path,callback,p_abort);
}
template<typename t_list>
static void listFilesRecur(const char * p_path,t_list & p_out,abort_callback & p_abort) {
directory_callback_retrieveListRecur<t_list> callback(p_out);
filesystem::g_list_directory(p_path,callback,p_abort);
}
bool extract_native_path(const char * p_fspath,pfc::string_base & p_native);
bool _extract_native_path_ptr(const char * & p_fspath);
template<typename T>
pfc::string getPathDisplay(const T& source) {
pfc::string_formatter temp;
filesystem::g_get_display_path(pfc::stringToPtr(source),temp);
return temp.toString();
}
template<typename T>
pfc::string getPathCanonical(const T& source) {
pfc::string_formatter temp;
filesystem::g_get_canonical_path(pfc::stringToPtr(source),temp);
return temp.toString();
}
}
using namespace foobar2000_io;
#include "filesystem_helper.h"
| [
"carl@72871cd9-16e1-0310-933f-800000000000"
] | [
[
[
1,
591
]
]
] |
cbfc20b71ea3802dbe9bd51956bd2e7570b0ec2d | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Common/Base/Container/PointerMap/hkMap.cxx | b2808bbb73c6b61a11a6e28e3acca40aa4c4588e | [] | no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,047 | cxx | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#if 0
// Debugging for iterators. The most common problem is using an iterator after the map has been modified.
// We can catch resizes easily by watching m_hashMod, but to do this properly we need an int m_serial which
// gets incremented on every mutate. (otherwise we may miss a delete&insert, as m_hashMod and m_size remain constant)
struct Iterator { Iterator(int i, int s) : index(i), serial(s) {} int index; int serial; };
#define HK_MAP_INDEX_TO_ITERATOR(i) Iterator(i,m_serial)
inline int HK_MAP_ITERATOR_TO_INDEX(Iterator it) const
{
HK_ASSERT2(0x1be297d6, it.hashMod == m_hashMod, "iterator invalidated" );
return it.index;
}
#endif
// Quick description:
// The hash table is stored as a linear list. Initially all keys
// are zero (empty). When we insert an element, we jump to the items
// hash and scan forwards until we find the key or we come to a zero entry.
// If the hash function is good and the table is not too crowded, we're
// likely to have good performance and be cache friendly.
static const int s_minimumCapacity = 8;
template < typename KEY, typename VAL, typename OPS >
hkMapBase<KEY,VAL,OPS>::hkMapBase(void* ptr, int sizeInBytes)
{
int maxKeys = unsigned(sizeInBytes) / (sizeof(Pair)); // unsigned div = shift
HK_ASSERT( 0x6129a7bc, maxKeys >= s_minimumCapacity );
HK_ASSERT( 0x549309be, isPower2(maxKeys) );
m_elem = static_cast<Pair*>(ptr);
m_numElems = DONT_DEALLOCATE_FLAG;
m_hashMod = maxKeys - 1;
HK_ASSERT( 0x549309bf, (maxKeys*hkSizeOf(Pair)) == sizeInBytes );
for (int i = 0; i < maxKeys; i++)
{
OPS::invalidate( m_elem[i].key );
}
}
template < typename KEY, typename VAL, typename OPS >
void hkMapBase<KEY,VAL,OPS>::clear()
{
int capacity = m_hashMod+1;
for (int i = 0; i < capacity; i++)
{
OPS::invalidate( m_elem[i].key );
}
m_numElems = 0 | (m_numElems & static_cast<int>(DONT_DEALLOCATE_FLAG));
}
template < typename KEY, typename VAL, typename OPS >
void hkMapBase<KEY,VAL,OPS>::clearAndDeallocate(hkMemoryAllocator& alloc)
{
clear();
if( (m_numElems & DONT_DEALLOCATE_FLAG) == 0 )
{
alloc.blockFree( m_elem, sizeof(Pair)* (m_hashMod+1) );
HK_ON_DEBUG( m_numElems |= DONT_DEALLOCATE_FLAG );
}
}
template < typename KEY, typename VAL, typename OPS >
hkMapBase<KEY,VAL,OPS>::~hkMapBase()
{
HK_ASSERT2(0x2a1ebb4e, (m_numElems & DONT_DEALLOCATE_FLAG) || (m_elem == HK_NULL), "memory not freed" );
}
template < typename KEY, typename VAL, typename OPS >
hkBool32 hkMapBase<KEY,VAL,OPS>::insert( hkMemoryAllocator& alloc, KEY key, VAL val )
{
HK_ASSERT2(0x19291575, OPS::isValid(key), "pointer map keys must not be the empty value");
// This is quite conservative. We could grow more
// slowly at the cost of potentially longer searches.
int numElems = m_numElems & static_cast<int>(NUM_ELEMS_MASK);
if( (numElems + numElems) > m_hashMod )
{
resizeTable(alloc, m_hashMod + m_hashMod + 2);
}
unsigned i;
hkBool32 isNewKey = true;
for( i = OPS::hash(key, m_hashMod);
OPS::isValid(m_elem[i].key);
i = (i+1) & m_hashMod )
{
// find free slot
if( OPS::equal( m_elem[i].key, key ) )
{
isNewKey = false;
break;
}
}
// dont increment m_numElems if overwriting.
m_numElems += isNewKey;
// insert key,value
m_elem[i].key = key;
m_elem[i].val = val;
return isNewKey;
}
template < typename KEY, typename VAL, typename OPS >
typename hkMapBase<KEY,VAL,OPS>::Iterator hkMapBase<KEY,VAL,OPS>::findKey( KEY key ) const
{
if( m_hashMod > 0 )
{
for( unsigned i = OPS::hash(key, m_hashMod);
OPS::isValid( m_elem[i].key );
i = (i+1) & m_hashMod)
{
if( OPS::equal( m_elem[i].key, key ) )
{
return HK_MAP_INDEX_TO_ITERATOR(i); // found
}
}
}
return HK_MAP_INDEX_TO_ITERATOR(m_hashMod+1); // not found
}
template < typename KEY, typename VAL, typename OPS >
typename hkMapBase<KEY,VAL,OPS>::Iterator hkMapBase<KEY,VAL,OPS>::findOrInsertKey( hkMemoryAllocator& alloc, KEY key, VAL val )
{
HK_ASSERT2(0x19291575, OPS::isValid(key), "pointer map keys must not be the empty value");
// reserve space for another element
int numElems = m_numElems & static_cast<int>(NUM_ELEMS_MASK);
if( (numElems + numElems) > m_hashMod )
{
resizeTable(alloc, m_hashMod + m_hashMod + 2);
}
unsigned i;
for( i = OPS::hash(key, m_hashMod);
true;
i = (i+1) & m_hashMod)
{
if( OPS::equal( m_elem[i].key, key ) )
{
return HK_MAP_INDEX_TO_ITERATOR(i); // found
}
else if( OPS::isValid(m_elem[i].key) == false ) // end of chain, insert
{
m_elem[i].key = key;
m_elem[i].val = val;
m_numElems += 1;
return HK_MAP_INDEX_TO_ITERATOR( i ); // new elem
}
}
// notreached
}
template < typename KEY, typename VAL, typename OPS >
hkResult hkMapBase<KEY,VAL,OPS>::get( KEY key, VAL* out ) const
{
Iterator it = findKey(key);
if( isValid(it) )
{
*out = getValue(it);
return HK_SUCCESS;
}
return HK_FAILURE;
}
template < typename KEY, typename VAL, typename OPS >
VAL hkMapBase<KEY,VAL,OPS>::getWithDefault( KEY key, VAL def ) const
{
if( m_hashMod > 0 )
{
for( unsigned i = OPS::hash(key, m_hashMod);
OPS::isValid( m_elem[i].key );
i = (i+1) & m_hashMod)
{
if( OPS::equal( m_elem[i].key, key ) )
{
return m_elem[i].val;
}
}
}
return def;
}
template < typename KEY, typename VAL, typename OPS >
void hkMapBase<KEY,VAL,OPS>::remove( Iterator it )
{
HK_ASSERT(0x5a6d564c, isValid(it));
HK_ASSERT(0x5a6d564d, getSize() > 0);
unsigned i = HK_MAP_ITERATOR_TO_INDEX(it);
// remove it
--m_numElems;
OPS::invalidate( m_elem[i].key );
// find lowest element of this unbroken run
unsigned lo = ( i + m_hashMod ) & m_hashMod;
while( OPS::isValid( m_elem[lo].key ) )
{
lo = ( lo + m_hashMod ) & m_hashMod;
}
lo = ( lo + 1 ) & m_hashMod;
// the slot which has become empty
unsigned empty = i;
// shift up, closing any gaps we find
for(i = (i + 1) & m_hashMod;
OPS::isValid( m_elem[i].key ); // end of run
i = (i + 1) & m_hashMod )
{
unsigned hash = OPS::hash( m_elem[i].key, m_hashMod );
// Three cases to consider here.
// a) The normal case where lo <= empty < i.
// b) The case where i has wrapped around.
// c) The case where both i and empty have wrapped around.
// The initial case will be a. (Or b if the last slot is freed).
// and may progress to b, and finally c.
// The algorithm will terminate before 'i' reaches 'lo'
// otherwise the table would have no free slots.
// 'normal' 'i wrapped' 'i and empty wrapped'
// ===== lo ===== i ===== empty
// ===== empty ===== lo ===== i
// ===== i ===== empty ===== lo
if( ( i >= lo ) && ( hash > empty ) )
{
continue;
}
else if( ( i < empty ) && ( hash > empty || hash <= i ) )
{
continue;
}
else if( /*i > empty && */ ( hash > empty && hash < lo ) )
{
continue;
}
HK_ASSERT(0x45e3d455, i != empty ); // by design
HK_ASSERT(0x5ef0d6c0, i != lo ); // table became full?!
// copy up
m_elem[empty].key = m_elem[i].key;
m_elem[empty].val = m_elem[i].val;
// source slot is now free
OPS::invalidate( m_elem[i].key );
empty = i;
}
}
template < typename KEY, typename VAL, typename OPS >
hkResult hkMapBase<KEY,VAL,OPS>::remove( KEY key )
{
Iterator it = findKey(key);
if( isValid(it) )
{
remove(it);
return HK_SUCCESS;
}
return HK_FAILURE;
}
template < typename KEY, typename VAL, typename OPS >
void hkMapBase<KEY,VAL,OPS>::reserve( hkMemoryAllocator& alloc, int numElements )
{
// Make sure that the actual table size is not going to be less than twice the current number of elements
HK_ASSERT(0x4d0c5314, numElements >= 0 && (m_numElems & static_cast<int>(NUM_ELEMS_MASK)) * 2 <= numElements * 3 );
int minCap = numElements * 2;
int cap = s_minimumCapacity;
while (cap < minCap) { cap *= 2; }
resizeTable( alloc, cap );
}
template < typename KEY, typename VAL, typename OPS >
void hkMapBase<KEY,VAL,OPS>::resizeTable(hkMemoryAllocator& alloc, int newcap)
{
newcap = hkMath::max2( newcap, s_minimumCapacity );
HK_ASSERT2(0x57c91b4a, m_numElems < newcap, "table size is not big enough" );
HK_ASSERT2(0x6c8f2576, HK_NEXT_MULTIPLE_OF(2, newcap) == newcap, "table size should be a power of 2" );
hkBool32 dontDeallocate = m_numElems & static_cast<int>(DONT_DEALLOCATE_FLAG);
int oldcap = m_hashMod+1;
Pair* oldelem = m_elem;
m_elem = static_cast<Pair*>( alloc.blockAlloc( sizeof(Pair)*newcap ) ); // space for values too
for (int i = 0; i < newcap; i++)
{
OPS::invalidate( m_elem[i].key );
}
m_numElems = 0;
m_hashMod = newcap - 1;
for( int i = 0; i < oldcap; ++i )
{
if( OPS::isValid( oldelem[i].key ) )
{
insert( alloc, oldelem[i].key, oldelem[i].val );
}
}
if (dontDeallocate == 0)
{
alloc.blockFree( oldelem, sizeof(Pair)*oldcap );
}
}
template < typename KEY, typename VAL, typename OPS >
hkBool hkMapBase<KEY,VAL,OPS>::isOk() const
{
// is count consistent?
int count = 0;
int i;
for( i = 0; i <= m_hashMod; ++i )
{
count += OPS::isValid( m_elem[i].key );
}
HK_ASSERT(0x26f64ec4, count == (m_numElems & static_cast<int>(NUM_ELEMS_MASK)) );
// is element reachable from its hash?
for( i = 0; i <= m_hashMod; ++i )
{
if( OPS::isValid(m_elem[i].key) )
{
unsigned j = OPS::hash( m_elem[i].key, m_hashMod );
while( OPS::equal(m_elem[j].key, m_elem[i].key) == false )
{
j = (j + 1) & m_hashMod;
HK_ASSERT(0x4f6528df, OPS::isValid(m_elem[j].key) );
}
}
}
return true;
}
template < typename KEY, typename VAL, typename OPS >
int hkMapBase<KEY,VAL,OPS>::getSizeInBytesFor(int numOfKeys)
{
// adjust the number to the power of 2
int numSlots = numOfKeys * 2; // half full
int cap;
for( cap = s_minimumCapacity; cap < numSlots; cap *= 2 )
{
// double until sufficient capacity
}
return cap * hkSizeOf(Pair);
}
template < typename KEY, typename VAL, typename OPS >
int hkMapBase<KEY,VAL,OPS>::getMemSize() const
{
return (m_hashMod + 1) * hkSizeOf(Pair);
}
template < typename KEY, typename VAL, typename OPS, typename ALLOC >
void hkMap<KEY,VAL,OPS,ALLOC>::swap( hkMap& other )
{
typename hkMapBase<KEY,VAL,OPS>::Pair* te = hkMapBase<KEY,VAL,OPS>::m_elem;
hkUlong tn = hkMapBase<KEY,VAL,OPS>::m_numElems;
hkUlong th = hkMapBase<KEY,VAL,OPS>::m_hashMod;
hkMapBase<KEY,VAL,OPS>::m_elem = other.m_elem;
hkMapBase<KEY,VAL,OPS>::m_numElems = other.m_numElems;
hkMapBase<KEY,VAL,OPS>::m_hashMod = other.m_hashMod;
other.m_elem = te;
other.m_numElems = static_cast<int>(tn);
other.m_hashMod = static_cast<int>(th);
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
] | [
[
[
1,
390
]
]
] |
43adba57371f7808a71a8fea5c7ced2de42fcf9d | a1fc2d997221a801e11b57c5d7d28dbd2f462978 | /gravsim420/planetObj.cpp | e8147fdd66eb8ac1c90375e39a6b66f3009e76a0 | [] | no_license | misterbowtie/gravsim420 | daf2a262de88db4f8bb520bb9fae2f6aa01932a5 | f5532aa3c8fd64a7f85881e698f1025058dee189 | refs/heads/master | 2021-01-19T06:19:56.460262 | 2006-12-03T23:40:24 | 2006-12-03T23:40:24 | 32,546,587 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,438 | cpp | #ifndef PLANETOBJ_CPP
#define PLANETOBJ_CPP
#include <iostream>
#include <math.h>
#include "const.h"
#include "planetObj.h"
using namespace std;
planetObj::planetObj(ISceneManager *smgrz, IVideoDriver* driverz, vector3df p = vector3df(0,0,0), vector3df v = vector3df(0,0,0), vector3df r = vector3df(0,ROT,0), float m = 1, float s=1)
{
smgr = smgrz;
driver = driverz;
rotationSpeed = r;
position = p;
velocity = v;
force = vector3df(0,0,0);
rotation = vector3df(0,0,0);
mass = m;
volume = s;
//mesh = smgr->getMesh("media/earth.x");
node = smgr->addSphereSceneNode(1,10);
particle = smgr->addParticleSystemSceneNode(false,node);
changeAttb();
}
planetObj::~planetObj()
{
node->remove();
if (D){cout<<"\nDELETE PLANET.";report();}
}
void planetObj::report()
{
cout << "\n M: " << mass << " S: " << volume << " V: " << velocity.getLength() << " P: " << position.getLength();
}
void planetObj::join(planetObj *p2)
{
if (D){
cout << "\nJoin:";
report();
(*p2).report();
}
mass += (*p2).mass;
float p2scale = (*p2).mass / mass;
float p1scale = 1.0 - p2scale;
position = position * p1scale + (*p2).position * p2scale;
velocity = velocity * p1scale + (*p2).velocity * p2scale;
force += (*p2).force;
volume += (*p2).volume;
(*p2).createParticleExplosion();
changeAttb();
if (D){
cout << "\nPlanet Joined";
}
}
void planetObj::addForce(vector3df f)
{
force += f;
}
void planetObj::move()
{
a = force / mass;
velocity += a * t;
position += velocity * t;
force.set(0,0,0);
node->setPosition(vector3df(0,0,0));
rotation-=rotationSpeed/size;
node->setRotation(rotation);
node->setPosition(position);
}
void planetObj::explode(std::list<planetObj> &poList)
{
if (D){cout<<"\nExplode before: ";report();}
std::list<planetObj>::iterator p1 = poList.end();
vector3df centerG;
for(int p=0; p<numPieces; p++)
{
planetObj *npo = new planetObj(smgr, driver);
float mscale = 1/numPieces;// * (1.0f + randf()*.2-.1); // +/-10% error
(*npo).mass = mscale * mass;
float sscale = mscale*(1.0f + randf()*.4-.2); // +/-20% error
(*npo).volume = volume * sscale;
(*npo).changeAttb();
// make displacement vector
vector3df offset;
if(randf()<.8)
offset.set(randf()-.5, randf()-.5, randf()-.5);
else
offset = -centerG;
offset.setLength((.5+randf()*1.5)* size);
centerG+=offset;
// displace radius of orignal size
(*npo).position = position + offset;
// retain rotaional velocity, but linear
(*npo).velocity = velocity + offset*OFORCE + offset.crossProduct(rotationSpeed);
/*float display[4];
if (D){ (offset * dist * (1-mscale)).getAs4Values(display);
cout<<"\n offset: "<<display[0]<<","<<display[1]<<","<<display[2];
}*/
force -= (*npo).velocity/t;
poList.push_back(*npo);
}
force/=numPieces;
}
void planetObj::changeAttb()
{
size = pow(volume,.3333f);
//node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true); //fixes lighting?
node->setMaterialFlag(EMF_LIGHTING, false);
//particle->setEmitter(0);
if (mass>SystemMass*.1f)
{ //star
node->setMaterialTexture( 0, driver->getTexture("media/sun.jpg") );
smgr->addLightSceneNode(node); //if this is being executed for all nodes....then the lighting is fucked up too
node->setMaterialFlag(video::EMF_LIGHTING, false);
node->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);
//particle = smgr->addParticleSystemSceneNode(false,node);
particle->setScale(vector3df(2,2,2));
particle->setParticleSize(dimension2d<f32>(8.0f, 8.0f));
particle->setParticlesAreGlobal(false); //makes it only create particles when changeattr is called
IParticleEmitter* em = particle->createPointEmitter(vector3df(0.0f,size*.002f,0.0f),10,50,SColor(0,255,255,255), SColor(0,255,255,255), 800,850,180);
//
particle->setEmitter(em);
em->drop();
IParticleAffector* paf = particle->createFadeOutParticleAffector();
particle->addAffector(paf);
paf->drop();
particle->setMaterialFlag(video::EMF_LIGHTING, false);
particle->setMaterialTexture(0, driver->getTexture("media/fire.bmp"));
particle->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);
}
else
{
if (mass/volume > 1.2)
{ //rock
node->setMaterialTexture( 0, driver->getTexture("media/dirt.jpg") );
}
else if(mass/volume > 1.1)
{
//redrock
node->setMaterialTexture( 0, driver->getTexture("media/redrock.jpg") );
}
else if(mass/volume > 1)
{
//ice
node->setMaterialTexture( 0, driver->getTexture("media/ice.jpg") );
}
else if(mass/volume > .9)
{
//gas
node->setMaterialTexture( 0, driver->getTexture("media/gas.jpg"));
}
else
{
//planet
node->setMaterialTexture( 0, driver->getTexture("media/earth.jpg"));
}
node->setMaterialFlag(video::EMF_LIGHTING, true);
}
node->setScale(vector3df(size,size,size));
}
vector3df planetObj::getRotation(){ return rotation;}
vector3df planetObj::getPosition(){ return position;}
vector3df planetObj::getVelocity(){ return velocity;}
vector3df planetObj::getForce(){ return force;}
float planetObj::getMass(){ return mass;}
float planetObj::getSize(){ return size;}
float planetObj::getVolume(){ return volume;}
void planetObj::createParticleExplosion()
{
IParticleSystemSceneNode* ps = smgr->addParticleSystemSceneNode(false);
ps->setPosition((position));
ps->setParticleSize(dimension2d<f32>(size, size));
ps->setParticlesAreGlobal(false); //makes it only create particles when changeattr is called
IParticleEmitter* em = ps->createPointEmitter(velocity.normalize()/500,4000,5000,SColor(0,255,255,255), SColor(0,255,255,255), volume*800, volume*1000,110);
ps->setEmitter(em);
em->drop();
IParticleAffector* paf = ps->createFadeOutParticleAffector();
ps->addAffector(paf);
paf->drop();
ps->setMaterialFlag(video::EMF_LIGHTING, false);
ps->setMaterialTexture(0, driver->getTexture("media/fire.bmp"));
ps->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);
ISceneNodeAnimator *anim = smgr->createDeleteAnimator(1000/UpdatesPerFrame);
ps->addAnimator(anim);
}
#endif
| [
"aaron.canary@b131a309-ab20-0410-8173-7914f2e55ca6",
"wmluckett@b131a309-ab20-0410-8173-7914f2e55ca6"
] | [
[
[
1,
34
],
[
37,
82
],
[
90,
144
],
[
147,
193
],
[
200,
213
],
[
217,
236
]
],
[
[
35,
36
],
[
83,
89
],
[
145,
146
],
[
194,
199
],
[
214,
216
]
]
] |
e1c826f526536c61f6613df5712ba8b61af53f30 | 02cd7f7be30f7660f6928a1b8262dc935673b2d7 | / invols --username [email protected]/Region.h | d18ba6a8e45d2e9786e0dfe6485e7bab94ac7280 | [] | no_license | hksonngan/invols | f0886a304ffb81594016b3b82affc58bd61c4c0b | 336b8c2d11d97892881c02afc2fa114dbf56b973 | refs/heads/master | 2021-01-10T10:04:55.844101 | 2011-11-09T07:44:24 | 2011-11-09T07:44:24 | 46,898,469 | 1 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 861 | h | #ifndef REGION_INC
#define REGION_INC
#include <stdio.h>
#include <stdlib.h>
#include "AllDef.h"
#include "AllInc.h"
#include "vec3.h"
#include <vector>
//облать в пространстве
class Region
{
public:
virtual vec3 GetRand()=0;//случ. точка из области
virtual bool InRegion(vec3& v)=0;//из области?
virtual ~Region(){}
};
//область, образованная пересечением полупространств
//нужна для выделения мышкой точек на экране, т.к. проекция перспективная
class Flats: public Region
{
public:
Flats(vec3 pos,vec3 nv1,vec3 nv2,vec3 nv3,vec3 nv4);
virtual vec3 GetRand();
virtual bool InRegion(vec3& v);
void AddFlat(flat&nf);
private:
std::vector<flat> flats;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
ff3c3750762f2aa4aaa4912fe3040e647b56ea0b | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/06112002/Include/arch/Win32/Win32ModuleDB.h | 668cebc838576989810ba61c5844a5e13dfb44ee | [] | no_license | christhomas/fusionengine | 286b33f2c6a7df785398ffbe7eea1c367e512b8d | 95422685027bb19986ba64c612049faa5899690e | refs/heads/master | 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 700 | h | #ifndef _WIN32MODULEDB_H_
#define _WIN32MODULEDB_H_
#include <IModuleDB.h>
#include <windows.h>
/** @ingroup Win32_ModuleDB_Group
* @brief Derived IModuleDB class for the Win32 Platform
*/
class Win32ModuleDB: public IModuleDB{
protected:
virtual IModule * GetModule (char *name);
public:
Win32ModuleDB ();
virtual ~Win32ModuleDB ();
virtual void AddPath (char *path);
virtual void AddModule (IModule *module);
virtual IModule * LoadModule (char *name);
virtual bool UnloadModule (char *name);
virtual void UnloadAll (void);
virtual void * GetFunction (char *name,char *func);
};
#endif // #ifndef _WIN32MODULEDB_H_
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
] | [
[
[
1,
25
]
]
] |
42cfd13aead3bf38dbd61a87b03ff02b7979fe32 | 975e3cacad2b513dff73ddd5ce3d449ad40c293b | /babel-2014-minett_a/trunk/portaudio/NonCopyable.h | 7e2dfcadc2ab8bd3664791adaf8fb07c486a97d5 | [] | no_license | alex-min/babelroxor | 08a2babfbd1cf51dcfcba589d9acc7afcebee6e3 | 53cbdedd7d4b68943fe99d74dbb5443b799cca05 | refs/heads/master | 2021-01-10T14:24:12.257931 | 2011-12-13T10:57:30 | 2011-12-13T10:57:30 | 46,981,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | h |
#ifndef UTILS_NON_COPYABLE_H_
#define UTILS_NON_COPYABLE_H_
#include "Config.h"
namespace Utils
{
class LINK_OPTION_UTILS NonCopyable
{
protected:
NonCopyable() {}
private:
NonCopyable(const NonCopyable&);
NonCopyable& operator =(const NonCopyable&);
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
20
]
]
] |
98752611cc3104094abad5af06ad26116037adc3 | e1d76663bb020dc27abb53c8f8bb979b4738373f | /source/support/datastruct/map.hpp | 8f1628803ae28314c3195e1cfb829563ee1d30c1 | [] | no_license | fanopi/autoFloderSync | 97e29f9aa24bc8bf78aa8325996e176572f46f8a | 5232e01f43c9cc31df349a8b474c5d35a1e92ac5 | refs/heads/master | 2020-06-03T15:28:13.583695 | 2011-09-19T13:52:25 | 2011-09-19T13:52:25 | 2,338,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,632 | hpp | /*
* map.hpp
*
* Created on: 2011-4-20
* Author: fanopi
*/
#ifndef __YF_INCLUDE_SUPPORT_MAP_H__
#define __YF_INCLUDE_SUPPORT_MAP_H__
#include "redblacktree.hpp"
namespace YF{
template <typename Tf, typename Ts>
class Pair {
public:
Pair(){
first = Tf();
second = Ts();
}
Pair(const Tf &f, const Ts &s){
first = f;
second = s;
}
bool operator < (const Pair &other) const{
return (first < other.first);
}
Tf first;
Ts second;
};
template <typename Tk, typename Tv>
class Map{
public:
class Iterator {
public:
Iterator (){
node_ = NULL;
tree_ = NULL;
}
bool operator != (const Iterator &other) const{
return ((tree_ != other.tree_) || (node_ != other.node_));
}
const Pair<Tk, Tv>& operator * () const{
return node_->key;
}
Iterator& operator ++ (int){
node_ = tree_->Next(node_);
return *this;
}
Iterator operator ++ (){
typename RBTree<Pair<Tk, Tv> >::Node *cur = node_;
node_ = tree_->Next(node_);
return Iterator(tree_, cur);
}
Iterator operator - (size_t num) const{
size_t count;
typename RBTree<Pair<Tk, Tv> >::Node *cur = node_;
cur = tree_->Prev(node_);
for (count = 0; count < num; count++) {
cur = tree_->Prev(node_);
if (cur == NULL) {
return Iterator(tree_, NULL);
}
}
return Iterator(tree_, cur);
}
bool operator == (const Iterator &other) const{
return ((tree_ == other.tree_) && (node_ == other.node_));
}
private:
Iterator(const RBTree<Pair<Tk, Tv> > *tree, typename RBTree<Pair<Tk, Tv> >::Node *node){
node_ = node;
tree_ = tree;
}
typename RBTree<Pair<Tk, Tv> >::Node* node_;
const RBTree<Pair<Tk, Tv> >* tree_;
friend class Map<Tk, Tv>;
};
Iterator Begin() const{
return Iterator(&tree_, tree_.Begin());
}
Iterator End() const{
return Iterator(&tree_, NULL);
}
void Erase(Iterator& it){
tree_.Erase(it.node_);
}
void Erase(const Tk &key){
tree_.Erase(Pair<Tk, Tv>(key, Tv()));
}
Iterator Find(const Tk &key) const{
return Iterator(&tree_, tree_.Find(Pair<Tk, Tv>(key, Tv())));
}
Iterator Insert(const Tk &key, const Tv &data){
return Iterator(&tree_, tree_.Insert(Pair<Tk, Tv>(key, data)));
}
size_t Reserve(size_t count){
return tree_.Reserve(count);
}
private:
RBTree<Pair<Tk, Tv> > tree_;
};
} /// namespace YF ///
#endif /// __YF_INCLUDE_SUPPORT_MAP_H__
| [
"[email protected]"
] | [
[
[
1,
128
]
]
] |
ee73d1b32003df25d037c13fae8671f9d01b1992 | 300647f6857b2474b192a7db9d5986baede11934 | /titleitem.h | 5e35e8d9d455a7f5f08e0a900b756b3466127408 | [] | no_license | xyhp915/hoolai-note | 1d0492a4735318d2b4fb900103bd147d673aa904 | f87fb1e9a2b43301a5ea6df6124ec200133f662c | refs/heads/master | 2021-03-12T20:25:04.403449 | 2011-03-19T05:41:49 | 2011-03-19T05:41:49 | 42,341,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 750 | h | #ifndef TITLEITEM_H
#define TITLEITEM_H
#include <QStyledItemDelegate>
QT_FORWARD_DECLARE_CLASS(QPushButton)
QT_FORWARD_DECLARE_CLASS(QFrame)
QT_FORWARD_DECLARE_CLASS(QLabel)
class TitleItem : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit TitleItem(QObject *parent = 0);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
signals:
public slots:
void DeleteTitle();
private:
QPushButton *del;
QLabel *title;
QFrame *frame;
};
#endif // TITLEITEM_H
| [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
1f716e477c1118f34d318c1ac445edafd4052375 | 16ba4fade5a6aa7f3f7c4bd73874df7ebed4477e | /src/support/debug/checkscopetime.h | 85d1ec16d836e9745c80e76b7a1f953555d3cb4e | [] | no_license | jleahred/maiquel-toolkit-cpp | f31304307d7da9af5ddeed73ffc8fcc0eceb926e | f19415a48a0d06ebe21b31aacc95da174c02d14f | refs/heads/master | 2020-05-01T14:11:48.263204 | 2011-02-09T22:01:00 | 2011-02-09T22:01:00 | 37,780,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | h | #ifndef MTK_CHECKSCOPETIME_H
#define MTK_CHECKSCOPETIME_H
#include <map>
#include "support/tuples.hpp"
namespace mtk{
class CheckScopeTime
{
public:
CheckScopeTime(const char* _name);
~CheckScopeTime();
void Stop (void);
void Start(void);
static void PrintTimes (void);
private:
const char* name;
__int64 start;
bool running;
static std::map<std::string, mtk::tuple<__int64, int/*contador*/, bool/*running*/> > mNameTime;
static void AddTime (const char* name, __int64 tq);
static bool RegisterStart (const char* name);
static void RegisterStop (const char* name);
static void IncrementCounter(const char* name);
};
}; // end namespace mtk
#endif // CHECKSCOPETIME_H
| [
"none"
] | [
[
[
1,
45
]
]
] |
d7f059d9f7c8d2fd6d6cd86e14829a758a56cd52 | 59abf9cf4595cc3d2663fcb38bacd328ab6618af | /MCD/Render/SphereBuilder.h | b797ca075ffe101a5f61458282fe7d5be28c72e8 | [] | no_license | DrDrake/mcore3d | 2ce53148ae3b9c07a3d48b15b3f1a0eab7846de6 | 0bab2c59650a815d6a5b581a2c2551d0659c51c3 | refs/heads/master | 2021-01-10T17:08:00.014942 | 2011-03-18T09:16:28 | 2011-03-18T09:16:28 | 54,134,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | h | #ifndef __MCD_RENDER_SPHEREBUILDER__
#define __MCD_RENDER_SPHEREBUILDER__
#include "MeshBuilder.h"
namespace MCD {
//! Create a chamfer box with length = 2
class MCD_RENDER_API SphereBuilder : public MCD::MeshBuilderIM
{
public:
SphereBuilder(float radius, uint16_t segmentCount);
//! The index id generated.
int posId, normalId, uvId;
}; // SphereBuilder
} // namespace MCD
#endif // __MCD_RENDER_SPHEREBUILDER__
| [
"mtlung@080b3119-2d51-0410-af92-4d39592ae298"
] | [
[
[
1,
20
]
]
] |
994485f65733ce9ebf25621e92d5e4fa7ae5ea43 | fd47272bb959679789cf1c65afa778569886232f | /Lights/AreaLight.h | 775fc41ccf63d85a9dbdb5b4089fe323560e0afc | [] | no_license | dicta/ray | 5aeed98fe0cc76b7a5dea2c4b93c38caf0485b6c | 5e6290077a92b8468877a8b6751f1ed13da81a43 | refs/heads/master | 2021-01-17T16:16:21.768537 | 2011-09-26T06:03:12 | 2011-09-28T04:36:22 | 2,471,865 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | h | /*
* AreaLight.h
* RayTracer
*
* Created by Eric Saari on 12/20/10.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _AREA_LIGHT_H_
#define _AREA_LIGHT_H_
#include "Light.h"
#include "Math/Point3D.h"
#include "Math/Vector3D.h"
class LightObject;
class AreaLight : public Light {
public:
AreaLight();
virtual ~AreaLight();
virtual Vector3D getLightDirection(ShadeRecord& sr);
virtual void setHash(Hash* hash);
virtual bool inShadow(const Ray& ray, const ShadeRecord& sr);
virtual Color L(const ShadeRecord& sr);
virtual float G(const ShadeRecord& sr);
virtual float pdf(const ShadeRecord& sr);
virtual int getNumLightSamples() const { return 5; }
private:
LightObject* object;
Material* material;
// Point3D samplePoint;
// Vector3D lightNormal;
// Vector3D wi;
};
#endif
| [
"esaari1@13d0956a-e706-368b-88ec-5b7e5bac2ff7",
"[email protected]@13d0956a-e706-368b-88ec-5b7e5bac2ff7"
] | [
[
[
1,
19
],
[
21,
23
],
[
25,
27
],
[
29,
30
],
[
34,
42
]
],
[
[
20,
20
],
[
24,
24
],
[
28,
28
],
[
31,
33
]
]
] |
7d28ba5bf7e8c81a2e8de9980bef0c0770d6644b | d9da783f4bf071364d500e27ad6c0f807d413eca | /stdc++/Types.cpp | 7f1a6746bd14931f155c0625b63b85c873593e31 | [
"WTFPL"
] | permissive | Kaedenn/CodeMines | 9ad9b2e345582a388e625abad445e52853124cfb | a526d96c643bc1442bea25776cee5c912aabb2fc | refs/heads/master | 2020-04-06T07:11:57.959356 | 2011-12-27T19:56:30 | 2011-12-27T19:56:30 | 3,058,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 881 | cpp | // Types.cpp
/* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
#include "Types.hpp"
namespace CM {
const mine_t NUMBER_OF_ROWS = 20;
const mine_t NUMBER_OF_COLS = 26;
const mine_t DEF_NUMBER_OF_MINES = 50;
// Little easter-egg/cheating thing, if you want.
short userIsCheating = false;
// I guess having toLower(string) was too much to ask.
std::string toLower(std::string array) {
return std::use_facet<std::ctype<char> >(
std::locale()
).tolower(
&array[0],
&array[0] + array.length()
) - array.length();
}
}
| [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
0c269059686e657df1d9c8b3b92918840f906628 | 65da00cc6f20a83dd89098bb22f8f93c2ff7419b | /HabuGraphics/Library/Source/HabuGraphics.cpp | 31484e6e7582ec9d7f54dc2a6756aa30161b306c | [] | no_license | skevy/CSC-350-Assignment-5 | 8b7c42257972d71e3d0cd3e9566e88a1fdcce73c | 8091a56694f4b5b8de7e278b64448d4f491aaef5 | refs/heads/master | 2021-01-23T11:49:35.653361 | 2011-04-20T02:20:06 | 2011-04-20T02:20:06 | 1,638,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,983 | cpp | //***************************************************************************//
// HabuGraphics Base Class Implementation
//
// Created Jan 01, 2005
// By: Jeremy M Miller
//
// Copyright (c) 2005-2010 Jeremy M Miller. All rights reserved.
// This source code module, and all information, data, and algorithms
// associated with it, are part of BlueHabu technology (tm).
//
// Usage of HabuGraphics is subject to the appropriate license agreement.
// A proprietary/commercial licenses are available.
//
// HabuGraphics is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// HabuGraphics is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with HabuGraphics. If not, see <http://www.gnu.org/licenses/>.
//***************************************************************************//
//***************************************************************************//
// System Includes
#include <assert.h>
//***************************************************************************//
//***************************************************************************//
// 3rd Party Includes
#include <GL\glew.h> // Must be called before GL.h
//***************************************************************************//
//***************************************************************************//
// Platform Includes
#include <Windows.h>
#include <GL\GL.h>
#include <GL\GLU.h>
//***************************************************************************//
//***************************************************************************//
// Local Includes
#include "HabuGraphics.hpp"
#include "Utility.hpp"
//***************************************************************************//
//***************************************************************************//
#define CLEAR_COLOR 0xFFEEEEEE
//***************************************************************************//
//***************************************************************************//
namespace HabuTech
{
HDC Graphics::smhDeviceContext = NULL;
HGLRC Graphics::smhRenderingContext = NULL;
HWND Graphics::smhWindow = NULL;
HINSTANCE Graphics::smhInstance = NULL;
unsigned int Graphics::smuiMaxNumberOfIndexElements = 0UL;
unsigned int Graphics::smuiMaxNumberOfVertexElements = 0UL;
//*************************************************************************//
Graphics::Graphics(bool bWindowed)
{
//-----------------------------------------------------------------------//
this->mpActiveScene = NULL;
this->mulWindowHeight = DEFAULT_WINDOW_HEIGHT;
this->mulWindowWidth = DEFAULT_WINDOW_WIDTH;
//-----------------------------------------------------------------------//
}
//*************************************************************************//
//*************************************************************************//
Graphics::~Graphics()
{
}
//*************************************************************************//
//*************************************************************************//
bool Graphics::SetMultiSample(unsigned long ulSamples)
{
// This bool is for returning to the callee the success or failure
// or trying to set the given multi-sample type.
bool bReturnValue = false;
// Return either success or failure.
return bReturnValue;
}
//*************************************************************************//
//*************************************************************************//
long Graphics::Initialize(HWND hWindow, unsigned long ulWidth, unsigned long ulHeight)
{
//-----------------------------------------------------------------------//
// Create a data member to hold the result of this method. In this method's
// case it will hold any error codes. By default set to 1 to signal no error.
long lResultCode = 1;
//-----------------------------------------------------------------------//
smhWindow = hWindow;
static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
32, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
GLuint PixelFormat;
if(!(smhDeviceContext = GetDC(hWindow)))
{
lResultCode = -1;
smhDeviceContext = NULL;
}
if(lResultCode > 0 && !(PixelFormat = ChoosePixelFormat(smhDeviceContext, &pfd))) // Did Windows Find A Matching Pixel Format?
{
lResultCode = -1;
}
if(lResultCode > 0 && !SetPixelFormat(smhDeviceContext, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format?
{
lResultCode = -1;
}
if(lResultCode > 0 && !(smhRenderingContext = wglCreateContext(smhDeviceContext))) // Are We Able To Get A Rendering Context?
{
lResultCode = -1;
}
if(lResultCode > 0 && !wglMakeCurrent(smhDeviceContext, smhRenderingContext)) // Try To Activate The Rendering Context
{
lResultCode = -1;
}
if(lResultCode > 0)
{
// Check Required Extensions
GLenum err = glewInit();
if(err == GLEW_OK)
{
glewGetString(GLEW_VERSION);
/// \TODO DO something with version.
if(GLEW_ARB_vertex_buffer_object)
{
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glEnable ( GL_LIGHTING ) ;
float global_ambient[] = { 0.5f, 0.5f, 0.5f, 1.0f };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient);
GLfloat specular[] = {1.0f, 1.0f, 1.0f , 1.0f};
glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
glShadeModel(GL_SMOOTH);
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
glEnable(GL_TEXTURE_2D);
glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, reinterpret_cast<GLint*>(&(smuiMaxNumberOfVertexElements)));
glGetIntegerv(GL_MAX_ELEMENTS_INDICES, reinterpret_cast<GLint*>(&(smuiMaxNumberOfIndexElements)));
}
else
{
lResultCode = -1;
}
}
else
{
glewGetErrorString(err);
lResultCode = -1;
/// \TODO do something with error.
}
}
//-----------------------------------------------------------------------//
// Return result/error code
return lResultCode;
//-----------------------------------------------------------------------//
} // End of long Graphics::Initialize(HWND hWindow)
//*************************************************************************//
//*************************************************************************//
long Graphics::Uninitialize()
{
long lReturnCode = 1;
if(smhRenderingContext) // Do We Have A Rendering Context?
{
if(!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
lReturnCode = -1;
}
if(!wglDeleteContext(smhRenderingContext)) // Are We Able To Delete The RC?
{
MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
lReturnCode = -1;
}
smhRenderingContext = NULL; // Set RC To NULL
}
if(smhDeviceContext && !ReleaseDC(smhWindow, smhDeviceContext)) // Are We Able To Release The DC
{
MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
smhDeviceContext = NULL; // Set DC To NULL
lReturnCode = -1;
}
return lReturnCode;
} // End of long Graphics::Uninitialize()
//*************************************************************************//
//*************************************************************************//
void Graphics::WindowDimensions(unsigned long ulWidth, unsigned long ulHeight)
{
this->mulWindowWidth = ulWidth;
this->mulWindowHeight = ulHeight;
}
//*************************************************************************//
//*************************************************************************//
unsigned long Graphics::WindowWidth() const
{
return this->mulWindowWidth;
}
//*************************************************************************//
//*************************************************************************//
unsigned long Graphics::WindowHeight() const
{
return this->mulWindowHeight;
}
//*************************************************************************//
//*************************************************************************//
// Base::RenderScene() clears the depth and color buffer and starts
// rendering the scene
int Graphics::Render()
{
mpActiveScene->Render();
return 0;
}
//*************************************************************************//
//*************************************************************************//
// Base::SwapBuffers
void Graphics::SwapBuffer()
{
SwapBuffers(smhDeviceContext);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
//*************************************************************************//
//*************************************************************************//
class Scene* Graphics::CreateScene(const std::string& rstrName)
{
this->mpActiveScene = new Scene(this);
return this->mpActiveScene;
}
//*************************************************************************//
//*************************************************************************//
bool Graphics::LoadConfig(const std::string& strFileName)
{
return false;
}
//*************************************************************************//
//*************************************************************************//
unsigned long Graphics::GetNumberOfAdapters()
{
return 0;
}
//*************************************************************************//
//*************************************************************************//
bool Graphics::DeviceLost()
{
bool bReturnValue = false;
return bReturnValue;
}
//*************************************************************************//
//*************************************************************************//
void Graphics::SetBackBufferSize(unsigned long ulWidth, unsigned long ulHeight)
{
this->ResetDevice();
}
//*************************************************************************//
//*************************************************************************//
bool Graphics::ResetDevice()
{
bool bReturnValue = true;
return bReturnValue;
}
//*************************************************************************//
unsigned int Graphics::MaxVertexBufferSize() const
{
return smuiMaxNumberOfVertexElements;
}
unsigned int Graphics::MaxIndexBufferSize() const
{
return smuiMaxNumberOfIndexElements;
}
}
//***************************************************************************//
| [
"[email protected]"
] | [
[
[
1,
330
]
]
] |
24423333d29988aa74e4b42595d780b28307e08a | 0acd6fcc1cea8013574d6f90f14258eb569abbc9 | /rendersystem/renderpath.h | 2acf100ec920fd83d063ac4daddb8ba99c0bd8ca | [] | no_license | leandronunescorreia/prelight | 54aa4f2743e2bc38fb1421bf8362a3a78ed0e1b4 | 8fe5bf1027cdefe97827178a01a51794e9e1ae4f | refs/heads/master | 2021-01-10T08:38:13.282012 | 2009-12-14T16:50:05 | 2009-12-14T16:50:05 | 45,936,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,519 | h | #ifndef _RENDERPATH_H_
#define _RENDERPATH_H_
#include "rendersystem.h"
/**
\class RenderPath
It's an abstract base class for all different render path class implementions.
RenderPath is an abstract layer for render strategy.
When RenderSystem calls RenderPath to draw a render resource, RenderSystem will use
a proper strategy to draw it.
- It hides different features supported by hardwares(e.g. sm 3.0, sm 2.x or fixed pipeline).
For exampler, if you want take advantage from sm3.0 when game running at 9 series video cards,
and keep the compatibility with MX440 card. You may implement two render path classes named
RenderPathSM30, RenderPathFPP derived from RenderPathDX9, and RenderPathDX9 class is derived
from RenderPath class.
- It create proper kernel resources for render resources, and use kernel resources and RenderDevice
to draw render resources.
All interfaces are virtual functions, so RenderSystem can create a proper RenderPath class after detected
hardware cap at runtime.
\class DrawCallObject
At RenderPath layer, there exists a sort of objects called drawcall objects.
Each drawcall objects may corresponds to a drawcall.
It contains reference to kernel resources like vertex buffer, index buffer, shader, and contain reference
to render resources, then it can get shader parameters from it.
RenderPath should build an drawcall objects queue for a camera, and sort them by using shader, render states.
*/
class RenderPath
{
public:
};
#endif | [
"liuyao0713@6b569256-3e9b-11de-b83a-779c162a6e82"
] | [
[
[
1,
40
]
]
] |
7b027f07de4783af21113acdea628435414a7463 | 3fe4cb1c37ed16389f90818b7d07aa5d05bf59e3 | /ImageProcessing/ImageProcessing/PanelView.h | cbc3ba3596325518c8df44a8fdb8ad34b5b35e8d | [] | no_license | zinking/advancedimageprocessing | e0fbc1c69810202b89b2510ddaf60561ce0fe806 | 0c68e11109c0d6299881aecefaf3a85efa8d4471 | refs/heads/master | 2021-01-21T11:46:53.348948 | 2008-12-08T06:15:06 | 2008-12-08T06:15:06 | 32,132,965 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,285 | h | #pragma once
#include "afxwin.h"
#include "afxcmn.h"
// CPanelView 窗体视图
class Histogram;
class CPanelView : public CFormView
{
DECLARE_DYNCREATE(CPanelView)
protected:
CPanelView(); // 动态创建所使用的受保护的构造函数
virtual ~CPanelView();
public:
enum { IDD = IDD_TOOL_FORM };
#ifdef _DEBUG
virtual void AssertValid() const;
#ifndef _WIN32_WCE
virtual void Dump(CDumpContext& dc) const;
#endif
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
// 图像分割的阈值
int mThreshhold;
public:
afx_msg void OnCbnDropdownComboAlgo();
afx_msg void OnCbnSelchangeComboAlgo();
afx_msg void OnBtnErosionClick();
afx_msg void OnBtnDialationClick();
public:
// 分割算法选择
CComboBox m_cbAlgorithm;
public:
// virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL);
public:
// afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
public:
virtual void OnInitialUpdate();
public:
// 阈值滑杆
CSliderCtrl mSliderBar;
public:
// afx_msg void OnNMCustomdrawSldThr(NMHDR *pNMHDR, LRESULT *pResult);
public:
afx_msg void OnNMReleasedcaptureSldThr(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg BOOL OnToolTipNotify(UINT id, NMHDR * pNMHDR, LRESULT * pResult);
// 与pan关联的hist
Histogram* histogram;
// tooltip for slidercontrol
CToolTipCtrl m_tooltip;
afx_msg void OnBnClickedBtnGauss();
afx_msg void OnBnClickedBtnEdge();
// gaussian delta parameter slider
CSliderCtrl deltaSlider;
afx_msg void OnNMReleasedcaptureSldGdelta(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedBtnopen();
afx_msg void OnBnClickedBtnclose();
afx_msg void OnBnClickedBtndistance();
afx_msg void OnBnClickedBtnskeleton();
afx_msg void OnBnClickedBtnrestore();
afx_msg void OnBnClickedBtngradient();
afx_msg void OnBnClickedBtnedge();
CComboBox m_cbEdgeType;
afx_msg void OnBnClickedBtncond();
afx_msg void OnBnClickedBtngrayre();
afx_msg void OnBnClickedBtnLdmask();
public:
//afx_msg void OnBnClickedBtnMode();
public:
afx_msg void OnBnClickedBtnCbr();
};
| [
"zinking3@f9886646-c4e6-11dd-8bad-cde060d8fd3c"
] | [
[
[
1,
82
]
]
] |
1f376fe2c247742bf4fe5de5cff53661820fffb6 | 2b32433353652d705e5558e7c2d5de8b9fbf8fc3 | /PTOC/PTOC/MAIN.H | 370607e6cbdb713ef4bca6e4f6998212cf6d56b6 | [] | no_license | smarthaert/d-edit | 70865143db2946dd29a4ff52cb36e85d18965be3 | 41d069236748c6e77a5a457280846a300d38e080 | refs/heads/master | 2020-04-23T12:21:51.180517 | 2011-01-30T00:37:18 | 2011-01-30T00:37:18 | 35,532,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,437 | h | #ifndef __MAIN_H__
#define __MAIN_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define items(a) (sizeof(a) / sizeof(*(a)))
#define bool int
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
// Some declarations
extern bool language_c;
extern bool no_array_assign_operator;
extern bool compile_system_library;
extern bool small_enum;
extern bool unsigned_comparison;
extern bool nological;
#define CALL_GRAPH_FILE "call.grp"
#define RECURSIVE_PROC_FILE "recur.prc"
#define CONFIG_FILE "ptoc.cfg"
extern bool use_call_graph;
extern bool pio_init;
extern bool short_set;
extern FILE* call_graph_file;
bool is_recursive_proc(const char* name);
void scanner_input(char *file);
class memory_allocator {
private:
size_t free;
char* ptr;
public:
void* alloc(size_t size) {
const int alloc_quant = 8;
const int alloc_block = 1024*1024;
size = (size + alloc_quant - 1) & ~(alloc_quant - 1);
if (size > free) {
free = (alloc_block < size) ? size : alloc_block;
ptr = (char*)malloc(free);
}
free -= size;
void* t = (void*)ptr;
ptr += size;
return t;
}
memory_allocator() { free = 0; }
};
extern memory_allocator heap;
class heap_object {
public:
void* operator new(size_t size) { return heap.alloc(size); }
};
#endif
| [
"[email protected]"
] | [
[
[
1,
70
]
]
] |
101632b145d6e29307180650f0dedca1796d38be | 842997c28ef03f8deb3422d0bb123c707732a252 | /3rdparty/box2d-2.1.2/Box2D/Box2D/Dynamics/b2World.h | ff26975935b5593e01f3d199086665e6c438eae4 | [
"Zlib"
] | permissive | bjorn/moai-beta | e31f600a3456c20fba683b8e39b11804ac88d202 | 2f06a454d4d94939dc3937367208222735dd164f | refs/heads/master | 2021-01-17T11:46:46.018377 | 2011-06-10T07:33:55 | 2011-06-10T07:33:55 | 1,837,561 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,030 | h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_WORLD_H
#define B2_WORLD_H
#include <Box2D/Common/b2Math.h>
#include <Box2D/Common/b2BlockAllocator.h>
#include <Box2D/Common/b2StackAllocator.h>
#include <Box2D/Dynamics/b2ContactManager.h>
#include <Box2D/Dynamics/b2WorldCallbacks.h>
struct b2AABB;
struct b2BodyDef;
struct b2JointDef;
struct b2TimeStep;
class b2Body;
class b2Fixture;
class b2Joint;
/// The world class manages all physics entities, dynamic simulation,
/// and asynchronous queries. The world also contains efficient memory
/// management facilities.
class b2World
{
public:
/// Construct a world object.
/// @param gravity the world gravity vector.
/// @param doSleep improve performance by not simulating inactive bodies.
b2World(const b2Vec2& gravity, bool doSleep);
/// Destruct the world. All physics entities are destroyed and all heap memory is released.
~b2World();
/// Register a destruction listener. The listener is owned by you and must
/// remain in scope.
void SetDestructionListener(b2DestructionListener* listener);
/// Register a contact filter to provide specific control over collision.
/// Otherwise the default filter is used (b2_defaultFilter). The listener is
/// owned by you and must remain in scope.
void SetContactFilter(b2ContactFilter* filter);
/// Register a contact event listener. The listener is owned by you and must
/// remain in scope.
void SetContactListener(b2ContactListener* listener);
/// Register a routine for debug drawing. The debug draw functions are called
/// inside with b2World::DrawDebugData method. The debug draw object is owned
/// by you and must remain in scope.
void SetDebugDraw(b2DebugDraw* debugDraw);
/// Create a rigid body given a definition. No reference to the definition
/// is retained.
/// @warning This function is locked during callbacks.
b2Body* CreateBody(const b2BodyDef* def);
/// Destroy a rigid body given a definition. No reference to the definition
/// is retained. This function is locked during callbacks.
/// @warning This automatically deletes all associated shapes and joints.
/// @warning This function is locked during callbacks.
void DestroyBody(b2Body* body);
/// Create a joint to constrain bodies together. No reference to the definition
/// is retained. This may cause the connected bodies to cease colliding.
/// @warning This function is locked during callbacks.
b2Joint* CreateJoint(const b2JointDef* def);
/// Destroy a joint. This may cause the connected bodies to begin colliding.
/// @warning This function is locked during callbacks.
void DestroyJoint(b2Joint* joint);
/// Take a time step. This performs collision detection, integration,
/// and constraint solution.
/// @param timeStep the amount of time to simulate, this should not vary.
/// @param velocityIterations for the velocity constraint solver.
/// @param positionIterations for the position constraint solver.
void Step( float32 timeStep,
int32 velocityIterations,
int32 positionIterations);
/// Call this after you are done with time steps to clear the forces. You normally
/// call this after each call to Step, unless you are performing sub-steps. By default,
/// forces will be automatically cleared, so you don't need to call this function.
/// @see SetAutoClearForces
void ClearForces();
/// Call this to draw shapes and other debug draw data.
void DrawDebugData();
/// Query the world for all fixtures that potentially overlap the
/// provided AABB.
/// @param callback a user implemented callback class.
/// @param aabb the query box.
void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const;
/// Ray-cast the world for all fixtures in the path of the ray. Your callback
/// controls whether you get the closest point, any point, or n-points.
/// The ray-cast ignores shapes that contain the starting point.
/// @param callback a user implemented callback class.
/// @param point1 the ray starting point
/// @param point2 the ray ending point
void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const;
/// Get the world body list. With the returned body, use b2Body::GetNext to get
/// the next body in the world list. A NULL body indicates the end of the list.
/// @return the head of the world body list.
b2Body* GetBodyList();
/// Get the world joint list. With the returned joint, use b2Joint::GetNext to get
/// the next joint in the world list. A NULL joint indicates the end of the list.
/// @return the head of the world joint list.
b2Joint* GetJointList();
/// Get the world contact list. With the returned contact, use b2Contact::GetNext to get
/// the next contact in the world list. A NULL contact indicates the end of the list.
/// @return the head of the world contact list.
/// @warning contacts are
b2Contact* GetContactList();
/// Enable/disable warm starting. For testing.
void SetWarmStarting(bool flag) { m_warmStarting = flag; }
/// Enable/disable continuous physics. For testing.
void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; }
/// Get the number of broad-phase proxies.
int32 GetProxyCount() const;
/// Get the number of bodies.
int32 GetBodyCount() const;
/// Get the number of joints.
int32 GetJointCount() const;
/// Get the number of contacts (each may have 0 or more contact points).
int32 GetContactCount() const;
/// Change the global gravity vector.
void SetGravity(const b2Vec2& gravity);
/// Get the global gravity vector.
b2Vec2 GetGravity() const;
/// Is the world locked (in the middle of a time step).
bool IsLocked() const;
/// Set flag to control automatic clearing of forces after each time step.
void SetAutoClearForces(bool flag);
/// Get the flag that controls automatic clearing of forces after each time step.
bool GetAutoClearForces() const;
private:
// m_flags
enum
{
e_newFixture = 0x0001,
e_locked = 0x0002,
e_clearForces = 0x0004,
};
friend class b2Body;
friend class b2ContactManager;
friend class b2Controller;
void Solve(const b2TimeStep& step);
void SolveTOI();
void SolveTOI(b2Body* body);
void DrawJoint(b2Joint* joint);
void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color);
b2BlockAllocator m_blockAllocator;
b2StackAllocator m_stackAllocator;
int32 m_flags;
b2ContactManager m_contactManager;
b2Body* m_bodyList;
b2Joint* m_jointList;
int32 m_bodyCount;
int32 m_jointCount;
b2Vec2 m_gravity;
bool m_allowSleep;
b2Body* m_groundBody;
b2DestructionListener* m_destructionListener;
b2DebugDraw* m_debugDraw;
// This is used to compute the time step ratio to
// support a variable time step.
float32 m_inv_dt0;
// This is for debugging the solver.
bool m_warmStarting;
// This is for debugging the solver.
bool m_continuousPhysics;
};
inline b2Body* b2World::GetBodyList()
{
return m_bodyList;
}
inline b2Joint* b2World::GetJointList()
{
return m_jointList;
}
inline b2Contact* b2World::GetContactList()
{
return m_contactManager.m_contactList;
}
inline int32 b2World::GetBodyCount() const
{
return m_bodyCount;
}
inline int32 b2World::GetJointCount() const
{
return m_jointCount;
}
inline int32 b2World::GetContactCount() const
{
return m_contactManager.m_contactCount;
}
inline void b2World::SetGravity(const b2Vec2& gravity)
{
m_gravity = gravity;
}
inline b2Vec2 b2World::GetGravity() const
{
return m_gravity;
}
inline bool b2World::IsLocked() const
{
return (m_flags & e_locked) == e_locked;
}
inline void b2World::SetAutoClearForces(bool flag)
{
if (flag)
{
m_flags |= e_clearForces;
}
else
{
m_flags &= ~e_clearForces;
}
}
/// Get the flag that controls automatic clearing of forces after each time step.
inline bool b2World::GetAutoClearForces() const
{
return (m_flags & e_clearForces) == e_clearForces;
}
#endif
| [
"[email protected]"
] | [
[
[
1,
285
]
]
] |
d67bfcce7c1aca507ce1c2ee229ab28c4a68c6da | 191d4160cba9d00fce9041a1cc09f17b4b027df5 | /ZeroLag2/ZeroLag/Public/LnkHelper.h | 205f7a2c28f29d5e45162da6bbf8d88a8840d43e | [] | no_license | zapline/zero-lag | f71d35efd7b2f884566a45b5c1dc6c7eec6577dd | 1651f264c6d2dc64e4bdcb6529fb6280bbbfbcf4 | refs/heads/master | 2021-01-22T16:45:46.430952 | 2011-05-07T13:22:52 | 2011-05-07T13:22:52 | 32,774,187 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,728 | h | #pragma once
#include <shlobj.h>
class CLnkDecode
{
public:
static BOOL IsLnkPostFile(LPCTSTR lpFileName)
{
LPCTSTR lpPostFix = GetFilePostFix(lpFileName);
if (lpPostFix==NULL)
return FALSE;
return (_tcsicmp(lpPostFix,_T("lnk"))==0);
}
static BOOL QueryLnk(LPCTSTR lpLinkPath,CString & strExePath,CString &strExeParam)
{
IShellLink* pShellLink;
LPCTSTR lpPostFix = GetFilePostFix(lpLinkPath);
BOOL bReturn = (::CoInitialize(NULL) == S_OK);
if(TRUE || bReturn)
{
bReturn = ::CoCreateInstance (CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
IID_IShellLink, (void **)&pShellLink) >= 0;
if(bReturn)
{
IPersistFile *ppf;
bReturn = pShellLink->QueryInterface(IID_IPersistFile, (void **)&ppf) >= 0;
if(bReturn)
{
bReturn = ppf->Load((LPCOLESTR)lpLinkPath, TRUE) >= 0;
if(bReturn)
{
CString strIePath;
CString strParam;
pShellLink->GetPath( strIePath.GetBuffer(MAX_PATH+1), MAX_PATH, NULL, SLGP_UNCPRIORITY );
pShellLink->GetArguments( strParam.GetBuffer(MAX_PATH + 1),MAX_PATH);
strIePath.ReleaseBuffer();
strParam.ReleaseBuffer();
if (!strIePath.IsEmpty())
{
strExePath = (LPCTSTR)strIePath;
if (!strParam.IsEmpty())
strExeParam = strParam;
bReturn = TRUE;
}
else
bReturn = FALSE;
}
ppf->Release();
}
pShellLink->Release();
}
::CoUninitialize();
}
return bReturn;
}
protected:
static LPCTSTR GetFilePostFix(LPCTSTR lpFile)
{
LPCTSTR lpPostFix = _tcsrchr(lpFile, _T('.'));
if ( lpPostFix != NULL )
lpPostFix++;
return lpPostFix;
}
}; | [
"Administrator@PC-200201010241"
] | [
[
[
1,
73
]
]
] |
ad50c3d118e042eaf7b51232cf55804a7c592a3c | ff5c060273aeafed9f0e5aa7018f371b8b11cdfd | /Codigo/C/Tipos_Estructura.cpp | 9ec1558388d49768e22cb9753a7fe716e3a59c8f | [] | no_license | BackupTheBerlios/genaro | bb14efcdb54394e12e56159313151930d8f26d6b | 03e618a4f259cfb991929ee48004b601486d610f | refs/heads/master | 2020-04-20T19:37:21.138816 | 2008-03-25T16:15:16 | 2008-03-25T16:15:16 | 40,075,683 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 35,994 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#include <fstream.h>
#pragma hdrstop
#include "Tipos_Estructura.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
Pista::Pista(Tipo_Pista tipopista)
{
Tipo=tipopista;
Mute=false;
Instrumento=0;
Bloques.clear();
}
//---------------------------------------------------------------------------
void Cancion::Nueva_Pista(Tipo_Pista tipopista)
{
Pista *Pista_Nueva=new Pista(tipopista);
if (Pistas.size()>0)//iniciamos copiado de bloques
{
Bloque temporal;
for (int i=0;i<Pistas[0]->Dame_Numero_Bloques();i++)
{
temporal=Pistas[0]->Dame_Bloque(i);
temporal.Vacio=true;
temporal.Curva_Melodica=NULL;
temporal.Tipo_Music=NULL;
temporal.Progresion=NULL;
temporal.N_Divisiones=2;
temporal.Fase2=2;
temporal.Fase3=2;
temporal.Fase4=2;
Pista_Nueva->Inserta_Bloque(temporal);
}
}
Pistas.push_back(Pista_Nueva);
}
//---------------------------------------------------------------------------
void Cancion::Nuevo_Bloque(int Num_Compases,String P_Ritmico,String Disposicion, String Inversion)
{
Bloque Bloque_Vacio;
Bloque_Vacio.Inicializa();
Bloque_Vacio.Num_Compases=Num_Compases;
Bloque_Vacio.Patron_Ritmico=P_Ritmico;
Bloque_Vacio.Disposicion=Disposicion;
Bloque_Vacio.Inversion=Inversion;
Bloque_Vacio.N_Divisiones=2;
Bloque_Vacio.Fase2=2;
Bloque_Vacio.Fase3=2;
Bloque_Vacio.Fase4=2;
for (int i=0;i<Pistas.size();i++)
{
Pistas[i]->Inserta_Bloque(Bloque_Vacio);
}
}
//---------------------------------------------------------------------------
void Cancion::Inserta_Bloque(Bloque Nuevo_Bloque, int Num_Pista)
{
Bloque Bloque_Vacio=Nuevo_Bloque;
Bloque_Vacio.Vacio=true;
for (int i=0; i<Pistas.size(); i++)
{
if (i==Num_Pista)
{
Pistas[i]->Inserta_Bloque(Nuevo_Bloque);
}
else
{
Pistas[i]->Inserta_Bloque(Bloque_Vacio);
}
}
}
//---------------------------------------------------------------------------
void Cancion::Guarda_Archivo(String nombre_archivo)
{
ofstream fichero_salida;
fichero_salida.open(nombre_archivo.c_str());
//guardamos datos de cancion
Bloque bloque_temp;
fichero_salida<<"Pistas: "<<Pistas.size()<<"\n";
for (int i=0;i<Pistas.size();i++)
{
//Escribimos los datos de pista
fichero_salida<<"Nº "<<i<<"\n";
fichero_salida<<"Bloques "<<Pistas[i]->Dame_Numero_Bloques()<<" ";
fichero_salida<<"Tipo "<<Pistas[i]->Dame_Tipo()<<" ";
fichero_salida<<"Mute "<<Pistas[i]->Dame_Mute()<<" ";
fichero_salida<<"Instrumento "<<Pistas[i]->Dame_Instrumento()<<"\n";
for (int j=0;j<Pistas[i]->Dame_Numero_Bloques();j++)
{
bloque_temp=Pistas[i]->Dame_Bloque(j);
fichero_salida<<"bloque "<<j<<"\n";
fichero_salida<<"Compases "<<bloque_temp.Num_Compases<<" ";
fichero_salida<<"vacio "<<bloque_temp.Vacio<<" ";
fichero_salida<<"Patron "<<bloque_temp.Patron_Ritmico.Length()<<" ";
for (int k=0;k<bloque_temp.Patron_Ritmico.Length();k++)
{
fichero_salida<<bloque_temp.Patron_Ritmico[k+1];
}
fichero_salida<<" ";
fichero_salida<<"Aplicacion_Horizontal "<<bloque_temp.Aplicacion_Horizontal<<" ";
fichero_salida<<"Aplicacion_Vertical_Mayor "<<bloque_temp.Aplicacion_Vertical_Mayor<<" ";
fichero_salida<<"Aplicacion_Vertical_Menor "<<bloque_temp.Aplicacion_Vertical_Menor<<" ";
fichero_salida<<"Octava_Inicial "<<bloque_temp.Octava_Inicial<<" ";
fichero_salida<<"Triadas "<<bloque_temp.Triadas<<" ";
fichero_salida<<"Sistema "<<bloque_temp.Es_Sistema_Paralelo<<" ";
fichero_salida<<"Notas "<<bloque_temp.Notas_Totales<<" ";
fichero_salida<<"Inversion "<<bloque_temp.Inversion.Length()<<" ";
for (int k=0;k<bloque_temp.Inversion.Length();k++)
{
fichero_salida<<bloque_temp.Inversion[k+1];
}
fichero_salida<<" ";
fichero_salida<<"Disposicion "<<bloque_temp.Disposicion.Length()<<" ";
for (int k=0;k<bloque_temp.Disposicion.Length();k++)
{
fichero_salida<<bloque_temp.Disposicion[k+1];
}
fichero_salida<<" ";
fichero_salida<<"Tipo_Melodia "<<bloque_temp.Tipo_Melodia<<" ";//0=delegar en haskell, 1=curva melodica, 2= fichero midi
fichero_salida<<"Curva_Melodica "<<bloque_temp.Curva_Melodica.Length()<<" ";
for (int p=0;p<bloque_temp.Curva_Melodica.Length();p++)
{
fichero_salida<<bloque_temp.Curva_Melodica[p+1];
}
fichero_salida<<" ";
fichero_salida<<"Pista_Acomp "<<bloque_temp.N_Pista_Acomp<<" ";
fichero_salida<<"Num_Divisiones "<<bloque_temp.N_Divisiones<<" ";
fichero_salida<<"Fase2 "<<bloque_temp.Fase2<<" ";
fichero_salida<<"Fase3 "<<bloque_temp.Fase3<<" ";
fichero_salida<<"Fase4 "<<bloque_temp.Fase4<<" ";
fichero_salida<<"Bajo_Numerador "<<bloque_temp.Bajo_Duracion_Numerador<<" ";
fichero_salida<<"Bajo_Denominador "<<bloque_temp.Bajo_Duracion_Denominador<<" ";
fichero_salida<<"Bajo_Tipo "<<bloque_temp.Bajo_Tipo<<" ";
fichero_salida<<"Bajo_Parametro1 "<<bloque_temp.Bajo_Parametro1<<" ";
fichero_salida<<"Bajo_Parametro2 "<<bloque_temp.Bajo_Parametro2<<" ";
fichero_salida<<"Bajo_Parametro3 "<<bloque_temp.Bajo_Parametro3<<" ";
fichero_salida<<"Bajo_Parametro4 "<<bloque_temp.Bajo_Parametro4<<" ";
fichero_salida<<"Bajo_Parametro5 "<<bloque_temp.Bajo_Parametro5<<" ";
fichero_salida<<"Progresion "<<bloque_temp.Progresion.Length()<<" ";
for (int k=0;k<bloque_temp.Progresion.Length();k++)
{
fichero_salida<<bloque_temp.Progresion[k+1];
}
fichero_salida<<" ";
fichero_salida<<"Tipo_Music "<<bloque_temp.Tipo_Music.Length()<<" ";
for (int h=0;h<bloque_temp.Tipo_Music.Length();h++)
{
fichero_salida<<bloque_temp.Tipo_Music[h+1];
}
fichero_salida<<" ";
fichero_salida<<"FINBLOQUE"<<"\n";
}
fichero_salida<<"FINPISTA"<<"\n";
}
fichero_salida<<"FINCANCION";
fichero_salida.close();
}
//---------------------------------------------------------------------------
void Bloque::Inicializa()
{
Notas_Totales=0;
Vacio=true;
Curva_Melodica=NULL;
Tipo_Music=NULL;
N_Pista_Acomp=-1;
Octava_Inicial=1;
Tipo_Melodia=0;
Progresion=NULL;
Aplicacion_Horizontal=0;
Aplicacion_Vertical_Mayor=0;
Aplicacion_Vertical_Menor=0;
N_Divisiones=0;
Fase2=0;
Fase3=0;
Fase4=0;
Bajo_Duracion_Numerador=1;
Bajo_Duracion_Denominador=4;
Bajo_Tipo=0;
Bajo_Parametro1=2;
Bajo_Parametro2=2;
Bajo_Parametro3=2;
Bajo_Parametro4=2;
Bajo_Parametro5=2;
Triadas=false;
}
//---------------------------------------------------------------------------
int Es_Progresion_Valida(String fichero_Progresion)
{
String Progresion=Come_Azucar(fichero_Progresion);
String Inutil="";
if(Procesar(Progresion,"progresion([")==-1){return -1;};
//ahora empieza el listado de cifrados
//--punto de retorno para el cifrado ya escrito
//guail tru
while (true)
{
if (Procesar(Progresion,"(")==-1){break;}
//comemos cifrado
if(Procesar(Progresion,"cifrado(")==-1)
{break;}//salimos del while true puesto que ya hemos terminado el listado de cifrados
//comemos el grado
if (Procesar_Grado(Progresion,Inutil)==-1){return -1;}
//comemos ,
if(Procesar(Progresion,",")==-1){return -1;}
//comemos matricula
if (Procesar_Matricula(Progresion)==-1){return -1;}
//comemos cerrar paréntesis
if (Procesar(Progresion,")")==-1){return -1;}
//comemos ,
if (Procesar(Progresion,",")==-1){return -1;}
//comemos figura
if(Procesar(Progresion,"figura(")==-1){return -1;}
//procesamos un entero natural
if (Procesa_Num_Natural(Progresion)==-1){return -1;}
//procesamos ,
if(Procesar(Progresion,",")==-1){return -1;}
//procesamos otro entero natural
if (Procesa_Num_Natural(Progresion)==-1){return -1;}
//comemos )
if(Procesar(Progresion,")")==-1){return -1;}
//cerramos el cifrado
if (Procesar(Progresion,")")==-1){return -1;}
if (Procesar(Progresion,",")==-1){break;}
}
//fin del guail tru
if (Procesar(Progresion,"]).")==-1){return -1;};
return 0;
}
//---------------------------------------------------------------------------
String Come_Azucar(String Fichero)
{
ifstream fichero_origen;
String salida="";
fichero_origen.open(Fichero.c_str());
char temp;
while (fichero_origen.eof()!=true)
{
fichero_origen>>temp;
if (fichero_origen.eof()!=true)
{
if ((temp!='\t')&&(temp!='\n')&&(temp!=' '))
{salida+=temp;}
}
}
return salida;
}
//---------------------------------------------------------------------------
int Procesar(String &Total,String A_Eliminar)
{
for (int i=0;i<A_Eliminar.Length();i++)
{
if(Total[i+1]!=A_Eliminar[i+1])
{
return -1;
}
}
String nuevo_total="";
//buscar el nuevo total
for (int j=0;j<Total.Length()-A_Eliminar.Length();j++)
{
nuevo_total+=Total[j+A_Eliminar.Length()+1];
}
Total=nuevo_total;
return 0;
}
//---------------------------------------------------------------------------
String Procesar2(String &Total,int A_Eliminar)
{
String salida="";
for (int i=0;i<A_Eliminar;i++)
{
salida+=Total[i+1];
}
String nuevo_total="";
//buscar el nuevo total
for (int j=0;j<Total.Length()-A_Eliminar;j++)
{
nuevo_total+=Total[j+A_Eliminar+1];
}
Total=nuevo_total;
return salida;
}
//-----------------------------------------------------------------------------
int Num_Inter_Simple(String &Progresion)
{
//hay que mirar en que posicion esta el punto
int Num_Inter_Simple;
bool Encontrado=false;
String Progresion_Temporal=Progresion;
for (int i=0;((i<Tam_Inter_Simples)&&(!Encontrado));i++)
{
if (Procesar(Progresion_Temporal,Inter_Simples[i])!=-1){Num_Inter_Simple=i;Encontrado=true;}
if (Encontrado)
{
//miramos si el siguiente caracter es bueno o no
if ((Progresion_Temporal[1]!='i')&&(Progresion_Temporal[1]!='b')&&(Progresion_Temporal[1]!='v')&&(Progresion_Temporal[1]!='a')&&(Progresion_Temporal[1]!='u'))
{//es válido, actualizamos progresion
Progresion=Progresion_Temporal;
Num_Inter_Simple=i;
}
else
{//si es no valido, ponemos progresion_temporal=progresion
Progresion_Temporal=Progresion;
Encontrado=false;
}
}
} //fin for
if (Encontrado){return Num_Inter_Simple;}
else{return -1;}
}
//------------------------------------------------------------------------------
int Procesar_Grado(String &Progresion,String &Salida)
{
Salida="";
int grado=0;
bool es_grado=true;
if((Procesar(Progresion,"grado(")!=-1)||(Procesar(Progresion,"(")!=-1))
{ //o bien es v7 o iim7
grado=-2;
Salida=" v7";
if (Procesar(Progresion,"v7")==-1)
{
grado=-3;
Salida=" iim7";
if(Procesar(Progresion,"iim7")==-1){es_grado=false;}//no es ni v7 ni iim7
}
if (es_grado)
{
//comemos el /
String Salida_Parcial="";
if (Procesar(Progresion,"/")==-1){return -1;}
//procesamos el grado
//llamada recursiva
int entero_temp=Procesar_Grado(Progresion,Salida_Parcial);
Salida=Salida+Salida_Parcial;
grado*10+entero_temp;
if (entero_temp==-1)
{
return -1;
}
if(Procesar(Progresion,")")==-1){}
return grado;
}
}
//o bien es intervalo simple
//miramos si es correcto lo que encuentra
int Num_Inter_Temp=Num_Inter_Simple(Progresion);
if (Num_Inter_Temp!=-1)
{
if (Procesar(Progresion,")")==-1){return -1;}
Salida=" "+Inter_Simples[Num_Inter_Temp];
return Num_Inter_Temp;
}
else
{return -1;}
}
//------------------------------------------------------------------------------
int Procesar_Matricula(String &Progresion)
{
if(Procesar(Progresion,"matricula(")==-1){return -1;}
//hay que mirar en que posicion esta el punto
int Num_matricula;
bool Encontrado=false;
String Progresion_Temporal=Progresion;
for (int i=0;(i<Tam_Matriculas)&&(!Encontrado);i++)
{
if (Procesar(Progresion_Temporal,Matriculas[i])!=-1){Num_matricula=i;Encontrado=true;}
if (Encontrado)
{
//miramos si el siguiente caracter es bueno o no
if ((Progresion_Temporal[1]!='m')&&(Progresion_Temporal[1]!='a')&&(Progresion_Temporal[1]!='y')&&(Progresion_Temporal[1]!='o')&&(Progresion_Temporal[1]!='r')&&(Progresion_Temporal[1]!='u')&&(Progresion_Temporal[1]!='d')&&(Progresion_Temporal[1]!='s')&&(Progresion_Temporal[1]!='i')&&(Progresion_Temporal[1]!='6')&&(Progresion_Temporal[1]!='b')&&(Progresion_Temporal[1]!='5')&&(Progresion_Temporal[1]!='7')&&(Progresion_Temporal[1]!='M')&&(Progresion_Temporal[1]!='j'))
{//es válido, actualizamos progresion
Progresion=Progresion_Temporal;
Num_matricula=i;
}
else
{//si es no valido, ponemos progresion_temporal=progresion
Progresion_Temporal=Progresion;
Encontrado=false;
}
}
} //fin for
if(Procesar(Progresion,")")==-1){return -1;}
return Num_matricula;
}
//------------------------------------------------------------------------------
int Procesa_Num_Natural(String &Progresion)
{
String Nuevo_String="";
int Numero=0;
int Digitos=0;
while ((Progresion[Digitos+1]=='0')||(Progresion[Digitos+1]=='1')||(Progresion[Digitos+1]=='2')||(Progresion[Digitos+1]=='3')||(Progresion[Digitos+1]=='4')||(Progresion[Digitos+1]=='5')||(Progresion[Digitos+1]=='6')||(Progresion[Digitos+1]=='7')||(Progresion[Digitos+1]=='8')||(Progresion[Digitos+1]=='9'))
{
Numero=Numero*10+StrToInt(Progresion[Digitos+1]);
Digitos++;
}
for (int i=0;i<Progresion.Length()-Digitos;i++)
{
Nuevo_String+=Progresion[i+Digitos+1];
}
Progresion=Nuevo_String;
if (Digitos=0){return -1;}
return Numero;
}
//------------------------------------------------------------------------------
TStringList* Come_Progresion(String fichero_Progresion)
{
TStringList* Cadenas;
Cadenas=new TStringList();
Cadenas->Clear();
String Temporal="";
String Cadena_Temporal="";
String Progresion=Come_Azucar(fichero_Progresion);
if(Procesar(Progresion,"progresion([")==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
//ahora empieza el listado de cifrados
//--punto de retorno para el cifrado ya escrito
//guail tru
while (true)
{
if (Procesar(Progresion,"(")==-1){break;}
//comemos cifrado
if(Procesar(Progresion,"cifrado(")==-1)
{break;}//salimos del while true puesto que ya hemos terminado el listado de cifrados
Cadena_Temporal="";
//comemos el grado
int entero=Procesar_Grado(Progresion,Temporal);
Cadena_Temporal+=Temporal;
//comemos ,
if(Procesar(Progresion,",")==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
//comemos matricula
entero=Procesar_Matricula(Progresion);
if(entero==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
Cadena_Temporal+=" "+Matriculas[entero];
//comemos cerrar paréntesis
if (Procesar(Progresion,")")==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
//comemos ,
if (Procesar(Progresion,",")==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
//comemos figura
if(Procesar(Progresion,"figura(")==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
//procesamos un entero natural
entero=Procesa_Num_Natural(Progresion);
if(entero==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
Cadena_Temporal+=" "+IntToStr(entero);
//procesamos ,
if(Procesar(Progresion,",")==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
Cadena_Temporal+=" /";
//procesamos otro entero natural
entero=Procesa_Num_Natural(Progresion);
if (entero==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
Cadena_Temporal+=" "+IntToStr(entero);
//comemos )
if(Procesar(Progresion,")")==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
//cerramos el cifrado
if (Procesar(Progresion,")")==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
//añadimos la cadena
Cadenas->Add(Cadena_Temporal);
Cadena_Temporal="";
if (Procesar(Progresion,",")==-1){break;}
}
//fin del guail tru
if (Procesar(Progresion,"]).")==-1){ShowMessage("ERROR comiendo progresión");return NULL;}
return Cadenas;
}
//------------------------------------------------------------------------------
void Cancion::Guarda_Archivo_Haskell(String Fichero_Gen,int tempo,String tonalidad)
{
ofstream fichero_salida;
fichero_salida.open(Fichero_Gen.c_str());
//guardamos datos de cancion
Bloque bloque_temp;
fichero_salida<<"Pistas: "<<Pistas.size()<<"\n";
fichero_salida<<"Tempo: "<<tempo<<"\n";
fichero_salida<<"Tonalidad: ";
for (int o=0;o<tonalidad.Length();o++)
{
fichero_salida<<tonalidad[o+1];
}
fichero_salida<<"\n";
for (int i=0;i<Pistas.size();i++)
{
//Escribimos los datos de pista
fichero_salida<<"N "<<i<<"\n";
fichero_salida<<"Bloques "<<Pistas[i]->Dame_Numero_Bloques()<<" ";
fichero_salida<<"Tipo ";
if (Pistas[i]->Dame_Tipo()==0)
{
fichero_salida<<"Acompanamiento"<<" ";
}
if (Pistas[i]->Dame_Tipo()==1)
{
fichero_salida<<"Melodia"<<" ";
}
if (Pistas[i]->Dame_Tipo()==2)
{
fichero_salida<<"Bajo"<<" ";
}
if (Pistas[i]->Dame_Tipo()==3)
{
fichero_salida<<"Bateria"<<" ";
}
fichero_salida<<"Mute "<<Pistas[i]->Dame_Mute()<<" ";
fichero_salida<<"Instrumento "<<Pistas[i]->Dame_Instrumento()<<"\n";
for (int j=0;j<Pistas[i]->Dame_Numero_Bloques();j++)
{
bloque_temp=Pistas[i]->Dame_Bloque(j);
fichero_salida<<"bloque "<<j<<"\n";
fichero_salida<<"Compases "<<bloque_temp.Num_Compases<<" ";
fichero_salida<<"vacio "<<bloque_temp.Vacio<<" ";
fichero_salida<<"Tipo_Music "<<bloque_temp.Tipo_Music.Length()<<" ";
for (int h=0;h<bloque_temp.Tipo_Music.Length();h++)
{
fichero_salida<<bloque_temp.Tipo_Music[h+1];
}
fichero_salida<<" ";
fichero_salida<<"FINBLOQUE"<<"\n";
}
fichero_salida<<"FINPISTA"<<"\n";
}
fichero_salida<<"FINCANCION"<<"\n";
fichero_salida.close();
}
//---------------------------------------------------------------------------
void Cancion::Limpia()
{
for (int i=0;i<Pistas.size();i++)
{
delete Pistas[i];
}
Pistas.clear();
}
//---------------------------------------------------------------------------
Cancion::~Cancion()
{
for (int i=0;i<Pistas.size();i++)
{
delete Pistas[i];
}
Pistas.clear();
}
//---------------------------------------------------------------------------
int Cancion::Cargar(String fichero)
{
ifstream archivo;
archivo.open(fichero.c_str(),ios::binary);
char agua;
String Total="";
archivo.read((char*)&agua,sizeof(char));
while(!archivo.eof())
{
Total+=agua;
archivo.read((char*)&agua,sizeof(char));
}
//ya tenemos en Total el archivo que buscamos;
archivo.close();
//procesamos palabra pistas
if (Procesar(Total,"Pistas: ")==-1){ShowMessage("Error cargando fichero, leyendo palabra \"Pistas: \"");return -1;}
int Total_Pistas=Procesa_Num_Natural(Total);
int Total_Bloques;
int Tipo_De_Pista;
int Mute_Pista;
int Instrumento_Pista;
if (Total_Pistas==-1){ShowMessage("Error cargando fichero, leyendo número de pistas");return -1;}
if (Procesar(Total,"\r\n")==-1){ShowMessage("Error cargando fichero, procesando salto de línea");return -1;}
//para cada pista procesamos los datos
for (int Pista_Actual=0;Pista_Actual<Total_Pistas;Pista_Actual++)
{
if (Procesar(Total,"Nº ")==-1){ShowMessage("Error cargando fichero, procesando palabra \"Nº \"");return -1;}
if (Procesa_Num_Natural(Total)!=Pista_Actual){ShowMessage("Error, las pistas no están en orden, o faltan pistas");return -1;}
if (Procesar(Total,"\r\n")==-1){ShowMessage("Error cargando fichero, procesando salto de línea");return -1;}
if (Procesar(Total,"Bloques ")==-1){ShowMessage("Error cargando fichero, procesando palabra \"Bloques \"");return -1;}
Total_Bloques=Procesa_Num_Natural(Total);
if (Total_Bloques==-1){ShowMessage("Error cargando fichero, leyendo número de bloques");return -1;}
if (Procesar(Total," Tipo ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Tipo \"");return -1;}
Tipo_De_Pista=Procesa_Num_Natural(Total);
if (Tipo_De_Pista==-1){ShowMessage("Error carganda tipo de pista");return -1;}
if (Procesar(Total," Mute ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Tipo \"");return -1;}
Mute_Pista=Procesa_Num_Natural(Total);
if (Mute_Pista==-1){ShowMessage("Error carganda mute pista");return -1;}
if (Procesar(Total," Instrumento ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Tipo \"");return -1;}
Instrumento_Pista=Procesa_Num_Natural(Total);
if (Instrumento_Pista==-1){ShowMessage("Error carganda instrumento pista");return -1;}
if (Procesar(Total,"\r\n")==-1){ShowMessage("Error cargando fichero, procesando salto de línea");return -1;}
//ahora creamos una pista y le metemos los bloques
Pista* Pista_Temporal;
Pista_Temporal=new Pista((Tipo_Pista)Tipo_De_Pista);
Pista_Temporal->Cambia_Mute(Mute_Pista);
Pista_Temporal->Cambia_Instrumento(Instrumento_Pista);
Bloque Bloque_Temporal;
for (int SubBloque_Actual=0;SubBloque_Actual<Total_Bloques;SubBloque_Actual++)
{//ahora por cada bloque tenemos que procesar
int Numero_Compases;
int vacio;
String Patron_Ritmico;
int Aplicacion_Horizontal;
int Aplicacion_Vertical_Mayor;
int Aplicacion_Vertical_Menor;
int Octava_Inicial;
int Sistema;
int Notas;
String Inversion;
String Disposicion;
int Tipo_Melodia;
String Curva_Melodica;
int Pista_Acomp;
int Num_Divisiones;
int Fase2,Fase3,Fase4;
int Bajo_Numera;
int Bajo_Denomina;
int Bajo_Tip;
int Bajo_Param1;
int Bajo_Param2;
int Bajo_Param3;
int Bajo_Param4;
int Bajo_Param5;
int Triada;
String Progresion;
String Tipo_Music;
int ent_temp;
if (Procesar(Total,"bloque ")==-1){ShowMessage("Error cargando fichero, procesando palabra \"bloque \"");return -1;}
if (Procesa_Num_Natural(Total)!=SubBloque_Actual){ShowMessage("Error, loss bloques no están en orden, o faltan bloques");return -1;}
if (Procesar(Total,"\r\n")==-1){ShowMessage("Error cargando fichero, procesando salto de línea");return -1;}
Bloque Bloque_Temporal;
if (Procesar(Total,"Compases ")==-1){ShowMessage("Error cargando fichero, procesando palabra \"Compases \"");return -1;}
Numero_Compases=Procesa_Num_Natural(Total);
if (Numero_Compases==-1){ShowMessage("Error procesando el número de compases");return -1;}
if (Procesar(Total," vacio ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" vacio \"");return -1;}
vacio=Procesa_Num_Natural(Total);
if (vacio==-1){ShowMessage("Error procesando el mute del bloque");return -1;}
if (Procesar(Total," Patron ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Patron \"");return -1;}
ent_temp=Procesa_Num_Natural(Total);
if (ent_temp==-1){ShowMessage("Error leyendo el tamaño del patrón rítmico");return -1;}
if (Procesar(Total," ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" \"");return -1;}
if (ent_temp==0){Patron_Ritmico=NULL;}
else{Patron_Ritmico=Procesar2(Total,ent_temp);}
if (Procesar(Total," Aplicacion_Horizontal ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Aplicacion_Horizontal \"");return -1;}
Aplicacion_Horizontal=Procesa_Num_Natural(Total);
if (Aplicacion_Horizontal==-1){ShowMessage("Error leyendo Aplicacion_Horizontal");return -1;}
if (Procesar(Total," Aplicacion_Vertical_Mayor ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Aplicacion_Vertical_Mayor \"");return -1;}
Aplicacion_Vertical_Mayor=Procesa_Num_Natural(Total);
if (Aplicacion_Vertical_Mayor==-1){ShowMessage("Error leyendo Aplicacion_Vertical_Mayor");return -1;}
if (Procesar(Total," Aplicacion_Vertical_Menor ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Aplicacion_Vertical_Menor \"");return -1;}
Aplicacion_Vertical_Menor=Procesa_Num_Natural(Total);
if (Aplicacion_Vertical_Menor==-1){ShowMessage("Error leyendo Aplicacion_Vertical_Menor");return -1;}
if (Procesar(Total," Octava_Inicial ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Octava_Inicial \"");return -1;}
Octava_Inicial=Procesa_Num_Natural(Total);
if (Octava_Inicial==-1){ShowMessage("Error leyendo Octava_Inicial");return -1;}
if (Procesar(Total," Triadas ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Triadas \"");return -1;}
Triada=Procesa_Num_Natural(Total);
if (Triada==-1){ShowMessage("Error leyendo Triada");return -1;}
if (Procesar(Total," Sistema ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Sistema \"");return -1;}
Sistema=Procesa_Num_Natural(Total);
if (Sistema==-1){ShowMessage("Error leyendo Sistema");return -1;}
if (Procesar(Total," Notas ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Notas \"");return -1;}
Notas=Procesa_Num_Natural(Total);
if (Notas==-1){ShowMessage("Error leyendo Notas");return -1;}
if (Procesar(Total," Inversion ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Inversion \"");return -1;}
ent_temp=Procesa_Num_Natural(Total);
if (ent_temp==-1){ShowMessage("Error leyendo el tamaño delInversion");return -1;}
if (Procesar(Total," ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" \"");return -1;}
if (ent_temp==0){Inversion=NULL;}
else{Inversion=Procesar2(Total,ent_temp);}
if (Procesar(Total," Disposicion ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Disposicion \"");return -1;}
ent_temp=Procesa_Num_Natural(Total);
if (ent_temp==-1){ShowMessage("Error leyendo el tamaño de la disposición");return -1;}
if (Procesar(Total," ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" \"");return -1;}
if (ent_temp==0){Disposicion=NULL;}
else{Disposicion=Procesar2(Total,ent_temp);}
if (Procesar(Total," Tipo_Melodia ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Tipo_Melodia \"");return -1;}
Tipo_Melodia=Procesa_Num_Natural(Total);
if (Tipo_Melodia==-1){ShowMessage("Error leyendo Tipo_Melodia");return -1;}
if (Procesar(Total," Curva_Melodica ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Curva_Melodica \"");return -1;}
ent_temp=Procesa_Num_Natural(Total);
if (ent_temp==-1){ShowMessage("Error leyendo el tamaño de la curva melódica");return -1;}
if (Procesar(Total," ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" \"");return -1;}
if (ent_temp==1){Curva_Melodica=NULL;Procesar(Total,"0");}
else{Curva_Melodica=Procesar2(Total,ent_temp);}
if (Procesar(Total," Pista_Acomp ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Curva_Melodica \"");return -1;}
Pista_Acomp=1;
if (Total[1]=='-'){Procesar(Total,"-");Pista_Acomp=-1;}
Pista_Acomp*=Procesa_Num_Natural(Total);
if (Procesar(Total," Num_Divisiones ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Num_Divisiones \"");return -1;}
Num_Divisiones=Procesa_Num_Natural(Total);
if (Num_Divisiones==-1){ShowMessage("Error leyendo Num_Divisiones");return -1;}
if (Procesar(Total," Fase2 ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Fase2 \"");return -1;}
Fase2=Procesa_Num_Natural(Total);
if (Fase2==-1){ShowMessage("Error leyendo Fase2");return -1;}
if (Procesar(Total," Fase3 ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Fase3 \"");return -1;}
Fase3=Procesa_Num_Natural(Total);
if (Fase3==-1){ShowMessage("Error leyendo Fase3");return -1;}
if (Procesar(Total," Fase4 ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Fase4 \"");return -1;}
Fase4=Procesa_Num_Natural(Total);
if (Fase4==-1){ShowMessage("Error leyendo Fase4");return -1;}
if (Procesar(Total," Bajo_Numerador ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Bajo_Numerador \"");return -1;}
Bajo_Numera=Procesa_Num_Natural(Total);
if (Bajo_Numera==-1){ShowMessage("Error leyendo Bajo_Numerador");return -1;}
if (Procesar(Total," Bajo_Denominador ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Bajo_Denominador \"");return -1;}
Bajo_Denomina=Procesa_Num_Natural(Total);
if (Bajo_Denomina==-1){ShowMessage("Error leyendo Bajo_Denominador");return -1;}
if (Procesar(Total," Bajo_Tipo ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Bajo_Tipo \"");return -1;}
Bajo_Tip=Procesa_Num_Natural(Total);
if (Bajo_Tip==-1){ShowMessage("Error leyendo Bajo_Tipo");return -1;}
if (Procesar(Total," Bajo_Parametro1 ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Bajo_Parametro1 \"");return -1;}
Bajo_Param1=Procesa_Num_Natural(Total);
if (Bajo_Param1==-1){ShowMessage("Error leyendo Bajo_Parametro1");return -1;}
if (Procesar(Total," Bajo_Parametro2 ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Bajo_Parametro2 \"");return -1;}
Bajo_Param2=Procesa_Num_Natural(Total);
if (Bajo_Param2==-1){ShowMessage("Error leyendo Bajo_Parametro3");return -1;}
if (Procesar(Total," Bajo_Parametro3 ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Bajo_Parametro3 \"");return -1;}
Bajo_Param3=Procesa_Num_Natural(Total);
if (Bajo_Param3==-1){ShowMessage("Error leyendo Bajo_Parametro4");return -1;}
if (Procesar(Total," Bajo_Parametro4 ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Bajo_Parametro4 \"");return -1;}
Bajo_Param4=Procesa_Num_Natural(Total);
if (Bajo_Param4==-1){ShowMessage("Error leyendo Bajo_Parametro4");return -1;}
if (Procesar(Total," Bajo_Parametro5 ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Bajo_Parametro5 \"");return -1;}
Bajo_Param5=Procesa_Num_Natural(Total);
if (Bajo_Param5==-1){ShowMessage("Error leyendo Bajo_Parametro5");return -1;}
if (Procesar(Total," Progresion ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Progresion \"");return -1;}
ent_temp=Procesa_Num_Natural(Total);
if (ent_temp==-1){ShowMessage("Error leyendo el tamaño de la curva melódica");return -1;}
if (Procesar(Total," ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" \"");return -1;}
if (ent_temp==1){Progresion=NULL;Procesar(Total,"0");}
else{Progresion=Procesar2(Total,ent_temp);}
if (Procesar(Total," Tipo_Music ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" Tipo_Music \"");return -1;}
ent_temp=Procesa_Num_Natural(Total);
if (ent_temp==-1){ShowMessage("Error leyendo el tamaño de la curva melódica");return -1;}
if (Procesar(Total," ")==-1){ShowMessage("Error cargando fichero, procesando palabra \" \"");return -1;}
if (ent_temp==1){Tipo_Music=NULL;Procesar(Total,"0");}
else{Tipo_Music=Procesar2(Total,ent_temp);}
if (Procesar(Total," FINBLOQUE\r\n")==-1){ShowMessage("Error finalizando lectura bloque");return -1;}
Bloque_Temporal.Num_Compases=Numero_Compases;
Bloque_Temporal.Vacio=vacio;
Bloque_Temporal.Patron_Ritmico=Patron_Ritmico;
Bloque_Temporal.Aplicacion_Horizontal=Aplicacion_Horizontal;
Bloque_Temporal.Aplicacion_Vertical_Mayor=Aplicacion_Vertical_Mayor;
Bloque_Temporal.Aplicacion_Vertical_Menor=Aplicacion_Vertical_Menor;
Bloque_Temporal.Octava_Inicial=Octava_Inicial;
Bloque_Temporal.Es_Sistema_Paralelo=Sistema;
Bloque_Temporal.Notas_Totales=Notas;
Bloque_Temporal.Inversion=Inversion;
Bloque_Temporal.Disposicion=Disposicion;
Bloque_Temporal.Tipo_Melodia=Tipo_Melodia;
Bloque_Temporal.Curva_Melodica=Curva_Melodica;
Bloque_Temporal.N_Pista_Acomp=Pista_Acomp;
Bloque_Temporal.N_Divisiones=Num_Divisiones;
Bloque_Temporal.Fase2=Fase2;
Bloque_Temporal.Fase3=Fase3;
Bloque_Temporal.Fase4=Fase4;
Bloque_Temporal.Bajo_Duracion_Numerador=Bajo_Numera;
Bloque_Temporal.Bajo_Duracion_Denominador=Bajo_Denomina;
Bloque_Temporal.Bajo_Tipo=Bajo_Tip;
Bloque_Temporal.Bajo_Parametro1=Bajo_Param1;
Bloque_Temporal.Bajo_Parametro2=Bajo_Param2;
Bloque_Temporal.Bajo_Parametro3=Bajo_Param3;
Bloque_Temporal.Bajo_Parametro4=Bajo_Param4;
Bloque_Temporal.Bajo_Parametro5=Bajo_Param5;
Bloque_Temporal.Triadas=Triada;
Bloque_Temporal.Progresion=Progresion;
Bloque_Temporal.Tipo_Music=Tipo_Music;
Pista_Temporal->Inserta_Bloque(Bloque_Temporal);
}
if (Procesar(Total,"FINPISTA\r\n")==-1){ShowMessage("Error finalizando lectura Pista");return -1;}
//una vez introducidos los bloques, metemos la pista en la canción
Pistas.push_back(Pista_Temporal);
}
if (Procesar(Total,"FINCANCION")==-1){ShowMessage("Error finalizando lectura fichero");return -1;}
}
//---------------------------------------------------------------------------
String Dame_Token(String &Total)
{
String salida="";
String NuevoTotal="";
int i=1;
if (Total.Length()<=1){return "FIN";}
while (((Total[i]==' ')||(Total[i]=='\t')||(Total[i]=='\n')||(Total[i]=='\r'))&&(i<=Total.Length()))
{
i++;
}
while ((i<=Total.Length())&&(Total[i]!=' ')&&(Total[i]!='\t')&&(Total[i]!='\n')&&(Total[i]!='\r'))
{
salida+=Total[i];
i++;
}
for (int j=i;j<=Total.Length();j++)
{
NuevoTotal+=Total[j];
}
Total=NuevoTotal;
return salida;
}
//----------------------------------------------------------------------------
void Bloque::Copia(Bloque Original, int bloque)
{
Vacio=Original.Vacio;
Patron_Ritmico=Original.Patron_Ritmico;
Es_Sistema_Paralelo=Original.Es_Sistema_Paralelo;
Notas_Totales=Original.Notas_Totales;
Inversion=Original.Inversion;
Disposicion=Original.Disposicion;
ifstream curva_origen;
curva_origen.open(Original.Curva_Melodica.c_str(),ios::binary);
ifstream Music_origen;
Music_origen.open(Original.Tipo_Music.c_str(),ios::binary);
Curva_Melodica="copia_"+IntToStr(bloque)+"_"+Original.Curva_Melodica;
Tipo_Music="copia_"+IntToStr(bloque)+"_"+Original.Tipo_Music;
ofstream curva_salida;
curva_salida.open(Curva_Melodica.c_str(),ios::binary);
ofstream Music_salida;
Music_salida.open(Tipo_Music.c_str(),ios::binary);
char agua;
//copiamos
curva_origen.read((char*)&agua,sizeof(char));
while(!curva_origen.eof())
{
curva_salida.write((char*)&agua,sizeof(char));
curva_origen.read((char*)&agua,sizeof(char));
}
Music_origen.read((char*)&agua,sizeof(char));
while(!Music_origen.eof())
{
Music_salida.write((char*)&agua,sizeof(char));
Music_origen.read((char*)&agua,sizeof(char));
}
curva_origen.close();
Music_origen.close();
curva_salida.close();
Music_salida.close();
//copiar curva-melodica en otro archivo y lo mismo cobn music //Curva_Melodica;
// Tipo_Music;
Octava_Inicial=Original.Octava_Inicial;
N_Pista_Acomp=Original.N_Pista_Acomp;
Tipo_Melodia=Original.Tipo_Melodia;
Aplicacion_Horizontal=Original.Aplicacion_Horizontal;
Aplicacion_Vertical_Mayor=Original.Aplicacion_Vertical_Mayor;
Aplicacion_Vertical_Menor=Original.Aplicacion_Vertical_Menor;
N_Divisiones=Original.N_Divisiones;
Fase2=Original.Fase2;
Fase3=Original.Fase3;
Fase4=Original.Fase4;
}
| [
"gatchan"
] | [
[
[
1,
865
]
]
] |
bc6c34c3625fca2940c78dc456e53e427945f387 | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib-test/mgl_test/AFチュートリアルB/tutorial_1B.cpp | 44c5eb279090c8ce4f7e4d02f445ab3b2391306b | [] | no_license | myun2ext/open-mgl-legacy | 21ccadab8b1569af8fc7e58cf494aaaceee32f1e | 8faf07bad37a742f7174b454700066d53a384eae | refs/heads/master | 2016-09-06T11:41:14.108963 | 2009-12-28T12:06:58 | 2009-12-28T12:06:58 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 738 | cpp | #include "stdafx.h"
class CMglTestFrame : public CAugustWindow
{
private:
CAugustImage m_img;
public:
// 初期化時に呼ばれる
void OnInit(){
EnableEscEnd();
RegistControl(&m_img);
m_img.Load("test.jpg");
}
// ウインドウ生成前に呼ばれる
void OnCreateWindow(agh::CREATE_WINDOW_INFO *pWindowInfo){
pWindowInfo->nWinWidthSize = 800;
pWindowInfo->nWinHeightSize = 600;
pWindowInfo->strWindowTitle = "さんぷるぷろぐらむ";
}
};
// WinMain
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
CMglTestFrame frame;
frame.Start();
return 0;
}
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
] | [
[
[
1,
31
]
]
] |
f9dec04c1f5ab57247160293a5805c84550a653b | 3ea33f3b6b61d71216d9e81993a7b6ab0898323b | /src/Multiplayer.cpp | eb551698b904d09364d9b6854b702c1d06f19336 | [] | no_license | drivehappy/tlmp | fd1510f48ffea4020a277f28a1c4525dffb0397e | 223c07c6a6b83e4242a5e8002885e23d0456f649 | refs/heads/master | 2021-01-10T20:45:15.629061 | 2011-07-07T00:43:00 | 2011-07-07T00:43:00 | 32,191,389 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 155,451 | cpp | #include <windows.h>
#include "Multiplayer.h"
using namespace TLMP;
TLMP::Logger TLMP::multiplayerLogger;
TLAPI::CGameClient *TLMP::gameClient = NULL;
bool TLMP::LevelLoading = true;
void TLMP::SetupNetwork()
{
multiplayerLogger.SetLoggingLevel(Info);
multiplayerLogger.WriteLine(Info, L"Torchlight Multiplayer Log");
multiplayerLogger.WriteLine(Info, L"Registering Events...");
//
// Register event callbacks we need
_GLOBAL::RegisterEvent_WndProc(WndProcPre, NULL);
CInventoryMenu::RegisterEvent_InventoryMenu_OpenClose(InventoryMenu_OpenClosePre, NULL);
CInventoryMenu::RegisterEvent_InventoryMenu_MouseEvent(InventoryMenu_MouseEventPre, NULL);
CCharacterSaveState::RegisterEvent_CharacterSaveState_LoadFromFile(NULL, CharacterSaveState_ReadFromFile);
CPath::RegisterEvent_Path_GetNextNode(Path_GetNextNodePre, Path_GetNextNodePost);
CGame::RegisterEvent_GameCtor(Game_Ctor, NULL);
CGame::RegisterEvent_Game_CreateUI(NULL, GameClient_CreateUI);
CBaseUnit::RegisterEvent_BaseUnit_AddSkill(BaseUnit_AddSkillPre, BaseUnit_AddSkillPost);
CEffect::RegisterEvent_Effect_Effect_Something(Effect_EffectSomethingPre, Effect_EffectSomethingPost);
CEffect::RegisterEvent_Effect_Something0(Effect_Something0Pre, NULL);
CEffect::RegisterEvent_Effect_ParamCtor(Effect_Effect_ParamCtorPre, NULL);
//CEffect::RegisterEvent_Effect_CopyCtor(Effect_CtorPre, Effect_CtorPost);
//CEffect::RegisterEvent_Effect_Character_Unk0(Effect_Character_Unk0Pre, Effect_Character_Unk0Post);
CEffectManager::RegisterEvent_EffectManagerCreateEffect(Effect_EffectManagerCreateEffectPre, Effect_EffectManagerCreateEffectPost);
CEffectManager::RegisterEvent_EffectManager_AddEffectToEquipment(EffectManager_AddEffectToEquipmentPre, EffectManager_AddEffectToEquipmentPost);
CResourceManager::RegisterEvent_ResourceManagerCreatePlayer(CreatePlayer, NULL);
CResourceManager::RegisterEvent_ResourceManagerCreateMonster(CreateMonsterPre, CreateMonsterPost);
CResourceManager::RegisterEvent_ResourceManagerCreateItem(CreateItemPre, CreateItemPost);
CLevel::RegisterEvent_LevelCharacterInitialize(Level_CharacterInitializePre, Level_CharacterInitializePost);
CLevel::RegisterEvent_LevelDropItem(Level_DropItemPre, Level_DropItemPost);
CLevel::RegisterEvent_Level_Dtor(Level_Dtor, NULL);
CLevel::RegisterEvent_Level_Ctor(Level_Ctor, NULL);
CLevel::RegisterEvent_Level_Update(Level_UpdatePre, Level_UpdatePost);
CLevel::RegisterEvent_Level_CharacterKilledCharacter(Level_Level_CharacterKilledCharacterPre, Level_Level_CharacterKilledCharacterPost);
CLevel::RegisterEvent_Level_RemoveEquipment(Level_Level_RemoveEquipmentPre, Level_Level_RemoveEquipmentPost);
CLevel::RegisterEvent_Level_CheckCharacterProximity(Level_CheckCharacterProximityPre, Level_CheckCharacterProximityPost);
CLevel::RegisterEvent_Level_RemoveCharacter(Level_RemoveCharacterPre, NULL);
CLevel::RegisterEvent_Level_RemoveItem(Level_RemoveItemPre, Level_RemoveItemPost);
CGameClient::RegisterEvent_GameClientCtor(NULL, GameClient_Ctor);
CGameClient::RegisterEvent_GameClientProcessObjects(GameClient_ProcessObjects, NULL);
CGameClient::RegisterEvent_GameClientProcessTitleScreen(NULL, GameClient_TitleProcessObjects);
CGameClient::RegisterEvent_GameClient_CreateLevel(GameClient_CreateLevelPre, GameClient_CreateLevelPost);
CGameClient::RegisterEvent_GameClient_LoadLevel(GameClient_LoadLevelPre, GameClient_LoadLevelPost);
CGameClient::RegisterEvent_GameClient_LoadMap(GameClient_LoadMapPre, GameClient_LoadMapPost);
CGameClient::RegisterEvent_GameClient_SaveGame(GameClientSaveGamePre, GameClientSaveGamePost);
CGameClient::RegisterEvent_GameClientGamePaused(NULL, GameClientGamePausedPost);
CGameClient::RegisterEvent_GameClient_ChangeLevel(GameClient_ChangeLevelPre, GameClient_ChangeLevelPost);
CMainMenu::RegisterEvent_MainMenu_Event(MainMenuEventPre, NULL);
CEquipment::RegisterEvent_EquipmentDtor(Equipment_DtorPre, Equipment_DtorPost);
CEquipment::RegisterEvent_EquipmentInitialize(EquipmentInitialize, NULL);
CEquipment::RegisterEvent_EquipmentAddStackCount(NULL, EquipmentAddStackCountPost);
CEquipment::RegisterEvent_Equipment_AddGem(EquipmentAddGemPre, NULL);
CEquipment::RegisterEvent_EquipmentIdentify(EquipmentIdentifyPre, NULL);
CEquipment::RegisterEvent_EquipmentEnchant(Equipment_EnchantPre, NULL);
CEquipmentRef::RegisterEvent_EquipmentRef_Dtor(EquipmentRefDtorPre, EquipmentRefDtorPost);
CEnchantMenu::RegisterEvent_EnchantMenu_EnchantItem(EnchantMenuEnchantItemPre, NULL);
CItemGold::RegisterEvent_ItemGold_Ctor(ItemGold_CtorPre, ItemGold_CtorPost);
CMonster::RegisterEvent_MonsterProcessAI(Monster_ProcessAIPre, NULL);
CMonster::RegisterEvent_MonsterProcessAI2(Monster_ProcessAI2Pre, NULL);
CMonster::RegisterEvent_MonsterProcessAI3(Monster_ProcessAI3Pre, NULL);
CMonster::RegisterEvent_MonsterIdle(Monster_Idle, NULL);
CMonster::RegisterEvent_MonsterGetCharacterClose(Monster_GetCharacterClosePre, Monster_GetCharacterClosePost);
CCharacter::RegisterEvent_CharacterDtor(Character_DtorPre, Character_DtorPost);
CCharacter::RegisterEvent_CharacterSetAction(Character_SetActionPre, NULL);
CCharacter::RegisterEvent_CharacterSetAlignment(Character_SetAlignmentPre, Character_SetAlignmentPost);
CCharacter::RegisterEvent_CharacterAttack(Character_AttackPre, Character_AttackPost);
CCharacter::RegisterEvent_CharacterSetTarget(Character_SetTarget, NULL);
CCharacter::RegisterEvent_CharacterUseSkill(Character_UseSkillPre, Character_UseSkillPost);
CCharacter::RegisterEvent_CharacterSetDestination(NULL, Character_SetDestination);
CCharacter::RegisterEvent_CharacterPickupEquipment(Character_PickupEquipmentPre, Character_PickupEquipmentPost);
CCharacter::RegisterEvent_Character_Update(Character_Character_UpdatePre, Character_Character_UpdatePost);
CCharacter::RegisterEvent_Character_SetOrientation(Character_SetOrientationPre, NULL);
CCharacter::RegisterEvent_Character_UpdateOrientation(Character_UpdateOrientationPre, NULL);
CCharacter::RegisterEvent_CharacterSetupSkills(Character_SetupSkillsPre, NULL);
CCharacter::RegisterEvent_CharacterAddSkill(Character_AddSkillPre, Character_AddSkillPost);
CCharacter::RegisterEvent_CharacterAddSkill2(Character_AddSkill2Pre, NULL);
CCharacter::RegisterEvent_CharacterUpdateHealth(Character_UpdateHealthPre, NULL);
CCharacter::RegisterEvent_CharacterStrike(Character_StrikePre, NULL);
CCharacter::RegisterEvent_PlayerResurrect(Character_ResurrectPre, NULL);
CCharacter::RegisterEvent_Character_Update_Level(Character_Update_LevelPre, NULL);
CCharacter::RegisterEvent_Character_Update_Character(Character_Update_CharacterPre, NULL);
CCharacter::RegisterEvent_Player_KillMonsterExperience(Character_Player_KillMonsterExperiencePre, Character_Player_KillMonsterExperiencePost);
CCharacter::RegisterEvent_Character_Killed(Character_KilledPre, Character_KilledPost);
CCharacter::RegisterEvent_Player_SwapWeapons(Player_SwapWeaponsPre, NULL);
CPlayer::RegisterEvent_PlayerLevelUp(Player_LevelUpPre, Player_LevelUpPost);
CAutomap::RegisterEvent_Automap_AddBillboard(Automap_AddBillboardPre, NULL);
CTriggerUnit::RegisterEvent_TriggerUnitTriggered(TriggerUnit_TriggeredPre, NULL);
CTriggerUnit::RegisterEvent_TriggerUnit_Ctor(NULL, TriggerUnit_CtorPost);
//CTriggerUnit::RegisterEvent_TriggerUnit_Triggered2(TriggerUnit_Triggered2Pre, NULL);
CBreakable::RegisterEvent_BreakableTriggered(Breakable_TriggeredPre, NULL);
//_GLOBAL::RegisterEvent_SetSeedValue0(Global_SetSeedValue0Pre, Global_SetSeedValue0Post);
//_GLOBAL::RegisterEvent_SetSeedValue0(Global_SetSeedValue0Pre, NULL);
_GLOBAL::RegisterEvent_SetSeedValue0(Global_SetSeedValue0Pre, Global_SetSeedValue0Post);
_GLOBAL::RegisterEvent_SetSeedValue2(Global_SetSeedValue2Post, Global_SetSeedValue2Post);
CSkillManager::RegisterEvent_SkillManagerAddSkill(SkillManager_AddSkillPre, NULL);
CSkillManager::RegisterEvent_SkillManagerSetSkillLevel(SkillManager_SetSkillLevelPre, SkillManager_SetSkillLevelPost);
CQuestManager::RegisterEvent_QuestManagerSetQuestCompleted(QuestManager_SetQuestCompletedPre, QuestManager_SetQuestCompletedPost);
CInventory::RegisterEvent_InventoryAddEquipment(Inventory_AddEquipmentPre, Inventory_AddEquipmentPost);
CInventory::RegisterEvent_InventoryRemoveEquipment(Inventory_RemoveEquipmentPre, Inventory_RemoveEquipmentPost);
CInventory::RegisterEvent_Inventory_EquipmentAutoEquip(Inventory_EquipmentAutoEquipPre, NULL);
CGameUI::RegisterEvent_GameUI_TriggerPause(GameUI_TriggerPausePre, NULL);
CGameUI::RegisterEvent_GameUI_HandleKeyboardInput(GameUI_HandleKeyboardInputPre, GameUI_HandleKeyboardInputPost);
CGameUI::RegisterEvent_GameUI_WindowResized(NULL, GameUI_WindowResizedPost);
CKeyManager::RegisterEvent_KeyManager_InjectKey(KeyManager_HandleInputPre, NULL);
CMouseManager::RegisterEvent_MouseManagerInput(MouseManager_HandleInputPre, NULL);
CPositionableObject::RegisterEvent_PositionableObject_SetNearPlayer(PositionableObject_SetNearPlayerPre, NULL);
CParticleCache::RegisterEvent_ParticleCache_Dtor2(ParticleCache_Dtor2Pre, ParticleCache_Dtor2Post);
CGenericModel::RegisterEvent_GenericModel_Dtor(GenericModel_DtorPre, GenericModel_DtorPost);
// --
multiplayerLogger.WriteLine(Info, L"Registering Events... Done.");
Server::getSingleton().SetCallback_OnClientConnect(&ServerOnClientConnected);
Server::getSingleton().SetCallback_OnClientDisconnect(&ServerOnClientDisconnect);
Client::getSingleton().SetCallback_OnConnected(&ClientOnConnect);
Hook(GetProcAddress(GetModuleHandle("OgreMain.dll"), "?isActive@RenderWindow@Ogre@@UBE_NXZ"), OgreIsActive, 0, HOOK_THISCALL, 0);
const char *mangledResourceLocationFunc = "?addResourceLocation@ResourceGroupManager@Ogre@@QAEXABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@00_N@Z";
void (__thiscall *addResourceLocation)(PVOID, Ogre::String&, Ogre::String&, Ogre::String&, bool) =
(void (__thiscall *)(PVOID, Ogre::String&, Ogre::String&, Ogre::String&, bool))GetProcAddress(GetModuleHandle("OgreMain.dll"), mangledResourceLocationFunc);
Hook(addResourceLocation, 0, OgreAddResourceLocation, HOOK_THISCALL, 4);
log(L"Done.");
}
void TLMP::OgreAddResourceLocation STDARG
{
static bool setup = false;
Ogre::String *name = *(Ogre::String**)&Pz[0];
Ogre::String *loc = *(Ogre::String**)&Pz[1];
Ogre::String *resGroup = *(Ogre::String**)&Pz[2];
/*
printf("DEBUG:\n");
for (int i = 0; i < 16; i++) {
char *temp = (char*)name + i;
printf("%c %x\n", *temp, *temp);
}
printf("\n");
*/
/*
// Setup the resource location for our TLAPI folder to correctly load our UI layouts
if (!setup) {
const char *mangledResourceLocationFunc = "?addResourceLocation@ResourceGroupManager@Ogre@@QAEXABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@00_N@Z";
void (__thiscall *addResourceLocation)(PVOID, std::string&, std::string&, std::string&, bool) =
(void (__thiscall *)(PVOID, std::string&, std::string&, std::string&, bool))GetProcAddress(GetModuleHandle("OgreMain.dll"), mangledResourceLocationFunc);
setup = true;
addResourceLocation(e->_this, std::string("TLAPI/"), std::string("FileSystem"), std::string("General"), false);
}
*/
//log("AddResourceLocation: (%p) (%s %s %s)", e->_this, name->c_str(), loc->c_str(), resGroup->c_str());
if (!setup) {
setup = true;
//log(L"Adding Ogre Resource Location...");
try {
Ogre::ResourceGroupManager::getSingletonPtr()->addResourceLocation(Ogre::String("TLAPI/"), Ogre::String("FileSystem"));
Ogre::ResourceGroupManager::getSingletonPtr()->addResourceLocation(Ogre::String("TLAPI/ogretray"), Ogre::String("FileSystem"));
} catch (Ogre::ItemIdentityException &ex) {
log("Ogre Exception: %s", ex.what());
}
//log(L"Done.\n");
}
}
void TLMP::CharacterSaveState_ReadFromFile(CCharacterSaveState* saveState, PVOID file, u32 unk)
{
/*
// Dump character save state
multiplayerLogger.WriteLine(Info, L"CharacterSaveState_ReadFromFile: %s (GUID: %016I64X)",
saveState->name.c_str(), saveState->guid2);
multiplayerLogger.WriteLine(Info, L" Strength: %i", saveState->strength);
multiplayerLogger.WriteLine(Info, L" Dexterity: %i", saveState->dexterity);
multiplayerLogger.WriteLine(Info, L" Defense: %i", saveState->defense);
multiplayerLogger.WriteLine(Info, L" Magic: %i", saveState->magic);
multiplayerLogger.WriteLine(Info, L" Gold: %i", saveState->gold);
multiplayerLogger.WriteLine(Info, L" Spell 1: %s", saveState->nameSpell1.c_str());
multiplayerLogger.WriteLine(Info, L" Spell 2: %s", saveState->nameSpell2.c_str());
multiplayerLogger.WriteLine(Info, L" Spell 3: %s", saveState->nameSpell3.c_str());
multiplayerLogger.WriteLine(Info, L" Spell 4: %s", saveState->nameSpell4.c_str());
// Dump character's item save states
CItemSaveState **itr = saveState->itemSaveStateBegin;
CItemSaveState **itrEnd = saveState->itemSaveStateEnd1;
while (itr != itrEnd) {
multiplayerLogger.WriteLine(Info, L" Item: %s (GUID: %016I64X) Slot: %i",
(*itr)->name.c_str(), (*itr)->guid2, (*itr)->slot);
multiplayerLogger.WriteLine(Info, L" Prefix: %s",
(*itr)->name2.c_str());
multiplayerLogger.WriteLine(Info, L" Suffix: %s",
(*itr)->name3.c_str());
for (int i = 0; i < 6; i++) {
multiplayerLogger.WriteLine(Info, L" Unk1[%i]: %x",
i, (*itr)->unk1[i]);
}
for (int i = 0; i < 30; i++) {
multiplayerLogger.WriteLine(Info, L" Unk2[%i]: %x",
i, (*itr)->unk2[i]);
}
multiplayerLogger.WriteLine(Info, L"");
itr++;
}
*/
}
void TLMP::Equipment_DtorPre(CEquipment* equipment)
{
//log(L"Equipment::DtorPre = %p Removing from network list... %s", equipment, equipment->nameReal.c_str());
vector<NetworkEntity*>::iterator itr;
for (itr = NetworkSharedEquipment->begin(); itr != NetworkSharedEquipment->end(); itr++) {
CEquipment *equipment2 = (CEquipment*)(*itr)->getInternalObject();
if (equipment == equipment2) {
NetworkSharedEquipment->erase(itr);
break;
}
}
// Attempt to duct-tape a bug with item duping, move across our player's inventory
// and cleanup the equipment in any equipmentRef's that are tied to the equipment
if (gameClient) {
CPlayer* player = gameClient->pCPlayer;
// Check dups against player inventory
if (player) {
CInventory *inventory = player->pCInventory;
if (inventory) {
for (u32 i = 0; i < inventory->equipmentList.size; i++) {
CEquipmentRef *equipmentRef = inventory->equipmentList[i];
if (equipmentRef) {
if (equipmentRef->pCEquipment == equipment) {
// Null it so the destructor plays nice
equipmentRef->pCEquipment = NULL;
}
}
}
}
}
}
}
void TLMP::Equipment_DtorPost(CEquipment* equipment)
{
// Clear the vtable just in case to aid in debugging - it will should crash outright if accessing later
*((u32*)equipment) = NULL;
//log(L"Equipment::DtorPost = %p", equipment);
}
void TLMP::Character_DtorPre(CCharacter* character)
{
log(L"Character::Dtor = %p", character);
log(L" %s", character->characterName.c_str());
multiplayerLogger.WriteLine(Info, L"Character::Dtor = %p", character);
multiplayerLogger.WriteLine(Info, L" %s", character->characterName.c_str());
// If we're the server, send the client that the character has been destroyed
if (NetworkState::getSingleton().GetState() == SERVER) {
NetworkEntity *entity = searchCharacterByInternalObject(character);
if (entity) {
NetworkMessages::CharacterDestroy msgCharacterDestroy;
msgCharacterDestroy.set_characterid(entity->getCommonId());
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterDestroy>(S_PUSH_CHAR_DESTROY, &msgCharacterDestroy);
} else {
//log(L"Server: Error could not find network ID for character destroyed: %p", character);
}
}
// Remove it from our list
vector<NetworkEntity*>::iterator itr;
for (itr = NetworkSharedCharacters->begin(); itr != NetworkSharedCharacters->end(); itr++) {
CCharacter* charItem = (CCharacter*)((*itr)->getInternalObject());
if (charItem == character) {
//log(L" Found and removed character");
NetworkSharedCharacters->erase(itr);
break;
}
}
}
void TLMP::Character_DtorPost(CCharacter* character)
{
log(L"Character::DtorPost = %p", character);
multiplayerLogger.WriteLine(Info, L"Character::DtorPost = %p", character);
}
void TLMP::Character_SetAlignmentPre(CCharacter* character, u32 alignment, bool& calloriginal)
{
//log(L"CharacterAlignment Pre: %x", character->alignment);
}
void TLMP::Character_SetAlignmentPost(CCharacter* character, u32 alignment, bool& calloriginal)
{
//log(L"CharacterAlignment Post: %x", character->alignment);
//log(L"Setting Character Alignment = %x", alignment);
multiplayerLogger.WriteLine(Info, L"Setting Character (%s) Alignment = %x",
character->characterName.c_str(), alignment);
//log(L"Setting Character (%s) Alignment = %x",
// character->characterName.c_str(), alignment);
// Client would never send alignment, just worry about the server
if (NetworkState::getSingleton().GetState() == SERVER) {
NetworkEntity *entity = searchCharacterByInternalObject(character);
if (entity) {
NetworkMessages::CharacterAlignment msgCharacterAlignment;
msgCharacterAlignment.set_characterid(entity->getCommonId());
msgCharacterAlignment.set_alignment(alignment);
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterAlignment>(S_PUSH_CHARACTER_ALIGNMENT, &msgCharacterAlignment);
} else {
//log(L"Error: Cannot send alignment, could not find entity ID");
}
}
else if (NetworkState::getSingleton().GetState() == CLIENT) {
}
}
void TLMP::Game_Ctor(CGame* game)
{
//log(L"Game::Ctor = %p", game);
}
void TLMP::GameClient_Ctor(CGameClient* client)
{
//log(L"GameClient::Ctor = %p", client);
gameClient = client;
}
void TLMP::CreatePlayer(CPlayer* character, CResourceManager* resourceManager, wchar_t* type, u32 unk0, bool & calloriginal)
{
//logColor(B_RED, L"CreatePlayer: %s %x", type, unk0);
}
void TLMP::Character_UpdateHealthPre(CCharacter* character, float amount, bool& calloriginal)
{
if (amount < 0 || (character->type__ == 0x1C && amount > 0)) {
//logColor(B_RED, L"Character (%p) update health", character);
//logColor(B_RED, L"Character (%s) Update health (%f)", character->characterName.c_str(), amount);
// Ignore the following to display updated health correctly for client
// Don't update the health on the client unless the server has sent it
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetAllow_HealthUpdate()) {
//calloriginal = false;
}
} else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
NetworkEntity *entity = searchCharacterByInternalObject(character);
if (entity) {
NetworkMessages::CharacterUpdateHealth msgCharacterUpdateHealth;
msgCharacterUpdateHealth.set_amount(amount);
msgCharacterUpdateHealth.set_current_health(character->healthCurrent);
msgCharacterUpdateHealth.set_max_health(character->healthMax);
msgCharacterUpdateHealth.set_characterid(entity->getCommonId());
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterUpdateHealth>(S_PUSH_CHAR_UPDATE_HEALTH, &msgCharacterUpdateHealth);
} else {
//log(L"Error: Could not find network ID for character");
}
}
}
}
void TLMP::CreateMonsterPre(CMonster*& character, CResourceManager* resourceManager, u64 guid, u32 level, bool noItems, bool & calloriginal)
{
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
multiplayerLogger.WriteLine(Info, L"Creating character: %016I64X %i", guid, noItems);
//log(L"Creating character: %016I64X %i", guid, noItems);
if (Client::getSingleton().GetSuppressed_CharacterCreation()) {
if (guid != CAT && guid != DOG && guid != DESTROYER && guid != ALCHEMIST &&
guid != VANQUISHER && guid != BRINK && guid != STASH && guid != SHAREDSTASH)
{
//calloriginal = false;
//character = NULL;
}
}
}
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
multiplayerLogger.WriteLine(Info, L"Created character with guid of: %016I64X (%p)", guid, character);
}
if (calloriginal) {
multiplayerLogger.WriteLine(Info, L"Creating character: %016I64X %i", guid, gameClient->flagLevelLoading);
//log(L"Creating character: %016I64X %i %i %i %i", guid,
// gameClient->flagLevelLoading, gameClient->unkFlag1, gameClient->unkFlag2, gameClient->unkFlag3);
}
}
void TLMP::CreateMonsterPost(CMonster*& character, CResourceManager* resourceManager, u64 guid, u32 level, bool unk0, bool &)
{
}
void TLMP::CreateItemPre(CItem* item, CResourceManager* resourceManager, u64 guid, u32 level, u32 unk0, u32 unk1, bool & calloriginal)
{
//
if (calloriginal) {
multiplayerLogger.WriteLine(Info, L"Creating equipment with guid of: %016I64X Level: %i (%p) %x %x",
guid, level, item, unk0, unk1);
//logColor(B_RED, L"Creating equipment with guid of: %016I64X Level: %i (%p) %x %x",
// guid, level, item, unk0, unk1);
} else {
multiplayerLogger.WriteLine(Info, L"Suppressing equipment creation with guid of: %016I64X Level: %i (%p) %x %x",
guid, level, item, unk0, unk1);
//logColor(B_RED, L"Suppressing equipment creation with guid of: %016I64X Level: %i (%p) %x %x",
// guid, level, item, unk0, unk1);
}
}
void TLMP::CreateItemPost(CItem* item, CResourceManager* resourceManager, u64 guid, u32 level, u32 unk0, u32 unk1, bool & calloriginal)
{
if (item) {
//logColor(B_RED, L"Created equipment with guid of: %016I64X Level: %i (%p, %s) Type = %x",
// guid, level, item, item->nameReal.c_str(), item->type__);
multiplayerLogger.WriteLine(Info, L"Created equipment with guid of: %016I64X Level: %i (%p, %s) Type = %x",
guid, level, item, item->nameReal.c_str(), item->type__);
multiplayerLogger.WriteLine(Info, L"Created equipment with guid of: %016I64X Level: %i (%p, %s) Type = %x",
guid, level, item, item->nameReal.c_str(), item->type__);
// If we are real equipment (not Interactable, Openable, Breakable, Gold, ...)
if (item->type__ != BREAKABLE && item->type__ != OPENABLE &&
item->type__ != GOLD && item->type__ != INTERACTABLE &&
item->type__ != WAYPOINTNODE && item->type__ != TOWNPORTAL &&
item->type__ != TEMPPORTAL)
{
// --
if (Network::NetworkState::getSingleton().GetState() == SERVER) {
if (!Server::getSingleton().GetSuppressed_SendEquipmentCreation()) {
//logColor(B_RED, L"Adding Regular Item of Type: %x %s", item->type__, item->nameReal.c_str());
NetworkEntity *newEntity = addEquipment(item);
NetworkMessages::Equipment msgEquipment;
Server::getSingleton().Helper_PopulateEquipmentMessage(&msgEquipment, (CEquipment*)item, newEntity);
Server::getSingleton().BroadcastMessage<NetworkMessages::Equipment>(S_PUSH_NEWEQUIPMENT, &msgEquipment);
}
}
}
// Just send the standard Item Creation
else {
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetSuppressed_EquipmentCreation()) {
// Assume the above is set to true when the server sends the LevelCreateItem message
// For assigning to NetworkSharedLevelItems CItem* is returned on the call
} else {
/*
if (item->type__ == OPENABLE) {
item->Destroy();
item = NULL;
return;
}
*/
}
}
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
//if (item->type__ != OPENABLE && item->type__ != INTERACTABLE) {
if (!Server::getSingleton().GetSuppressed_SendEquipmentCreation()) {
//logColor(B_RED, L"Adding Special Item of Type: %x %s", item->type__, item->nameReal.c_str());
NetworkEntity *entity = addItem(item);
NetworkMessages::LevelCreateItem msgLevelCreateItem;
msgLevelCreateItem.set_itemid(entity->getCommonId());
msgLevelCreateItem.set_guid(item->GUID);
msgLevelCreateItem.set_level(level);
msgLevelCreateItem.set_unk0(unk0);
msgLevelCreateItem.set_unk1(unk1);
Server::getSingleton().BroadcastMessage<NetworkMessages::LevelCreateItem>(S_PUSH_LEVEL_CREATE_ITEM, &msgLevelCreateItem);
}
//}
}
}
}
}
void TLMP::EquipmentInitialize(CEquipment* equipment, CItemSaveState* itemSaveState, bool & calloriginal)
{
//log(L"Equipment initializing: %p", equipment);
//log(L" ItemSaveState: %s %s %s",
// itemSaveState->name.c_str(), itemSaveState->name2.c_str(), itemSaveState->name3.c_str());
//log(L"Equipment Initialized (GUID: %016I64X %s)",
// equipment->GUID, equipment->nameReal.c_str());
multiplayerLogger.WriteLine(Info, L"Equipment Initialized (GUID: %016I64X %s)",
equipment->GUID, equipment->nameReal.c_str());
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (Client::getSingleton().GetSuppressed_EquipmentCreation()) {
//calloriginal = false;
}
}
if (calloriginal) {
} else {
multiplayerLogger.WriteLine(Info, L"Suppressing Equipment Initialize (GUID: %016I64X %s)",
equipment->GUID, equipment->nameReal.c_str());
}
}
// This is really an equipment use
void TLMP::EquipmentIdentifyPre(CEquipment* equipment, CCharacter *player, CBaseUnit* target, bool& calloriginal)
{
log(L"Equipment Identify Pre (%p, player: %p, target: %p)", equipment, player, target);
log(L" Equipment: %s, Player: %s", equipment->nameReal.c_str(), player->characterName.c_str());
NetworkEntity *entity = searchEquipmentByInternalObject(equipment);
if (!entity) {
log(L"Error: Could not find Network Entity for Equipment");
return;
}
NetworkEntity *netCharacter = searchCharacterByInternalObject(player);
if (!netCharacter) {
log(L"Error: Could not find Network Entity for Player");
return;
}
NetworkMessages::EquipmentIdentify msgEquipmentIdentify;
// Search characters first for the target
NetworkEntity *netTarget = searchCharacterByInternalObject(target);
if (!netTarget) {
// If not, we might be targetting an item, search
netTarget = searchEquipmentByInternalObject(target);
if (!netTarget) {
log(L"Error: Could not find Network Entity for Target");
return;
} else {
// Set item type
msgEquipmentIdentify.set_target_player_type(false);
}
} else {
// Set player type
msgEquipmentIdentify.set_target_player_type(true);
}
msgEquipmentIdentify.set_equipmentid(entity->getCommonId());
msgEquipmentIdentify.set_characterid(netCharacter->getCommonId());
msgEquipmentIdentify.set_targetid(netTarget->getCommonId());
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetAllow_EquipmentIdentify()) {
calloriginal = false;
Client::getSingleton().SendMessage<NetworkMessages::EquipmentIdentify>(C_REQUEST_EQUIPMENT_IDENTIFY, &msgEquipmentIdentify);
}
} else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().BroadcastMessage<NetworkMessages::EquipmentIdentify>(S_PUSH_EQUIPMENT_IDENTIFY, &msgEquipmentIdentify);
}
}
void TLMP::Level_CharacterInitializePre(CCharacter* retval, CLevel* level, CCharacter* character, Vector3* position, u32 unk0, bool & calloriginal)
{
log(L"Level_CharacterInitializePre: Level = %p Character = %p", level, character);
multiplayerLogger.WriteLine(Info, L"Level_CharacterInitializePre: Level = %p Character = %p", level, character);
if (!character) {
calloriginal = false;
return;
}
u64 guid = character->GUID;
multiplayerLogger.WriteLine(Info, L"Level::CharacterInitialize: %s (%f %f %f) unk0: %x",
character->characterName.c_str(), position->x, position->y, position->z, unk0);
log(L"Level::CharacterInitialize: %s (%f %f %f) unk0: %x",
character->characterName.c_str(), position->x, position->y, position->z, unk0);
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
// Not suppressed, server sent it
if (!Client::getSingleton().GetSuppressed_CharacterCreation()) {
if (guid == STASH || guid == SHAREDSTASH) {
// Delete the stash the server sent
character->SetPosition(&Ogre::Vector3(10000, 0, 10000));
character->destroy = true;
}
// True, attempt to suppress the character initialization
} else if (Client::getSingleton().GetSuppressed_CharacterCreation()) {
log("Client's suppressed character initialize guid: %016I64X", guid);
// Hacky character checks for specific characters and whether we're in town or not
if (guid == STASH || guid == SHAREDSTASH) {
// Remove the stash or shared stash if we're not in the town
if (wcscmp(level->levelName.c_str(), L"TOWN")) {
character->destroy = true;
}
/*
} else if (guid == DESTROYER || guid == VANQUISHER || guid == ALCHEMIST ||
guid == DOG || guid == CAT || guid == BRINK)
{
//log("Client: Detected CPlayer addition to CLevel, not suppressing load");
} else {
// Town characters won't be destroyed, so just don't call this
if (!wcscmp(level->levelName.c_str(), L"TOWN")) {
log(L"Client: Suppressing Monster load into level: %016I64X %s", character->GUID, character->characterName.c_str());
calloriginal = false;
retval = NULL;
}
*/
} else {
const u32 townsFolkSize = sizeof(TOWNSFOLK) / sizeof(TOWNSFOLK[0]);
for (u32 i = 0; i < townsFolkSize; ++i) {
if (guid == TOWNSFOLK[i]) {
log(L"Client: Suppressing TownsFolk load into level: %016I64X %s", character->GUID, character->characterName.c_str());
calloriginal = false;
retval = NULL;
}
}
}
//log("Character destroy = %s", character->destroy ? "true" : "false");
}
}
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
if (gameClient->inGame) {
multiplayerLogger.WriteLine(Info, L"Level Character Initialized: %p %s (%f %f %f) unk0: %x",
character, character->characterName.c_str(), position->x, position->y, position->z, unk0);
//log(L"Level Character Initialized: %p %s (%f %f %f) unk0: %x",
// character, character->characterName.c_str(), position->x, position->y, position->z, unk0);
// Create a network ID to identify this character later
NetworkEntity *newEntity = addCharacter(character);
if (!newEntity) {
//log(L"NetworkEntity is NULL");
return;
}
// If the server isn't in the process of changing levels, we're safe to send this out
if (!LevelLoading) {
// Send this character to be created on the clients if it isn't suppressed
if (!Server::getSingleton().GetSuppressed_SendCharacterCreation()) {
if (guid != STASH && guid != SHAREDSTASH) {
multiplayerLogger.WriteLine(Info, L"Server: Pushing Initialized Character out to clients...");
//log(L"Server: Pushing Initialized Character out to clients...");
string characterName(character->characterName.begin(), character->characterName.end());
characterName.assign(character->characterName.begin(), character->characterName.end());
// Create a new network message for all clients to create this character
NetworkMessages::Character msgNewCharacter;
msgNewCharacter.set_guid(character->GUID);
msgNewCharacter.set_name(characterName);
NetworkMessages::Position *msgPlayerPosition = msgNewCharacter.mutable_position();
msgPlayerPosition->set_x(character->GetPosition().x);
msgPlayerPosition->set_y(character->GetPosition().y);
msgPlayerPosition->set_z(character->GetPosition().z);
msgNewCharacter.set_id(newEntity->getCommonId());
msgNewCharacter.set_alignment(character->alignment);
Helper_BuildInventoryTabIndexSize(msgNewCharacter, character);
// This will broadcast to all clients except the one we received it from
Server::getSingleton().BroadcastMessage<NetworkMessages::Character>(S_PUSH_NEWCHAR, &msgNewCharacter);
}
}
}
}
}
}
void TLMP::Level_CharacterInitializePost(CCharacter* retval, CLevel* level, CCharacter* character, Vector3* position, u32 unk0, bool & calloriginal)
{
log(L"Level_CharacterInitializePost");
multiplayerLogger.WriteLine(Info, L"Level_CharacterInitializePost");
u64 guid = character->GUID;
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
// Client created character, not the servers'
if (Client::getSingleton().GetSuppressed_CharacterCreation()) {
log(" Client's suppressed character initialize guid: %016I64X", guid);
// Hacky character checks for specific characters and whether we're in town or not
if (guid == STASH || guid == SHAREDSTASH || guid == DESTROYER || guid == VANQUISHER || guid == ALCHEMIST ||
guid == DOG || guid == CAT || guid == BRINK || guid == 0xFFFFFFFFFFFFFFFF)
{
} else {
// Anything not in the town
if (wcscmp(level->levelName.c_str(), L"TOWN")) {
log(L" Post Destroying character... %p %p", retval, character);
/*
// Destroy the character if we're not going to load it
character->SetPosition(&Ogre::Vector3(10000, 0, 10000));
character->destroy = true;
character->healthCurrent = -1;
character->healthMax = -1;
character->state = DYING;
*/
character->destroy = true;
ClientDuplicateCharacters->push_back(retval);
//level->RemoveCharacter(retval);
}
}
}
}
}
void TLMP::GameClient_ProcessObjects(CGameClient *client, float dTime, PVOID unk1, PVOID unk2)
{
//CPlayer *player = client->pCPlayer;
//log(L"Test: CPositionableObject: %x CBaseUnit: %x CCharacter: %x (Player = %p)",
// sizeof(CPositionableObject), sizeof(CBaseUnit), sizeof(CCharacter), player);
/*
log(L"Test: destroy = %x", player->destroy);
log(L"Test: offset destroy = %x", ((u32)&player->destroy - (u32)player) );
*/
/*
log(L"Test: health = %x", player->health);
log(L"Test: offset health = %x", ((u32)&player->health - (u32)player) );
log(L"Test: mana = %x", player->mana);
log(L"Test: offset mana = %x", ((u32)&player->mana - (u32)player) );
*/
/*
log(L"Test: target = %x", player->target);
log(L"Test: offset target = %x", ((u32)&player->target - (u32)player) );
log(L"Test: running = %x", player->running);
log(L"Test: offset running = %x", ((u32)&player->running - (u32)player) );
log(L"Test: moving = %x", player->moving);
log(L"Test: attacking = %x", player->attacking);
log(L"Test: offset moving = %x", ((u32)&player->moving - (u32)player) );
log(L"Test: offset attacking = %x", ((u32)&player->attacking - (u32)player) );
gameClient->pCGameUI->dumpSubMenuPtrs();
//log(L"TargetName: %p offset = %x (gameUI = %p)", gameClient->pCGameUI->sheetTargetName, ((u8*)&gameClient->pCGameUI->sheetTargetName - (u8*)gameClient->pCGameUI), &gameClient->pCGameUI);
//log(" TargetName: %s", gameClient->pCGameUI->sheetTargetName->getText().c_str());
//log(L" Target: %p", gameClient->pCGameUI->pCTargetCharacter);
if (gameClient->pCGameUI->pCTargetCharacter) {
log(L" Target: %s", gameClient->pCGameUI->pCTargetCharacter->characterName.c_str());
}
*/
/*
ShowCursor(false);
CEGUI::MouseCursor* mouseCursor = CEGUI::MouseCursor::getSingletonPtr();
mouseCursor->setImage("logo", "destroyericon");
mouseCursor->show();
mouseCursor->draw();
*/
// Set the started flag - don't bother checking, it's just as fast to set it
switch (Network::NetworkState::getSingleton().GetState()) {
case SERVER:
// Only set game started when the town is the level loaded
if (!wcscmp(gameClient->pCDungeon->name0.c_str(), L"TOWN")) {
Server::getSingleton().SetGameStarted(true);
} else {
Server::getSingleton().SetGameStarted(false);
}
Server::getSingleton().ReceiveMessages();
break;
case CLIENT:
Client::getSingleton().SetGameStarted(true);
Client::getSingleton().ReceiveMessages();
break;
}
// Process messages from the Lobby server
LobbyClient::getSingleton().ReceiveMessages();
}
void TLMP::GameClient_TitleProcessObjects(CGameClient *client, float dTime, PVOID unk1, PVOID unk2)
{
//log("MainMenuShown: %i", MainMenuShown());
// Determine if we've exited an existing game in network mode
switch (Network::NetworkState::getSingleton().GetState()) {
case SERVER:
// Shutdown the Server if this is the first iteration out of the game
//if (Server::getSingleton().GetGameStarted() && Server::getSingleton().HasGameStarted()) {
// Server::getSingleton().Shutdown();
//}
Server::getSingleton().SetGameStarted(false);
Server::getSingleton().ReceiveMessages();
break;
case CLIENT:
// Shutdown the Client if this is the first iteration out of the game
//if (Client::getSingleton().GetGameStarted() && Client::getSingleton().HasGameStarted()) {
// Client::getSingleton().Disconnect();
//}
Client::getSingleton().SetGameStarted(false);
Client::getSingleton().ReceiveMessages();
break;
}
// Process messages from the Lobby server
LobbyClient::getSingleton().ReceiveMessages();
}
void TLMP::GameClient_CreateLevelPre(CGameClient* client, wstring unk0, wstring unk1, u32 unk2, u32 unk3, u32 unk4, wstring unk5, bool & calloriginal)
{
multiplayerLogger.WriteLine(Info, L"GameClient::CreateLevel Pre (%s, %s, %s %x %x %x)",
unk0.c_str(), unk1.c_str(), unk5.c_str(), unk2, unk3, unk4);
//logColor(B_GREEN, L"GameClient::CreateLevel Pre (%s, %s, %s %x %x %x)",
// unk0.c_str(), unk1.c_str(), unk5.c_str(), unk2, unk3, unk4);
/*
logColor(B_GREEN, L"Level: %i", client->level);
logColor(B_GREEN, L"levelAbsolute: %x", client->levelAbsolute);
logColor(B_GREEN, L"DungeonName: %s", client->dungeonName.c_str());
logColor(B_GREEN, L"Dungeon: %p", client->pCDungeon);
logColor(B_GREEN, L" Name0: %s", client->pCDungeon->name0.c_str());
logColor(B_GREEN, L" Name1: %s", client->pCDungeon->name1.c_str());
logColor(B_GREEN, L" Name2: %s", client->pCDungeon->name2.c_str());
static bool firstLevel = true;
if (firstLevel) {
firstLevel = false;
unk5.assign(L"TOWN");
gameClient->pCDungeon->name0.assign(L"TOWN");
}
*/
}
void TLMP::GameClient_CreateLevelPost(CGameClient* client, wstring unk0, wstring unk1, u32 unk2, u32 unk3, u32 unk4, wstring unk5, bool & calloriginal)
{
//log(L"CreateLevel Post");
// Do this in Post to ensure it loads at the right time
// Send a Message to clients that the Server's game has started
if (Network::NetworkState::getSingleton().GetState() == SERVER) {
// Only set game started when the town is the level loaded
if (!wcscmp(gameClient->pCDungeon->name0.c_str(), L"TOWN")) {
Server::getSingleton().SetGameStarted(true);
} else {
Server::getSingleton().SetGameStarted(false);
}
NetworkMessages::GameStarted msgGameStarted;
Server::getSingleton().BroadcastMessage<NetworkMessages::GameStarted>(S_PUSH_GAMESTARTED, &msgGameStarted);
}
// Send a Message to the Server that the client has entered the game
else if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
Client::getSingleton().SetGameStarted(true);
NetworkMessages::GameEnter msgGameEnter;
NetworkMessages::CurrentLevel *msgCurrentLevel = msgGameEnter.mutable_currentlevel();
string sDungeonSection(gameClient->pCDungeon->name0.begin(), gameClient->pCDungeon->name0.end());
sDungeonSection.assign(gameClient->pCDungeon->name0.begin(), gameClient->pCDungeon->name0.end());
//logColor(B_GREEN, L"Client: Sending GAME_ENTER: %s %i %i",
// gameClient->pCDungeon->name0.c_str(), gameClient->level, gameClient->levelAbsolute);
msgCurrentLevel->set_dungeonsection(sDungeonSection);
msgCurrentLevel->set_relativelevel(gameClient->level);
msgCurrentLevel->set_absolutelevel(gameClient->levelAbsolute);
Client::getSingleton().SendMessage<NetworkMessages::GameEnter>(C_PUSH_GAMEENTER, &msgGameEnter);
}
}
void TLMP::Level_Dtor(CLevel* level, u32, bool&)
{
logColor(B_RED, L"Level Dtor (%p)", level);
multiplayerLogger.WriteLine(Info, L"Level Dtor (%p)", level);
//level->DumpCharacters1();
//level->DumpTriggerUnits();
//level->DumpCharacters2();
level->DumpItems();
log(L"Level::Dtor Done Dumping Level Info");
}
void TLMP::Level_Ctor(wstring name, CSettings* settings, CGameClient* gameClient, CResourceManager* resourceManager, PVOID OctreeSM, CSoundManager* soundManager, u32 unk0, u32 unk1, bool&)
{
//logColor(B_RED, L"Level Ctor");
multiplayerLogger.WriteLine(Info, L"Level Ctor");
/*
log(L" Name: %s", name.c_str());
log(L" Settings: %p", settings);
log(L" GameClient: %p", gameClient);
log(L" ResourceManager: %p", resourceManager);
log(L" SoundManager: %p", soundManager);
*/
}
void TLMP::GameClient_LoadLevelPre(CGameClient* client, bool & calloriginal)
{
logColor(B_GREEN, L"LoadLevelPre (GameClient = %p, player = %p)", client, client->pCPlayer);
multiplayerLogger.WriteLine(Info, L"LoadLevelPre (GameClient = %p)", client);
/* Player may be deleted at this point?
log("Player state: %i", client->pCPlayer->state);
if (client->pCPlayer->state == DEAD || client->pCPlayer->state == DYING) {
client->pCPlayer->Resurrect();
client->pCPlayer->healthCurrent = client->pCPlayer->healthMax;
}
*/
// Clear the duplicate character list that will be created by this level load
ClientDuplicateCharacters->clear();
/*
// Suppress level changes
{
calloriginal = false;
logColor(B_GREEN, L"Level changes suppressed");
multiplayerLogger.WriteLine(Info, L"Level changes suppressed");
}
*/
CLevel *level = client->pCLevel;
//level->DumpCharacters1();
//level->DumpTriggerUnits();
//level->DumpCharacters2();
//level->DumpItems();
// Dump level items
{
multiplayerLogger.WriteLine(Info, L"");
multiplayerLogger.WriteLine(Info, L"Level Item Dump:");
LinkedListNode* itr = *(level->itemsAll);
while (itr != NULL) {
//log(L" Level Item: itr = %p", itr);
CItem* item = (CItem*)itr->pCBaseUnit;
multiplayerLogger.WriteLine(Info, L" itrNext: %p, Item: %p, Name: %s", itr->pNext, item, item->nameReal.c_str());
itr = itr->pNext;
}
multiplayerLogger.WriteLine(Info, L"Done dumping items.");
multiplayerLogger.WriteLine(Info, L"");
}
// Dump level trigger items
{
multiplayerLogger.WriteLine(Info, L"");
multiplayerLogger.WriteLine(Info, L"Level Trigger Dump:");
LinkedListNode* itr = *(level->itemsProximity);
while (itr != NULL) {
//log(L" Level Item: itr = %p", itr);
CItem* item = (CItem*)itr->pCBaseUnit;
multiplayerLogger.WriteLine(Info, L" itrNext: %p, Item: %p, Name: %s", itr->pNext, item, item->nameReal.c_str());
itr = itr->pNext;
}
multiplayerLogger.WriteLine(Info, L"Done dumping triggers.");
multiplayerLogger.WriteLine(Info, L"");
}
// Dump level characters
{
multiplayerLogger.WriteLine(Info, L"Level Character2 Dump:");
LinkedListNode* itr = *(level->charactersAll);
while (itr != NULL) {
CCharacter* character = (CCharacter*)itr->pCBaseUnit;
CInventory* inv = character->pCInventory;
multiplayerLogger.WriteLine(Info, L" Character (%p %s): Inventory (%p)", character, character->characterName.c_str(), inv);
multiplayerLogger.WriteLine(Info, L" Inventory Dump: %p for character %p", inv, inv->pCCharacter);
multiplayerLogger.WriteLine(Info, L" Inventory MaxSize: %i", inv->maxSize);
multiplayerLogger.WriteLine(Info, L" Inventory Equipment Size: %i", inv->equipmentList.size);
for (u32 i = 0; i < inv->equipmentList.size; ++i) {
multiplayerLogger.WriteLine(Info, L" Inventory Equipment [%i]: %p slot: %i", i, inv->equipmentList[i]->pCEquipment, inv->equipmentList[i]->slot);
multiplayerLogger.WriteLine(Info, L" Name: (%s)", inv->equipmentList[i]->pCEquipment->nameReal.c_str());
}
itr = itr->pNext;
}
}
/*
logColor(B_GREEN, L"Level: %i", client->level);
logColor(B_GREEN, L"levelAbsolute: %x", client->levelAbsolute);
logColor(B_GREEN, L"DungeonName: %s", client->dungeonName.c_str());
logColor(B_GREEN, L"Dungeon: %p", client->pCDungeon);
logColor(B_GREEN, L" Name0: %s", client->pCDungeon->name0.c_str());
logColor(B_GREEN, L" Name1: %s", client->pCDungeon->name1.c_str());
logColor(B_GREEN, L" Name2: %s", client->pCDungeon->name2.c_str());
*/
LevelLoading = true;
// Suppress level changes
if (NetworkState::getSingleton().GetSuppressed_LevelChange()) {
//calloriginal = false;
//client->flagLevelLoading = 0;
}
if (!calloriginal) {
multiplayerLogger.WriteLine(Info, L"GameClient::LoadLevel Suppressed");
//logColor(B_GREEN, L"GameClient::LoadLevel Suppressed");
}
log(L"GameClient_LoadLevelPre Done Dumping Info.");
}
void TLMP::GameClient_LoadLevelPost(CGameClient* client, bool & calloriginal)
{
logColor(B_GREEN, L"GameClient_LoadLevelPost");
multiplayerLogger.WriteLine(Info, L"GameClient_LoadLevelPost");
CLevel *level = client->pCLevel;
log(L"Level: %p", level);
level->DumpCharacters1();
level->DumpTriggerUnits();
level->DumpCharacters2();
level->DumpItems();
/*
logColor(B_GREEN, L" Level: %i", client->level);
logColor(B_GREEN, L" levelAbsolute: %x", client->levelAbsolute);
logColor(B_GREEN, L" DungeonName: %s", client->dungeonName.c_str());
logColor(B_GREEN, L" Dungeon: %p", client->pCDungeon);
logColor(B_GREEN, L" Name0: %s", client->pCDungeon->name0.c_str());
logColor(B_GREEN, L" Name1: %s", client->pCDungeon->name1.c_str());
logColor(B_GREEN, L" Name2: %s", client->pCDungeon->name2.c_str());
*/
LevelLoading = false;
log(L"GameClient_LoadLevelPost Done Dumping Info.");
if (NetworkState::getSingleton().GetState() == CLIENT) {
log(L"Client destroying duplicate characters...");
multiplayerLogger.WriteLine(Info, L"Client destroying duplicate characters...");
vector<CCharacter*>::iterator itr;
for (itr = ClientDuplicateCharacters->begin(); itr != ClientDuplicateCharacters->end(); ++itr) {
log(L" Destroying %s %016I64X", (*itr)->characterName.c_str(), (*itr)->GUID);
multiplayerLogger.WriteLine(Info, L" Destroying %s %016I64X", (*itr)->characterName.c_str(), (*itr)->GUID);
(*itr)->destroy = true;
}
ClientDuplicateCharacters->clear();
log(L"Done destroying.");
}
}
void TLMP::GameClient_LoadMapPre(CGameClient*, u32 unk0, u32 unk1, bool & calloriginal)
{
multiplayerLogger.WriteLine(Info, L"GameClient::LoadMap Pre(%x %x)", unk0, unk1);
logColor(B_GREEN, L"GameClient::LoadMap Pre(%x %x)", unk0, unk1);
// unk0 unk1
// 0 3 is the character load screen
// 0 0 is the main title screen
// 0 1 is the new player screen
// 2 0 is the game
// 0: Player loading into title menu from game
// 2: Player loading into game from title menu
if (unk0 == 0 && unk1 == 0) {
// If we are loading into the main menu then send off our intention to leave
// to either the server or client, then forcefully disconnect on PostLoadMap
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
NetworkMessages::GameEnded msgGameEnded;
Client::getSingleton().SendMessage<NetworkMessages::GameEnded>(C_PUSH_GAMEEXITED, &msgGameEnded);
} else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
//NetworkMessages::GameEnded msgGameEnded;
//Server::getSingleton().BroadcastMessage<NetworkMessages::GameEnded>(S_PUSH_GAMEENDED, &msgGameEnded);
}
} else if (unk0 == 2) {
// This will suppress the game load if the Server hasn't setup the game yet
// TODO: Re-show the UI and Display an Error dialog
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetServerGameStarted()) {
log("Suppressing client load - server has not started game yet.");
calloriginal = false;
// Display the UI message for waiting for server to start
DisplayWaitForServerWindow();
}
}
}
}
void TLMP::GameClient_LoadMapPost(CGameClient*, u32 unk0, u32 unk1, bool & calloriginal)
{
multiplayerLogger.WriteLine(Info, L"GameClient::LoadMap Post(%x %x)", unk0, unk1);
logColor(B_GREEN, L"GameClient::LoadMap Post(%x %x)", unk0, unk1);
// 0: Player loading into title menu from game
// 2: Player loading into game from title menu
if (unk0 == 0 && unk1 == 0) {
// Forcefully disconnect here after we've sent off our exited/ended message in LoadMapPre
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
Client::getSingleton().Disconnect();
} else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().Shutdown();
}
} else if (unk0 == 2) {
// Testing out speeding up Client load times and issues
if (NetworkState::getSingleton().GetState() == SERVER) {
// Force load the Player into the Town
wstring Town(L"TOWN");
if (gameClient->pCDungeon->name0 == Town) {
multiplayerLogger.WriteLine(Info, L"Player already in town");
//logColor(B_RED, L"Player already in town");
} else {
multiplayerLogger.WriteLine(Info, L"Player not in town, force loading...");
//logColor(B_RED, L"Player not in town, force loading...");
NetworkState::getSingleton().SetSuppressed_LevelChange(false);
gameClient->ForceToTown();
NetworkState::getSingleton().SetSuppressed_LevelChange(true);
}
}
}
}
void TLMP::MainMenuEventPre(CMainMenu* mainMenu, u32 unk0, wstring str, bool & calloriginal)
{
enum {
CONTINUELASTGAME = 3,
NEWGAME = 4,
CONTINUEGAME = 5, // Load Game
};
log(L"MainMenuEventPre: %x %s", unk0, str.c_str());
// New: Attempt to suppress this at the GameClient_LoadMap function
// -Problem: UI is hidden when failed, go ahead and stop this function
// Suppress this event if any of these actions are taken
if (unk0 == CONTINUELASTGAME || unk0 == NEWGAME || unk0 == CONTINUEGAME) {
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetServerGameStarted()) {
calloriginal = false;
multiplayerLogger.WriteLine(Info, L"Enter game suppressed: Client, Server not in game");
// Display the UI message for waiting for server to start
DisplayWaitForServerWindow();
}
}
}
}
void TLMP::Monster_Idle(CMonster* monster, float dTime, bool & calloriginal)
{
if (monster->GUID == DESTROYER || monster->GUID == ALCHEMIST || monster->GUID == VANQUISHER) {
calloriginal = false;
}
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
//calloriginal = false;
}
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
//if (monster->GUID == DESTROYER || monster->GUID == ALCHEMIST || monster->GUID == VANQUISHER) {
// calloriginal = false;
//}
}
}
void TLMP::Character_SetDestination(CCharacter* character, CLevel* level, float x, float z)
{
// Buffer character position, check if it exists
// If the position is the same then don't push it out
map<CCharacter*, Vector3>::iterator itr;
itr = CharacterNetworkPositionBuffer->find(character);
if (itr != CharacterNetworkPositionBuffer->end()) {
Vector3& position = (*CharacterNetworkPositionBuffer)[character];
if (fabs(position.x - x) < 0.01f && fabs(position.z - z) < 0.01f) {
return;
}
}
(*CharacterNetworkPositionBuffer)[character].x = x;
(*CharacterNetworkPositionBuffer)[character].z = z;
//log(L"Character set destination: %s %p %f %f", character->characterName.c_str(), level, x, z);
//
if (Network::NetworkState::getSingleton().GetState() == SINGLEPLAYER) {
return;
}
NetworkMessages::CharacterDestination msgCharacterDestination;
NetworkMessages::Position *msgPositionCurrent = msgCharacterDestination.mutable_current();
NetworkMessages::Position *msgPositionDestination = msgCharacterDestination.mutable_destination();
msgPositionCurrent->set_x(character->GetPosition().x);
msgPositionCurrent->set_y(character->GetPosition().y);
msgPositionCurrent->set_z(character->GetPosition().z);
msgPositionDestination->set_x(x);
msgPositionDestination->set_y(0);
msgPositionDestination->set_z(z);
// Find the CommonID for the Character
u32 commonId;
NetworkEntity* entity = searchCharacterByInternalObject((PVOID)character);
if (entity) {
commonId = entity->getCommonId();
} else {
multiplayerLogger.WriteLine(Error, L"Error: Could not find Network Common ID for Character ptr: %p in SetDestination", character);
return;
}
msgCharacterDestination.set_id(commonId);
msgCharacterDestination.set_running(character->running);
msgCharacterDestination.set_attacking(character->attacking);
// Send a Network message off to the server if we're a client
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetSuppressed_SetDestination()) {
Client::getSingleton().SendMessage<NetworkMessages::CharacterDestination>(C_PUSH_CHARACTER_SETDEST, &msgCharacterDestination);
}
}
// Send this message to all clients if this is the Server
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
if (!Server::getSingleton().GetSuppressed_SetDestination()) {
//multiplayerLogger.WriteLine(Info, L" Sending Destination for Common: %x (%p)", commonId, character);
//log(L" Sending Destination for Common: %x (%p)", commonId, character);
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterDestination>(S_PUSH_CHARACTER_SETDEST, &msgCharacterDestination);
}
}
}
void TLMP::Level_DropItemPre(CLevel* level, CItem* item, Vector3 & position, bool unk0, bool& calloriginal)
{
multiplayerLogger.WriteLine(Info, L"Level pre dropping Item %s at (unk0: %i) %f, %f, %f Type = %x",
item->nameReal.c_str(), unk0, position.x, position.y, position.z, item->type__);
log(L"Level pre dropping Item %s at (unk0: %i) %f, %f, %f Type = %x",
item->nameReal.c_str(), unk0, position.x, position.y, position.z, item->type__);
// Iterate over the existing items on the level and ensure the same item doesn't already exist
LinkedListNode* itr = *level->itemsAll;
while (itr != NULL) {
CItem* itemLevel = (CItem*)itr->pCBaseUnit;
if (itemLevel == item) {
log(L"Level Drop Found Identical Item already on the Ground! Suppressing the drop.");
calloriginal = false;
break;
}
itr = itr->pNext;
}
//
if (NetworkState::getSingleton().GetState() == CLIENT) {
// Allow interactable and stash/shared stash (these may not be needed)
if (item->type__ == OPENABLE ||
item->type__ == INTERACTABLE)
{
if (!wcscmp(item->nameReal.c_str(), L"Barrel") ||
!wcscmp(item->nameReal.c_str(), L"Stairs Up") ||
!wcscmp(item->nameReal.c_str(), L"Stairs Down") ||
!wcscmp(item->nameReal.c_str(), L"Return to Dungeon") ||
!wcscmp(item->nameReal.c_str(), L"Waygate to Town") ||
!wcscmp(item->nameReal.c_str(), L"Mine Entrance"))
{
calloriginal = false;
}
}
/*
if (item->type__ != INTERACTABLE &&
item->type__ != OPENABLE)
{*/
else {
if (!Client::getSingleton().GetAllow_LevelItemDrop()) {
log(L"Suppressed");
calloriginal = false;
item->SetPosition(&Ogre::Vector3(10000, 0, 10000));
//item->Destroy();
item->destroy;
}
}
} else if (NetworkState::getSingleton().GetState() == SERVER) {
}
if (!calloriginal) {
//log(L" Suppressing level drop item: type = %i", item->type__);
}
}
void TLMP::Level_DropItemPost(CLevel* level, CItem* item, Vector3 & position, bool unk0, bool& calloriginal)
{
multiplayerLogger.WriteLine(Info, L"Level post dropped Item %s at %f, %f, %f (unk0: %i)",
item->nameReal.c_str(), position.x, position.y, position.z, unk0);
//log(L"Level post dropped Item %s at %f, %f, %f (unk0: %i)",
// item->nameReal.c_str(), position.x, position.y, position.z, unk0);
// DEBUGGING SERVER CRASH
// Iterate over the existing items on the level and dump their names
//log(L"Current Items on Ground: %p", level->itemsAll);
/*
LinkedListNode* itr2 = *level->itemsAll;
while (itr2) {
CEquipment* itemItr = (CEquipment*)itr2->pCBaseUnit;
// Ensure this is Equipment (Check vtable ptr) before dumping info
if (*(u32*)itemItr == 0xA7EA8C) {
log(L" Item: %s (Sockets: %i, GemList Size: %i)", itemItr->nameReal.c_str(), itemItr->socketCount, itemItr->gemList.size);
for (u32 i = 0; i < itemItr->gemList.size; ++i) {
log(L" Gem[%i]: %s", i, itemItr->gemList[i]->nameReal.c_str());
}
}
itr2 = itr2->pNext;
}
*/
// --
// Bump out before sending the network message if we're not supposed to
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (Client::getSingleton().GetAllow_LevelItemDrop()) {
return;
}
}
//
NetworkEntity *equipmentEntity = searchEquipmentByInternalObject((PVOID)item);
if (equipmentEntity) {
// Create a Network Message for sending off to clients the equipment addition to the inventory
NetworkMessages::EquipmentDrop msgEquipmentDrop;
NetworkMessages::Position *msgPosition = msgEquipmentDrop.add_position();
msgPosition->set_x(position.x);
msgPosition->set_y(position.y);
msgPosition->set_z(position.z);
msgEquipmentDrop.set_equipmentid(equipmentEntity->getCommonId());
msgEquipmentDrop.set_unk0(unk0);
// Client
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
Client::getSingleton().SendMessage<NetworkMessages::EquipmentDrop>(C_PUSH_EQUIPMENT_DROP, &msgEquipmentDrop);
}
// Server
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().BroadcastMessage<NetworkMessages::EquipmentDrop>(S_PUSH_EQUIPMENT_DROP, &msgEquipmentDrop);
// Add this to our Equipment on the Ground list
ServerEquipmentOnGround->push_back(equipmentEntity);
}
}
else {
if (Network::NetworkState::getSingleton().GetState() == SERVER) {
NetworkEntity *entity = searchItemByInternalObject(item);
if (!entity) {
entity = addItem(item);
}
if (entity) {
NetworkMessages::LevelDropItem msgLevelDropItem;
NetworkMessages::Position *msgPosition = msgLevelDropItem.mutable_position();
msgPosition->set_x(position.x);
msgPosition->set_y(position.y);
msgPosition->set_z(position.z);
msgLevelDropItem.set_itemid(entity->getCommonId());
msgLevelDropItem.set_unk0(unk0);
Server::getSingleton().BroadcastMessage<NetworkMessages::LevelDropItem>(S_PUSH_LEVEL_ITEM_DROP, &msgLevelDropItem);
}
}
}
}
void TLMP::SendInventoryAddEquipmentToServer(CCharacter* owner, CEquipment* equipment, u32 slot, u32 unk)
{
NetworkEntity *ownerEntity = searchCharacterByInternalObject((PVOID)owner);
NetworkEntity *equipmentEntity = searchEquipmentByInternalObject((PVOID)equipment);
multiplayerLogger.WriteLine(Info, L"Character (%s) Adding Equipment to Inventory: %s (Slot=%i) (Unk = %i)",
owner->characterName.c_str(), equipment->nameReal.c_str(), slot, unk);
//log(L"Character (%s) Adding Equipment to Inventory: %s (Slot=%i) (Unk = %i)",
// owner->characterName.c_str(), equipment->nameReal.c_str(), slot, unk);
if (ownerEntity) {
// If the equipment hasn't yet been created for network use
// request the server create it and add it to the slot and reply with a network id for it
if (!equipmentEntity) {
Client::getSingleton().Helper_ClientPushEquipment(equipment);
} else {
// Create a Network Message for sending off to clients the equipment addition to the inventory
NetworkMessages::InventoryAddEquipment msgInventoryAddEquipment;
msgInventoryAddEquipment.set_ownerid(ownerEntity->getCommonId());
msgInventoryAddEquipment.set_slot(slot);
msgInventoryAddEquipment.set_unk0(unk);
msgInventoryAddEquipment.set_guid(equipment->GUID);
msgInventoryAddEquipment.set_equipmentid(equipmentEntity->getCommonId());
Client::getSingleton().SendMessage<NetworkMessages::InventoryAddEquipment>(C_PUSH_EQUIPMENT_EQUIP, &msgInventoryAddEquipment);
}
} else {
multiplayerLogger.WriteLine(Error, L"Could not find NetworkEntity for inventory owner: %p (%s)",
owner, owner->characterName.c_str());
//log(L"Could not find NetworkEntity for inventory owner: %p (%s)",
// owner, owner->characterName.c_str());
}
}
void TLMP::Inventory_AddEquipmentPre(CEquipment* retval, CInventory* inventory, CEquipment* equipment, u32& slot, u32 unk0, bool& calloriginal)
{
log(L"Inventory adding Equipment: %016I64X (%s %p) (slot = %x) (Owner = %s)",
equipment->GUID, equipment->nameReal.c_str(), equipment, slot, inventory->pCCharacter->characterName.c_str());
if (inventory) {
CCharacter *owner = inventory->pCCharacter;
// Client - Allow the equipment to be added to the inventory, but send it out to the server to create
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (Client::getSingleton().GetSuppressed_EquipmentCreation()) {
// If we're suppressing this, we need to send it to the Server
// The server will create, add the equipment and send the message back to us with the network id
SendInventoryAddEquipmentToServer(owner, equipment, slot, unk0);
//calloriginal = false;
}
}
// Server
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
// If we're not suppressed to send this out -
// The reason this would be suppressed if a character had sent a Pickup message,
// That triggers an Equip then a Pickup message on the client, causing a phantom item in the inventory
if (!Server::getSingleton().GetSuppressed_SendEquipmentEquip()) {
NetworkEntity *ownerEntity = searchCharacterByInternalObject((PVOID)owner);
NetworkEntity *equipmentEntity = searchEquipmentByInternalObject((PVOID)equipment);
if (ownerEntity) {
if (equipmentEntity) {
// Create a Network Message for sending off to clients the equipment addition to the inventory
NetworkMessages::InventoryAddEquipment msgInventoryAddEquipment;
msgInventoryAddEquipment.set_ownerid(ownerEntity->getCommonId());
msgInventoryAddEquipment.set_equipmentid(equipmentEntity->getCommonId());
msgInventoryAddEquipment.set_slot(slot);
msgInventoryAddEquipment.set_unk0(unk0);
Server::getSingleton().BroadcastMessage<NetworkMessages::InventoryAddEquipment>(S_PUSH_EQUIPMENT_EQUIP, &msgInventoryAddEquipment);
} else {
multiplayerLogger.WriteLine(Error, L"Could not find NetworkEntity for equipment: %p",
equipment);
//log(L"Could not find NetworkEntity for equipment: %p",
// equipment);
}
} else {
multiplayerLogger.WriteLine(Error, L"Could not find NetworkEntity for inventory owner: (%p) %p",
inventory, owner);
//log(L"Could not find NetworkEntity for inventory owner: (%p) %p",
// inventory, owner);
}
}
}
multiplayerLogger.WriteLine(Info, L"Inventory::AddEquipmentPre(%p) (%p) (%s)",
inventory, equipment, equipment->nameReal.c_str());
//log(L"Inventory::AddEquipmentPre(%p) (%p) (%s)",
// inventory, equipment, equipment->nameReal.c_str());
} else {
//log(L"Error: Character has no Inventory!");
multiplayerLogger.WriteLine(Error, L"Error: Character has no Inventory!");
}
}
void TLMP::Inventory_AddEquipmentPost(CEquipment* retval, CInventory* inventory, CEquipment* equipment, u32& slot, u32 unk0, bool& calloriginal)
{
multiplayerLogger.WriteLine(Info, L"Inventory::AddEquipmentPost(%p) (%p) (%s) (slot = %x) (unk0 = %x)",
inventory, equipment, equipment->nameReal.c_str(), slot, unk0);
//log(L"Inventory::AddEquipmentPost(%p) (%p) (%s) (slot = %x) (unk0 = %x)",
// inventory, equipment, equipment->nameReal.c_str(), slot, unk0);
}
void TLMP::Inventory_RemoveEquipmentPre(CInventory* inventory, CEquipment* equipment)
{
//log(L"Inventory removing Equipment Pre:");
multiplayerLogger.WriteLine(Info, L"Inventory::RemoveEquipment(%p) (%s)", inventory, equipment->nameReal.c_str());
log(L"Inventory::RemoveEquipment(%p) (%s)", inventory, equipment->nameReal.c_str());
}
void TLMP::Inventory_RemoveEquipmentPost(CInventory* inventory, CEquipment* equipment)
{
//log(L"Inventory removing Equipment Post:");
//
CCharacter *owner = inventory->pCCharacter;
NetworkEntity *ownerEntity = searchCharacterByInternalObject((PVOID)owner);
NetworkEntity *equipmentEntity = searchEquipmentByInternalObject((PVOID)equipment);
//
if (!ownerEntity) {
multiplayerLogger.WriteLine(Error, L"Could not find NetworkEntity for inventory owner: (%p) %p",
inventory, owner);
//log(L"Could not find NetworkEntity for inventory owner: (%p) %p",
// inventory, owner);
return;
} else if (!equipmentEntity) {
multiplayerLogger.WriteLine(Error, L"Could not find NetworkEntity for equipment: %p",
equipment);
//log(L"Could not find NetworkEntity for equipment: %p",
// equipment);
return;
}
// Client
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetSuppressed_SendEquipmentUnequip() &&
Client::getSingleton().GetSuppressed_EquipmentCreation())
{
// Send the server that we're unequipping the equipment
NetworkMessages::InventoryRemoveEquipment msgInventoryRemoveEquipment;
msgInventoryRemoveEquipment.set_ownerid(ownerEntity->getCommonId());
msgInventoryRemoveEquipment.set_equipmentid(equipmentEntity->getCommonId());
Client::getSingleton().SendMessage<NetworkMessages::InventoryRemoveEquipment>(C_PUSH_EQUIPMENT_UNEQUIP, &msgInventoryRemoveEquipment);
}
}
// Server
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
if (!Server::getSingleton().GetSuppressed_SendEquipmentUnequip() &&
!Server::getSingleton().GetSuppressed_SendEquipmentEquip())
{
// Create a Network Message for sending off to clients the equipment addition to the inventory
NetworkMessages::InventoryRemoveEquipment msgInventoryRemoveEquipment;
msgInventoryRemoveEquipment.set_ownerid(ownerEntity->getCommonId());
msgInventoryRemoveEquipment.set_equipmentid(equipmentEntity->getCommonId());
Server::getSingleton().BroadcastMessage<NetworkMessages::InventoryRemoveEquipment>(S_PUSH_EQUIPMENT_UNEQUIP, &msgInventoryRemoveEquipment);
}
}
}
void TLMP::Character_PickupEquipmentPre(CCharacter* character, CEquipment* equipment, CLevel* level, bool & calloriginal)
{
log(L"Character picking up Equipment Pre: %p Type: %x", equipment, equipment->type__);
log(L" Position: %f %f %f",
equipment->GetPosition().x,
equipment->GetPosition().y,
equipment->GetPosition().z);
// Make sure the item is in the level before attempting to pick it up
// halts crashes on multiple CItemGold pickups after it's been destroyed
{
NetworkEntity *netEquipment = searchEquipmentByInternalObject((PVOID)equipment);
if (!netEquipment) {
netEquipment = searchItemByInternalObject((PVOID)equipment);
}
if (netEquipment) {
CItem *item = (CItem*)netEquipment->getInternalObject();
if (!gameClient->pCLevel->containsItem(item)) {
log("Couldn't find item in the level, jumping out before we crash...");
calloriginal = false;
return;
}
}
}
multiplayerLogger.WriteLine(Info, L" Character::PickupEquipmentPre(Character: %p) (%p) (Level: %p)",
character, equipment, level);
multiplayerLogger.WriteLine(Info, L" Character::PickupEquipmentPre(Character: %s) (%s)",
character->characterName.c_str(), equipment->nameReal.c_str());
//log(L" Character::PickupEquipment(Character: %p) (%p %s) (Level: %p)",
// character, equipment, equipment->nameReal.c_str(), level);
//log(L"Dumping Level Items...");
//gameClient->pCLevel->DumpItems();
//gameClient->pCLevel->DumpTriggerUnits();
// If the client is requesting a pickup, request the server first
// The server will respond with a pickup message
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (Client::getSingleton().GetSuppressed_EquipmentPickup()) {
// Remove the IsSendingPickup since I'm putting in Requests to pickup item
//if (!Client::getSingleton().Get_IsSendingPickup()) {
// Send the server a message requesting our character to pickup the item
NetworkEntity *netPlayer = searchCharacterByInternalObject((PVOID)character);
NetworkEntity *netEquipment = searchEquipmentByInternalObject((PVOID)equipment);
if (!netEquipment) {
netEquipment = searchItemByInternalObject((PVOID)equipment);
}
if (!netPlayer) {
multiplayerLogger.WriteLine(Error, L"Error: Could not retrieve network entity of character for equipment pickup!");
log(L"Error: Could not retrieve network entity of character for equipment pickup!");
/*} else *if (!netEquipment) {
multiplayerLogger.WriteLine(Error, L"Error: Could not retrieve network entity of equipment for equipment pickup!");
log(L"Error: Could not retrieve network entity of equipment for equipment pickup!");*/
} else {
NetworkMessages::EquipmentPickup msgEquipmentPickup;
msgEquipmentPickup.set_characterid(netPlayer->getCommonId());
if (netEquipment) {
msgEquipmentPickup.set_equipmentid(netEquipment->getCommonId());
} else {
msgEquipmentPickup.set_equipmentid(-1);
}
NetworkMessages::Position *msgPosition = msgEquipmentPickup.mutable_position();
msgPosition->set_x(equipment->GetPosition().x);
msgPosition->set_y(equipment->GetPosition().y);
msgPosition->set_z(equipment->GetPosition().z);
Client::getSingleton().SendMessage<NetworkMessages::EquipmentPickup>(C_REQUEST_EQUIPMENT_PICKUP, &msgEquipmentPickup);
Client::getSingleton().Set_IsSendingPickup(true);
}
//}
calloriginal = false;
}
else {
Client::getSingleton().SetSuppressed_EquipmentCreation(false);
}
}
// Send the message off to the clients
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
NetworkEntity *netEquipment = searchEquipmentByInternalObject(equipment);
NetworkEntity *netCharacter = searchCharacterByInternalObject(character);
if (!netEquipment) {
netEquipment = searchItemByInternalObject((PVOID)equipment);
}
if (netEquipment) {
if (netCharacter) {
NetworkMessages::EquipmentPickup msgEquipmentPickup;
msgEquipmentPickup.set_characterid(netCharacter->getCommonId());
msgEquipmentPickup.set_equipmentid(netEquipment->getCommonId());
NetworkMessages::Position *msgPosition = msgEquipmentPickup.mutable_position();
msgPosition->set_x(equipment->GetPosition().x);
msgPosition->set_y(equipment->GetPosition().y);
msgPosition->set_z(equipment->GetPosition().z);
Server::getSingleton().BroadcastMessage<NetworkMessages::EquipmentPickup>(S_PUSH_EQUIPMENT_PICKUP, &msgEquipmentPickup);
//Server::getSingleton().SetSuppressed_SendEquipmentEquip(true);
// Remove the Equipment from the Ground list
vector<NetworkEntity*>::iterator itr;
for (itr = ServerEquipmentOnGround->begin(); itr != ServerEquipmentOnGround->end(); itr++) {
if ((*itr) == netEquipment) {
ServerEquipmentOnGround->erase(itr);
break;
}
}
} else {
multiplayerLogger.WriteLine(Error, L"Error: Could not find Network Entity for Character (%s)",
character->characterName.c_str());
//log(L"Error: Could not find Network Entity for Character (%s)",
// character->characterName.c_str());
}
} else {
multiplayerLogger.WriteLine(Error, L"Error: Could not find Network Entity for Equipment (%s)",
equipment->nameReal.c_str());
//log(L"Error: Could not find Network Entity for Equipment (%s)",
// equipment->nameReal.c_str());
}
}
}
void TLMP::Character_PickupEquipmentPost(CCharacter* character, CEquipment* equipment, CLevel* level, bool & calloriginal)
{
log(L" Character picking up Equipment Post");
/*
CInventory* inv = character->pCInventory;
multiplayerLogger.WriteLine(Info, L" Debug sizes: %i", inv->tabIndices.size());
log(L" Debug sizes: %i", inv->tabIndices.size());
for (u32 i = 0; i < inv->tabIndices.size(); ++i) {
multiplayerLogger.WriteLine(Info, L" Tab[%i] = %i", inv->tabIndices[i], inv->tabSizes[i]);
log(L" Tab[%i] = %i", inv->tabIndices[i], inv->tabSizes[i]);
}
*/
//log(L"Dumping Level Items...");
//gameClient->pCLevel->DumpItems();
//gameClient->pCLevel->DumpTriggerUnits();
// Turn on suppression again if we're the client
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
// If the original call was let through...
if (calloriginal) {
Client::getSingleton().SetSuppressed_EquipmentCreation(true);
Client::getSingleton().Set_IsSendingPickup(false);
}
}
// Server turn off suppression of Equipment Equips
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().SetSuppressed_SendEquipmentEquip(false);
}
//log(L"Character Done Picking up Item");
}
void TLMP::Character_SetActionPre(CCharacter* character, u32 action, bool & calloriginal)
{
//logColor(B_GREEN, L"Character::SetActionPre(%s %x)", character->characterName.c_str(), action);
// The below doesn't work too well when transferring over the network.
// The client will receive the state (or action) with creature deathes and the creatures will appear to be still
// alive but unattackable.
/*
multiplayerLogger.WriteLine(Info, L"Character::SetActionPre(%s, %x)", character->characterName.c_str(), action);
log(L"Character::SetActionPre(%s %x)", character->characterName.c_str(), action);
// Client - Requests the set action from the server
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (Client::getSingleton().GetSuppressed_CharacterAction()) {
calloriginal = false;
}
}
// Server - Always send this out to every client becuase it's request-based
else if (NetworkState::getSingleton().GetState() == SERVER) {
NetworkEntity *networkCharacter = searchCharacterByInternalObject(character);
if (networkCharacter) {
NetworkMessages::CharacterAction msgCharacterAction;
msgCharacterAction.set_characterid(networkCharacter->getCommonId());
msgCharacterAction.set_action(action);
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterAction>(S_PUSH_CHARACTER_ACTION, &msgCharacterAction);
} else {
multiplayerLogger.WriteLine(Error, L"Error: Could not find network id for character: %s", character->characterName.c_str());
log(L"Error: Could not find network id for character: %s", character->characterName.c_str());
}
}
*/
}
void TLMP::SkillManager_AddSkillPre(CSkillManager* skillManager, CSkill* skill, bool skillAlreadyCreated, u32 unk1, bool& calloriginal)
{
//log(L"SkillManager (%p) AddSkill: %p", skillManager, skill);
//log(L" skillAlreadyCreated: %x unk1: %x GUID: %016I64X", skillAlreadyCreated, unk1, skill->GUID);
//log(L" baseUnit: %p", skillManager->pCBaseUnit);
//log(L" name: %s", ((CCharacter*)(skillManager->pCBaseUnit))->characterName.c_str());
//skillManager->dumpSkillManager();
}
void TLMP::SkillManager_SetSkillLevelPre(CSkillManager* skillManager, CSkill* skill, u32 skillLevel, bool& calloriginal)
{
/*
log(L"SkillManager (%p) SetSkillLevelPre: %p skillLevel: %i", skillManager, skill, skillLevel);
log(L" Character: %016I64X", skillManager->pCBaseUnit->GUID);
*/
multiplayerLogger.WriteLine(Info, L"SkillManager (%p) SetSkillLevelPre: %p skillLevel: %i",
skillManager, skill, skillLevel);
multiplayerLogger.WriteLine(Info, L" Character: %016I64X", skillManager->pCBaseUnit->GUID);
//
CCharacter* character = (CCharacter*)skillManager->pCBaseUnit;
NetworkEntity *netPlayer = searchCharacterByInternalObject((PVOID)character);
if (Network::NetworkState::getSingleton().GetState() == SINGLEPLAYER) {
return;
}
if (!netPlayer) {
//log(L"Error: Could not find networkID for character: %p", character);
return;
}
// Push off the network message
NetworkMessages::CharacterSetSkillPoints msgCharacterSetSkillPoints;
msgCharacterSetSkillPoints.set_characterid(netPlayer->getCommonId());
msgCharacterSetSkillPoints.set_skillguid(skill->GUID);
msgCharacterSetSkillPoints.set_skilllevel(skillLevel);
// If the client is requesting a pickup, request the server first
// The server will respond with a pickup message
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetAllow_SetSkillPoints()) {
Client::getSingleton().SendMessage<NetworkMessages::CharacterSetSkillPoints>(C_REQUEST_SKILLLEVEL, &msgCharacterSetSkillPoints);
calloriginal = false;
}
}
// Send the message off to the clients
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterSetSkillPoints>(S_PUSH_SKILLLEVEL, &msgCharacterSetSkillPoints);
}
}
void TLMP::SkillManager_SetSkillLevelPost(CSkillManager* skillManager, CSkill* skill, u32 skillLevel, bool& calloriginal)
{
/*
log(L"SkillManager (%p) SetSkillLevelPost: %p skillLevel: %i", skillManager, skill, skillLevel);
log(L" Level: %i", skill->skillLevel);
*/
}
void TLMP::Character_SetupSkillsPre(CCharacter* character, CDataGroup* dataGroup, u32 unk0, bool& calloriginal)
{
}
void TLMP::Character_AddSkillPre(CCharacter* character, wstring* skillName, u32 unk1, bool& calloriginal)
{
/*
log(L"Character::AddSkillPre: %p", character);
log(L" %s", skillName->c_str());
log(L" Character Available Skill Points: %i", character->GetAvailableSkillPoints());
// Appears to be a flag if the character is valid
if (unk1) {
log(L" %s", character->characterName.c_str());
}
*/
}
void TLMP::Character_AddSkillPost(CCharacter* character, wstring* skillName, u32 unk1, bool& calloriginal)
{
//log(L"Character::AddSkillPost: %p", character);
}
void TLMP::Character_AddSkill2Pre(CCharacter* character, wstring skillName, bool& calloriginal)
{
//log(L"Character::AddSkill2: %s %s", character->characterName.c_str(), skillName.c_str());
}
void TLMP::Character_UseSkillPre(CCharacter* character, u64 skillGUID, bool & calloriginal)
{
if (skillGUID != 0xFFFFFFFFFFFFFFFF) {
//log(L"Test: Character Mana max: %i", character->manaMax);
/*
log(L"Character (%s) used skill pre: (%016I64X)", character->characterName.c_str(), skillGUID);
log(L" SkillManager: %p (Offset: %x)", character->pCSkillManager, ((u32)&character->pCSkillManager - (u32)character));
*/
multiplayerLogger.WriteLine(Info, L"Character (%s) used skill pre: (%016I64X)",
character->characterName.c_str(), skillGUID);
multiplayerLogger.WriteLine(Info, L" SkillManager: %p (Offset: %x)",
character->pCSkillManager, ((u32)&character->pCSkillManager - (u32)character));
// Testing for Skill Graphic Effect
if (!character->usingSkill) {
/*
log(L" EffectManager: %p", character->pCEffectManager);
log(L" Type: %x", character->type__);
log(L" Skill: %p", character->pCSkill);
log(L" ResourceManager: %p", character->pCResourceManager);
log(L" pCSkillManager: %p", character->pCSkillManager);
log(L" UsingSkill: %i", character->usingSkill);
*/
//character->pCSkillManager->dumpSkillManager();
} else {
// Save us the trouble of the constant keydown function spam
calloriginal = false;
}
// --
NetworkEntity *netPlayer = searchCharacterByInternalObject((PVOID)character);
if (!netPlayer) {
multiplayerLogger.WriteLine(Error, L"Error: Could not retrieve network entity of character for equipment pickup!");
//log(L"Error: Could not retrieve network entity of character for equipment pickup!");
return;
}
// Send the skill level before we push off the skill use,
//
{
CSkill* skill = character->pCSkillManager->getSkillFromGUID(skillGUID);
if (!skill) {
log("Error: Could not find skill in skillmanager of guid: %016I64X", skillGUID);
return;
}
NetworkMessages::CharacterSetSkillPoints msgCharacterSetSkillPoints;
msgCharacterSetSkillPoints.set_characterid(netPlayer->getCommonId());
msgCharacterSetSkillPoints.set_skillguid(skill->GUID);
msgCharacterSetSkillPoints.set_skilllevel(skill->skillLevel);
// If the client is requesting a pickup, request the server first
// The server will respond with a pickup message
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
Client::getSingleton().SendMessage<NetworkMessages::CharacterSetSkillPoints>(C_REQUEST_SKILLLEVEL, &msgCharacterSetSkillPoints);
}
// Send the message off to the clients
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterSetSkillPoints>(S_PUSH_SKILLLEVEL, &msgCharacterSetSkillPoints);
}
}
//
NetworkMessages::CharacterUseSkill msgCharacterUseSkill;
msgCharacterUseSkill.set_characterid(netPlayer->getCommonId());
msgCharacterUseSkill.set_skill(skillGUID);
NetworkMessages::Position *msgPosition = msgCharacterUseSkill.mutable_direction();
msgPosition->set_x(character->orientation.x);
msgPosition->set_y(character->orientation.y);
msgPosition->set_z(character->orientation.z);
if (!character->usingSkill) {
// If the client is requesting a pickup, request the server first
// The server will respond with a pickup message
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetSuppressed_SendUseSkill()) {
Client::getSingleton().SendMessage<NetworkMessages::CharacterUseSkill>(C_REQUEST_CHARACTER_USESKILL, &msgCharacterUseSkill);
calloriginal = false;
}
}
// Send the message off to the clients
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().BroadcastMessage<NetworkMessages::EquipmentPickup>(S_PUSH_CHARACTER_USESKILL, &msgCharacterUseSkill);
}
}
}
}
void TLMP::Character_UseSkillPost(CCharacter* character, u64 skillGUID, bool & calloriginal)
{
if (skillGUID != 0xFFFFFFFFFFFFFFFF) {
//log(L"Character_UseSkillPost: Character Mana: %f / %i", character->manaCurrent, character->manaMax);
multiplayerLogger.WriteLine(Info, L"Character (%s) used skill post: (%016I64X)",
character->characterName.c_str(), skillGUID);
//log(L"Character (%s) used skill post: (%016I64X)",
// character->characterName.c_str(), skillGUID);
// Turn on suppression again if we're the client
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
// If the original call was let through...
if (calloriginal) {
Client::getSingleton().Set_IsSendingUseSkill(false);
}
}
// Server turn off suppression of Equipment Equips
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().SetSuppressed_SendEquipmentEquip(false);
}
}
}
void TLMP::Character_SetOrientationPre(CCharacter* character, Vector3* orient1, float dTime, bool& calloriginal)
{
/*
if (character == gameClient->pCPlayer) {
log(L"Character_SetOrientationPre: %s (%p)", character->characterName.c_str(), orient1);
log(L" Current: %f, %f, %f", character->orientation.x, character->orientation.y, character->orientation.z);
log(L" Orient1: %f %f %f", orient1->x, orient1->y, orient1->z);
log(L" dTime: %f", dTime);
log(L" unkBool0: %i usingSkill: %i", character->unkBool0, character->usingSkill);
}
*/
}
void TLMP::Character_SetTarget(CCharacter* character, CCharacter* target, bool & calloriginal)
{
if (target != NULL) {
//multiplayerLogger.WriteLine(Info, L"Character (%s) Set Target: %s", character->characterName.c_str(), target->characterName.c_str());
//log(L"Character (%s) Set Target: %s", character->characterName.c_str(), target->characterName.c_str());
} else {
//multiplayerLogger.WriteLine(Info, L"Character (%s) Set Target: null", character->characterName.c_str());
}
// Setup the information
NetworkEntity *netCharacter = searchCharacterByInternalObject(character);
NetworkEntity *netTarget = searchCharacterByInternalObject(target);
NetworkMessages::CharacterSetTarget msgCharacterSetTarget;
if (netCharacter) {
s32 targetID = -1; // Sometimes there's no target
if (netTarget) {
targetID = netTarget->getCommonId();
}
msgCharacterSetTarget.set_characterid(netCharacter->getCommonId());
msgCharacterSetTarget.set_targetid(targetID);
} else {
//log(L"Error: Could not find network entity for character: %s", character->characterName.c_str());
return;
}
// Network push it out
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetAllow_CharacterSetTarget()) {
//calloriginal = false;
//if (character == gameClient->pCPlayer) {
// Attempt to send AI request to server if the character has no current target but wants one
if (!character->target && target) {
Client::getSingleton().SendMessage<NetworkMessages::CharacterSetTarget>(C_REQUEST_CHARACTER_SETTARGET, &msgCharacterSetTarget);
}
}
} else if (NetworkState::getSingleton().GetState() == SERVER) {
// Only send out target changes
map<CCharacter*, CCharacter*>::iterator itr;
itr = CharacterTargetBuffer->find(character);
if (itr != CharacterTargetBuffer->end()) {
if (itr->second != target) {
log(L"New target set: %p -> %p", character, target);
//Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterSetTarget>(S_PUSH_CHARACTER_SETTARGET, &msgCharacterSetTarget);
}
}
(*CharacterTargetBuffer)[character] = target;
}
}
void TLMP::Character_AttackPost(CCharacter* character, bool & calloriginal)
{
/*
log(L"Character (%s) Set Attack Post", character->characterName.c_str());
log(L" Test: %x %x %x %x", character->destroy, character->destroy1, character->destroy2, character->destroy3);
log(L" Test: %x %x %x %x", character->moving, character->unkBool0, character->attacking, character->usingSkill);
*/
}
void TLMP::Character_AttackPre(CCharacter* character, bool & calloriginal)
{
multiplayerLogger.WriteLine(Info, L"Character (%s) Set Attack Pre", character->characterName.c_str());
/*
log(L"Character (%s) Set Attack Pre", character->characterName.c_str());
log(L" Test: %x %x %x %x", character->destroy, character->destroy1, character->destroy2, character->destroy3);
log(L" Test: %x %x %x %x", character->moving, character->unkBool0, character->attacking, character->usingSkill);
*/
/*
log(L"Character (%s) Set Attack Pre", character->characterName.c_str());
if (character->pCAttackDescription)
character->pCAttackDescription->dumpAttack();
log(L"Character Attack Descriptions: %i", character->attackDescriptions.size());
vector<CAttackDescription*>::iterator itr;
for (itr = character->attackDescriptions.begin(); itr != character->attackDescriptions.end(); itr++) {
log(L" Character Attack Desc:");
(*itr)->dumpAttack();
}
*/
// Client - Requests the set action from the server
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (Client::getSingleton().GetSuppressed_CharacterAttack()) {
//calloriginal = false;
NetworkEntity *networkCharacter = searchCharacterByInternalObject(character);
if (networkCharacter) {
NetworkMessages::CharacterAttack msgCharacterAttack;
msgCharacterAttack.set_characterid(networkCharacter->getCommonId());
Client::getSingleton().SendMessage<NetworkMessages::CharacterAttack>(C_PUSH_CHARACTER_ATTACK, &msgCharacterAttack);
} else {
multiplayerLogger.WriteLine(Error, L"Error: Could not find network id for character: %s", character->characterName.c_str());
//log(L"Error: Could not find network id for character: %s", character->characterName.c_str());
}
}
}
// Server - Always send this out to every client becuase it's request-based
else if (NetworkState::getSingleton().GetState() == SERVER) {
if (!Server::getSingleton().GetSuppressed_SendCharacterAttack()) {
NetworkEntity *networkCharacter = searchCharacterByInternalObject(character);
if (networkCharacter) {
NetworkMessages::CharacterAttack msgCharacterAttack;
msgCharacterAttack.set_characterid(networkCharacter->getCommonId());
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterAttack>(S_PUSH_CHARACTER_ATTACK, &msgCharacterAttack);
}
} else {
multiplayerLogger.WriteLine(Error, L"Error: Could not find network id for character: %s", character->characterName.c_str());
//log(L"Error: Could not find network id for character: %s", character->characterName.c_str());
}
}
}
void TLMP::EquipmentAddStackCountPost(CEquipment *equipment, u32 amount)
{
//logColor(B_RED, L"Add StackCount: %s %i", equipment->nameReal.c_str(), amount);
NetworkEntity *netEquipment = searchEquipmentByInternalObject(equipment);
if (netEquipment) {
NetworkMessages::EquipmentUpdateStackSize msgEquipmentUpdateStackSize;
msgEquipmentUpdateStackSize.set_id(netEquipment->getCommonId());
msgEquipmentUpdateStackSize.set_change_amount(amount);
// Client
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetSuppressed_SendEquipmentStack()) {
Client::getSingleton().SendMessage<NetworkMessages::EquipmentUpdateStackSize>(C_PUSH_EQUIPMENT_STACKUPDATE, &msgEquipmentUpdateStackSize);
}
}
// Server
else if (NetworkState::getSingleton().GetState() == SERVER) {
if (!Server::getSingleton().GetSuppressed_SendEquipmentStack()) {
Server::getSingleton().BroadcastMessage<NetworkMessages::EquipmentUpdateStackSize>(S_PUSH_EQUIPMENT_STACKUPDATE, &msgEquipmentUpdateStackSize);
}
}
} else {
multiplayerLogger.WriteLine(Error, L"Error: Could not find network id for equipment: %s", equipment->nameReal.c_str());
//log(L"Error: Could not find network id for equipment: %s", equipment->nameReal.c_str());
}
}
void TLMP::GameClientSaveGamePre(CGameClient *gameClient, u32 unk0, u32 unk1, bool & calloriginal)
{
//log(L"Suppressing Game Save: %p (%x %x)", gameClient, unk0, unk1);
multiplayerLogger.WriteLine(Info, L"Suppressing Game Save: %p (%x %x)", gameClient, unk0, unk1);
CLevel *level = gameClient->pCLevel;
// Remove any characters that have been added through multiplayer before saving
LinkedListNode* itrInv = *level->charactersAll;
while (itrInv != NULL) {
CCharacter* character = (CCharacter*)itrInv->pCBaseUnit;
if (character) {
if (character != gameClient->pCPlayer &&
(character->GUID == DESTROYER ||
character->GUID == DESTROYER ||
character->GUID == DESTROYER))
{
vector<CCharacter*>::iterator itrMinion;
vector<CCharacter*> *minions = character->GetMinions();
for (itrMinion = minions->begin(); itrMinion != minions->end(); itrMinion++) {
(*itrMinion)->Destroy();
}
character->Destroy();
}
}
itrInv = itrInv->pNext;
}
// Fix bug when trying to save game on client that is loading
if (gameClient->pCLevel->pCLevelLayout == NULL) {
calloriginal = false;
}
//callOriginal = false;
/* Removed - New characters will try to save right off and Disconnect - move this
to a proper function where the game exits.
if (NetworkState::getSingleton().GetState() == CLIENT) {
// Force disconnect, crashes when rejoining
log(L"Forcing client disconnect.");
multiplayerLogger.WriteLine(Info, L"Forcing client disconnect.");
Client::getSingleton().Disconnect();
NetworkState::getSingleton().SetState(SINGLEPLAYER);
} else if (NetworkState::getSingleton().GetState() == SERVER) {
log(L"Forcing server disconnect.");
multiplayerLogger.WriteLine(Info, L"Forcing server disconnect.");
Server::getSingleton().Shutdown();
NetworkState::getSingleton().SetState(SINGLEPLAYER);
}
*/
}
void TLMP::GameClientSaveGamePost(CGameClient *gameClient, u32 unk0, u32 unk1, bool & callOriginal)
{
//log(L"Suppressed Game Save Successful");
multiplayerLogger.WriteLine(Info, L"Suppressed Game Save Successful");
}
void TLMP::GameClientGamePausedPost(bool& retval, CGameClient *gameClient, bool & calloriginal)
{
retval = false;
}
void TLMP::GameUI_TriggerPausePre(CGameUI *gameUI, bool & calloriginal)
{
calloriginal = false;
}
void TLMP::EnchantMenuEnchantItemPre(CEnchantMenu* enchantMenu, bool & calloriginal)
{
// Suppress enchants
{
multiplayerLogger.WriteLine(Info, L"EnchantMenu suppressed.");
log(L"EnchantMenu suppressed.");
calloriginal = false;
return;
}
multiplayerLogger.WriteLine(Info, L"EnchantMenu::EnchantItem(%p) Type = %x", enchantMenu, enchantMenu->EnchantType);
log(L"EnchantMenu::EnchantItem(%p) Type = %x", enchantMenu, enchantMenu->EnchantType);
multiplayerLogger.WriteLine(Info, L"EnchantMenu debug: Player: %p (%s), Character: %p (%s)",
enchantMenu->player, enchantMenu->player->characterName.c_str(), enchantMenu->character, enchantMenu->character->characterName.c_str());
log(L"EnchantMenu debug: Player: %p (%s), Character: %p (%s)",
enchantMenu->player, enchantMenu->player->characterName.c_str(), enchantMenu->character, enchantMenu->character->characterName.c_str());
// !!!
// This is assuming the gameClient->Player is the Owner
CInventory *inventory = gameClient->pCPlayer->pCInventory;
CEquipment *equipment = inventory->GetEquipmentFromSlot(0xE);
//log(L" Acting on Equipment: %s", equipment->nameReal.c_str());
multiplayerLogger.WriteLine(Info, L" Acting on Equipment: %s", equipment->nameReal.c_str());
if (!inventory) {
//log(L" Inventory is null!");
multiplayerLogger.WriteLine(Error, L" Inventory is null!");
}
NetworkEntity* netEntity = searchEquipmentByInternalObject(equipment);
if (netEntity) {
if (enchantMenu->EnchantType == 0x19) {
//log(L"Destroying gems from Equipment...");
multiplayerLogger.WriteLine(Info, L"Destroying gems from Equipment...");
NetworkMessages::EquipmentRemoveGems msgEquipmentRemoveGems;
msgEquipmentRemoveGems.set_equipmentid(netEntity->getCommonId());
if (NetworkState::getSingleton().GetState() == CLIENT) {
calloriginal = false;
Client::getSingleton().SendMessage<NetworkMessages::EquipmentRemoveGems>(C_PUSH_EQUIPMENT_REMOVE_GEMS, &msgEquipmentRemoveGems);
} else if (NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().BroadcastMessage<NetworkMessages::EquipmentRemoveGems>(S_PUSH_EQUIPMENT_REMOVE_GEMS, &msgEquipmentRemoveGems);
}
} else if (enchantMenu->EnchantType == 0x1A) {
//log(L"Removing gems and destroying equipment...");
multiplayerLogger.WriteLine(Info, L"Removing gems and destroying equipment...");
}
} else {
//log(L"Error: Could not find NetworkEntity for equipment");
multiplayerLogger.WriteLine(Error, L"Error: Could not find NetworkEntity for equipment");
}
}
void TLMP::EquipmentAddGemPre(CEquipment* equipment, CEquipment* gem, bool & calloriginal)
{
//log(L"Equipment (%s) Adding Gem (%s)", equipment->nameReal.c_str(), gem->nameReal.c_str());
multiplayerLogger.WriteLine(Info, L"Equipment (%s) Adding Gem (%s)", equipment->nameReal.c_str(), gem->nameReal.c_str());
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (gameClient->inGame) {
if (!Client::getSingleton().Get_IsSendingEquipmentAddGem()) {
calloriginal = false;
NetworkEntity *netEquipment = searchEquipmentByInternalObject(equipment);
NetworkEntity *netGem = searchEquipmentByInternalObject(gem);
if (netEquipment && netGem) {
// Send the server a message requsting the Gem be Added to the equipment
NetworkMessages::EquipmentAddGem msgEquipmentAddGem;
msgEquipmentAddGem.set_equipmentid(netEquipment->getCommonId());
msgEquipmentAddGem.set_gemid(netGem->getCommonId());
Client::getSingleton().SendMessage<NetworkMessages::EquipmentAddGem>(C_PUSH_EQUIPMENT_ADD_GEM, &msgEquipmentAddGem);
} else {
//log(L"Error: Client could not send off EquipmentAddGem - Could not find NetworkEntity for either Equipment (%p) or Gem (%p)",
// netEquipment, netGem);
multiplayerLogger.WriteLine(Error, L"Error: Client could not send off EquipmentAddGem - Could not find NetworkEntity for either Equipment (%p) or Gem (%p)",
netEquipment, netGem);
}
}
}
} else if (NetworkState::getSingleton().GetState() == SERVER) {
NetworkEntity *netEquipment = searchEquipmentByInternalObject(equipment);
NetworkEntity *netGem = searchEquipmentByInternalObject(gem);
if (netEquipment && netGem) {
// Send the server a message requsting the Gem be Added to the equipment
NetworkMessages::EquipmentAddGem msgEquipmentAddGem;
msgEquipmentAddGem.set_equipmentid(netEquipment->getCommonId());
msgEquipmentAddGem.set_gemid(netGem->getCommonId());
Server::getSingleton().BroadcastMessage<NetworkMessages::EquipmentAddGem>(S_PUSH_EQUIPMENT_ADD_GEM, &msgEquipmentAddGem);
} else {
//log(L"Error: Server could not send off EquipmentAddGem - Could not find NetworkEntity for either Equipment (%p) or Gem (%p)",
// netEquipment, netGem);
multiplayerLogger.WriteLine(Error, L"Error: Server could not send off EquipmentAddGem - Could not find NetworkEntity for either Equipment (%p) or Gem (%p)",
netEquipment, netGem);
}
}
}
// Uses the KeyManager_HandleInput now to suppress this if needed
void TLMP::GameUI_HandleKeyboardInputPre(CGameUI* gameUI, u32 unk0, u32 unk1, u32 unk2, bool & calloriginal)
{
/*
//log(L"GameUI::HandleKeyboardInput (%p, %x, %x, %x)", gameUI, unk0, unk1, unk2);
multiplayerLogger.WriteLine(Info, L"GameUI::HandleKeyboardInput (%p, %x, %x, %x)", gameUI, unk0, unk1, unk2);
CEGUI::Editbox* pInGameChatEntry = (CEGUI::Editbox*)UserInterface::getWindowFromName("1010_ChatEntry");
CEGUI::Window* pInGameChatEntryBackground = UserInterface::getWindowFromName("1010_ChatEntryBackground");
if (pInGameChatEntry && pInGameChatEntryBackground) {
// Keydown and 'Enter'
if (unk0 == 0x100 && unk1 == 0xD) {
if (!pInGameChatEntry->isActive()) {
log("%p %p", pInGameChatEntry, pInGameChatEntryBackground);
log("vis: %i", pInGameChatEntry->isVisible());
pInGameChatEntryBackground->setVisible(true);
pInGameChatEntry->show();
pInGameChatEntry->activate();
}
}
}
*/
}
void TLMP::GameUI_HandleKeyboardInputPost(CGameUI* gameUI, u32 unk0, u32 unk1, u32 unk2, bool& calloriginal)
{
// Keydown and 'Enter'
if (unk0 == 0x100 && unk1 == 0xD) {
CEGUI::Editbox* pInGameChatEntry = (CEGUI::Editbox*)UserInterface::getWindowFromName("1010_ChatEntry");
CEGUI::Window* pInGameChatEntryBackground = UserInterface::getWindowFromName("1010_ChatEntryBackground");
if (pInGameChatEntry && pInGameChatEntryBackground) {
if (!pInGameChatEntry->isActive()) {
pInGameChatEntryBackground->setVisible(true);
pInGameChatEntry->show();
pInGameChatEntry->activate();
}
}
}
}
void TLMP::KeyManager_HandleInputPre(CKeyManager* keyManager, u32 unk0, u32 unk1, bool & calloriginal)
{
//log(L"KeyManager::HandleInput(%p %x %x)", keyManager, unk0, unk1);
multiplayerLogger.WriteLine(Info, L"KeyManager::HandleInput(%p %x %x)", keyManager, unk0, unk1);
CEGUI::Editbox* pInGameChatEntry = (CEGUI::Editbox*)UserInterface::getWindowFromName("1010_ChatEntry");
if (pInGameChatEntry) {
if (pInGameChatEntry->isVisible()) {
calloriginal = false;
}
} else {
multiplayerLogger.WriteLine(Error, L"Error could not find 1010_ChatEntry");
}
}
void TLMP::MouseManager_HandleInputPre(CMouseManager* mouseManager, u32 wParam, u32 mouseButton, bool& calloriginal)
{
//log(L"MouseManager::handleInput(%p %x %x)", mouseManager, wParam, mouseButton);
if (wParam == 0x201 || wParam == 0x204) {
CEGUI::Editbox* pInGameChatEntry = (CEGUI::Editbox*)UserInterface::getWindowFromName("1010_ChatEntry");
if (pInGameChatEntry) {
if (pInGameChatEntry->hasInputFocus()) {
//log(L"Suppressing Mouse Input - ChatEntry has focus");
calloriginal = false;
}
} else {
multiplayerLogger.WriteLine(Error, L"Error could not find 1010_ChatEntry");
}
/*
CEGUI::PushButton* pInGameChatSay = (CEGUI::PushButton*)UserInterface::getWindowFromName("1010_Say");
if (pInGameChatSay) {
if (pInGameChatSay->isPushed()) {
log(L"Suppressing Mouse Input - ChatHistory has focus");
calloriginal = false;
}
} else {
multiplayerLogger.WriteLine(Error, L"Error could not find 1010_Say");
}
*/
}
}
void TLMP::GameUI_WindowResizedPost(CGameUI* game, bool & calloriginal)
{
//log(L"Window Resized");
multiplayerLogger.WriteLine(Info, L"Window Resized");
ResizeUI();
}
void TLMP::Character_Character_UpdatePre(CCharacter* character, PVOID octree, float* unk0, float unk1, bool& calloriginal)
{
//CharacterUpdateTime[character].reset();
u32 bitFieldVisibility = (character->flagFadingIn << 2) | (character->flagHasBeenDisplayed << 1) | (character->flagFadingOut);
// DEBUG
bitFieldVisibility |= (character->unkTransparencyFlag1 << 6) | (character->unkTransparencyFlag2 << 5) | (character->unkTransparencyFlag3 << 4) | (character->unkTransparencyFlag5 << 3);
// --
map<CCharacter*, u32>::iterator itr = CharacterVisibilityBuffer->find(character);
if (itr != CharacterVisibilityBuffer->end()) {
// Already exists, if it differs push it out to clients
if ((*CharacterVisibilityBuffer)[character] != bitFieldVisibility) {
if (NetworkState::getSingleton().GetState() == SERVER) {
NetworkEntity *netCharacter = searchCharacterByInternalObject(character);
if (netCharacter) {
NetworkMessages::Visibility msgVisibility;
// DEBUG
log(L" Character: %p %s %f %f", character, character->characterName.c_str(), character->unkTransparency0, character->unkTransparency1);
log(L" Fading in: %i", character->flagFadingIn);
log(L" HasBeenDisplayed: %i", character->flagHasBeenDisplayed);
log(L" Fading out: %i", character->flagFadingOut);
log(L" Other: %i %i %i %i", character->unkTransparencyFlag1, character->unkTransparencyFlag2, character->unkTransparencyFlag3, character->unkTransparencyFlag5);
// --
msgVisibility.set_id(netCharacter->getCommonId());
msgVisibility.set_fading_in(character->flagFadingIn);
msgVisibility.set_has_been_displayed(character->flagHasBeenDisplayed);
msgVisibility.set_fading_out(character->flagFadingOut);
msgVisibility.set_transparency(character->unkTransparency1);
Server::getSingleton().BroadcastMessage<NetworkMessages::Visibility>(S_PUSH_CHARACTER_VISIBILITY, &msgVisibility);
}
}
}
}
(*CharacterVisibilityBuffer)[character] = bitFieldVisibility;
}
void TLMP::Character_Character_UpdatePost(CCharacter* character, PVOID octree, float* unk0, float unk1, bool& calloriginal)
{
//log(L" CharacterUpdateTime: %s %f (%f, %f, %f)", character->characterName.c_str(), CharacterUpdateTime[character].getTime(),
// character->position.x, character->position.y, character->position.z);
// Off weird characters that may have been setup by the client... don't know how these got created but they're all at Y=100.0
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (character->GetPosition().y >= 100.0)
character->destroy = true;
}
/*
// Testing Visibility
if (!wcscmp(L"Shade", character->characterName.c_str()))
{
static u8 oldVis = character->visibility_test2;
static u32* petData = NULL;
static u32 petDataSize = 0;
log(L" Post: unkPos[1]: %i", character->unkPositionable[1]);
if (character->visibility_test2 != oldVis) {
oldVis = character->visibility_test2;
log(L"Dumping Shade, visibility changed to: %i offset: %x", character->visibility_test2, (u32*)&character->unkPositionable - (u32*)character);
character->dumpCharacter(petData, petDataSize);
log(L" Flags: %x %x %x %x", character->unkFlags[0], character->unkFlags[1], character->unkFlags[2], character->unkFlags[3]);
character->unkPositionable[1] = 0;
}
//log(L"%s Update: vis: %i state: %i check: %x %i %i %i %i %i %i %i (offset: %x)", character->characterName.c_str(), character->visibility_test2,
// character->state,
// character->unk6,
// character->unk06[0], character->unk06[1], character->unk06[2], character->unk06[3],
// character->destroy1, character->destroy2, character->destroy3,
// &character->unk06[1] - (u8*)character);
}
*/
}
void TLMP::GameClient_ChangeLevelPre(CGameClient* client, wstring dungeonName, s32 level, u32 unk0, u32 unk1, wstring str2, u32 unk2, bool& calloriginal)
{
logColor(B_RED, L"GameClient::ChangeLevel (%s %i %i %i %s %i)", dungeonName.c_str(), level, unk0, unk1, str2.c_str(), unk2);
multiplayerLogger.WriteLine(Info, L"GameClient::ChangeLevel (%s %i %i %i %s %i)", dungeonName.c_str(), level, unk0, unk1, str2.c_str(), unk2);
// Remove any other player characters and equipment or else we'll crash
// TODO: For my Destroyer "Drivehappy"
// Suppress the change if we're the client
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetAllow_ChangeLevel()) {
calloriginal = false;
}
}
else if (NetworkState::getSingleton().GetState() == SERVER) {
NetworkMessages::ChangeLevel msgChangeLevel;
string sDungeonName(dungeonName.begin(), dungeonName.end());
sDungeonName.assign(dungeonName.begin(), dungeonName.end());
string sUnkString(str2.begin(), str2.end());
sUnkString.assign(str2.begin(), str2.end());
msgChangeLevel.set_dungeon(sDungeonName);
msgChangeLevel.set_level(level);
msgChangeLevel.set_unk0(unk0);
msgChangeLevel.set_unk1(unk1);
msgChangeLevel.set_unkstring(sUnkString);
msgChangeLevel.set_unk2(unk2);
Server::getSingleton().BroadcastMessage<NetworkMessages::ChangeLevel>(S_PUSH_CHANGE_LEVEL, &msgChangeLevel);
}
// If we're going ahead with the change level, remove all the network information,
// we'll repopulate it when the new level loads
if (calloriginal) {
removeAllNetworkBaseUnits();
// Flush Network IDs
//logColor(B_GREEN, L"Flushing item network IDs");
clearAllNetworkIDs();
}
// Suppress level changes
//calloriginal = false;
}
void TLMP::GameClient_ChangeLevelPost(CGameClient* client, wstring dungeonName, s32 level, u32 unk0, u32 unk1, wstring str2, u32 unk2, bool& calloriginal)
{
//log(L"GameClient::ChangeLevel Post");
multiplayerLogger.WriteLine(Info, L"GameClient::ChangeLevel Post");
}
void TLMP::Global_SetSeedValue0Pre(u32 seed, bool& calloriginal)
{
Seed1 = (u32*)EXEOFFSET(SeedOffset1);
Seed2 = (u32*)EXEOFFSET(SeedOffset2);
Seed3 = (u32*)EXEOFFSET(SeedOffset3);
Seed4 = (u32*)EXEOFFSET(SeedOffset4);
if (NetworkState::getSingleton().GetState() == CLIENT) {
seed = Client::getSingleton().GetSeed();
//logColor(B_GREEN, L"Client reseting seed to:: %x (%i)", seed, seed);
*Seed1 = seed;
*Seed2 = 0;
} else if (NetworkState::getSingleton().GetState() == SERVER) {
//logColor(B_GREEN, L"Server reseting seed to:: %x (%i)", *Seed1, *Seed1);
*Seed1 = Server::getSingleton().GetSeed();
*Seed2 = 0;
}
calloriginal = false;
}
void TLMP::Global_SetSeedValue0Post(u32 seed, bool &calloriginal)
{
/*
static u32 rand = time(NULL);
logColor(B_GREEN, L"GameClient SetSeedValue0 Post: %x (%i)", seed, seed);
multiplayerLogger.WriteLine(Info, L"GameClient SetSeedValue0 Post: %x (%i)", seed, seed);
// Ugly, but fix later
Seed1 = (u32*)EXEOFFSET(SeedOffset1);
Seed2 = (u32*)EXEOFFSET(SeedOffset2);
Seed3 = (u32*)EXEOFFSET(SeedOffset3);
Seed4 = (u32*)EXEOFFSET(SeedOffset4);
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (Client::getSingleton().GetAllow_RandomSeed()) {
logColor(B_GREEN, L"Client setting random seed to: %x", seed);
*Seed1 = seed;
*Seed2 = seed;
*Seed3 = seed;
*Seed4 = seed;
}
} else if (NetworkState::getSingleton().GetState() == SERVER) {
seed = rand;
NetworkMessages::RandomSeed msgRandomSeed;
msgRandomSeed.set_seed(seed);
Server::getSingleton().BroadcastMessage<NetworkMessages::RandomSeed>(S_PUSH_RANDOM_SEED, &msgRandomSeed);
}
*/
}
void TLMP::Global_SetSeedValue2Pre(u32 seed, bool& calloriginal)
{
//logColor(B_GREEN, L"GameClient SetSeedValue2 Pre: %x (%i)", seed, seed);
//calloriginal = false;
}
void TLMP::Global_SetSeedValue2Post(u32 seed, bool& calloriginal)
{
//logColor(B_GREEN, L"GameClient SetSeedValue2 Post: %x (%i)", seed, seed);
multiplayerLogger.WriteLine(Info, L"GameClient SetSeedValue2 Post: %x (%i)", seed, seed);
}
void TLMP::TriggerUnit_TriggeredPre(CTriggerUnit* triggerUnit, CPlayer* player, bool& calloriginal)
{
log(L"TriggerUnit: %p %p (%f, %f, %f)", triggerUnit, player,
triggerUnit->GetPosition().x, triggerUnit->GetPosition().y, triggerUnit->GetPosition().z);
// Breakable was null on client, adding here to be safe -
// This can be null, e.g. when door after bad Brink opens up
//if (!player)
// return;
if (triggerUnit->type__ != OPENABLE && triggerUnit->type__ != INTERACTABLE) {
return;
}
NetworkEntity *netCharacter = NULL;
NetworkEntity *entity = searchItemByInternalObject(triggerUnit);
if (player) {
logColor(B_RED, L"TriggerUnit (%s)(%p) trigger by player (%s)", triggerUnit->nameReal.c_str(), triggerUnit, player->characterName.c_str());
multiplayerLogger.WriteLine(Info, L"TriggerUnit (%s)(%p) trigger by player (%s)", triggerUnit->nameReal.c_str(), triggerUnit, player->characterName.c_str());
netCharacter = searchCharacterByInternalObject(player);
}
NetworkMessages::TriggerUnitTriggered msgTriggerUnitTrigger;
if (netCharacter) {
msgTriggerUnitTrigger.set_characterid(netCharacter->getCommonId());
} else {
msgTriggerUnitTrigger.set_characterid(-1);
}
if (entity) {
msgTriggerUnitTrigger.set_itemid(entity->getCommonId());
}
NetworkMessages::Position *msgPosition = msgTriggerUnitTrigger.mutable_position();
if (triggerUnit->GetPosition().length() > EPSILON) {
msgPosition->set_x(triggerUnit->GetPosition().x);
msgPosition->set_y(triggerUnit->GetPosition().y);
msgPosition->set_z(triggerUnit->GetPosition().z);
}
// Client
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetSuppressed_SendTriggerUnitTriggered()) {
calloriginal = false;
Client::getSingleton().SendMessage<NetworkMessages::TriggerUnitTriggered>(C_REQUEST_TRIGGER_TRIGGERED, &msgTriggerUnitTrigger);
}
}
// Server
else if (NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().BroadcastMessage<NetworkMessages::TriggerUnitTriggered>(S_PUSH_TRIGGER_TRIGGERED, &msgTriggerUnitTrigger);
}
}
void TLMP::TriggerUnit_Triggered2Pre(CTriggerUnit* triggerUnit, CCharacter* character, bool& calloriginal)
{
log(L"TriggerUnit Triggered2Pre: %p %p", triggerUnit, character);
}
void TLMP::Breakable_TriggeredPre(CBreakable* breakable, CPlayer* player, bool& calloriginal)
{
log(L"Breakable: %p %p", breakable, player);
log(L" Position: %f %f %f", breakable->GetPosition().x, breakable->GetPosition().y, breakable->GetPosition().z);
if (player) {
logColor(B_RED, L"Breakable item (%s) triggered by Player (%s)", breakable->nameReal.c_str(), player->characterName.c_str());
multiplayerLogger.WriteLine(Info, L"Breakable item (%s) triggered by Player (%s)", breakable->nameReal.c_str(), player->characterName.c_str());
}
NetworkEntity *netCharacter = searchCharacterByInternalObject(player);
NetworkEntity *entity = searchItemByInternalObject(breakable);
//if (entity) {
if (netCharacter) {
NetworkMessages::BreakableTriggered msgBreakableTriggered;
if (entity) {
msgBreakableTriggered.set_itemid(entity->getCommonId());
} else {
msgBreakableTriggered.set_itemid(-1);
}
// Character can be null if skill was used to kill it
if (player) {
msgBreakableTriggered.set_characterid(netCharacter->getCommonId());
} else {
msgBreakableTriggered.set_characterid(-1);
}
// Build the position of the breakable object
NetworkMessages::Position *msgPosition = msgBreakableTriggered.mutable_position();
msgPosition->set_x(breakable->GetPosition().x);
msgPosition->set_y(breakable->GetPosition().y);
msgPosition->set_z(breakable->GetPosition().z);
// Client
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetSuppressed_SendBreakableTriggered()) {
calloriginal = false;
Client::getSingleton().SendMessage<NetworkMessages::BreakableTriggered>(C_REQUEST_BREAKABLE_TRIGGERED, &msgBreakableTriggered);
}
}
// Server
else if (NetworkState::getSingleton().GetState() == SERVER) {
Server::getSingleton().BroadcastMessage<NetworkMessages::BreakableTriggered>(S_PUSH_BREAKABLE_TRIGGERED, &msgBreakableTriggered);
}
} else {
//log(L"Error: Could not find network character in network shared list");
}
//} else {
//log(L"Error: Could not find breakable item in network shared list");
//}
}
void TLMP::TriggerUnit_CtorPost(CTriggerUnit* triggerUnit, CLayout* layout, bool& calloriginal)
{
//logColor(B_RED, L"TriggerUnit Created: %p", triggerUnit);
}
void TLMP::ItemGold_CtorPost(CItemGold* itemGold, PVOID _this, CResourceManager* resourceManager, u32 amount, bool&)
{
//logColor(B_RED, L"ItemGold Created: %p %p %i", itemGold, resourceManager, amount);
//logColor(B_RED, L" GUID: %016I64X", itemGold->GUID);
//logColor(B_RED, L" Amount: %i", itemGold->amount);
if (NetworkState::getSingleton().GetState() == SERVER) {
NetworkEntity *entity = addItem(itemGold);
NetworkMessages::ItemGoldCreate msgItemGoldCreate;
msgItemGoldCreate.set_itemid(entity->getCommonId());
msgItemGoldCreate.set_amount(itemGold->amount);
Server::getSingleton().BroadcastMessage<NetworkMessages::LevelCreateItem>(S_PUSH_ITEM_GOLD, &msgItemGoldCreate);
//logColor(B_RED, L" ID: %x", entity->getCommonId());
}
}
void TLMP::ItemGold_CtorPre(CItemGold* itemRetval, PVOID _this, CResourceManager* resourceManager, u32 amount, bool& calloriginal)
{
if (!calloriginal) {
//logColor(B_RED, L"ItemGold Ctor Suppressed for Testing");
}
//calloriginal = false;
//itemRetval = NULL;
}
void TLMP::Character_StrikePre(CCharacter* character, CLevel* level, CCharacter* characterOther, PVOID unk0, u32 unk1, float unk2, float unk3, u32 unk4, bool& calloriginal)
{
logColor(B_GREEN, L"Character Strike: %p %p %p %p %x %f %f %x",
character, level, characterOther, unk0, unk1, unk2, unk3, unk4);
NetworkEntity *attacker = searchCharacterByInternalObject(character);
NetworkEntity *defender = searchCharacterByInternalObject(characterOther);
if (attacker && defender) {
if (NetworkState::getSingleton().GetState() == CLIENT) {
NetworkMessages::CharacterStrikeCharacter msgCharacterStrike;
msgCharacterStrike.set_characteridsource(attacker->getCommonId());
msgCharacterStrike.set_characteridtarget(defender->getCommonId());
msgCharacterStrike.set_unk0(unk2);
msgCharacterStrike.set_unk1(unk3);
msgCharacterStrike.set_unk2(unk4);
Client::getSingleton().SendMessage<NetworkMessages::CharacterStrikeCharacter>(C_PUSH_CHARACTER_STRIKE, &msgCharacterStrike);
}
}
}
void TLMP::Character_ResurrectPre(CCharacter* character, bool& calloriginal)
{
log(L"PlayerResurrectPre (%p)", character);
log(L" Name: (%s)", character->characterName.c_str());
NetworkEntity *entity = searchCharacterByInternalObject(character);
NetworkMessages::CharacterResurrect msgCharacterResurrect;
if (entity) {
msgCharacterResurrect.set_characterid(entity->getCommonId());
}
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetAllow_CharacterResurrect()) {
calloriginal = false;
if (entity) {
Client::getSingleton().SendMessage<NetworkMessages::CharacterResurrect>(C_REQUEST_CHARACTER_RESURRECT, &msgCharacterResurrect);
}
} else {
if (character) {
character->healthCurrent = character->healthMax;
}
}
} else if (NetworkState::getSingleton().GetState() == SERVER) {
if (entity) {
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterResurrect>(S_PUSH_CHARACTER_RESURRECT, &msgCharacterResurrect);
}
}
}
void TLMP::EquipmentRefDtorPre(CEquipmentRef* equipmentRef, u32 unk0)
{
//log(L"EquipmentRef::Dtor Pre (%p %x Equipment: %p)", equipmentRef, unk0, equipmentRef->pCEquipment);
multiplayerLogger.WriteLine(Info, L"EquipmentRef::Dtor Pre (%p %x Equipment: %p)", equipmentRef, unk0, equipmentRef->pCEquipment);
// Move through the character inventory items and invalid any equipment tied to the same Ref
CEquipment *equipment = equipmentRef->pCEquipment;
CLevel *level = gameClient->pCLevel;
if (level) {
LinkedListNode* itr = *level->charactersAll;
while (itr != NULL) {
CCharacter* character = (CCharacter*)itr->pCBaseUnit;
if (character) {
CInventory* inventory = character->pCInventory;
if (inventory) {
for (u32 i = 0; i < inventory->equipmentList.size; ++i) {
CEquipmentRef *equipmentRef2 = inventory->equipmentList[i];
//log(L"DEBUG: %i %i - %p %p", i, inventory->equipmentList.size, inventory, equipmentRef2);
if (equipmentRef2) {
if (equipment == equipmentRef2->pCEquipment && equipmentRef2 != equipmentRef) {
log(L"Removed duplicate equipment in equipmentRef: %p", equipmentRef2);
multiplayerLogger.WriteLine(Info, L"Removed duplicate equipment in equipmentRef: %p", equipmentRef2);
equipmentRef2->pCEquipment = NULL;
}
}
}
}
}
itr = itr->pNext;
}
}
}
void TLMP::EquipmentRefDtorPost(CEquipmentRef* equipmentRef, u32 unk0)
{
//log(L"EquipmentRef::Dtor Post");
multiplayerLogger.WriteLine(Info, L"EquipmentRef::Dtor Post");
// Invalidate our equipment
if (equipmentRef->pCEquipment) {
equipmentRef->pCEquipment = NULL;
}
}
void TLMP::Monster_GetCharacterClosePre(CCharacter*& retval, CMonster* monster, u32 unk0, float unk1, bool& calloriginal)
{
//log(L"Monster GetCharacterClosePre: %s, %i %f", monster->characterName.c_str(),unk0, unk1);
//calloriginal = false;
//retval = NULL;
}
void TLMP::Monster_GetCharacterClosePost(CCharacter*& retval, CMonster* monster, u32 unk0, float unk1, bool& calloriginal)
{
if (retval) {
//log(" retval: %p monster: %p %i %f", retval, monster, unk0, unk1);
//log(L"Monster GetCharacterClosePost: %s, %i %f to: %s", monster->characterName.c_str(), unk0, unk1, retval->characterName.c_str());
}
}
void TLMP::Monster_ProcessAIPre(CMonster* monster, float dTime, u32 unk0, bool & calloriginal)
{
//log(L"Monster_ProcessAIPre (%p %s), %f %p", monster, monster->characterName.c_str(), dTime, unk0);
if (monster->GUID == DESTROYER || monster->GUID == ALCHEMIST || monster->GUID == VANQUISHER) {
calloriginal = false;
}
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
//calloriginal = false;
}
}
void TLMP::Monster_ProcessAI2Pre(CMonster* monster, float dTime, CLevel *level, u32 unk1, bool & calloriginal)
{
//log(L"Monster_ProcessAI2Pre (%s), %f %p %i", monster->characterName.c_str(), dTime, level, unk1);
//calloriginal = false;
if (monster->GUID == DESTROYER || monster->GUID == ALCHEMIST || monster->GUID == VANQUISHER) {
calloriginal = false;
}
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
//calloriginal = false;
}
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
//if (monster->GUID == DESTROYER || monster->GUID == ALCHEMIST || monster->GUID == VANQUISHER) {
// calloriginal = false;
//}
}
}
void TLMP::Monster_ProcessAI3Pre(CMonster* monster, u32 unk0, bool & calloriginal)
{
//log(L"Monster_ProcessAI3Pre (%s), %i", monster->characterName.c_str(), unk0);
if (monster->GUID == DESTROYER || monster->GUID == ALCHEMIST || monster->GUID == VANQUISHER) {
calloriginal = false;
}
if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
calloriginal = false;
}
else if (Network::NetworkState::getSingleton().GetState() == SERVER) {
//if (monster->GUID == DESTROYER || monster->GUID == ALCHEMIST || monster->GUID == VANQUISHER) {
//calloriginal = false;
//}
}
}
void TLMP::Character_Update_LevelPre(CCharacter* character, CLevel* level, float unk0, bool& calloriginal)
{
//if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
// calloriginal = false;
//}
}
void TLMP::Character_Update_CharacterPre(CCharacter*, CCharacter*, bool& calloriginal)
{
//if (Network::NetworkState::getSingleton().GetState() == CLIENT) {
// calloriginal = false;
//}
}
void TLMP::Level_UpdatePre(CLevel*, Vector3*, u32, float, bool& calloriginal)
{
LevelUpdateTime.reset();
}
void TLMP::Level_UpdatePost(CLevel* level, Vector3* position, u32 unk0, float unk1, bool&)
{
/*
log("Level_UpdatePost: %f", LevelUpdateTime.getTime());
log(" Position: %f %f %f", position->x, position->y, position->z);
log(" unk0: %i unk1: %f", unk0, unk1);
log(" Character Count: %i", level->GetCharacterCount());
*/
}
void TLMP::Level_Level_RemoveEquipmentPre(CLevel* level, CEquipment* equipment, bool&)
{
//log("Level_Level_RemoveEquipmentPre -- Level: %p, Equipment: %p", level, equipment);
}
void TLMP::Level_Level_RemoveEquipmentPost(CLevel* level, CEquipment* equipment, bool&)
{
//log("Level_Level_RemoveEquipmentPost -- Level: %p, Equipment: %p", level, equipment);
}
void TLMP::Effect_EffectSomethingPre(CEffect* effect, CEffect* other, bool & calloriginal)
{
/*
log(L"EffectSomethingPre: %p %p", effect, other);
log(L" BaseUnit: %p", other->pCBaseUnit);
// Other
if (other) {
log(L" other Name: %s", other->name.c_str());
log(" other Type: %s %i", searchForEffectName(other->effectType), other->effectType);
log(L" other listUnknown size: %x", other->listUnknown.size);
u32 maxTerm = 20;
for (u32 i = 0; i < other->listUnknown.size && maxTerm >= 0; ++i, --maxTerm) {
log(L" other listUnknown[%i]: %p", i, other->listUnknown[i]);
}
if (other->pCBaseUnit) {
log(L" BaseUnit2 Type: %x (%016I64X)", other->pCBaseUnit->type__, other->pCBaseUnit->GUID);
if (other->pCBaseUnit->type__ == 0x1B) {
CCharacter* character = (CCharacter*)other->pCBaseUnit;
log(L" Character Name: %s", character->characterName.c_str());
}
}
}
*/
}
void TLMP::Effect_EffectSomethingPost(CEffect* effect, CEffect* other, bool & calloriginal)
{
//log(L"EffectSomethingPost: %p %p", effect, other);
}
void TLMP::Effect_Character_Unk0Pre(CEffect* effect, CCharacter* character, bool unk)
{
//log(L"Effect::Character_Unk0Pre: %p %p %i", effect, character, unk);
}
void TLMP::Effect_Character_Unk0Post(CEffect* effect, CCharacter* character, bool unk)
{
//log(L"Effect::Character_Unk0Post: %p %p %i", effect, character, unk);
}
void TLMP::Level_CleanupPre(CLevel* level, u32 unk0, u32 unk1, bool& calloriginal)
{
log(L"Level::Cleanup Pre: %s %x %x", level->levelName.c_str(), unk0, unk1);
}
void TLMP::Level_CleanupPost(CLevel* level, u32 unk0, u32 unk1, bool& calloriginal)
{
log(L"Level::Cleanup Post: %s %x %x", level->levelName.c_str(), unk0, unk1);
}
void TLMP::Character_Player_KillMonsterExperiencePre(CCharacter* player, CLevel* level, CCharacter* monster, u32 experience, u32 unk0, bool& calloriginal)
{
//log(L"Player Kill Monster Experience Pre");
//log(L"Player Killed Monster Pre: %s %p", player->characterName.c_str(), monster);
if (monster) {
//log(L"Player Killed Monster Pre: %s worth %i experience, unk0: %x", monster->characterName.c_str(), experience, unk0);
//log(L" Test: %x %x %x %x", monster->destroy, monster->destroy1, monster->destroy2, monster->destroy3);
//log(L" Test: %x %x %x %x", monster->moving, monster->unkBool0, monster->attacking, monster->usingSkill);
}
if (NetworkState::getSingleton().GetState() == SINGLEPLAYER) {
return;
}
// Work on network messages
NetworkEntity *netCharacter = searchCharacterByInternalObject(player);
if (!netCharacter) {
//log(L"Error: Could not find network id for player: %s", player->characterName.c_str());
return;
}
// Client
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetAllow_AddExperience()) {
calloriginal = false;
}
}
// Server
else if (NetworkState::getSingleton().GetState() == SERVER) {
if (!Server::getSingleton().GetSuppressed_SendAddExperience()) {
// Only send experience when the player is tagged as a killer (should always happen, and only 1 player should be tagged so)
if (player->GUID == ALCHEMIST || player->GUID == DESTROYER || player->GUID == VANQUISHER) {
NetworkMessages::CharacterAddExperience msgCharacterAddExperience;
msgCharacterAddExperience.set_characterid(netCharacter->getCommonId());
msgCharacterAddExperience.set_experience(experience);
msgCharacterAddExperience.set_unk0(unk0);
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterAddExperience>(S_PUSH_ADDEXPERIENCE, &msgCharacterAddExperience);
// If the player isn't ours, go ahead and give our player the experience too
if (gameClient->pCPlayer != player) {
Server::getSingleton().SetSuppressed_SendAddExperience(true);
gameClient->pCPlayer->KillMonsterExperience(level, NULL, experience, unk0);
Server::getSingleton().SetSuppressed_SendAddExperience(false);
}
}
}
}
}
void TLMP::Character_Player_KillMonsterExperiencePost(CCharacter* player, CLevel* level, CCharacter* monster, u32 experience, u32 unk0, bool& calloriginal)
{
//log(L"Player Killed Monster Post: %p experience: %i", monster, experience);
if (monster) {
//log(L"Player Killed Monster Pre: %s worth %i experience, unk0: %x", monster->characterName.c_str(), experience, unk0);
//log(L" Test: %x %x %x %x", monster->destroy, monster->destroy1, monster->destroy2, monster->destroy3);
//log(L" Test: %x %x %x %x", monster->moving, monster->unkBool0, monster->attacking, monster->usingSkill);
}
}
void TLMP::Level_Level_CharacterKilledCharacterPre(CLevel* level, CCharacter* character, CCharacter* other, Vector3* position, u32 unk0, bool& calloriginal)
{
/*
log(L"Level_CharacterKilledCharacterPre: character = %p", character);
if (character) {
log(L"Level_CharacterKilledCharacterPre: %p, %s, %f %f %f, unk0: %x",
level, character->characterName.c_str(), position->x, position->y, position->z, unk0);
}
*/
// Skip sending, this is probably a barrel and we sync it up anyways
if (!other) {
return;
}
//
if (NetworkState::getSingleton().GetState() == SERVER) {
NetworkEntity *entityCharacter = searchCharacterByInternalObject(character);
NetworkEntity *entityOther = searchCharacterByInternalObject(other);
if (!entityCharacter) {
//log(L"Error: Could not find network ID for : %s", character->characterName.c_str());
return;
}
if (!entityOther) {
//log(L"Error: Could not find network ID for character: %s", other->characterName.c_str());
return;
}
NetworkMessages::CharacterKilledCharacter msgCharacterKilledCharacter;
NetworkMessages::Position *msgPosition = msgCharacterKilledCharacter.mutable_position();
msgPosition->set_x(position->x);
msgPosition->set_y(position->y);
msgPosition->set_z(position->z);
msgCharacterKilledCharacter.set_characterid(entityCharacter->getCommonId());
msgCharacterKilledCharacter.set_otherid(entityOther->getCommonId());
msgCharacterKilledCharacter.set_unk0(unk0);
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterKilledCharacter>(S_PUSH_CHARACTERKILLED, &msgCharacterKilledCharacter);
}
}
void TLMP::Level_Level_CharacterKilledCharacterPost(CLevel* level, CCharacter* character, CCharacter* other, Vector3* position, u32 unk0, bool& calloriginal)
{
//log(L"Level_CharacterKilledCharacterPost");
}
void TLMP::Character_KilledPre(CCharacter* charKilled, CCharacter* charKillingBlow, Ogre::Vector3* direction, float unk0, u32 unk1, bool& calloriginal)
{
/*
log(L"Character KilledPre: direction: %p", direction);
if (charKillingBlow && direction) {
log(L" Character KilledPre: %s %s, %f %f %f %f %x",
charKilled->characterName.c_str(), charKillingBlow->characterName.c_str(), direction->x, direction->y, direction->z, unk0, unk1);
}
*/
//calloriginal = false;
}
void TLMP::Character_KilledPost(CCharacter* charKilled, CCharacter* charKillingBlow, Ogre::Vector3* direction, float unk0, u32 unk1, bool& calloriginal)
{
/*
log(L"Character KilledPost");
if (charKillingBlow && direction) {
log(L" Character KilledPost: %s %s, %f %f %f %f %x",
charKilled->characterName.c_str(), charKillingBlow->characterName.c_str(), direction->x, direction->y, direction->z, unk0, unk1);
}
log(L"Character KilledPost2");
*/
}
void TLMP::Effect_EffectManagerCreateEffectPre(CEffect* retval, CEffectManager* effectManager)
{
//log(L"EffectManagerCreate EffectPre: %p Effects in Manager: %i", effectManager, effectManager->effectList.size);
}
void TLMP::Effect_EffectManagerCreateEffectPost(CEffect* retval, CEffectManager* effectManager)
{
//log(L"EffectManagerCreate EffectPost: %p Effects in Manager: %i", effectManager, effectManager->effectList.size);
//log(L" BaseUnit: %p", retval->pCBaseUnit);
}
void TLMP::EffectManager_AddEffectToEquipmentPre(CEffectManager* manager, CEquipment* equipment, CEffect* effect)
{
//log(L"EffectManager_AddEffectToEquipmentPre: %p %p %p", manager, equipment, effect);
}
void TLMP::EffectManager_AddEffectToEquipmentPost(CEffectManager* manager, CEquipment* equipment, CEffect* effect)
{
//log(L"EffectManager_AddEffectToEquipmentPost: %p %p %p", manager, equipment, effect);
//log(L" Effect Name: %s", effect->name.c_str());
}
void TLMP::BaseUnit_AddSkillPre(CBaseUnit* baseUnit, wstring* skillName, u32 unk0, bool& calloriginal)
{
const u32 PLAYER = 0x1C;
if (baseUnit->type__ != PLAYER) {
return;
}
if (NetworkState::getSingleton().GetState() == SINGLEPLAYER) {
return;
}
//log(L"BaseUnit AddSkillPre: %p %s %x", baseUnit, skillName->c_str(), unk0);
//log(L" SkillManager: %p", baseUnit->pCSkillManager);
// Get the character
CCharacter *character = (CCharacter*)baseUnit;
NetworkEntity *netCharacter = searchCharacterByInternalObject(character);
if (!netCharacter) {
//log("Error: Could not find network ID for character: %s", character->characterName.c_str());
return;
}
// Network push it out
if (NetworkState::getSingleton().GetState() == CLIENT) {
// Do Nothing for now
} else if (NetworkState::getSingleton().GetState() == SERVER) {
string skillNameAscii(skillName->begin(), skillName->end());
skillNameAscii.assign(skillName->begin(), skillName->end());
NetworkMessages::BaseUnitAddSkill msgBaseUnitAddSkill;
msgBaseUnitAddSkill.set_characterid(netCharacter->getCommonId());
msgBaseUnitAddSkill.set_skillname(skillNameAscii.c_str());
Server::getSingleton().BroadcastMessage<NetworkMessages::BaseUnitAddSkill>(S_PUSH_CHARACTER_ADD_SKILL, &msgBaseUnitAddSkill);
}
}
void TLMP::BaseUnit_AddSkillPost(CBaseUnit* baseUnit, wstring* skillName, u32 unk0, bool& calloriginal)
{
if (NetworkState::getSingleton().GetState() == SINGLEPLAYER) {
return;
}
//log(L"BaseUnit AddSkillPost: %p %s %x", baseUnit, skillName->c_str(), unk0);
}
void TLMP::Path_GetNextNodePre(CPath* path, Vector3* vec, float unk0)
{
return;
if (path == gameClient->pCPlayer->pCPath)
{
log(L"Path::GetNextNode Pre (%p) %f %f %f, %f", path, vec->x, vec->y, vec->z, unk0);
}
}
void TLMP::Path_GetNextNodePost(CPath* path, Vector3* vec, float unk0)
{
return;
if (path == gameClient->pCPlayer->pCPath)
{
log(L"Path::GetNextNode Post (%p) %f %f %f, %f", path, vec->x, vec->y, vec->z, unk0);
log(L" unk3:");
vector<Vector3>::iterator itr;
for (itr = path->unk3.begin(); itr != path->unk3.end(); itr++) {
log(L" %f, %f, %f", (*itr).x, (*itr).y, (*itr).z);
}
log(L" unk4:");
vector<float>::iterator itr2;
for (itr2 = path->unk4.begin(); itr2 != path->unk4.end(); itr2++) {
log(L" %f", (*itr2));
}
log(L" unk5:");
for (itr2 = path->unk5.begin(); itr2 != path->unk5.end(); itr2++) {
log(L" %f", (*itr2));
}
log(L" unk6:");
vector<u32>::iterator itr3;
for (itr3 = path->unk6.begin(); itr3 != path->unk6.end(); itr3++) {
log(L" %x", (*itr3));
}
log(L" unk7:");
for (itr2 = path->unk7.begin(); itr2 != path->unk7.end(); itr2++) {
log(L" %f", (*itr2));
}
}
}
void TLMP::Character_UpdateOrientationPre(CCharacter* character, float x, float z, bool& calloriginal)
{
// Check if the new values differ before bothering to continue
if (character->orientation.x != x || character->orientation.z != z) {
//log(L"Character updated orientation: %p %f %f", character, x, z);
if (NetworkState::getSingleton().GetState() == SINGLEPLAYER) {
return;
}
NetworkEntity *netCharacter = searchCharacterByInternalObject(character);
if (!netCharacter) {
log(L"Could not find network ID for character!");
return;
}
u32 characterId = netCharacter->getCommonId();
NetworkMessages::CharacterOrientation msgCharacterOrientation;
NetworkMessages::Position *msgOrientation = msgCharacterOrientation.mutable_orientation();
msgCharacterOrientation.set_characterid(characterId);
msgOrientation->set_x(x);
msgOrientation->set_y(0);
msgOrientation->set_z(z);
//
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (Client::getSingleton().GetAllow_UpdateOrientation()) {
} else {
calloriginal = false;
Client::getSingleton().SendMessage<NetworkMessages::CharacterOrientation>(C_REQUEST_ORIENTATION, &msgCharacterOrientation);
}
} else if (NetworkState::getSingleton().GetState() == SERVER) {
// Push it out to clients
Server::getSingleton().BroadcastMessage<NetworkMessages::CharacterOrientation>(S_PUSH_ORIENTATION, &msgCharacterOrientation);
}
}
}
void TLMP::Player_LevelUpPre(CPlayer* player, bool& calloriginal)
{
log("Player leveled up Pre %p", player);
if (gameClient->pCPlayer != player) {
log(" Player leveled up not my character");
//calloriginal = false;
}
}
void TLMP::Player_LevelUpPost(CPlayer* player, bool& calloriginal)
{
log("Player leveled up Post %p", player);
}
void TLMP::Player_SwapWeaponsPre(CCharacter* player, bool& calloriginal)
{
static Timer delayInput;
static bool firstSwap = true;
const float inputDelay = 0.1f;
NetworkEntity *netCharacter = searchCharacterByInternalObject(player);
if (!netCharacter) {
log(L"Could not find network ID for character!");
return;
}
u32 characterId = netCharacter->getCommonId();
NetworkMessages::PlayerSwapWeapons msgPlayerSwapWeapons;
msgPlayerSwapWeapons.set_characterid(characterId);
//
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (Client::getSingleton().GetAllow_WeaponSwap()) {
} else {
// Limit the amount of messages for this being sent out if this is our character
if (player == gameClient->pCPlayer) {
if (delayInput.getTime() < inputDelay && !firstSwap) {
calloriginal = false;
return;
} else if (firstSwap) {
firstSwap = false;
} else {
delayInput.reset();
}
calloriginal = false;
Client::getSingleton().SendMessage<NetworkMessages::PlayerSwapWeapons>(C_REQUEST_WEAPONSWAP, &msgPlayerSwapWeapons);
return;
} else {
// Halt any local weapon swaps not sent by the server and not on our character
calloriginal = false;
}
}
} else if (NetworkState::getSingleton().GetState() == SERVER) {
// Limit the amount of messages for this being sent out if this is our character
if (player == gameClient->pCPlayer) {
if (delayInput.getTime() < inputDelay && !firstSwap) {
calloriginal = false;
return;
} else if (firstSwap) {
firstSwap = false;
} else {
delayInput.reset();
}
}
// Push it out to clients
Server::getSingleton().BroadcastMessage<NetworkMessages::PlayerSwapWeapons>(S_PUSH_WEAPONSWAP, &msgPlayerSwapWeapons);
}
log("Player swapping weapons: %p", player);
}
void TLMP::Effect_Something0Pre(CEffect* effect, u32 unk0, bool &calloriginal)
{
//log("Effect_Something0: %p %i", effect, unk0);
}
void TLMP::Effect_Effect_ParamCtorPre(CEffect* effect, u32 unk0, bool unk1, bool unk2, float unk3, float unk4, float unk5, bool unk6, bool& calloriginal)
{
//log("Effect::ParamCtor (%p %i (%s) %i %i %f %f %f %i)", effect, unk0, searchForEffectName(unk0), unk1, unk2, unk3, unk4, unk5, unk6);
}
void TLMP::Effect_CtorPre(CEffect* effect)
{
//log(L"Effect::CtorPre (%p)", effect);
}
void TLMP::Effect_CtorPost(CEffect* effect)
{
//log(L"Effect::CtorPost (%p)", effect);
//effect->dumpEffect();
}
// Quest Manager
void TLMP::QuestManager_SetQuestCompletedPre(CQuestManager* questManager, CQuest* quest, CCharacter* character, u32 questActive, bool& calloriginal)
{
log(L"QuestManager::SetQuestCompletedPre (QMgr: %p, Quest: %p, Character: %p, QuestActive: %i)", questManager, quest, character, questActive);
if (quest) {
log(L" Quest Dungeon: %s", quest->dungeon.c_str());
log(L" Quest Location: %s", quest->location.c_str());
log(L" Quest Name: %s", quest->name.c_str());
}
}
void TLMP::QuestManager_SetQuestCompletedPost(CQuestManager* questManager, CQuest* quest, CCharacter* character, u32 questActive, bool& calloriginal)
{
log(L"QuestManager::SetQuestCompletedPost (QMgr: %p, Quest: %p, Character: %p, QuestActive: %i)", questManager, quest, character, questActive);
}
void TLMP::Automap_AddBillboardPre(CAutomap* automap, u32 unk0, float* unk1, Vector3* unk2, u32 unk3, u32 unk4, bool& calloriginal)
{
// Fix bug when Torchlight tries to call this with this == NULL
if (!automap) {
log("Halted this = null call on Automap, yay!");
multiplayerLogger.WriteLine(Error, L"Halted this = null call on Automap, yay!");
calloriginal = false;
}
}
void TLMP::InventoryMenu_OpenClosePre(CInventoryMenu *menu, bool open, bool& calloriginal)
{
//log(L"InventoryMenu_OpenClosePre: %p, %i", menu, open);
// Player inspection support
// Check if target character has CPlayer vtable
menu->player = gameClient->pCPlayer;
menu->weaponSwapCheckBox->enable();
if (gameClient->pCGameUI->pCTargetCharacter) {
if (gameClient->pCGameUI->pCTargetCharacter->GUID == DESTROYER ||
gameClient->pCGameUI->pCTargetCharacter->GUID == ALCHEMIST ||
gameClient->pCGameUI->pCTargetCharacter->GUID == VANQUISHER)
{
log(L" New character inv: %s, old char: %s", gameClient->pCGameUI->pCTargetCharacter->characterName.c_str(), menu->player->characterName.c_str());
menu->player = (CPlayer*)gameClient->pCGameUI->pCTargetCharacter;
menu->weaponSwapCheckBox->disable();
}
}
// Set the correct weapon set for the selected player
if (menu->weaponSwapCheckBox->isSelected() != (bool)menu->player->weaponSetToggle) {
menu->weaponSwapCheckBox->setSelected(!menu->weaponSwapCheckBox->isSelected());
}
// Strip off the extra scene nodes if there is more than our target
Ogre::SceneManager* sm = CMasterResourceManager::getInstance()->sceneManagerPlayerInventory;
Ogre::SceneNode* root = sm->getRootSceneNode();
Ogre::Node* targetNode = menu->player->pCGenericModel_Inventory->pOctreeNode_Inventory;
root->removeAllChildren();
root->addChild(targetNode);
}
void TLMP::InventoryMenu_MouseEventPre(CInventoryMenu* invMenu, const CEGUI::MouseEventArgs* args, bool & calloriginal)
{
log(L"InventoryMenu_MouseEventPre:: %p", invMenu);
log("InventoryMenu_MouseEventPre:: Window: %p %s", args->window, args->window->getName().c_str());
/*
log("Viewport Offset: %x", (u8*)&invMenu->paperDollViewport - (u8*)invMenu);
log("weaponSwapCheckBox Offset: %x", (u8*)&invMenu->weaponSwapCheckBox - (u8*)invMenu);
log("Viewport: %p", invMenu->paperDollViewport);
//invMenu->paperDollViewport->setBackgroundColour(Ogre::ColourValue(0.13f, 0.07f, 0.21f));
*/
if (invMenu->player != gameClient->pCPlayer) {
// If we're inspecting another player then ignore mouse events
calloriginal = false;
log(L"Suppressing inventory menu mouse event - inspecting another player");
}
}
void TLMP::Equipment_EnchantPre(u32 retval, CEquipment* equipment, u32 unk0, u32 unk1, u32 unk2, bool & calloriginal)
{
log(L"Equipment_Enchant: (%p, %i, %i, %i)", equipment, unk0, unk1, unk2);
multiplayerLogger.WriteLine(Info, L"Equipment_Enchant: (%p, %i, %i, %i)", equipment, unk0, unk1, unk2);
log(L"Suppressing equipment enchant.");
multiplayerLogger.WriteLine(Info, L"Suppressing equipment enchant.");
// Prevent enchanting
calloriginal = false;
}
void TLMP::ParticleCache_Dtor2Pre(CParticleCache *cache)
{
//log(L"ParticleCache_Dtor2Pre: %p", cache);
//log(L" ParticleSystems: %i", cache->listParticleSystems.size);
//log(L" CParticleCache children: %i", cache->listParticleCache->size);
/*
log(L" List Debug:");
log(L" unk1 size: %i", cache->unk1.size);
log(L" unk2 size: %i", cache->unk2.size);
log(L" unk3 size: %i", cache->unk3.size);
log(L" unk4 size: %i", cache->unk4.size);
log(L" unk5 size: %i", cache->unk5.size);
log(L" unk6 size: %i", cache->unk6.size);
log(L" unk7 size: %i", cache->unk7.size); 0x489F8D
*/
//for (u32 i = 0; i < cache->listParticleSystems.size; ++i) {
// log(L" ParticleSystem: %p", cache->listParticleSystems[i]);
//}
}
void TLMP::ParticleCache_Dtor2Post(CParticleCache *cache)
{
//log(L"ParticleCache_Dtor2Post: %p", cache);
}
void TLMP::PositionableObject_SetNearPlayerPre(CPositionableObject* object, bool& nearPlayer, bool& calloriginal)
{ /*
if (nearPlayer) {
logColor(B_GREEN, L"PositionableObject_SetNearPlayerPre: %p %i", object, nearPlayer);
logColor(B_GREEN, L" name: %s", object->name.c_str());
}
*/
}
void TLMP::Level_CheckCharacterProximityPre(CCharacter* retval, CLevel* level, Vector3* normalizedVec, u32 unk0, float x, float y, float z, u32 unk1, CCharacter* character, u32 unk2, bool& calloriginal)
{
/*
log(L"Level_CheckCharacterProximityPre: %p %p", level, character);
log(L" character: %s", character->characterName.c_str());
log(L" normVec: %f %f %f", normalizedVec->x, normalizedVec->y, normalizedVec->z);
log(L" unk0: %x unk1: %x unk2: %x", unk0, unk1, unk2);
log(L" x,y,z: %f %f %f", x, y, z);
*/
}
void TLMP::Level_CheckCharacterProximityPost(CCharacter* retval, CLevel* level, Vector3* normalizedVec, u32 unk0, float x, float y, float z, u32 unk1, CCharacter* character, u32 unk2, bool& calloriginal)
{
/*
if (retval) {
log(L"Level_CheckCharacterProximityPre: %p %p %p", level, character, retval);
if (character) {
log(L" character: %s", character->characterName.c_str());
}
log(L" normVec: %f %f %f", normalizedVec->x, normalizedVec->y, normalizedVec->z);
log(L" unk0: %x unk1: %x unk2: %x", unk0, unk1, unk2);
log(L" x,y,z: %f %f %f", x, y, z);
log(L" retval: %s", retval->characterName.c_str());
}
*/
}
void TLMP::Inventory_EquipmentAutoEquipPre(CInventory* inventory, CEquipment* equipment, bool& calloriginal)
{
log("Inventory_EquipmentAutoEquipPre: %p %p", inventory, equipment);
NetworkEntity *netCharacter = searchCharacterByInternalObject(inventory->pCCharacter);
NetworkEntity *netEquipment = searchEquipmentByInternalObject(equipment);
if (!netCharacter || !netEquipment) {
log(L"Error: Could not find network id for character or equipment: %p %p", netCharacter, netEquipment);
multiplayerLogger.WriteLine(Error, L"Error: Could not find network id for character or equipment: %p %p", netCharacter, netEquipment);
return;
}
u32 characterId = netCharacter->getCommonId();
u32 equipmentId = netEquipment->getCommonId();
NetworkMessages::EquipmentAutoEquip msgEquipmentAutoEquip;
msgEquipmentAutoEquip.set_characterid(characterId);
msgEquipmentAutoEquip.set_equipmentid(equipmentId);
//
if (NetworkState::getSingleton().GetState() == CLIENT) {
if (!Client::getSingleton().GetAllow_AutoEquip()) {
calloriginal = false;
Client::getSingleton().SendMessage<NetworkMessages::EquipmentAutoEquip>(C_REQUEST_AUTOEQUIP, &msgEquipmentAutoEquip);
}
} else if (NetworkState::getSingleton().GetState() == SERVER) {
// Push it out to clients
Server::getSingleton().BroadcastMessage<NetworkMessages::EquipmentAutoEquip>(S_PUSH_AUTOEQUIP, &msgEquipmentAutoEquip);
}
}
void TLMP::Level_RemoveCharacterPre(CLevel* level, CCharacter* character, bool& calloriginal)
{
logColor(B_RED, L"Level_RemoveCharacterPre: %p %p (%s)", level, character, character->characterName.c_str());
}
void TLMP::Level_RemoveItemPre(CLevel* level, CItem* item, bool& callorginal)
{
logColor(B_RED, L"Level_RemoveItemPre: %p %p", level, item);
NetworkEntity* netEquipment = NULL;
log(L"Removing item from equipment/item network lists...");
removeItem(item);
removeEquipment(item);
}
void TLMP::Level_RemoveItemPost(CLevel* level, CItem* item, bool& callorginal)
{
logColor(B_RED, L"Level_RemoveItemPost: %p %p", level, item);
}
void TLMP::GenericModel_DtorPre(CGenericModel *model, bool&)
{
log(L"GenericModel::DtorPre: %p", model);
}
void TLMP::GenericModel_DtorPost(CGenericModel *model, bool&)
{
log(L"GenericModel::DtorPost: %p", model);
}
// Server Events
void TLMP::ServerOnClientConnected(void *arg)
{
if (arg) {
SystemAddress address = *(SystemAddress *)arg;
NetworkMessages::Version msgVersion;
msgVersion.set_version(MessageVersion);
multiplayerLogger.WriteLine(Info, L"Client connected - sending S_VERSION push to: %x:%i", address.binaryAddress, address.port);
//log(L"Client connected - sending S_VERSION push to: %x:%i", address.binaryAddress, address.port);
Server::getSingleton().SendMessage<NetworkMessages::Version>(address, S_VERSION, &msgVersion);
}
}
void TLMP::ServerOnClientDisconnect(void *arg)
{
if (arg) {
SystemAddress address = *(SystemAddress *)arg;
multiplayerLogger.WriteLine(Info, L"Client disconnected: %x:%i", address.binaryAddress, address.port);
//log(L"Client disconnected: %x:%i", address.binaryAddress, address.port);
}
// TODO: Cleanup client characters.
}
// --
// Client Events
void TLMP::ClientOnConnect(void *arg)
{
if (arg) {
SystemAddress address = *(SystemAddress *)arg;
multiplayerLogger.WriteLine(Info, L"Client connected: %x:%i", address.binaryAddress, address.port);
//log(L"Client connected: %x:%i", address.binaryAddress, address.port);
}
}
// --
void TLMP::WndProcPre(HWND handle, UINT msg, WPARAM wParam, LPARAM lParam)
{
/*
if (!(msg == 0x100 || msg == 0x101 || msg == 0x102 || msg == 0x201))
return;
switch (msg) {
case WM_KEYUP:
switch (wParam) {
// T =
// Testing Equipment creation and crashes on level cleanup
case 'E':
case 'e':
{
static CEquipment* mainHand = NULL;
static CEquipment* secondHand = NULL;
CInventory* inv = gameClient->pCPlayer->pCInventory;
CEquipment* tmp1 = inv->GetEquipmentFromSlot(0);
CEquipment* tmp2 = inv->GetEquipmentFromSlot(1);
CEquipmentRef* ref1 = inv->GetEquipmentRefFromEquipment(tmp1);
CEquipmentRef* ref2 = inv->GetEquipmentRefFromEquipment(tmp2);
log("ref1 = %p, ref2 = %p", ref1, ref2);
}
break;
}
*/
}
| [
"drivehappy@7af81de8-dd64-11de-95c9-073ad895b44c"
] | [
[
[
1,
3767
]
]
] |
2fca6a604a34e158170ecc9f8474e56303b9d1d6 | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/wsdlitems.hpp | 8c6b2f1c35d4a704099ac000c0177f4668e420c2 | [] | no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,435 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'WSDLItems.pas' rev: 6.00
#ifndef WSDLItemsHPP
#define WSDLItemsHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <HTTPUtil.hpp> // Pascal unit
#include <WSDLBind.hpp> // Pascal unit
#include <WSDLIntf.hpp> // Pascal unit
#include <msxmldom.hpp> // Pascal unit
#include <XMLSchema.hpp> // Pascal unit
#include <xmldom.hpp> // Pascal unit
#include <XMLDoc.hpp> // Pascal unit
#include <XMLIntf.hpp> // Pascal unit
#include <TypInfo.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <Variants.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Wsdlitems
{
//-- type declarations -------------------------------------------------------
__interface IWSDLItems;
typedef System::DelphiInterface<IWSDLItems> _di_IWSDLItems;
class DELPHICLASS TWSDLItems;
__interface INTERFACE_UUID("{F71B4B05-C5AB-4484-B994-64F3F9E805C7}") IWSDLItems : public IInterface
{
public:
virtual TWSDLItems* __fastcall GetWSDLItems(void) = 0 ;
virtual Wsdlbind::_di_IWSDLDocument __fastcall GetWSDLDoc(void) = 0 ;
virtual void __fastcall Load(const WideString WSDLFileName) = 0 ;
};
__interface IQualifiedName;
typedef System::DelphiInterface<IQualifiedName> _di_IQualifiedName;
__interface INTERFACE_UUID("{0173ABA2-34AB-4CB1-ADF0-AA99C98FCFBD}") IQualifiedName : public IInterface
{
public:
virtual WideString __fastcall GetName(void) = 0 ;
virtual void __fastcall SetName(const WideString name) = 0 ;
virtual WideString __fastcall GetNamespace(void) = 0 ;
virtual void __fastcall SetNamespace(const WideString ns) = 0 ;
__property WideString Name = {read=GetName, write=SetName};
__property WideString Namespace = {read=GetNamespace, write=SetNamespace};
};
#pragma option push -b-
enum IterateImportOptions { ioBeforeLoad, ioLoaded };
#pragma option pop
typedef void __fastcall (__closure *TWSDLIterateProc)(const IterateImportOptions Options, const _di_IWSDLItems WSDLItems, const Xmlschema::_di_IXMLSchemaDoc XMLSchemaDoc, const WideString Name);
class PASCALIMPLEMENTATION TWSDLItems : public Wsdlbind::TWSDLDocument
{
typedef Wsdlbind::TWSDLDocument inherited;
private:
Httputil::_di_IStreamLoader FWSDLStreamLoader;
WideString __fastcall GetGenericBindingAttribute(const WideString BindingName, const WideString NodeName, const WideString Namespace, WideString Attribute);
WideString __fastcall MakeTNSName(const WideString Name);
public:
__fastcall virtual TWSDLItems(Classes::TComponent* AOwner)/* overload */;
__fastcall virtual TWSDLItems(const TWSDLItems* WSDLItems, const Httputil::_di_IStreamLoader StreamLoader)/* overload */;
TWSDLItems* __fastcall GetWSDLItems(void);
Wsdlbind::_di_IWSDLDocument __fastcall GetWSDLDoc();
void __fastcall Load(const WideString WSDLFileName);
bool __fastcall CompareName(const WideString NodeName, const WideString OtherName, const WideString TNS = L"");
WideString __fastcall GetName();
WideString __fastcall GetTargetNamespace();
WideString __fastcall GetTargetNamespacePrefix();
void __fastcall GetServices(Wsdlintf::TWideStrings* ServiceNames, bool QualifiedNames = false);
Xmlintf::_di_IXMLNode __fastcall GetServiceNode(const WideString ServiceName);
void __fastcall GetMessages(Wsdlintf::TWideStrings* MessageNames, bool QualifiedNames = false);
Xmlintf::_di_IXMLNode __fastcall GetMessageNode(const WideString MessageName);
void __fastcall GetParts(const WideString MessageName, Wsdlintf::TWideStrings* PartNames, bool QualifiedNames = false);
Xmlintf::_di_IXMLNode __fastcall GetPartNode(const WideString MessageName, const WideString PartName);
void __fastcall GetPortTypes(Wsdlintf::TWideStrings* PortTypeNames, bool SkipHttpBindings = true, bool QualifiedNames = false);
Xmlintf::_di_IXMLNode __fastcall GetPortTypeNode(const WideString PortTypeName);
void __fastcall GetOperations(const WideString PortTypeName, Wsdlintf::TWideStrings* OperationNames, bool QualifiedNames = false);
Xmlintf::_di_IXMLNode __fastcall GetOperationNode(const WideString PortTypeName, const WideString OperationName);
void __fastcall GetPortsForService(const WideString ServiceName, Wsdlintf::TWideStrings* PortNames, bool SkipHttpBindings = true, bool QualifiedNames = false);
_di_IQualifiedName __fastcall GetBindingForServicePort(const WideString ServiceName, const WideString PortName);
bool __fastcall GetServiceAndPortOfBinding(const _di_IQualifiedName BindingName, WideString &ServiceName, WideString &PortName);
WideString __fastcall GetSoapAddressForServicePort(const WideString ServiceName, const WideString PortName);
void __fastcall GetImports(Wsdlintf::TWideStrings* ImportNames);
void __fastcall IterateImports(TWSDLIterateProc IterateProc);
WideString __fastcall GetLocationForImport(const WideString ImportNameSpace);
bool __fastcall HasTypesNode(void);
void __fastcall GetSchemas(Wsdlintf::TWideStrings* SchemaNames);
Xmlintf::_di_IXMLNode __fastcall GetSchemaNode(const WideString SchemaTns);
void __fastcall GetBindings(Wsdlintf::TWideStrings* BindingNames, bool QualifiedNames = false);
WideString __fastcall GetBindingType(const WideString BindingName);
_di_IQualifiedName __fastcall GetBindingOfType(const WideString BindingTypeName, const WideString TNS = L"");
WideString __fastcall GetSoapBindingAttribute(const WideString BindingName, WideString Attribute);
WideString __fastcall GetHttpBindingAttribute(const WideString BindingName, WideString Attribute)/* overload */;
WideString __fastcall GetHttpBindingAttribute(const _di_IQualifiedName QualifiedName, WideString Attribute)/* overload */;
void __fastcall GetOperationsForBinding(const WideString BindingName, Wsdlintf::TWideStrings* OperationNames, bool QualifiedNames = false);
WideString __fastcall GetSoapOperationAttribute(const WideString BindingName, const WideString Operation, const WideString Attribute);
WideString __fastcall GetSoapAction(const WideString BindingName, const WideString Operation);
WideString __fastcall GetSoapOperationStyle(const WideString BindingName, const WideString Operation);
void __fastcall GetSoapActionList(const WideString BindingName, Wsdlintf::TWideStrings* ActionList, bool QualifiedNames = false);
WideString __fastcall GetSoapBodyAttribute(const WideString BindingName, const WideString Operation, const WideString IOType, const WideString Attribute);
WideString __fastcall GetSoapBodyInputAttribute(const WideString BindingName, const WideString Operation, const WideString Attribute);
WideString __fastcall GetSoapBodyOutputAttribute(const WideString BindingName, const WideString Operation, const WideString Attribute);
WideString __fastcall GetSoapBodyNamespace(const WideString BindingPortType);
bool __fastcall GetPartsForOperation(const WideString PortTypeName, const WideString OperationName, int OperationIndex, Wsdlintf::TWideStrings* PartNames);
__property Httputil::_di_IStreamLoader StreamLoader = {read=FWSDLStreamLoader};
__property WideString TargetNamespace = {read=GetTargetNamespace};
public:
#pragma option push -w-inl
/* TXMLDocument.Destroy */ inline __fastcall virtual ~TWSDLItems(void) { }
#pragma option pop
private:
void *__IWSDLItems; /* Wsdlitems::IWSDLItems */
public:
operator IWSDLItems*(void) { return (IWSDLItems*)&__IWSDLItems; }
};
//-- var, const, procedure ---------------------------------------------------
extern PACKAGE _di_IQualifiedName __fastcall NewQualifiedName(const WideString Name = L"", const WideString Namespace = L"");
extern PACKAGE bool __fastcall HasDefinition(const Wsdlbind::_di_IWSDLDocument WSDLDoc)/* overload */;
extern PACKAGE bool __fastcall HasDefinition(const _di_IWSDLItems WSDLItems)/* overload */;
} /* namespace Wsdlitems */
using namespace Wsdlitems;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // WSDLItems
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
] | [
[
[
1,
150
]
]
] |
68191155833fa8a853a9a8d07413d1b6c8fd0fec | 956e0201a3627226744a63075ea7b45dbf05208b | /GumShot/src/StandardFrameListener.cpp | 06fdc93d3257e7f386cadea36fb1806376fb85fc | [] | no_license | bogba1/gumshot | acd0e0f6aab5f7f8898e65dbafd924c0f3aded43 | d7f13866044f2d1a63566a3d3a5f9bae089ee746 | refs/heads/master | 2021-01-18T15:08:42.685134 | 2010-03-08T03:29:50 | 2010-03-08T03:29:50 | 40,660,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,215 | cpp | #include "StandardFrameListener.h"
//---------------------------------------------------------------------------
void StandardFrameListener::updateStats(void)
{
static String currFps = "Current FPS: ";
static String avgFps = "Average FPS: ";
static String bestFps = "Best FPS: ";
static String worstFps = "Worst FPS: ";
static String tris = "Triangle Count: ";
static String batches = "Batch Count: ";
// update stats when necessary
try
{
OverlayElement* guiAvg = OverlayManager::getSingleton().getOverlayElement("Core/AverageFps");
OverlayElement* guiCurr = OverlayManager::getSingleton().getOverlayElement("Core/CurrFps");
OverlayElement* guiBest = OverlayManager::getSingleton().getOverlayElement("Core/BestFps");
OverlayElement* guiWorst = OverlayManager::getSingleton().getOverlayElement("Core/WorstFps");
const RenderTarget::FrameStats& stats = mWindow->getStatistics();
guiAvg->setCaption(avgFps + StringConverter::toString(stats.avgFPS));
guiCurr->setCaption(currFps + StringConverter::toString(stats.lastFPS));
guiBest->setCaption(bestFps + StringConverter::toString(stats.bestFPS) + " " + StringConverter::toString(stats.bestFrameTime) + " ms");
guiWorst->setCaption(worstFps + StringConverter::toString(stats.worstFPS) + " " + StringConverter::toString(stats.worstFrameTime) + " ms");
OverlayElement* guiTris = OverlayManager::getSingleton().getOverlayElement("Core/NumTris");
guiTris->setCaption(tris + StringConverter::toString(stats.triangleCount));
OverlayElement* guiBatches = OverlayManager::getSingleton().getOverlayElement("Core/NumBatches");
guiBatches->setCaption(batches + StringConverter::toString(stats.batchCount));
OverlayElement* guiDbg = OverlayManager::getSingleton().getOverlayElement("Core/DebugText");
guiDbg->setCaption(mDebugText);
}
catch(...)
{
/* ignore */
}
}
//---------------------------------------------------------------------------
// Constructor takes a RenderWindow because it uses that to determine input context
StandardFrameListener::StandardFrameListener(RenderWindow* win, Camera* cam, bool bufferedKeys, bool bufferedMouse, bool bufferedJoy )
:
mCamera(cam), mTranslateVector(Vector3::ZERO), mCurrentSpeed(0), mWindow(win), mStatsOn(true), mNumScreenShots(0),
mMoveScale(0.0f), mRotScale(0.0f), mTimeUntilNextToggle(0), mFiltering(TFO_BILINEAR),
mAniso(1), mSceneDetailIndex(0), mMoveSpeed(100), mRotateSpeed(36), mDebugOverlay(0),
mInputManager(0), mMouse(0), mKeyboard(0), mJoy(0)
{
mDebugOverlay = OverlayManager::getSingleton().getByName("Core/DebugOverlay");
LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
OIS::ParamList pl;
size_t windowHnd = 0;
std::ostringstream windowHndStr;
win->getCustomAttribute("WINDOW", &windowHnd);
windowHndStr << windowHnd;
pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
mInputManager = OIS::InputManager::createInputSystem( pl );
//Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse)
mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, bufferedKeys ));
mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, bufferedMouse ));
try
{
mJoy = static_cast<OIS::JoyStick*>(mInputManager->createInputObject( OIS::OISJoyStick, bufferedJoy ));
}
catch(...)
{
mJoy = 0;
}
//Set initial mouse clipping size
windowResized(mWindow);
showDebugOverlay(true);
//Register as a Window listener
WindowEventUtilities::addWindowEventListener(mWindow, this);
}
//---------------------------------------------------------------------------
//Adjust mouse clipping area
void StandardFrameListener::windowResized(RenderWindow* rw)
{
unsigned int width, height, depth;
int left, top;
rw->getMetrics(width, height, depth, left, top);
const OIS::MouseState &ms = mMouse->getMouseState();
ms.width = width;
ms.height = height;
}
//---------------------------------------------------------------------------
//Unattach OIS before window shutdown (very important under Linux)
void StandardFrameListener::windowClosed(RenderWindow* rw)
{
//Only close for window that created OIS (the main window in these demos)
if( rw == mWindow )
{
if( mInputManager )
{
mInputManager->destroyInputObject( mMouse );
mInputManager->destroyInputObject( mKeyboard );
mInputManager->destroyInputObject( mJoy );
OIS::InputManager::destroyInputSystem(mInputManager);
mInputManager = 0;
}
}
}
//---------------------------------------------------------------------------
StandardFrameListener::~StandardFrameListener()
{
//Remove ourself as a Window listener
WindowEventUtilities::removeWindowEventListener(mWindow, this);
windowClosed(mWindow);
}
//---------------------------------------------------------------------------
bool StandardFrameListener::processUnbufferedKeyInput(const FrameEvent& evt)
{
if(mKeyboard->isKeyDown(OIS::KC_A))
mTranslateVector.x = -mMoveScale; // Move camera left
if(mKeyboard->isKeyDown(OIS::KC_D))
mTranslateVector.x = mMoveScale; // Move camera RIGHT
if(mKeyboard->isKeyDown(OIS::KC_UP) || mKeyboard->isKeyDown(OIS::KC_W) )
mTranslateVector.z = -mMoveScale; // Move camera forward
if(mKeyboard->isKeyDown(OIS::KC_DOWN) || mKeyboard->isKeyDown(OIS::KC_S) )
mTranslateVector.z = mMoveScale; // Move camera backward
if(mKeyboard->isKeyDown(OIS::KC_PGUP))
mTranslateVector.y = mMoveScale; // Move camera up
if(mKeyboard->isKeyDown(OIS::KC_PGDOWN))
mTranslateVector.y = -mMoveScale; // Move camera down
if(mKeyboard->isKeyDown(OIS::KC_RIGHT))
mCamera->yaw(-mRotScale);
if(mKeyboard->isKeyDown(OIS::KC_LEFT))
mCamera->yaw(mRotScale);
if( mKeyboard->isKeyDown(OIS::KC_ESCAPE) || mKeyboard->isKeyDown(OIS::KC_Q) )
return false;
if( mKeyboard->isKeyDown(OIS::KC_F) && mTimeUntilNextToggle <= 0 )
{
mStatsOn = !mStatsOn;
showDebugOverlay(mStatsOn);
mTimeUntilNextToggle = 1;
}
if( mKeyboard->isKeyDown(OIS::KC_T) && mTimeUntilNextToggle <= 0 )
{
switch(mFiltering)
{
case TFO_BILINEAR:
mFiltering = TFO_TRILINEAR;
mAniso = 1;
break;
case TFO_TRILINEAR:
mFiltering = TFO_ANISOTROPIC;
mAniso = 8;
break;
case TFO_ANISOTROPIC:
mFiltering = TFO_BILINEAR;
mAniso = 1;
break;
default: break;
}
MaterialManager::getSingleton().setDefaultTextureFiltering(mFiltering);
MaterialManager::getSingleton().setDefaultAnisotropy(mAniso);
showDebugOverlay(mStatsOn);
mTimeUntilNextToggle = 1;
}
if(mKeyboard->isKeyDown(OIS::KC_SYSRQ) && mTimeUntilNextToggle <= 0)
{
std::ostringstream ss;
ss << "screenshot_" << ++mNumScreenShots << ".png";
mWindow->writeContentsToFile(ss.str());
mTimeUntilNextToggle = 0.5;
mDebugText = "Saved: " + ss.str();
}
if(mKeyboard->isKeyDown(OIS::KC_R) && mTimeUntilNextToggle <=0)
{
mSceneDetailIndex = (mSceneDetailIndex+1)%3 ;
switch(mSceneDetailIndex) {
case 0 : mCamera->setPolygonMode(PM_SOLID); break;
case 1 : mCamera->setPolygonMode(PM_WIREFRAME); break;
case 2 : mCamera->setPolygonMode(PM_POINTS); break;
}
mTimeUntilNextToggle = 0.5;
}
static bool displayCameraDetails = false;
if(mKeyboard->isKeyDown(OIS::KC_P) && mTimeUntilNextToggle <= 0)
{
displayCameraDetails = !displayCameraDetails;
mTimeUntilNextToggle = 0.5;
if (!displayCameraDetails)
mDebugText = "";
}
// Print camera details
if(displayCameraDetails)
mDebugText = "P: " + StringConverter::toString(mCamera->getDerivedPosition());// + " " + "O: " + StringConverter::toString(mCamera->getDerivedOrientation());
// Return true to continue rendering
return true;
}
//---------------------------------------------------------------------------
bool StandardFrameListener::processUnbufferedMouseInput(const FrameEvent& evt)
{
// Rotation factors, may not be used if the second mouse button is pressed
// 2nd mouse button - slide, otherwise rotate
const OIS::MouseState &ms = mMouse->getMouseState();
if( ms.buttonDown( OIS::MB_Right ) )
{
mTranslateVector.x += ms.X.rel * 0.13;
mTranslateVector.y -= ms.Y.rel * 0.13;
}
else
{
mRotX = Degree(-ms.X.rel * 0.13);
mRotY = Degree(-ms.Y.rel * 0.13);
}
return true;
}
//---------------------------------------------------------------------------
void StandardFrameListener::moveCamera()
{
// Make all the changes to the camera
// Note that YAW direction is around a fixed axis (freelook style) rather than a natural YAW
//(e.g. airplane)
mCamera->yaw(mRotX);
mCamera->pitch(mRotY);
mCamera->moveRelative(mTranslateVector);
}
//---------------------------------------------------------------------------
void StandardFrameListener::showDebugOverlay(bool show)
{
if (mDebugOverlay)
{
if (show)
mDebugOverlay->show();
else
mDebugOverlay->hide();
}
}
//---------------------------------------------------------------------------
// Override frameRenderingQueued event to process that (don't care about frameEnded)
bool StandardFrameListener::frameRenderingQueued(const FrameEvent& evt)
{
if(mWindow->isClosed()) return false;
mSpeedLimit = mMoveScale * evt.timeSinceLastFrame;
//Need to capture/update each device
mKeyboard->capture();
mMouse->capture();
if( mJoy ) mJoy->capture();
bool buffJ = (mJoy) ? mJoy->buffered() : true;
Ogre::Vector3 lastMotion = mTranslateVector;
//Check if one of the devices is not buffered
if( !mMouse->buffered() || !mKeyboard->buffered() || !buffJ )
{
// one of the input modes is immediate, so setup what is needed for immediate movement
if (mTimeUntilNextToggle >= 0)
mTimeUntilNextToggle -= evt.timeSinceLastFrame;
// Move about 100 units per second
mMoveScale = mMoveSpeed * evt.timeSinceLastFrame;
// Take about 10 seconds for full rotation
mRotScale = mRotateSpeed * evt.timeSinceLastFrame;
mRotX = 0;
mRotY = 0;
mTranslateVector = Ogre::Vector3::ZERO;
}
//Check to see which device is not buffered, and handle it
if( !mKeyboard->buffered() )
if( processUnbufferedKeyInput(evt) == false )
return false;
if( !mMouse->buffered() )
if( processUnbufferedMouseInput(evt) == false )
return false;
// ramp up / ramp down speed
if (mTranslateVector == Ogre::Vector3::ZERO)
{
// decay (one third speed)
mCurrentSpeed -= evt.timeSinceLastFrame * 0.3;
mTranslateVector = lastMotion;
}
else
{
// ramp up
mCurrentSpeed += evt.timeSinceLastFrame;
}
// Limit motion speed
if (mCurrentSpeed > 1.0)
mCurrentSpeed = 1.0;
if (mCurrentSpeed < 0.0)
mCurrentSpeed = 0.0;
mTranslateVector *= mCurrentSpeed;
if( !mMouse->buffered() || !mKeyboard->buffered() || !buffJ )
moveCamera();
return true;
}
//---------------------------------------------------------------------------
bool StandardFrameListener::frameEnded(const FrameEvent& evt)
{
updateStats();
return true;
}
| [
"[email protected]"
] | [
[
[
1,
350
]
]
] |
79562eb1cacf49fc2c553529dbb52138ce2902a6 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/serialization/test/test_derived.cpp | 5e78e4085717eaa4dda81216b89679cd9196e0df | [] | no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,453 | cpp | /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_derived.cpp
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// should pass compilation and execution
#include <fstream>
#include <cstdio> // remove
#include <boost/config.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::remove;
}
#endif
#include <boost/archive/archive_exception.hpp>
#include "test_tools.hpp"
#include <boost/serialization/base_object.hpp>
class base
{
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & /* ar */, const unsigned int /* file_version */){
}
};
class derived1 : public base
{
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int /* file_version */){
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(base);
}
};
class derived2 : public base
{
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int /* file_version */){
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(base);
}
};
// save non-polymorphic classes through a base class pointer
void save_derived(const char *testfile)
{
test_ostream os(testfile, TEST_STREAM_FLAGS);
test_oarchive oa(os);
// registration not necessary when serializing the most derived pointer
derived1 *d1 = new derived1;
derived2 *d2 = new derived2;
oa << BOOST_SERIALIZATION_NVP(d1) << BOOST_SERIALIZATION_NVP(d2);
// upcasting non-polymorphic pointers may not lead to the expected
// result. In the current type id system
base *b1 = d1;
base *b2 = d2;
// Warning, the current type id system does not yield true
// type id for non-polymorphic types
const boost::serialization::extended_type_info & this_type
= * boost::serialization::type_info_implementation<base>::type
::get_instance();
// retrieve the true type of the object pointed to
const boost::serialization::extended_type_info & true_type
= * boost::serialization::type_info_implementation<base>::type
::get_derived_extended_type_info(*b1);
BOOST_WARN_MESSAGE(
(this_type != true_type),
"current type id system does not support non-polymorphic types"
);
oa << BOOST_SERIALIZATION_NVP(b1);
oa << BOOST_SERIALIZATION_NVP(b2);
delete d1;
delete d2;
}
// save non-polymorphic classes through a base class pointer
void load_derived(const char *testfile)
{
test_istream is(testfile, TEST_STREAM_FLAGS);
test_iarchive ia(is);
// registration not necessary when serializing the most derived pointer
derived1 *d1 = NULL;
derived2 *d2 = NULL;
ia >> BOOST_SERIALIZATION_NVP(d1) >> BOOST_SERIALIZATION_NVP(d2);
// upcasting non-polymorphic pointers may not lead to the expected
// result. In the current type id system
base *b1 = NULL;
base *b2 = NULL;
// Warning, the current type id system does not yield true
// type id for non-polymorphic types
const boost::serialization::extended_type_info & this_type
= * boost::serialization::type_info_implementation<base>::type
::get_instance();
// retrieve the true type of the object pointed to
const boost::serialization::extended_type_info & true_type
= * boost::serialization::type_info_implementation<base>::type
::get_derived_extended_type_info(*b1);
BOOST_WARN_MESSAGE(
this_type != true_type,
"current type id system does fails for non-polymorphic types"
);
// note: this will produce incorrect results for non-polymorphic classes
ia >> BOOST_SERIALIZATION_NVP(b1);
ia >> BOOST_SERIALIZATION_NVP(b2);
delete d1;
delete d2;
}
int
test_main( int /* argc */, char* /* argv */[] )
{
const char * testfile = boost::archive::tmpnam(NULL);
BOOST_REQUIRE(NULL != testfile);
save_derived(testfile);
load_derived(testfile);
std::remove(testfile);
return boost::exit_success;
}
// EOF
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
141
]
]
] |
9238a268fa4e82fe7d400ca470e59f77e99cbe73 | 8f828231b15af1203c30cac311dbbd166f9f743f | /hellocairo/myappview.h | 399ff77b46a4b37d686ffa4ff4950af87024d622 | [] | no_license | d3ru/cairo-for-symbian | 07a1e4ceeb433ab7bc3485134903f123884e1939 | 1031d4d020701003161f19e207b32324d89cf8b6 | refs/heads/master | 2016-08-11T14:19:16.881139 | 2009-03-15T14:00:11 | 2009-03-15T14:00:11 | 36,205,677 | 0 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,988 | h | /*
* Copyright © 2009 [email protected]
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting documentation, and
* that the name of the copyright holders not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no representations
* about the suitability of this software for any purpose. It is provided "as
* is" without express or implied warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#ifndef __MYAPPVIEW_H__
#define __MYAPPVIEW_H__
#include <e32base.h>
#include <coecntrl.h>
#include <cairo.h>
class CMyAppView : public CCoeControl
{
friend class CMyAppUi;
public:
static CMyAppView* NewL(const TRect& aRect);
static CMyAppView* NewLC(const TRect& aRect);
virtual ~CMyAppView();
void Draw(const TRect& aRect) const;
virtual void SizeChanged();
static TInt TimerCallBack(TAny* aArg);
void Start();
void Stop();
private:
void ConstructL(const TRect& aRect);
CMyAppView();
cairo_t* Context() const {return iContext;}
private:
CPeriodic* iTimer;
mutable TInt iIdx;
TInt iNumberOfSamples;
TBool iStarted;
cairo_surface_t* iSurface;
cairo_t* iContext;
};
#endif
| [
"[email protected]@a20834f0-d954-11dd-a2b5-e5f827957e07"
] | [
[
[
1,
62
]
]
] |
3c546d93466791a623be1b9b9f98abad4826187a | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.2/bctestpreviewpopup/src/bctestpreviewpopupdocument.cpp | f890dd231d6cb7c02294f73eb41f599c5df426b9 | [] | no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,307 | cpp | /*
* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Avkon PreviewPopup test application
*
*/
// INCLUDE FILES
#include "BCTestPreviewPopupDocument.h"
#include "BCTestPreviewPopupAppUi.h"
// ================= MEMBER FUNCTIONS =========================================
// ----------------------------------------------------------------------------
// CBCTestPreviewPopupDocument* CBCTestPreviewPopupDocument::NewL( CEikApplication& )
// Symbian OS two-phased constructor.
// ----------------------------------------------------------------------------
//
CBCTestPreviewPopupDocument* CBCTestPreviewPopupDocument::NewL( CEikApplication& aApp )
{
CBCTestPreviewPopupDocument* self = new( ELeave ) CBCTestPreviewPopupDocument( aApp );
return self;
}
// ----------------------------------------------------------------------------
// CBCTestPreviewPopupDocument::~CBCTestPreviewPopupDocument()
// Destructor.
// ----------------------------------------------------------------------------
//
CBCTestPreviewPopupDocument::~CBCTestPreviewPopupDocument()
{
}
// ----------------------------------------------------------------------------
// CBCTestPreviewPopupDocument::CBCTestPreviewPopupDocument( CEikApplication& )
// Overload constructor.
// ----------------------------------------------------------------------------
//
CBCTestPreviewPopupDocument::CBCTestPreviewPopupDocument( CEikApplication& aApp )
: CEikDocument( aApp )
{
}
// ----------------------------------------------------------------------------
// CEikAppUi* CBCTestPreviewPopupDocument::CreateAppUiL()
// Constructs CBCTestVolumeAppUi.
// ----------------------------------------------------------------------------
//
CEikAppUi* CBCTestPreviewPopupDocument::CreateAppUiL()
{
return new( ELeave ) CBCTestPreviewPopupAppUi;
}
// End of File
| [
"none@none"
] | [
[
[
1,
65
]
]
] |
8bd6e94783c983a68cb830cc979f1b3fa120c240 | 1585c7e187eec165138edbc5f1b5f01d3343232f | /LabActive/LabActive/stdafx.cpp | 216af5109a697807575eecb6370428d7c8bcc330 | [] | no_license | a-27m/vssdb | c8885f479a709dd59adbb888267a03fb3b0c3afb | d86944d4d93fd722e9c27cb134256da16842f279 | refs/heads/master | 2022-08-05T06:50:12.743300 | 2011-06-23T08:35:44 | 2011-06-23T08:35:44 | 82,612,001 | 1 | 0 | null | 2021-03-29T08:05:33 | 2017-02-20T23:07:03 | C# | UTF-8 | C++ | false | false | 207 | cpp | // stdafx.cpp : source file that includes just the standard includes
// LabActive.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"Axell@bf672a44-3a04-1d4a-850b-c2a239875c8c"
] | [
[
[
1,
5
]
]
] |
8fe9b7a4a096161e6417085ad48bd80b54e6ab7f | 317f62189c63646f81198d1692bed708d8f18497 | /contrib/orion/Wire.h | 6ade72190fc550e12bd223af4ef9ec3e27788f88 | [
"MIT"
] | permissive | mit-carbon/Graphite-Cycle-Level | 8fb41d5968e0a373fd4adbf0ad400a9aa5c10c90 | db3f1e986ddc10f3e5f3a5d4b68bd6a9885969b3 | refs/heads/master | 2021-01-25T07:08:46.628355 | 2011-11-23T08:53:18 | 2011-11-23T08:53:18 | 1,930,686 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,248 | h | #ifndef __WIRE_H__
#define __WIRE_H__
#include "Type.h"
class TechParameter;
class Wire
{
public:
enum WidthSpacingModel
{
SWIDTH_SSPACE,
SWIDTH_DSPACE,
DWIDTH_SSPACE,
DWIDTH_DSPACE
};
enum BufferScheme
{
MIN_DELAY,
STAGGERED
};
public:
Wire(
const string& wire_spacing_model_str_,
const string& buf_scheme_str_,
bool is_shielding_,
const TechParameter* tech_param_ptr_
);
~Wire();
public:
void calc_opt_buffering(int* k_, double* h_, double len_) const;
double calc_dynamic_energy(double len_) const;
double calc_static_power(double len_) const;
private:
void init();
void set_width_spacing_model(const string& wire_spacing_model_str_);
void set_buf_scheme(const string& buf_scheme_str_);
double calc_res_unit_len();
double calc_gnd_cap_unit_len();
double calc_couple_cap_unit_len();
private:
const TechParameter* m_tech_param_ptr;
WidthSpacingModel m_width_spacing_model;
BufferScheme m_buf_scheme;
bool m_is_shielding;
double m_res_unit_len;
double m_gnd_cap_unit_len;
double m_couple_cap_unit_len;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
57
]
]
] |
08771f7c175d418bca08b38fff539b4cbd0a67ca | edc1580926ff41a9c4e1eb1862bbdd7ce7fa46f9 | /IMesh/IMesh.UI/HDTimer.cpp | 85dfbf46e79f215f807b39562f88eaa6ba41ae89 | [] | no_license | bolitt/imesh-thu | 40209b89393981fa6bd6ed3c7f5cc367829bd913 | 477204edee0f387e92eec5e92283fb4233cbdcb3 | refs/heads/master | 2021-01-01T05:31:36.652001 | 2010-12-26T14:35:28 | 2010-12-26T14:35:28 | 32,119,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | cpp | #include "StdAfx.h"
#include "HDTimer.h"
namespace IMesh { namespace UI {
HDTimer::HDTimer(void)
{
QueryPerformanceFrequency(&m_freq);
MS_PER_TICK = 1000.0 / m_freq.QuadPart;
}
HDTimer::~HDTimer(void)
{
}
} }
| [
"bolitt@13b8c736-bc73-099a-6f45-29f97c997e63"
] | [
[
[
1,
19
]
]
] |
430455676caf433da7ae32efdc92e57cbf879cb5 | 7eb81dd252c71766e047eaf6c0a78549b3eeee20 | /branches/problem-branch/trunk/src/egmg/Stencil/MSV2D4.cpp | 8af8ae56d42c5088aaac7cde6232bb6173e3c035 | [] | no_license | BackupTheBerlios/egmg-svn | 1325afce712567c99bd7601e24c6cac44a032905 | 71d770fc123611de8a62d2cabf4134e783dbae49 | refs/heads/master | 2021-01-01T15:18:37.469550 | 2007-04-30T11:31:27 | 2007-04-30T11:31:27 | 40,614,587 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,444 | cpp | /** \file MSV2D4.cpp
* \author <a href="mailto:[email protected]">Jiri Kraus</a>
* \brief Contains the implementation of the class MSV2D4
*/
#include "MSV2D4.h"
namespace mg
{
PositionArray MSV2D4::initJx_() const
{
const int t[]={0,-1,0,1,0,-1,1,-1,1};
return PositionArray(t,9);
}
PositionArray MSV2D4::initJy_() const
{
const int t[]={0,0,1,0,-1,-1,-1,1,1};
return PositionArray(t,9);
}
MSV2D4::MSV2D4( Precision ax, Precision ay )
: jx_( initJx_() ), jy_( initJy_() ),
ax_( ax ), ay_( ay )
{}
MSV2D4::~MSV2D4() {}
Precision MSV2D4::apply(
const NumericArray& u,
const Position,
const Index sx,
const Index sy,
const Index nx,
const Index ny) const
{
return
((20.0*nx*nx+20.0*ny*ny)/12.0)*u[sy*(nx+1)+sx]
-10.0*nx*nx/12.0*u[sy*(nx+1)+sx-1]
-10.0*nx*nx/12.0*u[sy*(nx+1)+sx+1]
-10.0*ny*ny/12.0*u[sy*(nx+1)+sx-(nx+1)]
-10.0*ny*ny/12.0*u[sy*(nx+1)+sx+(nx+1)]
+2.0*nx*nx/12.0*u[sy*(nx+1)+sx-(nx+1)]
+2.0*nx*nx/12.0*u[sy*(nx+1)+sx+(nx+1)]
+2.0*ny*ny/12.0*u[sy*(nx+1)+sx-1]
+2.0*ny*ny/12.0*u[sy*(nx+1)+sx+1]
-1.0*nx*nx/12.0*
( u[sy*(nx+1)+sx-(nx+1)-1]+u[sy*(nx+1)+sx-(nx+1)+1]
+u[sy*(nx+1)+sx+(nx+1)-1]+u[sy*(nx+1)+sx+(nx+1)+1])
-1.0*ny*ny/12.0*
( u[sy*(nx+1)+sx-(nx+1)-1]+u[sy*(nx+1)+sx-(nx+1)+1]
+u[sy*(nx+1)+sx+(nx+1)-1]+u[sy*(nx+1)+sx+(nx+1)+1]);
}
Precision MSV2D4::getCenter(
const Position,
const Index,
const Index,
const Index nx,
const Index ny) const
{
return (20.0*nx*nx+20.0*ny*ny)/12.0;
}
NumericArray MSV2D4::getL(
const Position,
const Index,
const Index,
const Index nx,
const Index ny) const
{
NumericArray result( 0.0, 9 );
result[0]=20.0*nx*nx/12+20.0*ny*ny/12;
result[1]=result[3]=-10.0*nx*nx/12+2.0*ny*ny/12;
result[2]=result[4]=-10.0*ny*ny/12+2.0*nx*nx/12;
result[5]=result[6]=result[7]=result[8]=-1.0*nx*nx/12-1.0*ny*ny/12;
return result;
}
PositionArray MSV2D4::getJx(
const Position,
const Index,
const Index ) const
{
return jx_;
}
PositionArray MSV2D4::getJy(
const Position,
const Index,
const Index ) const
{
return jy_;
}
Index MSV2D4::size() const
{
return 1;
}
bool MSV2D4::isConstant() const
{
return true;
}
}
| [
"jirikraus@c8ad9165-030d-0410-b95e-c1df97c73749"
] | [
[
[
1,
107
]
]
] |
f2da09abe8ceb61c1e360ba9026779902158ab0b | eb869f3bc7728e55b5bd6ab2ad5f2a25e7f2a0a6 | /MustiEmu[PC]/MustiEmuchild.h | d638e5eed623716ccb0d6a8e0b607b0dc032ec61 | [] | no_license | runforu/musti-emulator | 257420f505a519113fe7c529a3eaeda4e91d918c | 0254eb549e5e0ec8e8a0a4da796b5652268aa17c | refs/heads/master | 2020-05-19T07:49:09.924331 | 2010-11-30T06:28:37 | 2010-11-30T06:28:37 | 32,321,074 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,201 | h | /****************************************************************************
**
** Copyright (C) 2009 Du Hui.
**
****************************************************************************/
#ifndef MDICHILD_H
#define MDICHILD_H
#include <QTextEdit>
class MustiEmuChild : public QTextEdit
{
Q_OBJECT
public:
MustiEmuChild();
~MustiEmuChild();
void newFile();
bool loadFile(const QString &fileName);
bool save();
bool saveAs();
void pauseTrace();
void continueTrace();
void flush();
void addNewLine( QString &line );
bool saveFile(const QString &fileName);
QString userFriendlyCurrentFile();
QString currentFile() { return curFile; }
signals:
void toBeClosed();
protected:
void closeEvent(QCloseEvent *event);
public slots:
void clear();
private slots:
void documentWasModified();
private:
bool maybeSave();
void setCurrentFile(const QString &fileName);
QString strippedName(const QString &fullFileName);
QString curFile;
bool isUntitled;
bool isPaused;
QVector<QString> vecString;
int shownSize;
QFont *font;
};
#endif
| [
"[email protected]@c3ffc87a-496d-339f-d77d-193528aa0bc0"
] | [
[
[
1,
55
]
]
] |
b1367be218e4f7d25258264d88d559ac4d239f9d | 72fd180ada3f7a5cf19c1df38f0d25a8ac09a823 | /Tema1/mainwindow.h | 19e65c6f94e8a05dd5601648356a12ab447f2a3f | [] | no_license | alexflorea/CN | f137a2c73fa7175e300908e8f00a608555db9ef8 | 99dcc451a7eb8adbd71ae27791826dde1c5f3050 | refs/heads/master | 2016-09-06T19:20:31.284239 | 2011-04-10T09:18:15 | 2011-04-10T09:18:15 | 1,386,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 612 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <math.h>
#include <stdio.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void startP1();
void startP2();
void startP3();
private:
Ui::MainWindow *ui;
double u;
double PI;
double Double_PI;
private:
void calcU(bool);
void calcSin(double);
void calcCos(double);
double formatare(double);
};
#endif // MAINWINDOW_H
| [
"[email protected]",
"Alex@.(none)"
] | [
[
[
1,
4
],
[
8,
22
],
[
25,
27
],
[
37,
39
]
],
[
[
5,
7
],
[
23,
24
],
[
28,
36
]
]
] |
32f885d78478e0e0307867c8337b6cd98fc359fb | 20bf3095aa164d0d3431b73ead8a268684f14976 | /cpp-labs/S1-1.CPP | cf67a42ab9ded0375e5ea3506d10ba19428e4911 | [] | no_license | collage-lab/mcalab-cpp | eb5518346f5c3b7c1a96627c621a71cc493de76d | c642f1f009154424f243789014c779b9fc938ce4 | refs/heads/master | 2021-08-31T10:28:59.517333 | 2006-11-10T23:57:09 | 2006-11-10T23:57:21 | 114,954,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 118 | cpp | #include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<"\"\'C\' with classes\" ";
getch();
} | [
"[email protected]"
] | [
[
[
1,
9
]
]
] |
95cda4131d27bbcb263ec0d7a3479ca8194d6e1a | 507d733770b2f22ea6cebc2b519037a5fa3cceed | /gs2d/src/Platform/android/NativeCommandForwarder.h | 155af91079d0e4e394eae7d327eb72f36744377c | [] | no_license | andresan87/Torch | a3e7fa338a675b0e552afa914cb86050d641afeb | cecdbb9b4ea742b6f03e609f9445849a932ed755 | refs/heads/master | 2021-01-20T08:47:25.624168 | 2011-07-08T12:40:55 | 2011-07-08T12:40:55 | 2,014,722 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,408 | h | /*-----------------------------------------------------------------------
gameSpace2d (C) Copyright 2008-2011 Andre Santee
http://www.asantee.net/gamespace/
http://groups.google.com/group/gamespacelib
This file is part of gameSpace2d.
gameSpace2d is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
gameSpace2d is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with gameSpace2d. If not, see
<http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------*/
#ifndef NATIVE_COMMAND_FORWARDER_H_
#define NATIVE_COMMAND_FORWARDER_H_
#include "../../gs2dtypes.h"
namespace Platform {
class NativeCommandForwarder
{
protected:
gs2d::str_type::string m_commands;
NativeCommandForwarder();
void ForwardCommands(gs2d::str_type::string& out);
public:
void Command(const gs2d::str_type::string& commandSt, const bool onTop = false);
};
} // namespace Platform
#endif | [
"Andre@AndreDell.(none)"
] | [
[
[
1,
44
]
]
] |
ba35887a9eb75f66c1614d464c98b56f41bc078e | 51ebb9684ac1a4b65a5426e5c9ee79ebf8eb3db8 | /Windows/gclib/Config/ConfigApp.cpp | 04de4fa1027ebf55e190fa98a8bb4acc23635f29 | [] | no_license | buf1024/lgcbasic | d4dfe6a6bd19e4e4ac0e5ac2b7a0590e04dd5779 | 11db32c9be46d9ac0740429e09ebf880a7a00299 | refs/heads/master | 2021-01-10T12:55:12.046835 | 2011-09-03T15:45:57 | 2011-09-03T15:45:57 | 49,615,513 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,277 | cpp | ////////////////////////////////////////////////////////////////////////////////////////
//
// LGCBasic Project
//
// FileName : ConfigApp.cpp
// Purpose :
// Version : 2011-02-11 (20:23) 1.0 Created
// Author : heidong
// Contact : [email protected]
// Copyright(c): HEIDONG
////////////////////////////////////////////////////////////////////////////////////////
#include "Config.h"
#include "ConfigApp.h"
#include "tinyxml.h"
ConfigApp::ConfigApp(void)
{
}
ConfigApp::~ConfigApp(void)
{
for (ConfigAppIter iter = _mapConfigAppOpt.begin();
iter != _mapConfigAppOpt.end(); ++iter)
{
delete iter->second;
}
}
Config* ConfigApp::GetConfig(StdString strName)
{
Config* pConfig = NULL;
ConfigAppIter iter = _mapConfigAppOpt.find(strName);
if (iter != _mapConfigAppOpt.end())
{
pConfig = iter->second;
}
return pConfig;
}
void ConfigApp::AddConfig(Config* pConfig)
{
if (pConfig)
{
StdString strName = pConfig->GetName();
ConfigAppIter iter = _mapConfigAppOpt.find(strName);
if (iter != _mapConfigAppOpt.end())
{
if (pConfig != iter->second)
{
delete iter->second;
}
}
_mapConfigAppOpt[strName] = pConfig;
}
}
bool ConfigApp::RemoveConfig(StdString strName)
{
bool bRet = true;
ConfigAppIter iter = _mapConfigAppOpt.find(strName);
if (iter != _mapConfigAppOpt.end())
{
delete iter->second;
_mapConfigAppOpt.erase(iter);
}
return bRet;
}
bool ConfigApp::Load(StdString strFileName)
{
TiXmlDocument doc;
bool bOK = doc.LoadFile(GetAnsiString(strFileName));
if (!bOK) return false;
TiXmlHandle hDoc(&doc);
TiXmlElement* pElemRoot = NULL;
TiXmlElement* pElem = NULL;
//Root, ConfigApp
pElemRoot = hDoc.FirstChildElement().Element();
if (!pElemRoot) return false;
pElem = pElemRoot->FirstChildElement();
while(pElem)
{
//Config
const char* szConfName = pElem->Attribute("name");
if (!szConfName)
{
continue;
}
Config* pConfig = new Config(GetStdString(szConfName));
TiXmlElement* pElemConf = pElem->FirstChildElement();
while(pElemConf)
{
if (std::string(pElemConf->Value()) != std::string("Value"))
{
continue;
}
const char* szName = pElemConf->Attribute("name");
const char* szType = pElemConf->Attribute("type");
if (!szType || !szName)
{
continue;
}
StdString strName(GetStdString(szName));
const char *szValue = pElemConf->GetText();
std::string strValue = szValue == NULL ? "" : szValue;
if (std::string(szType) == "BOOL")
{
pConfig->AddBoolValue(strName, std::string(strValue) == "0" ? 0 : 1);
}
else if (std::string(szType) == "String")
{
pConfig->AddStringValue(strName, GetStdString(strValue));
}
else if (std::string(szType) == "DWORD")
{
pConfig->AddDWORDValue(strName, GetLongFromString(strValue));
}
pElemConf = pElemConf->NextSiblingElement();
}
AddConfig(pConfig);
pElem = pElem->NextSiblingElement();
}
return true;
}
bool ConfigApp::Save(StdString strFileName)
{
TiXmlDocument doc;
TiXmlDeclaration* pDecl = new TiXmlDeclaration("1.0", "utf-8", "yes");
TiXmlElement* pConfApp = new TiXmlElement("ConfigApp");
for (ConfigAppIter iter = _mapConfigAppOpt.begin();
iter != _mapConfigAppOpt.end(); ++iter)
{
Config* pConf = iter->second;
TiXmlElement* pConfElem = new TiXmlElement("Config");
pConfElem->SetAttribute("name", GetAnsiString(pConf->_strName));
//bool opt
for(Config::BoolOptIter bIter = pConf->_mapBoolOpt.begin();
bIter != pConf->_mapBoolOpt.end(); ++bIter)
{
TiXmlElement* pBool = new TiXmlElement("Value");
pBool->SetAttribute("name", GetAnsiString(bIter->first));
pBool->SetAttribute("type", "BOOL");
TiXmlText* pText = new TiXmlText(bIter->second ? "1" : "0");
pBool->LinkEndChild(pText);
pConfElem->LinkEndChild(pBool);
}
//string opt
for(Config::StringOptIter strIter = pConf->_mapStringOpt.begin();
strIter != pConf->_mapStringOpt.end(); ++strIter)
{
TiXmlElement* pString = new TiXmlElement("Value");
pString->SetAttribute("name", GetAnsiString(strIter->first));
pString->SetAttribute("type", "String");
TiXmlText* pText = new TiXmlText(GetAnsiString(strIter->second));
pString->LinkEndChild(pText);
pConfElem->LinkEndChild(pString);
}
//dword opt
for(Config::DoubleWordOptIter dwIter = pConf->_mapDoubleWordOpt.begin();
dwIter != pConf->_mapDoubleWordOpt.end(); ++dwIter)
{
TiXmlElement* pDW = new TiXmlElement("Value");
pDW->SetAttribute("name", GetAnsiString(dwIter->first));
pDW->SetAttribute("type", "DWORD");
TiXmlText* pText = new TiXmlText(GetStringFromLong(dwIter->second));
pDW->LinkEndChild(pText);
pConfElem->LinkEndChild(pDW);
}
pConfApp->LinkEndChild(pConfElem);
}
doc.LinkEndChild(pDecl);
doc.LinkEndChild(pConfApp);
doc.SaveFile(GetAnsiString(strFileName));
return true;
}
std::string ConfigApp::GetStringFromLong(long dwValue)
{
char szBuf[32] = {0};
_snprintf_s(szBuf, 32, 32, "%ld", dwValue);
return szBuf;
}
long ConfigApp::GetLongFromString(std::string strValue)
{
if (strValue.empty())
{
return 0L;
}
long dwValue = 0L;
sscanf_s(strValue.c_str(), "%ld", &dwValue);
return dwValue;
} | [
"buf1024@10f8a008-2033-b5f4-5ad9-01b5c2a83ee0"
] | [
[
[
1,
199
]
]
] |
bae167738ab57b07aa475368471a93da34876b7b | 021e8c48a44a56571c07dd9830d8bf86d68507cb | /build/vtk/vtkPBGLConnectedComponents.h | 57736b6867f18ca14704738c460831be67b5f1de | [
"BSD-3-Clause"
] | permissive | Electrofire/QdevelopVset | c67ae1b30b0115d5c2045e3ca82199394081b733 | f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5 | refs/heads/master | 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,678 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkPBGLConnectedComponents.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .NAME vtkPBGLConnectedComponents - Compute connected components for a
// distributed vtkGraph. For directed graphs, this computes the connected
// components; for undirected graphs, this computes the strongly-connected
// components.
//
// .SECTION Description
// This VTK class uses the Parallel BGL's implementation of connected
// components and strongly-connectd components.
#ifndef __vtkPBGLConnectedComponents_h
#define __vtkPBGLConnectedComponents_h
#include "vtkStdString.h" // For string type
#include "vtkVariant.h" // For variant type
#include "vtkGraphAlgorithm.h"
class vtkSelection;
class VTK_PARALLEL_EXPORT vtkPBGLConnectedComponents : public vtkGraphAlgorithm
{
public:
static vtkPBGLConnectedComponents *New();
vtkTypeMacro(vtkPBGLConnectedComponents, vtkGraphAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Set the name of the component number output array, which contains the
// component number of each vertex (a non-negative value). If no component
// array name is set then the name 'Component' is used.
vtkSetStringMacro(ComponentArrayName);
protected:
vtkPBGLConnectedComponents();
~vtkPBGLConnectedComponents();
virtual int RequestData(
vtkInformation *,
vtkInformationVector **,
vtkInformationVector *);
virtual int FillInputPortInformation(
int port, vtkInformation* info);
virtual int FillOutputPortInformation(
int port, vtkInformation* info);
private:
char* ComponentArrayName;
vtkPBGLConnectedComponents(const vtkPBGLConnectedComponents&); // Not implemented.
void operator=(const vtkPBGLConnectedComponents&); // Not implemented.
};
#endif
| [
"ganondorf@ganondorf-VirtualBox.(none)"
] | [
[
[
1,
74
]
]
] |
505dea7d9518028cac944d0a2bf348a7bff2e7cd | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/cube/MainWindowController.cpp | caf91e2180840f6097f4a8904710262853dea030 | [
"BSD-3-Clause"
] | permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,628 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright © 2007, Casey Langen
//
// Sources and Binaries of: mC2, win32cpp
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include "pch.hpp"
#include <cube/MainWindowController.hpp>
#include <cube/TransportView.hpp>
#include <cube/LibraryWindowController.hpp>
#include <cube/LibraryWindowView.hpp>
#include <cube/TransportController.hpp>
#include <core/Preferences.h>
#include <cube/resources/resource.h>
#include <win32cpp/Types.hpp> // uichar, uistring
#include <win32cpp/TopLevelWindow.hpp>
#include <win32cpp/Splitter.hpp>
#include <win32cpp/TabView.hpp>
#include <win32cpp/RedrawLock.hpp>
#include <win32cpp/TrayIconManager.hpp>
//////////////////////////////////////////////////////////////////////////////
using namespace musik::cube;
//////////////////////////////////////////////////////////////////////////////
/*ctor*/ MainWindowController::MainWindowController(TopLevelWindow& mainWindow)
: mainWindow(mainWindow)
, transportController(NULL)
, menuController(mainWindow)
, libraryController(NULL)
{
this->mainWindow.Created.connect(
this, &MainWindowController::OnMainWindowCreated);
}
MainWindowController::~MainWindowController()
{
delete this->libraryController;
delete this->transportController;
}
void MainWindowController::OnFileExit(MenuItemRef menuItem)
{
Application::Instance().Terminate();
}
void MainWindowController::OnMainWindowCreated(Window* window)
{
// Start by setting the icon
HICON icon16 = (HICON)LoadImage(Application::Instance(), MAKEINTRESOURCE(IDI_MAINFRAME), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
HICON icon32 = (HICON)LoadImage(Application::Instance(), MAKEINTRESOURCE(IDI_MAINFRAME), IMAGE_ICON, 32, 32, LR_DEFAULTCOLOR);
SendMessage( window->Handle(), WM_SETICON, WPARAM( ICON_SMALL ), LPARAM( icon16 ) );
SendMessage( window->Handle(), WM_SETICON, WPARAM( ICON_BIG ), LPARAM( icon32 ) );
// Init Tray Icon
MenuRef myMenu = Menu::CreatePopup();
// Create Tray Menu
MenuItemRef trayExit = myMenu->Items().Append(MenuItem::Create(_(_T("E&xit"))));
// Bind Exit to handler
trayExit->Activated.connect(this, &MainWindowController::OnFileExit);
UINT uidTrayIcon = Application::Instance().SysTrayManager()->AddIcon(Application::Instance().MainWindow(), icon16);
Application::Instance().SysTrayManager()->SetTooltip(uidTrayIcon, _T("musikCube"));
Application::Instance().SysTrayManager()->SetPopupMenu(uidTrayIcon, myMenu);
Application::Instance().SysTrayManager()->ShowBalloon(uidTrayIcon, _T("musikCube 2"), _(_T("Welcome to musikCube!")), 2);
Application::Instance().SysTrayManager()->EnableMinimizeToTray(uidTrayIcon);
static const int TransportViewHeight = 54;
{
musik::core::Preferences windowPrefs("MainWindow");
this->mainWindow.MoveTo(windowPrefs.GetInt("x",200), windowPrefs.GetInt("y",200));
this->mainWindow.Resize(windowPrefs.GetInt("width",700), windowPrefs.GetInt("height",480));
this->mainWindow.SetMinimumSize(Size(320, 240));
}
Size clientSize = this->mainWindow.ClientSize();
// create transport view/controller
TransportView* transportView = new TransportView();
transportView->SetPadding(WindowPadding(2, 4, 0, 0));
this->transportController = new TransportController(*transportView);
// create library view/controller
LibraryWindowView* libraryView = new LibraryWindowView();
this->libraryController = new LibraryWindowController(*libraryView);
// Create a Frame that suround everything
this->clientView = this->mainWindow.AddChild(new Frame(0,4));
this->clientView->SetLayoutFlags(win32cpp::LayoutFillFill);
// the main splitter
Splitter* transportSplitter = this->clientView->AddChild(
new Splitter(SplitRow, libraryView, transportView));
// set initial sizes
transportSplitter->SetAnchor(AnchorBottom);
transportSplitter->SetAnchorSize(TransportViewHeight);
transportSplitter->SetSizable(false);
this->mainWindow.Resized.connect(this, &MainWindowController::OnResize);
this->mainWindow.Destroyed.connect(this, &MainWindowController::OnDestroyed);
}
void MainWindowController::OnResize(Window* window, Size size)
{
RedrawLock redrawLock(this->clientView);
this->clientView->Resize(this->mainWindow.ClientSize());
}
void MainWindowController::OnDestroyed(Window* window)
{
Point location( window->Location() );
Size size( window->WindowSize() );
musik::core::Preferences windowPrefs("MainWindow");
windowPrefs.SetInt("x",location.x);
windowPrefs.SetInt("y",location.y);
windowPrefs.SetInt("width",size.width);
windowPrefs.SetInt("height",size.height);
}
| [
"onnerby@6a861d04-ae47-0410-a6da-2d49beace72e",
"bjorn.olievier@6a861d04-ae47-0410-a6da-2d49beace72e",
"[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e",
"[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e"
] | [
[
[
1,
46
],
[
48,
54
],
[
57,
68
],
[
70,
71
],
[
73,
80
],
[
86,
95
],
[
104,
106
],
[
111,
124
],
[
126,
131
],
[
135,
136
],
[
138,
153
],
[
155,
164
]
],
[
[
47,
47
],
[
69,
69
],
[
72,
72
],
[
154,
154
]
],
[
[
55,
56
],
[
81,
85
],
[
96,
103
],
[
107,
110
]
],
[
[
125,
125
],
[
132,
134
],
[
137,
137
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.