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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2e047b0dbdec09999c82385838e699231f4463c3 | 21da454a8f032d6ad63ca9460656c1e04440310e | /src/org/xml/sax/wsiLocator.h | c8215c525ddec26ef3e84863e97ec1a9c9d1ed90 | []
| no_license | merezhang/wcpp | d9879ffb103513a6b58560102ec565b9dc5855dd | e22eb48ea2dd9eda5cd437960dd95074774b70b0 | refs/heads/master | 2021-01-10T06:29:42.908096 | 2009-08-31T09:20:31 | 2009-08-31T09:20:31 | 46,339,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 113 | h | #pragma once
class wsiLocator : public wsiObject
{
public:
static const ws_iid sIID;
public:
};
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
]
| [
[
[
1,
10
]
]
]
|
093ea06c73c75a33dcdb7c0fb53e2e4d1f0465bd | f8b364974573f652d7916c3a830e1d8773751277 | /emulator/allegrex/instructions/VMIN.h | 552f0a8f68963db468feb02efeae4700dfd58989 | []
| no_license | lemmore22/pspe4all | 7a234aece25340c99f49eac280780e08e4f8ef49 | 77ad0acf0fcb7eda137fdfcb1e93a36428badfd0 | refs/heads/master | 2021-01-10T08:39:45.222505 | 2009-08-02T11:58:07 | 2009-08-02T11:58:07 | 55,047,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | h | template< > struct AllegrexInstructionTemplate< 0x6d000000, 0xff800000 > : AllegrexInstructionUnknown
{
static AllegrexInstructionTemplate &self()
{
static AllegrexInstructionTemplate insn;
return insn;
}
static AllegrexInstruction *get_instance()
{
return &AllegrexInstructionTemplate::self();
}
virtual AllegrexInstruction *instruction(u32 opcode)
{
return this;
}
virtual char const *opcode_name()
{
return "VMIN";
}
virtual void interpret(Processor &processor, u32 opcode);
virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment);
protected:
AllegrexInstructionTemplate() {}
};
typedef AllegrexInstructionTemplate< 0x6d000000, 0xff800000 >
AllegrexInstruction_VMIN;
namespace Allegrex
{
extern AllegrexInstruction_VMIN &VMIN;
}
#ifdef IMPLEMENT_INSTRUCTION
AllegrexInstruction_VMIN &Allegrex::VMIN =
AllegrexInstruction_VMIN::self();
#endif
| [
"[email protected]"
]
| [
[
[
1,
41
]
]
]
|
c53f58e77cb1acbd219c47618fde4cc6e9f44f85 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-04-24/eeschema/libcmp.h | c20eb8f936da1b218a1c8a22fe32521a165ddedf | []
| no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 12,643 | h | /****************************************************************/
/* Headers fo library definition and lib component definitions */
/****************************************************************/
#ifndef LIBCMP_H
#define LIBCMP_H
#ifndef eda_global
#define eda_global extern
#endif
#include "priorque.h"
#define LIB_VERSION_MAJOR 2
#define LIB_VERSION_MINOR 3
#define LIBFILE_IDENT "EESchema-LIBRARY Version" /* Must be at the lib file start. */
#define DOCFILE_IDENT "EESchema-DOCLIB Version 2.0" /* Must be at the doc file start. */
#define DOC_EXT wxT(".dcm") /* extension des fichiers de documentation */
#define TARGET_PIN_DIAM 12 /* Diam cercle des extremites des pins */
#define DEFAULT_TEXT_SIZE 50 /* Default size for field texts */
#define PART_NAME_LEN 15 /* Maximum length of part name. */
#define PREFIX_NAME_LEN 5 /* Maximum length of prefix (IC, R, SW etc.). */
#define PIN_WIDTH 100 /* Width between 2 pins in internal units. */
#define PIN_LENGTH 300 /* Default Length of each pin to be drawn. */
#define INVERT_PIN_RADIUS 35 /* Radius of inverted pin circle. */
#define CLOCK_PIN_DIM 40 /* Dim of clock pin symbol. */
#define IEEE_SYMBOL_PIN_DIM 40 /* Dim of special pin symbol. */
#define NO_FILL 0 // Poly, Squar, Circle, Arc = option No Fill
#define FILLED_SHAPE 1 // Poly, Squar, Circle, Arc = option Fill with current color
#define FILLED_WITH_BG_BODYCOLOR 2 // Poly, Squar, Circle, Arc = option Fill
// with background body color
//Offsets used in editing library component, for handle aliad dats
#define ALIAS_NAME 0
#define ALIAS_DOC 1
#define ALIAS_KEYWORD 2
#define ALIAS_DOC_FILENAME 3
#define ALIAS_NEXT 4
typedef enum {
LOCATE_COMPONENT_ARC_DRAW_TYPE = 1,
LOCATE_COMPONENT_CIRCLE_DRAW_TYPE = 2,
LOCATE_COMPONENT_GRAPHIC_TEXT_DRAW_TYPE = 4,
LOCATE_COMPONENT_RECT_DRAW_TYPE = 8,
LOCATE_LINE_DRAW_TYPE = 0x10,
LOCATE_COMPONENT_POLYLINE_DRAW_TYPE = 0x20,
LOCATE_COMPONENT_LINE_DRAW_TYPE = 0x40
} LocateDrawStructType;
#define LOCATE_ALL_DRAW_ITEM 0xFFFFFFFF
/* flags utilises dans FindLibPart() : */
#define FIND_ROOT 0 /* indique la recherche du composant racine si
meme si le composant specifie est un alias */
#define FIND_ALIAS 1 /* indique la recherche du composant specifie
(alias ou racine) */
/* definition des types des structures d'elements de librairie */
typedef enum {
ROOT, /* Structure est a standard EDA_LibComponentStruct */
ALIAS /* Structure is an alias */
} LibrEntryType;
/* valeur du membre .m_Options */
typedef enum {
ENTRY_NORMAL, // Libentry is standard
ENTRY_POWER // Libentry is a power symbol
} LibrEntryOptions;
/* Definitions des Pins */
typedef enum { /* Type des Pins. si modif: modifier tableau des mgs suivant */
PIN_INPUT,
PIN_OUTPUT,
PIN_BIDI,
PIN_TRISTATE,
PIN_PASSIVE,
PIN_UNSPECIFIED,
PIN_POWER_IN,
PIN_POWER_OUT,
PIN_OPENCOLLECTOR,
PIN_OPENEMITTER,
PIN_NC, /* No connect */
PIN_NMAX /* Valeur limite ( utilisee comme limite de tableaux) */
} ElectricPinType;
/* Messages d'affichage du type electrique */
eda_global wxChar * MsgPinElectricType[]
#ifdef MAIN
= {
wxT("input"),
wxT("output"),
wxT("BiDi"),
wxT("3state"),
wxT("passive"),
wxT("unspc"),
wxT("power_in"),
wxT("power_out"),
wxT("openCol"),
wxT("openEm"),
wxT("?????")
}
#endif
;
/* Autres bits: bits du membre .Flag des Pins */
#define PINNOTDRAW 1 /* si 1: pin invisible */
typedef enum { /* Forme des Pins */
NONE = 0,
INVERT = 1,
CLOCK = 2,
LOWLEVEL_IN = 4,
LOWLEVEL_OUT = 8
} DrawPinShape;
typedef enum { /* Orientation des Pins */
PIN_RIGHT = 'R',
PIN_LEFT = 'L',
PIN_UP = 'U',
PIN_DOWN = 'D',
} DrawPinOrient;
/*************************************/
/* Classe representant une librairie */
/*************************************/
class LibraryStruct
{
public:
int m_Type; /* type indicator */
wxString m_Name; /* Name of library loaded. */
wxString m_FullFileName; /* Full File Name (with path) of library loaded. */
wxString m_Header; /* first line of library loaded. */
int m_NumOfParts; /* Number of parts this library has. */
PriorQue * m_Entries; /* Parts themselves are saved here. */
LibraryStruct * m_Pnext; /* Point on next lib in chain. */
int m_Modified; /* flag indicateur d'edition */
int m_Size; // Size in bytes (for statistics)
long m_TimeStamp; // Signature temporelle
int m_Flags; // variable used in some functions
bool m_IsLibCache; // False for the "standard" libraries,
// True for the library cache
public:
LibraryStruct(int type, const wxString & name, const wxString & fullname);
~LibraryStruct();
bool WriteHeader(FILE * file);
bool ReadHeader(FILE * file, int * LineNum);
};
/*******************************************************************/
/* Classes representant les eléments d'un composant d'une libraire */
/*******************************************************************/
/* class LibEDA_BaseStruct : Basic class for items used in a library component
(graphic shapes, texts, fields, pins)
*/
class LibEDA_BaseStruct : public EDA_BaseStruct
{
public:
int m_Unit; /* Unit identification (for multi part per parkage)
0 if the item is common to all units */
int m_Convert; /* Shape identification (for parts which have a convert shape)
0 if the item is common to all shapes */
public:
LibEDA_BaseStruct * Next(void) {return (LibEDA_BaseStruct *) Pnext;}
LibEDA_BaseStruct(int struct_type);
virtual ~LibEDA_BaseStruct(void){}
void Display_Infos_DrawEntry(WinEDA_DrawFrame * frame);
};
class LibDrawPin : public LibEDA_BaseStruct
{
public:
wxPoint m_Pos; /* Pin position */
short m_PinLen; /* Pin lenght */
short m_Orient; /* Pin orientation (Up, Down, Left, Right) */
short m_PinShape; /* Bitwise ORed: Pin shape (see enum DrawPinShape) */
char m_PinType; /* Electrical pin properties */
char m_Attributs; /* bit 0 != 0: pin invisible */
long m_PinNum; /* Pin number: 4 Ascii code like
"12" or "anod" or "G6"
"12" is really "12\0\0"*/
wxString m_PinName;
short m_SizeNum, m_SizeName; /* Pin num and Pin name sizes */
public:
LibDrawPin(void);
~LibDrawPin(void) {}
LibDrawPin * GenCopy(void);
bool WriteDescr( FILE * File );
void Display_Infos(WinEDA_DrawFrame * frame);
wxPoint ReturnPinEndPoint(void);
int ReturnPinDrawOrient(int TransMat[2][2]);
void ReturnPinStringNum(wxString & buffer);
void SetPinNumFromString(wxString & buffer);
void DrawPinTexts(WinEDA_DrawPanel * panel, wxDC * DC,
wxPoint & pin_pos, int orient,
int TextInside, bool DrawPinNum, bool DrawPinName,
int Color, int DrawMode);
void PlotPinTexts(wxPoint & pin_pos, int orient,
int TextInside, bool DrawPinNum, bool DrawPinName);
};
class LibDrawArc : public LibEDA_BaseStruct
{
public:
wxPoint m_Pos; /* Position du point de reference (Centre)*/
int m_Rayon;
int m_Width;
int m_Fill;
int t1, t2; /* position des 2 extremites de l'arc en 0,1 degres */
wxPoint m_Start, m_End; /* position des 2 extremites de l'arc en coord reelles*/
public:
LibDrawArc(void);
~LibDrawArc(void){}
LibDrawArc * GenCopy(void);
bool WriteDescr( FILE * File );
};
class LibDrawCircle : public LibEDA_BaseStruct
{
public:
wxPoint m_Pos; /* Position du point de reference */
int m_Rayon;
int m_Width;
int m_Fill;
public:
LibDrawCircle(void);
~LibDrawCircle(void){}
LibDrawCircle * GenCopy(void);
bool WriteDescr( FILE * File );
};
class LibDrawText : public LibEDA_BaseStruct
{
public:
wxPoint m_Pos; /* Position du point de reference */
int m_Horiz;
wxSize m_Size;
int m_Type;
wxString m_Text;
public:
LibDrawText(void);
~LibDrawText(void){}
LibDrawText * GenCopy(void);
bool WriteDescr( FILE * File );
};
class LibDrawSquare : public LibEDA_BaseStruct
{
public:
wxPoint m_Start;
wxPoint m_End;
int m_Width;
int m_Fill;
public:
LibDrawSquare(void);
~LibDrawSquare(void){}
LibDrawSquare * GenCopy(void);
bool WriteDescr( FILE * File );
};
class LibDrawSegment : public LibEDA_BaseStruct
{
public:
wxPoint m_Start;
wxPoint m_End;
int m_Width;
public:
LibDrawSegment(void);
~LibDrawSegment(void){}
LibDrawSegment * GenCopy(void);
bool WriteDescr( FILE * File );
};
class LibDrawPolyline : public LibEDA_BaseStruct
{
public:
int n, *PolyList;
int m_Width;
int m_Fill;
public:
LibDrawPolyline(void);
~LibDrawPolyline(void){ if ( PolyList ) free(PolyList);}
LibDrawPolyline * GenCopy(void);
void AddPoint(const wxPoint & point);
bool WriteDescr( FILE * File );
};
/* Fields identiques aux fields des composants, pouvant etre predefinis en lib
2 Fields sont toujours presents : Prefix (U, IC..) et Name (74LS00..)*/
class LibDrawField : public LibEDA_BaseStruct
{
public:
int m_FieldId; // 0 a 11
// 0 = Name 1 = Valeur 2 .. 11 autres fields
wxPoint m_Pos;
wxSize m_Size;
int m_Orient; /* Orientation */
int m_Attributs; /* Attributs (Non visible ...) */
int m_HJustify, m_VJustify; /* Justifications Horiz et Vert du texte */
wxString m_Text; /* Pointeur sur le texte */
public:
LibDrawField(int idfield = 2);
~LibDrawField(void);
LibDrawField * GenCopy(void);
void Copy(LibDrawField * Target);
bool WriteDescr( FILE * File );
};
/* classe de base de description des composants en librairie */
class LibCmpEntry : public EDA_BaseStruct
{
public:
LibrEntryType Type; /* Type = ROOT;
= ALIAS pour struct LibraryAliasType */
LibDrawField m_Name; // name (74LS00 ..) in lib ( = VALUE )
wxString m_Doc; /* ligne de documentation */
wxString m_KeyWord; /* liste des mots cles */
wxString m_DocFile; /* nom du fichier Doc Associe */
LibrEntryOptions m_Options; // special features (i.e. Entry is a POWER)
public:
LibCmpEntry(LibrEntryType CmpType, const wxChar * CmpName);
virtual ~LibCmpEntry(void);
bool WriteDescr( FILE * File );
};
class EDA_LibComponentStruct: public LibCmpEntry /* composant "racine" */
{
public:
LibDrawField m_Prefix; /* Prefix ( U, IC ... ) = REFERENCE */
wxArrayString m_AliasList; /* ALIAS list for the component */
int m_UnitCount; /* Units (or sections) per package */
bool m_UnitSelectionLocked; // True if units are differents and their selection is locked
// (i.e. if part A cannot be automatically changed in part B
int m_TextInside; /* if 0: pin name drawn on the pin itself
if > 0 pin name drawn inside the component,
with a distance of m_TextInside in mils */
bool m_DrawPinNum;
bool m_DrawPinName;
LibDrawField *Fields; /* Auxiliairy Field list (id = 2 a 11*/
LibEDA_BaseStruct * m_Drawings; /* How to draw this part */
long m_LastDate; // Last change Date
public:
EDA_LibComponentStruct( const wxChar * CmpName);
EDA_Rect GetBoundaryBox( int Unit, int Convert); /* return Box around the part. */
~EDA_LibComponentStruct( void );
void SortDrawItems(void);
};
class EDA_LibCmpAliasStruct: public LibCmpEntry
{
public:
wxString m_RootName; /* Part name pour le composant de reference */
public:
EDA_LibCmpAliasStruct( const wxChar * CmpName, const wxChar * CmpRootName);
~EDA_LibCmpAliasStruct(void);
};
/* Variables */
extern LibraryStruct *LibraryList; /* All part libs are saved here. */
/* Variables Utiles pour les editions de composants en librairie */
eda_global LibEDA_BaseStruct * LibItemToRepeat; /* pointeur sur l'élément que l'on
peut répéter (Pin..;) */
eda_global LibraryStruct *CurrentLib; /* Pointeur sur la librairie du
composant en cours d'edition */
eda_global EDA_LibComponentStruct *CurrentLibEntry; /* pointeur sur le composant en
cours d'edition */
eda_global LibEDA_BaseStruct * CurrentDrawItem; /* pointeur sur les
elements de dessin du comp. en edition */
eda_global wxString CurrentAliasName; // Nom de l'alias selectionné
eda_global bool g_AsDeMorgan; // Pour libedit:
eda_global int CurrentUnit
#ifdef MAIN
= 1
#endif
;
eda_global int CurrentConvert /* Convert = 1 .. 255 */
#ifdef MAIN
= 1
#endif
;
eda_global wxString FindLibName; /* nom de la librairie ou a ete trouve le
dernier composant recherche par FindLibPart() */
#endif // LIBCMP_H
| [
"fcoiffie@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
415
]
]
]
|
41169c114116aa9438f20dbb76439d1e3526c8d8 | b4f709ac9299fe7a1d3fa538eb0714ba4461c027 | /trunk/mainframe.h | 88d4589fb7b581407e600261c367c9548f0f885b | []
| no_license | BackupTheBerlios/ptparser-svn | d953f916eba2ae398cc124e6e83f42e5bc4558f0 | a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c | refs/heads/master | 2020-05-27T12:26:21.811820 | 2005-11-06T14:23:18 | 2005-11-06T14:23:18 | 40,801,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,474 | h | /////////////////////////////////////////////////////////////////////////////
// Name: mainframe.h
// Purpose: Main frame for the application
// Author: Brad Larsen
// Modified by:
// Created: Dec 3, 2004
// RCS-ID:
// Copyright: (c) Brad Larsen
// License: wxWindows license
/////////////////////////////////////////////////////////////////////////////
#ifndef __MAINFRAME_H__
#define __MAINFRAME_H__
// Menu Command Ids
enum mainFrameMenuCommandIds
{
IDM_HELP_ABOUT = 100,
IDM_TOOLS_MERGE_SCORES,
IDM_TEST_TESTINGFRAMEWORK,
IDM_TEST_BATCHFILESERIALIZATION,
};
// Menu Command Ids
enum powerTabViewMenuCommandIds
{
IDM_TEST_PARSE_FILE = 500
};
/// Main frame for the application
class MainFrame: public wxDocMDIParentFrame
{
DECLARE_CLASS(MainFrame)
public:
// Constructor/Destructor
MainFrame(wxDocManager* manager, wxFrame* frame, const wxString& title, const wxPoint& pos, const wxSize& size, long type);
// Command Events
void OnHelpAbout(wxCommandEvent& event);
void OnToolsMergeScores(wxCommandEvent& event);
void OnTestTestingFramework(wxCommandEvent& event);
void OnTestBatchFileSerialization(wxCommandEvent& event);
// Operations
wxMDIChildFrame* CreateChildFrame(wxDocument* document, wxView* view);
DECLARE_EVENT_TABLE()
};
#endif
| [
"blarsen@8c24db97-d402-0410-b267-f151a046c31a"
]
| [
[
[
1,
53
]
]
]
|
42a198577e25510a8d42d572e991cd2ae82221e2 | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvmath/SphericalHarmonic.h | 4e795d1e8c4abedda0273baae88956f0c1228033 | []
| no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,947 | h | // This code is in the public domain -- [email protected]
#ifndef NV_MATH_SPHERICALHARMONIC_H
#define NV_MATH_SPHERICALHARMONIC_H
#include <string.h> // memcpy
#include <nvmath/Vector.h>
namespace nv
{
NVMATH_API float legendrePolynomial( int l, int m, float x ) NV_CONST;
NVMATH_API float y( int l, int m, float theta, float phi ) NV_CONST;
NVMATH_API float y( int l, int m, Vector3::Arg v ) NV_CONST;
NVMATH_API float hy( int l, int m, float theta, float phi ) NV_CONST;
NVMATH_API float hy( int l, int m, Vector3::Arg v ) NV_CONST;
class Sh;
float dot(const Sh & a, const Sh & b) NV_CONST;
/// Spherical harmonic class.
class Sh
{
friend class Sh2;
friend class ShMatrix;
public:
/// Construct a spherical harmonic of the given order.
Sh(int o) : m_order(o)
{
m_elemArray = new float[basisNum()];
}
/// Copy constructor.
Sh(const Sh & sh) : m_order(sh.order())
{
m_elemArray = new float[basisNum()];
memcpy(m_elemArray, sh.m_elemArray, sizeof(float) * basisNum());
}
/// Destructor.
~Sh()
{
delete [] m_elemArray;
m_elemArray = NULL;
}
/// Get number of bands.
static int bandNum(int order) {
return order + 1;
}
/// Get number of sh basis.
static int basisNum(int order) {
return (order + 1) * (order + 1);
}
/// Get the index for the given coefficients.
static int index( int l, int m ) {
return l * l + l + m;
}
/// Get sh order.
int order() const
{
return m_order;
}
/// Get sh order.
int bandNum() const
{
return bandNum(m_order);
}
/// Get sh order.
int basisNum() const
{
return basisNum(m_order);
}
/// Get sh coefficient indexed by l,m.
float elem( int l, int m ) const
{
return m_elemArray[index(l, m)];
}
/// Get sh coefficient indexed by l,m.
float & elem( int l, int m )
{
return m_elemArray[index(l, m)];
}
/// Get sh coefficient indexed by i.
float elemAt( int i ) const {
return m_elemArray[i];
}
/// Get sh coefficient indexed by i.
float & elemAt( int i )
{
return m_elemArray[i];
}
/// Reset the sh coefficients.
void reset()
{
for( int i = 0; i < basisNum(); i++ ) {
m_elemArray[i] = 0.0f;
}
}
/// Copy spherical harmonic.
void operator= ( const Sh & sh )
{
nvDebugCheck(order() <= sh.order());
for(int i = 0; i < basisNum(); i++) {
m_elemArray[i] = sh.m_elemArray[i];
}
}
/// Add spherical harmonics.
void operator+= ( const Sh & sh )
{
nvDebugCheck(order() == sh.order());
for(int i = 0; i < basisNum(); i++) {
m_elemArray[i] += sh.m_elemArray[i];
}
}
/// Substract spherical harmonics.
void operator-= ( const Sh & sh )
{
nvDebugCheck(order() == sh.order());
for(int i = 0; i < basisNum(); i++) {
m_elemArray[i] -= sh.m_elemArray[i];
}
}
// Not exactly convolution, nor product.
void operator*= ( const Sh & sh )
{
nvDebugCheck(order() == sh.order());
for(int i = 0; i < basisNum(); i++) {
m_elemArray[i] *= sh.m_elemArray[i];
}
}
/// Scale spherical harmonics.
void operator*= ( float f )
{
for(int i = 0; i < basisNum(); i++) {
m_elemArray[i] *= f;
}
}
/// Add scaled spherical harmonics.
void addScaled( const Sh & sh, float f )
{
nvDebugCheck(order() == sh.order());
for(int i = 0; i < basisNum(); i++) {
m_elemArray[i] += sh.m_elemArray[i] * f;
}
}
/*/// Add a weighted sample to the sh coefficients.
void AddSample( const Vec3 & dir, const Color3f & color, float w=1.0f ) {
for(int l = 0; l <= order; l++) {
for(int m = -l; m <= l; m++) {
Color3f & elem = GetElem(l, m);
elem.Mad( elem, color, w * y(l, m, dir) );
}
}
}*/
/// Evaluate
void eval(Vector3::Arg dir)
{
for(int l = 0; l <= m_order; l++) {
for(int m = -l; m <= l; m++) {
elem(l, m) = y(l, m, dir);
}
}
}
/// Evaluate the spherical harmonic function.
float sample(Vector3::Arg dir) const
{
Sh sh(order());
sh.eval(dir);
return dot(sh, *this);
}
protected:
const int m_order;
float * m_elemArray;
};
/// Compute dot product of the spherical harmonics.
inline float dot(const Sh & a, const Sh & b)
{
nvDebugCheck(a.order() == b.order());
float sum = 0;
for( int i = 0; i < Sh::basisNum(a.order()); i++ ) {
sum += a.elemAt(i) * b.elemAt(i);
}
return sum;
}
/// Second order spherical harmonic.
class Sh2 : public Sh
{
public:
/// Constructor.
Sh2() : Sh(2) {}
/// Copy constructor.
Sh2(const Sh2 & sh) : Sh(sh) {}
/// Spherical harmonic resulting from projecting the clamped cosine transfer function to the SH basis.
void cosineTransfer()
{
const float c1 = 0.282095f; // K(0, 0)
const float c2 = 0.488603f; // K(1, 0)
const float c3 = 1.092548f; // sqrt(15.0f / PI) / 2.0f = K(2, -2)
const float c4 = 0.315392f; // sqrt(5.0f / PI) / 4.0f) = K(2, 0)
const float c5 = 0.546274f; // sqrt(15.0f / PI) / 4.0f) = K(2, 2)
const float normalization = PI * 16.0f / 17.0f;
const float const1 = c1 * normalization * 1.0f;
const float const2 = c2 * normalization * (2.0f / 3.0f);
const float const3 = c3 * normalization * (1.0f / 4.0f);
const float const4 = c4 * normalization * (1.0f / 4.0f);
const float const5 = c5 * normalization * (1.0f / 4.0f);
m_elemArray[0] = const1;
m_elemArray[1] = -const2;
m_elemArray[2] = const2;
m_elemArray[3] = -const2;
m_elemArray[4] = const3;
m_elemArray[5] = -const3;
m_elemArray[6] = const4;
m_elemArray[7] = -const3;
m_elemArray[8] = const5;
}
};
#if 0
/// Spherical harmonic matrix.
class ShMatrix
{
public:
/// Create an identity matrix of the given order.
ShMatrix(int o = 2) : order(o), identity(true)
{
nvCheck(order > 0);
e = new float[Size()];
band = new float *[GetBandNum()];
setupBands();
}
/// Destroy and free matrix elements.
~ShMatrix()
{
delete e;
delete band;
}
/// Set identity matrix.
void setIdentity()
{
identity = true;
}
/// Return true if this is an identity matrix, false in other case.
bool isIdentity() const {
return identity;
}
/// Get number of bands of this matrix.
int bandNum() const
{
return order+1;
}
/// Get total number of elements in the matrix.
int size() const
{
int size = 0;
for( int i = 0; i < bandNum(); i++ ) {
size += SQ(i * 2 + 1);
}
return size;
}
/// Get element at the given raw index.
float elem(const int idx) const
{
return e[idx];
}
/// Get element at the given with the given indices.
float & elem( const int b, const int x, const int y )
{
nvDebugCheck(b >= 0);
nvDebugCheck(b < bandNum());
return band[b][(b + y) * (b * 2 + 1) + (b + x)];
}
/// Get element at the given with the given indices.
float elem( const int b, const int x, const int y ) const
{
nvDebugCheck(b >= 0);
nvDebugCheck(b < bandNum());
return band[b][(b + y) * (b * 2 + 1) + (b + x)];
}
/** Copy matrix. */
void Copy( const ShMatrix & m )
{
nvDebugCheck(order == m.order);
memcpy(e, m.e, Size() * sizeof(float));
}
/** Rotate the given coefficients. */
void transform( const Sh & restrict source, Sh * restrict dest ) const {
piCheck( &source != dest ); // Make sure there's no aliasing.
piCheck( dest->order <= order );
piCheck( order <= source.order );
if( identity ) {
*dest = source;
return;
}
// Loop through each band.
for( int l = 0; l <= dest->order; l++ ) {
for( int mo = -l; mo <= l; mo++ ) {
Color3f rgb = Color3f::Black;
for( int mi = -l; mi <= l; mi++ ) {
rgb.Mad( rgb, source.elem(l, mi), elem(l, mo, mi) );
}
dest->elem(l, mo) = rgb;
}
}
}
MATHLIB_API void multiply( const ShMatrix &A, const ShMatrix &B );
MATHLIB_API void rotation( const Matrix & m );
MATHLIB_API void rotation( int axis, float angles );
MATHLIB_API void print();
private:
// @@ These could be static indices precomputed only once.
/// Setup the band pointers.
void setupBands()
{
int size = 0;
for( int i = 0; i < bandNum(); i++ ) {
band[i] = &e[size];
size += SQ(i * 2 + 1);
}
}
private:
// Matrix order.
const int m_order;
// Identity flag for quick transform.
bool m_identity;
// Array of elements.
float * m_e;
// Band pointers.
float ** m_band;
};
#endif // 0
} // nv namespace
#endif // NV_MATH_SPHERICALHARMONIC_H
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
]
| [
[
[
1,
420
]
]
]
|
93f377eb64420ba57ce60057420613aff77aee11 | b411e4861bc1478147bfc289c868b961a6136ead | /tags/DownhillRacing/Box.h | f9fd6926f1e26fff8a222fc5e8b5c300d51fa819 | []
| no_license | mvm9289/downhill-racing | d05df2e12384d8012d5216bc0b976bc7df9ff345 | 038ec4875db17a7898282d6ced057d813a0243dc | refs/heads/master | 2021-01-20T12:20:31.383595 | 2010-12-19T23:29:02 | 2010-12-19T23:29:02 | 32,334,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 247 | h | #pragma once
#include "Point.h"
class Box
{
public:
Point minimum;
Point maximum;
public:
Box(const Point& minim=Point(), const Point& maxim=Point());
~Box(void);
void init(const Point& p);
void update(const Point& p);
};
| [
"mvm9289@06676c28-b993-0703-7cf1-698017e0e3c1"
]
| [
[
[
1,
16
]
]
]
|
dabbd92bde59f4d555a11e6f5a8135ae8a8c81fc | 119ba245bea18df8d27b84ee06e152b35c707da1 | /unreal/branches/typeRefactor-newAge/qrrepo/private/serializer.cpp | 006f07bdf739d51216ba41d3ba762994ea70374c | []
| no_license | nfrey/qreal | 05cd4f9b9d3193531eb68ff238d8a447babcb3d2 | 71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164 | refs/heads/master | 2020-04-06T06:43:41.910531 | 2011-05-30T19:30:09 | 2011-05-30T19:30:09 | 1,634,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,142 | cpp | #include "serializer.h"
#include <QtCore/QDir>
#include <QtCore/QDebug>
#include <QtCore/QPointF>
#include <QtGui/QPolygon>
#include "../../utils/outFile.h"
#include "../../utils/xmlUtils.h"
using namespace qrRepo;
using namespace details;
using namespace utils;
using namespace qReal;
Serializer::Serializer(QString const& saveDirName)
: mWorkingDir(saveDirName + "/save")
{
}
void Serializer::clearWorkingDir() const
{
clearDir(mWorkingDir + "/tree");
}
void Serializer::removeFromDisk(Id id) const
{
QDir dir;
dir.remove(pathToElement(id));
}
void Serializer::setWorkingDir(QString const &workingDir)
{
mWorkingDir = workingDir + "/save";
}
void Serializer::saveToDisk(QList<Object*> const &objects) const
{
foreach (Object *object, objects) {
QString filePath = createDirectory(object->id(), object->logicalId());
QDomDocument doc;
QDomElement root = doc.createElement("object");
doc.appendChild(root);
root.setAttribute("id", object->id().toString());
root.setAttribute("type", object->type().toString());
if (object->logicalId() != Id())
root.setAttribute("logicalId", object->logicalId().toString());
root.setAttribute("parent", object->parent().toString());
root.appendChild(idListToXml("children", object->children(), doc));
root.appendChild(propertiesToXml(object, doc));
OutFile out(filePath);
doc.save(out(), 2);
}
}
void Serializer::loadFromDisk(QHash<qReal::Id, Object*> &objectsHash)
{
loadFromDisk(mWorkingDir + "/tree", objectsHash);
}
void Serializer::loadFromDisk(QString const ¤tPath, QHash<qReal::Id, Object*> &objectsHash)
{
QDir dir(currentPath);
if (dir.exists()) {
dir.cd("logical");
loadModel(dir, objectsHash);
dir.cdUp();
dir.cd("graphical");
loadModel(dir, objectsHash);
}
}
void Serializer::loadModel(QDir const &dir, QHash<qReal::Id, Object*> &objectsHash)
{
foreach (QFileInfo fileInfo, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
QString const path = fileInfo.filePath();
if (fileInfo.isDir())
loadModel(path, objectsHash);
else if (fileInfo.isFile()) {
QDomDocument doc = xmlUtils::loadDocument(path);
Object *object = parseObject(doc.documentElement());
Q_ASSERT(object); // All objects in a repository shall be loadable.
if (object != NULL)
objectsHash.insert(object->id(), object);
}
}
}
Object *Serializer::parseObject(QDomElement const &elem)
{
QString const id = elem.attribute("id", "");
QString const type = elem.attribute("type", "");
if (id == "")
return NULL;
QString const logicalIdString = elem.attribute("logicalId", "");
Id const logicalId = loadId(logicalIdString);
Object object(Id::loadFromString(id), Id(), logicalId, NewType::loadFromString(type));
QString const parentIdString = elem.attribute("parent", "");
Id const parent = loadId(parentIdString);
if (object.parent() != parent)
object.setParent(parent);
foreach (Id child, loadIdList(elem, "children"))
if (!object.children().contains(child))
object.addChild(child);
if (!loadProperties(elem, object))
return NULL;
return new Object(object);
}
bool Serializer::loadProperties(QDomElement const &elem, Object &object)
{
QDomNodeList propertiesList = elem.elementsByTagName("properties");
if (propertiesList.count() != 1) {
qDebug() << "Incorrect element: children list must appear once";
return false;
}
QDomElement properties = propertiesList.at(0).toElement();
QDomElement property = properties.firstChildElement();
while (!property.isNull()) {
if (property.hasAttribute("type")) {
// Тогда это список. Немного кривовато, зато унифицировано со
// списками детей/родителей.
if (property.attribute("type", "") == "qReal::IdList") {
QString key = property.tagName();
IdList value = loadIdList(properties, property.tagName());
object.setProperty(key, IdListHelper::toVariant(value));
} else {
Q_ASSERT(!"Unknown list type");
}
} else {
QString type = property.tagName();
QString key = property.attribute("key", "");
if (key == "")
return false;
QString valueStr = property.attribute("value", "");
QVariant value = parseValue(type, valueStr);
object.setProperty(key, value);
}
property = property.nextSiblingElement();
}
return true;
}
IdList Serializer::loadIdList(QDomElement const &elem, QString const &name)
{
QDomNodeList list = elem.elementsByTagName(name);
if (list.count() != 1) {
qDebug() << "Incorrect element: " + name + " list must appear once";
return IdList();
}
IdList result;
QDomElement elements = list.at(0).toElement();
QDomElement element = elements.firstChildElement();
while (!element.isNull()) {
QString elementStr = element.attribute("id", "");
if (elementStr == "") {
qDebug() << "Incorrect Child XML node";
return IdList();
}
result.append(Id::loadFromString(elementStr));
element = element.nextSiblingElement();
}
return result;
}
Id Serializer::loadId(QString const &elementStr)
{
return elementStr.isEmpty() ? Id() : Id::loadFromString(elementStr);
}
QVariant Serializer::parseValue(QString const &typeName, QString const &valueStr)
{
if (typeName.toLower() == "int") {
return QVariant(valueStr.toInt());
} else if (typeName.toLower() == "uint") {
return QVariant(valueStr.toUInt());
} else if (typeName.toLower() == "double") {
return QVariant(valueStr.toDouble());
} else if (typeName.toLower() == "bool") {
return QVariant(valueStr.toLower() == "true");
} else if (typeName == "QString") {
return QVariant(valueStr);
} else if (typeName.toLower() == "char") {
return QVariant(valueStr[0]);
} else if (typeName == "QPointF") {
return QVariant(parsePointF(valueStr));
} else if (typeName == "QPolygon") {
QStringList const points = valueStr.split(" : ", QString::SkipEmptyParts);
QPolygon result;
foreach (QString str, points) {
QPointF point = parsePointF(str);
result << point.toPoint();
}
return QVariant(result);
} else if (typeName == "qReal::Id") {
return Id::loadFromString(valueStr).toVariant();
} else {
Q_ASSERT(!"Unknown property type");
return QVariant();
}
}
QPointF Serializer::parsePointF(QString const &str)
{
double x = str.section(", ", 0, 0).toDouble();
double y = str.section(", ", 1, 1).toDouble();
return QPointF(x, y);
}
void Serializer::clearDir(QString const &path)
{
QDir dir(path);
if (dir.exists()) {
foreach (QFileInfo fileInfo, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
if (fileInfo.isDir()) {
clearDir(fileInfo.filePath());
dir.rmdir(fileInfo.fileName());
}
else
dir.remove(fileInfo.fileName());
}
}
}
QString Serializer::serializeQVariant(QVariant const &v)
{
switch (v.type()) {
case QVariant::Int:
return QString::number(v.toInt());
case QVariant::UInt:
return QString::number(v.toUInt());
case QVariant::Double:
return QString::number(v.toDouble());
case QVariant::Bool:
return QString("%1").arg(v.toBool());
case QVariant::String:
return v.toString();
case QVariant::Char:
return v.toChar();
case QVariant::PointF:
return serializeQPointF(v.toPointF());
case QVariant::Polygon:
return serializeQPolygon(v.value<QPolygon>());
case QVariant::UserType:
if (v.userType() == QMetaType::type("qReal::Id"))
return v.value<qReal::Id>().toString();
// Если нет, идём в default и там ругаемся.
default:
qDebug() << v;
Q_ASSERT(!"Unsupported QVariant type.");
return "";
}
}
QString Serializer::serializeQPointF(QPointF const &p)
{
return QString::number(p.x()) + ", " + QString::number(p.y());
}
QString Serializer::serializeQPolygon(QPolygon const &p)
{
QString result("");
foreach (QPoint point, p) {
result += serializeQPointF(point) + " : ";
}
return result;
}
QString Serializer::pathToElement(Id const &id) const
{
QString dirName = mWorkingDir;
QStringList partsList = id.toString().split('/');
Q_ASSERT(partsList.size() >=1 && partsList.size() <= 5);
for (int i = 1; i < partsList.size() - 1; ++i) {
dirName += "/" + partsList[i];
}
return dirName + "/" + partsList[partsList.size() - 1];
}
QString Serializer::createDirectory(Id const &id, Id const &logicalId) const
{
QString dirName = mWorkingDir + "/tree";
if (logicalId == Id()) {
dirName += "/logical";
} else {
dirName += "/graphical";
}
QStringList const partsList = id.toString().split('/');
Q_ASSERT(partsList.size() >= 1 && partsList.size() <= 5);
for (int i = 1; i < partsList.size() - 1; ++i) {
dirName += "/" + partsList[i];
}
QDir dir;
dir.rmdir(mWorkingDir);
dir.mkpath(dirName);
return dirName + "/" + partsList[partsList.size() - 1];
}
QDomElement Serializer::idListToXml(QString const &attributeName, IdList const &idList, QDomDocument &doc)
{
QDomElement result = doc.createElement(attributeName);
foreach (Id id, idList) {
QDomElement element = doc.createElement("object");
element.setAttribute("id", id.toString());
result.appendChild(element);
}
return result;
}
QDomElement Serializer::propertiesToXml(Object* const object, QDomDocument &doc)
{
QDomElement result = doc.createElement("properties");
QMapIterator<QString, QVariant> i = object->propertiesIterator();
while (i.hasNext()) {
i.next();
QString typeName = i.value().typeName();
if (typeName == "qReal::IdList") {
QDomElement list = idListToXml(i.key(), i.value().value<IdList>(), doc);
list.setAttribute("type", "qReal::IdList");
result.appendChild(list);
} else {
QDomElement property = doc.createElement(i.value().typeName());
property.setAttribute("key", i.key());
QString value = serializeQVariant(i.value());
property.setAttribute("value", value);
result.appendChild(property);
}
}
return result;
}
| [
"[email protected]"
]
| [
[
[
1,
348
]
]
]
|
5d4875a69878a21bd893bee37212e308598224e3 | 4d838ba98a21fc4593652e66eb7df0fac6282ef6 | /CaveProj/BillboardSpriteDrawer.h | c154c27aa360a6f063664ec3f6460274c7ce2a57 | []
| no_license | davidhart/ProceduralCaveEditor | 39ed0cf4ab4acb420fa2ad4af10f9546c138a83a | 31264591f2dcd250299049c826aeca18fc52880e | refs/heads/master | 2021-01-17T15:10:09.100572 | 2011-05-03T19:24:06 | 2011-05-03T19:24:06 | 69,302,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | h | #pragma once
#ifndef _BILLBOARDSPRITEDRAWER_H_
#define _BILLBOARDSPRITEDRAWER_H_
#include <d3d10.h>
#include <d3dx10.h>
#include <vector>
#include "Vector.h"
class RenderWindow;
class Camera;
class BillboardSpriteDrawer
{
public:
BillboardSpriteDrawer();
void Load(RenderWindow& renderWindow);
void Unload();
void Begin(const Camera& camera);
void Draw(const Vector3f& position, float size, DWORD color, ID3D10ShaderResourceView* texture);
void End();
void Flush();
private:
struct Sprite
{
Vector3f _position;
DWORD _color;
float _size;
};
ID3D10ShaderResourceView* _batchTexture;
ID3D10Effect* _renderEffect;
ID3D10EffectTechnique* _renderTechnique;
ID3D10InputLayout* _vertexLayout;
ID3D10EffectMatrixVariable* _worldviewprojection;
ID3D10EffectMatrixVariable* _invview;
ID3D10EffectShaderResourceVariable* _textureVar;
ID3D10Device* _device;
std::vector<Sprite> _sprites;
};
#endif | [
"[email protected]"
]
| [
[
[
1,
45
]
]
]
|
ac974e5c7865bcce4e365db8fe922a4272236f3c | 7c3428903c14830c8776acdb236abcd154813cdb | /Sales Item/Sales_Item.cpp | 4379df911a20fad6493c3357c8cd63e63f042bdb | []
| no_license | xhbang/Cpp-primer | 4a9f80a80dc2255965175548be314451d381b72c | 64fd3c4c2e016d1412fdcb812c394c452542be96 | refs/heads/master | 2016-09-06T17:34:12.630194 | 2011-12-03T05:50:49 | 2011-12-03T05:50:49 | 2,903,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | cpp | #include "Sales_Item.h"
//implement of sales.h file
std::istream& input(std::istream & in){
double price;
in>>isbn>>units_sold>>price;
if(in)
revenue = units_sold * price;
else{
units_sold = 0;
revenue = 0.0;
}
return in;
}
std::ostream& ouput(std::ostream out) const {
out<<isbn<<"\t"<<units_sold<<"\t"<<revenue<<"\t"<<avg price();
return out;
}
//there is another way to do this,using try/catch
double avg_price(){
if(units != 0)
return revenue / unit_sold;
else
return 0;
}
Sales_Item Sales_Item::add(Sales_Item & other){
revenue = this->revenue + other.revenue;
units_sold = this->units_sold + other.units_sold;
//why return this kind type?
return *this;
}
| [
"[email protected]"
]
| [
[
[
1,
36
]
]
]
|
30893ec48d3e73c62cc77e8681f5034ba6eed733 | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Components/Optimizers/AdaptiveStochasticGradientDescent/elxAdaptiveStochasticGradientDescent.hxx | 48cf1c3f2087c0c36e2c8d33366c1ff658c0e2c9 | []
| no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47,871 | hxx | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __elxAdaptiveStochasticGradientDescent_hxx
#define __elxAdaptiveStochasticGradientDescent_hxx
#include "elxAdaptiveStochasticGradientDescent.h"
#include <iomanip>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <utility>
#include "vnl/vnl_math.h"
#include "vnl/vnl_fastops.h"
#include "vnl/vnl_diag_matrix.h"
#include "vnl/vnl_sparse_matrix.h"
#include "vnl/vnl_matlab_filewrite.h"
#include "itkAdvancedImageToImageMetric.h"
#include "elxTimer.h"
namespace elastix
{
using namespace itk;
/**
* ********************** Constructor ***********************
*/
template <class TElastix>
AdaptiveStochasticGradientDescent<TElastix>
::AdaptiveStochasticGradientDescent()
{
this->m_MaximumNumberOfSamplingAttempts = 0;
this->m_CurrentNumberOfSamplingAttempts = 0;
this->m_PreviousErrorAtIteration = 0;
this->m_AutomaticParameterEstimationDone = false;
this->m_AutomaticParameterEstimation = false;
this->m_MaximumStepLength = 1.0;
this->m_NumberOfGradientMeasurements = 0;
this->m_NumberOfJacobianMeasurements = 0;
this->m_NumberOfSamplesForExactGradient = 100000;
this->m_RandomGenerator = RandomGeneratorType::New();
this->m_AdvancedTransform = 0;
} // Constructor
/**
* ***************** BeforeRegistration ***********************
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::BeforeRegistration( void )
{
/** Add the target cell "stepsize" to xout["iteration"]. */
xout["iteration"].AddTargetCell("2:Metric");
xout["iteration"].AddTargetCell("3a:Time");
xout["iteration"].AddTargetCell("3b:StepSize");
xout["iteration"].AddTargetCell("4:||Gradient||");
/** Format the metric and stepsize as floats. */
xl::xout["iteration"]["2:Metric"] << std::showpoint << std::fixed;
xl::xout["iteration"]["3a:StepSize"] << std::showpoint << std::fixed;
xl::xout["iteration"]["3b:StepSize"] << std::showpoint << std::fixed;
xl::xout["iteration"]["4:||Gradient||"] << std::showpoint << std::fixed;
this->m_SettingsVector.clear();
} // end BeforeRegistration()
/**
* ***************** BeforeEachResolution ***********************
*/
template <class TElastix>
void AdaptiveStochasticGradientDescent<TElastix>
::BeforeEachResolution( void )
{
/** Get the current resolution level. */
unsigned int level = static_cast<unsigned int>(
this->m_Registration->GetAsITKBaseType()->GetCurrentLevel() );
const unsigned int P = this->GetElastix()->GetElxTransformBase()
->GetAsITKBaseType()->GetNumberOfParameters();
/** Set the maximumNumberOfIterations. */
unsigned int maximumNumberOfIterations = 500;
this->GetConfiguration()->ReadParameter( maximumNumberOfIterations,
"MaximumNumberOfIterations", this->GetComponentLabel(), level, 0 );
this->SetNumberOfIterations( maximumNumberOfIterations );
/** Set the gain parameter A. */
double A = 20.0;
this->GetConfiguration()->ReadParameter( A,
"SP_A", this->GetComponentLabel(), level, 0 );
this->SetParam_A( A );
/** Set the MaximumNumberOfSamplingAttempts. */
unsigned int maximumNumberOfSamplingAttempts = 0;
this->GetConfiguration()->ReadParameter( maximumNumberOfSamplingAttempts,
"MaximumNumberOfSamplingAttempts", this->GetComponentLabel(), level, 0 );
this->SetMaximumNumberOfSamplingAttempts( maximumNumberOfSamplingAttempts );
/** Set/Get the initial time. Default: 0.0. Should be >=0. */
double initialTime = 0.0;
this->GetConfiguration()->ReadParameter( initialTime,
"SigmoidInitialTime", this->GetComponentLabel(), level, 0 );
this->SetInitialTime( initialTime );
/** Set the maximum band size of the covariance matrix. */
this->m_MaxBandCovSize = 192;
this->GetConfiguration()->ReadParameter( this->m_MaxBandCovSize,
"MaxBandCovSize", this->GetComponentLabel(), level, 0 );
/** Set the number of random samples used to estimate the structure of the covariance matrix. */
this->m_NumberOfBandStructureSamples = 10;
this->GetConfiguration()->ReadParameter( this->m_NumberOfBandStructureSamples,
"NumberOfBandStructureSamples", this->GetComponentLabel(), level, 0 );
/** Set/Get whether the adaptive step size mechanism is desired. Default: true
* NB: the setting is turned of in case of UseRandomSampleRegion=true.
* Deprecated alias UseCruzAcceleration is also still supported.
*/
bool useAdaptiveStepSizes = true;
this->GetConfiguration()->ReadParameter( useAdaptiveStepSizes,
"UseCruzAcceleration", this->GetComponentLabel(), level, 0, false );
this->GetConfiguration()->ReadParameter( useAdaptiveStepSizes,
"UseAdaptiveStepSizes", this->GetComponentLabel(), level, 0 );
this->SetUseAdaptiveStepSizes( useAdaptiveStepSizes );
/** Set whether automatic gain estimation is required; default: true. */
this->m_AutomaticParameterEstimation = true;
this->GetConfiguration()->ReadParameter( this->m_AutomaticParameterEstimation,
"AutomaticParameterEstimation", this->GetComponentLabel(), level, 0 );
if ( this->m_AutomaticParameterEstimation )
{
/** Set the maximum step length: the maximum displacement of a voxel in mm.
* Compute default value: mean spacing of fixed and moving image.
*/
const unsigned int fixdim = this->GetElastix()->FixedDimension;
const unsigned int movdim = this->GetElastix()->MovingDimension;
double sum = 0.0;
for (unsigned int d = 0; d < fixdim; ++d )
{
sum += this->GetElastix()->GetFixedImage()->GetSpacing()[d];
}
for (unsigned int d = 0; d < movdim; ++d )
{
sum += this->GetElastix()->GetMovingImage()->GetSpacing()[d];
}
this->m_MaximumStepLength = sum / static_cast<double>( fixdim + movdim );
/** Read user setting */
this->GetConfiguration()->ReadParameter( this->m_MaximumStepLength,
"MaximumStepLength", this->GetComponentLabel(), level, 0 );
/** Number of gradients N to estimate the average square magnitudes
* of the exact gradient and the approximation error.
* A value of 0 (default) means automatic estimation.
*/
this->m_NumberOfGradientMeasurements = 0;
this->GetConfiguration()->ReadParameter(
this->m_NumberOfGradientMeasurements,
"NumberOfGradientMeasurements",
this->GetComponentLabel(), level, 0 );
/** Set the number of Jacobian measurements M.
* By default, if nothing specified by the user, M is determined as:
* M = max( 1000, nrofparams );
* This is a rather crude rule of thumb, which seems to work in practice.
*/
this->m_NumberOfJacobianMeasurements = vnl_math_max(
static_cast<unsigned int>(1000), static_cast<unsigned int>(P) );
this->GetConfiguration()->ReadParameter(
this->m_NumberOfJacobianMeasurements,
"NumberOfJacobianMeasurements",
this->GetComponentLabel(), level, 0 );
/** Set the number of image samples used to compute the 'exact' gradient.
* By default, if nothing supplied by the user, 100000. This works in general.
* If the image is smaller, the number of samples is automatically reduced later.
*/
this->m_NumberOfSamplesForExactGradient = 100000;
this->GetConfiguration()->ReadParameter(
this->m_NumberOfSamplesForExactGradient,
"NumberOfSamplesForExactGradient",
this->GetComponentLabel(), level, 0 );
} // end if automatic parameter estimation
else
{
/** If no automatic parameter estimation is used, a and alpha also need
* to be specified.
*/
double a = 400.0; // arbitrary guess
double alpha = 0.602;
this->GetConfiguration()->ReadParameter(a, "SP_a", this->GetComponentLabel(), level, 0 );
this->GetConfiguration()->ReadParameter(alpha, "SP_alpha", this->GetComponentLabel(), level, 0 );
this->SetParam_a( a );
this->SetParam_alpha( alpha );
/** Set/Get the maximum of the sigmoid. Should be >0. Default: 1.0. */
double sigmoidMax = 1.0;
this->GetConfiguration()->ReadParameter( sigmoidMax,
"SigmoidMax", this->GetComponentLabel(), level, 0 );
this->SetSigmoidMax( sigmoidMax );
/** Set/Get the minimum of the sigmoid. Should be <0. Default: -0.8. */
double sigmoidMin = -0.8;
this->GetConfiguration()->ReadParameter( sigmoidMin,
"SigmoidMin", this->GetComponentLabel(), level, 0 );
this->SetSigmoidMin( sigmoidMin );
/** Set/Get the scaling of the sigmoid width. Large values
* cause a more wide sigmoid. Default: 1e-8. Should be >0.
*/
double sigmoidScale = 1e-8;
this->GetConfiguration()->ReadParameter( sigmoidScale,
"SigmoidScale", this->GetComponentLabel(), level, 0 );
this->SetSigmoidScale( sigmoidScale );
} // end else: no automatic parameter estimation
//temp save gradients
} // end BeforeEachResolution()
/**
* ***************** AfterEachIteration *************************
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::AfterEachIteration( void )
{
/** Print some information. */
xl::xout["iteration"]["2:Metric"] << this->GetValue();
xl::xout["iteration"]["3a:Time"] << this->GetCurrentTime();
xl::xout["iteration"]["3b:StepSize"] << this->GetLearningRate();
xl::xout["iteration"]["4:||Gradient||"] << this->GetGradient().magnitude();
/** Select new spatial samples for the computation of the metric. */
if ( this->GetNewSamplesEveryIteration() )
{
this->SelectNewSamples();
}
} // end AfterEachIteration()
/**
* ***************** AfterEachResolution *************************
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::AfterEachResolution( void )
{
/** Get the current resolution level. */
unsigned int level = static_cast<unsigned int>(
this->m_Registration->GetAsITKBaseType()->GetCurrentLevel() );
/**
* typedef enum {
* MaximumNumberOfIterations,
* MetricError,
* MinimumStepSize } StopConditionType;
*/
std::string stopcondition;
switch( this->GetStopCondition() )
{
case MaximumNumberOfIterations :
stopcondition = "Maximum number of iterations has been reached";
break;
case MetricError :
stopcondition = "Error in metric";
break;
case MinimumStepSize :
stopcondition = "The minimum step length has been reached";
break;
default:
stopcondition = "Unknown";
break;
}
/** Print the stopping condition. */
elxout << "Stopping condition: " << stopcondition << "." << std::endl;
/** Store the used parameters, for later printing to screen. */
SettingsType settings;
settings.a = this->GetParam_a();
settings.A = this->GetParam_A();
settings.alpha = this->GetParam_alpha();
settings.fmax = this->GetSigmoidMax();
settings.fmin = this->GetSigmoidMin();
settings.omega = this->GetSigmoidScale();
this->m_SettingsVector.push_back( settings );
/** Print settings that were used in this resolution. */
SettingsVectorType tempSettingsVector;
tempSettingsVector.push_back( settings );
elxout
<< "Settings of " << this->elxGetClassName()
<< " in resolution " << level << ":" << std::endl;
this->PrintSettingsVector( tempSettingsVector );
} // end AfterEachResolution()
/**
* ******************* AfterRegistration ************************
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::AfterRegistration( void )
{
/** Print the best metric value. */
double bestValue = this->GetValue();
elxout << std::endl
<< "Final metric value = "
<< bestValue
<< std::endl;
elxout
<< "Settings of " << this->elxGetClassName()
<< " for all resolutions:" << std::endl;
this->PrintSettingsVector( this->m_SettingsVector );
} // end AfterRegistration()
/**
* ****************** StartOptimization *************************
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::StartOptimization( void )
{
/** Check if the entered scales are correct and != [ 1 1 1 ...]. */
this->SetUseScales( false );
const ScalesType & scales = this->GetScales();
if ( scales.GetSize() == this->GetInitialPosition().GetSize() )
{
ScalesType unit_scales( scales.GetSize() );
unit_scales.Fill(1.0);
if ( scales != unit_scales )
{
/** only then: */
this->SetUseScales( true );
}
}
this->m_AutomaticParameterEstimationDone = false;
this->Superclass1::StartOptimization();
} //end StartOptimization()
/**
* ********************** ResumeOptimization **********************
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::ResumeOptimization( void )
{
if ( this->GetAutomaticParameterEstimation()
&& !this->m_AutomaticParameterEstimationDone )
{
this->AutomaticParameterEstimation();
// hack
this->m_AutomaticParameterEstimationDone = true;
}
this->Superclass1::ResumeOptimization();
} // end ResumeOptimization()
/**
* ****************** MetricErrorResponse *************************
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::MetricErrorResponse( ExceptionObject & err )
{
if ( this->GetCurrentIteration() != this->m_PreviousErrorAtIteration )
{
this->m_PreviousErrorAtIteration = this->GetCurrentIteration();
this->m_CurrentNumberOfSamplingAttempts = 1;
}
else
{
this->m_CurrentNumberOfSamplingAttempts++;
}
if ( this->m_CurrentNumberOfSamplingAttempts <= this->m_MaximumNumberOfSamplingAttempts )
{
this->SelectNewSamples();
this->ResumeOptimization();
}
else
{
/** Stop optimisation and pass on exception. */
this->Superclass1::MetricErrorResponse( err );
}
} // end MetricErrorResponse()
/**
* ******************* AutomaticParameterEstimation **********************
* Estimates some reasonable values for the parameters
* SP_a, SP_alpha (=1), SigmoidMin, SigmoidMax (=1), and SigmoidScale.
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::AutomaticParameterEstimation( void )
{
/** Setup timers. */
tmr::Timer::Pointer timer1 = tmr::Timer::New();
tmr::Timer::Pointer timer2 = tmr::Timer::New();
tmr::Timer::Pointer timer3 = tmr::Timer::New();
/** Total time. */
timer1->StartTimer();
elxout << "Starting automatic parameter estimation for "
<< this->elxGetClassName()
<< " ..." << std::endl;
/** Get the user input. */
const double delta = this->GetMaximumStepLength();
/** Compute the Jacobian terms. */
double TrC = 0.0;
double TrCC = 0.0;
double maxJJ = 0.0;
double maxJCJ = 0.0;
timer2->StartTimer();
this->ComputeJacobianTerms( TrC, TrCC, maxJJ, maxJCJ );
timer2->StopTimer();
elxout << " Computing the Jacobian terms took "
<< timer2->PrintElapsedTimeDHMS()
<< std::endl;
/** Determine number of gradient measurements such that
* E + 2\sqrt(Var) < K E
* with
* E = E(1/N \sum_n g_n^T g_n) = sigma_1^2 TrC
* Var = Var(1/N \sum_n g_n^T g_n) = 2 sigma_1^4 TrCC / N
* K = 1.5
* We enforce a minimum of 2.
*/
timer3->StartTimer();
if ( this->m_NumberOfGradientMeasurements == 0 )
{
const double K = 1.5;
if ( TrCC > 1e-14 && TrC > 1e-14 )
{
this->m_NumberOfGradientMeasurements = static_cast<unsigned int>(
vcl_ceil( 8.0 * TrCC / TrC / TrC / (K-1) / (K-1) ) );
}
else
{
this->m_NumberOfGradientMeasurements = 2;
}
this->m_NumberOfGradientMeasurements = vnl_math_max(
static_cast<unsigned int>( 2 ),
this->m_NumberOfGradientMeasurements );
elxout << " NumberOfGradientMeasurements to estimate sigma_i: "
<< this->m_NumberOfGradientMeasurements << std::endl;
}
/** Measure square magnitude of exact gradient and approximation error. */
const double sigma4factor = 1.0;
double sigma4 = 0.0;
double gg = 0.0;
double ee = 0.0;
if ( maxJJ > 1e-14 )
{
sigma4 = sigma4factor * delta / vcl_sqrt( maxJJ );
}
this->SampleGradients(
this->GetScaledCurrentPosition(), sigma4, gg, ee );
timer3->StopTimer();
elxout << " Sampling the gradients took "
<< timer3->PrintElapsedTimeDHMS()
<< std::endl;
/** Determine parameter settings. */
double sigma1 = 0.0;
double sigma3 = 0.0;
/** Estimate of sigma such that empirical norm^2 equals theoretical:
* gg = 1/N sum_n g_n' g_n
* sigma = gg / TrC
*/
if ( gg > 1e-14 && TrC > 1e-14 )
{
sigma1 = vcl_sqrt( gg / TrC );
}
if ( ee > 1e-14 && TrC > 1e-14 )
{
sigma3 = vcl_sqrt( ee / TrC );
}
const double alpha = 1.0;
const double A = this->GetParam_A();
double a_max = 0.0;
if ( sigma1 > 1e-14 && maxJCJ > 1e-14 )
{
a_max = A * delta / sigma1 / vcl_sqrt( maxJCJ );
}
const double noisefactor = sigma1 * sigma1
/ ( sigma1 * sigma1 + sigma3 * sigma3 + 1e-14 );
const double a = a_max * noisefactor;
const double omega = vnl_math_max( 1e-14, 0.1 * sigma3 * sigma3 * vcl_sqrt( TrCC ) );
const double fmax = 1.0;
const double fmin = -0.99 + 0.98 * noisefactor;
/** Set parameters in superclass. */
this->SetParam_a( a );
this->SetParam_alpha( alpha );
this->SetSigmoidMax( fmax );
this->SetSigmoidMin( fmin );
this->SetSigmoidScale( omega );
/** Print the elapsed time. */
timer1->StopTimer();
elxout << "Automatic parameter estimation took "
<< timer1->PrintElapsedTimeDHMS()
<< std::endl;
} // end AutomaticParameterEstimation()
/**
* ******************** SampleGradients **********************
*/
/** Measure some derivatives, exact and approximated. Returns
* the squared magnitude of the gradient and approximation error.
* Needed for the automatic parameter estimation.
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::SampleGradients( const ParametersType & mu0,
double perturbationSigma, double & gg, double & ee )
{
/** Some shortcuts. */
const unsigned int M = this->GetElastix()->GetNumberOfMetrics();
/** Variables for sampler support. Each metric may have a sampler. */
std::vector< bool > useRandomSampleRegionVec( M, false );
std::vector< ImageRandomSamplerBasePointer > randomSamplerVec( M, 0 );
std::vector< ImageRandomCoordinateSamplerPointer > randomCoordinateSamplerVec( M, 0 );
std::vector< ImageGridSamplerPointer > gridSamplerVec( M, 0 );
/** If new samples every iteration, get each sampler, and check if it is
* a kind of random sampler. If yes, prepare an additional grid sampler
* for the exact gradients, and set the stochasticgradients flag to true.
*/
bool stochasticgradients = false;
if ( this->GetNewSamplesEveryIteration() )
{
for ( unsigned int m = 0; m < M; ++m )
{
/** Get the sampler. */
ImageSamplerBasePointer sampler =
this->GetElastix()->GetElxMetricBase( m )->GetAdvancedMetricImageSampler();
randomSamplerVec[m] =
dynamic_cast< ImageRandomSamplerBaseType * >( sampler.GetPointer() );
randomCoordinateSamplerVec[m] =
dynamic_cast< ImageRandomCoordinateSamplerType * >( sampler.GetPointer() );
if ( randomSamplerVec[m].IsNotNull() )
{
/** At least one of the metric has a random sampler. */
stochasticgradients |= true;
/** If the sampler is a randomCoordinateSampler set the UseRandomSampleRegion
* property to false temporarily. It disturbs the parameter estimation.
* At the end of this function the original setting is set back.
* Also, the AdaptiveStepSize mechanism is turned off when any of the samplers
* has UseRandomSampleRegion==true.
* \todo Extend ASGD to really take into account random region sampling.
*/
if ( randomCoordinateSamplerVec[ m ].IsNotNull() )
{
useRandomSampleRegionVec[ m ]
= randomCoordinateSamplerVec[ m ]->GetUseRandomSampleRegion();
if ( useRandomSampleRegionVec[ m ] )
{
if ( this->GetUseAdaptiveStepSizes() )
{
xl::xout["warning"]
<< "WARNING: UseAdaptiveStepSizes is turned off, "
<< "because UseRandomSampleRegion is set to \"true\"."
<< std::endl;
this->SetUseAdaptiveStepSizes( false );
}
}
randomCoordinateSamplerVec[ m ]->SetUseRandomSampleRegion( false );
} // end if random coordinate sampler
/** Set up the grid samper for the "exact" gradients.
* Copy settings from the random sampler and update.
*/
gridSamplerVec[ m ] = ImageGridSamplerType::New();
gridSamplerVec[ m ]->SetInput( randomSamplerVec[ m ]->GetInput() );
gridSamplerVec[ m ]->SetInputImageRegion( randomSamplerVec[ m ]->GetInputImageRegion() );
gridSamplerVec[ m ]->SetMask( randomSamplerVec[ m ]->GetMask() );
gridSamplerVec[ m ]->SetNumberOfSamples( this->m_NumberOfSamplesForExactGradient );
gridSamplerVec[ m ]->Update();
} // end if random sampler
} // end for loop over metrics
} // end if NewSamplesEveryIteration.
/** Prepare for progress printing. */
ProgressCommandPointer progressObserver = ProgressCommandType::New();
progressObserver->SetUpdateFrequency(
this->m_NumberOfGradientMeasurements, this->m_NumberOfGradientMeasurements );
progressObserver->SetStartString( " Progress: " );
elxout << " Sampling gradients ..." << std::endl;
/** Initialize some variables for storing gradients and their magnitudes. */
DerivativeType approxgradient;
DerivativeType exactgradient;
DerivativeType diffgradient;
double exactgg = 0.0;
double diffgg = 0.0;
/** Compute gg for some random parameters. */
for ( unsigned int i = 0 ; i < this->m_NumberOfGradientMeasurements; ++i )
{
/** Show progress 0-100% */
progressObserver->UpdateAndPrintProgress( i );
/** Generate a perturbation, according to:
* \mu_i ~ N( \mu_0, perturbationsigma^2 I ).
*/
ParametersType perturbedMu0 = mu0;
this->AddRandomPerturbation( perturbedMu0, perturbationSigma );
/** Compute contribution to exactgg and diffgg. */
if ( stochasticgradients )
{
/** Set grid sampler(s) and get exact derivative. */
for ( unsigned int m = 0; m < M; ++m )
{
if ( gridSamplerVec[ m ].IsNotNull() )
{
this->GetElastix()->GetElxMetricBase( m )
->SetAdvancedMetricImageSampler( gridSamplerVec[ m ] );
}
}
this->GetScaledDerivativeWithExceptionHandling( perturbedMu0, exactgradient );
/** Set random sampler(s), select new spatial samples and get approximate derivative. */
for ( unsigned int m = 0; m < M; ++m )
{
if ( randomSamplerVec[ m ].IsNotNull() )
{
this->GetElastix()->GetElxMetricBase( m )->
SetAdvancedMetricImageSampler( randomSamplerVec[ m ] );
}
}
this->SelectNewSamples();
this->GetScaledDerivativeWithExceptionHandling( perturbedMu0, approxgradient );
/** Compute error vector. */
diffgradient = exactgradient - approxgradient;
/** Compute g^T g and e^T e */
exactgg += exactgradient.squared_magnitude();
diffgg += diffgradient.squared_magnitude();
}
else // no stochastic gradients
{
/** Get exact gradient. */
this->GetScaledDerivativeWithExceptionHandling( perturbedMu0, exactgradient );
/** Compute g^T g. NB: diffgg=0. */
exactgg += exactgradient.squared_magnitude();
} // end else: no stochastic gradients
} // end for loop over gradient measurements
progressObserver->PrintProgress( 1.0 );
/** Compute means. */
exactgg /= this->m_NumberOfGradientMeasurements;
diffgg /= this->m_NumberOfGradientMeasurements;
/** For output: gg and ee.
* gg and ee will be divided by Pd, but actually need to be divided by
* the rank, in case of maximum likelihood. In case of no maximum likelihood,
* the rank equals Pd.
*/
gg = exactgg;
ee = diffgg;
/** Set back useRandomSampleRegion flag to what it was. */
for ( unsigned int m = 0; m < M; ++m )
{
if ( randomCoordinateSamplerVec[ m ].IsNotNull() )
{
randomCoordinateSamplerVec[ m ]
->SetUseRandomSampleRegion( useRandomSampleRegionVec[ m ] );
}
}
} // end SampleGradients()
/**
* ******************** ComputeJacobianTerms **********************
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::ComputeJacobianTerms( double & TrC, double & TrCC,
double & maxJJ, double & maxJCJ )
{
/** This function computes four terms needed for the automatic parameter
* estimation. The equation number refers to the IJCV paper.
* Term 1: TrC, which is the trace of the covariance matrix, needed in (34):
* C = 1/n \sum_{i=1}^n J_i^T J_i (25)
* with n the number of samples, J_i the Jacobian of the i-th sample.
* Term 2: TrCC, which is the Frobenius norm of C, needed in (60):
* ||C||_F^2 = trace( C^T C )
* To compute equations (47) and (54) we need the four sub-terms:
* A: trace( J_j C J_j^T ) in (47)
* B: || J_j C J_j^T ||_F in (47)
* C: || J_j ||_F^2 in (54)
* D: || J_j J_j^T ||_F in (54)
* Term 3: maxJJ, see (47)
* Term 4: maxJCJ, see (54)
*/
typedef double CovarianceValueType;
typedef Array2D<CovarianceValueType> CovarianceMatrixType;
typedef vnl_sparse_matrix<CovarianceValueType> SparseCovarianceMatrixType;
typedef typename SparseCovarianceMatrixType::row SparseRowType;
typedef typename SparseCovarianceMatrixType::pair_t SparseCovarianceElementType;
typedef Array<unsigned int> NonZeroJacobianIndicesExpandedType;
typedef vnl_diag_matrix<CovarianceValueType> DiagCovarianceMatrixType;
typedef vnl_vector<CovarianceValueType> JacobianColumnType;
/** Initialize. */
TrC = TrCC = maxJJ = maxJCJ = 0.0;
this->CheckForAdvancedTransform();
/** Get samples. */
ImageSampleContainerPointer sampleContainer = 0;
this->SampleFixedImageForJacobianTerms( sampleContainer );
const unsigned int nrofsamples = sampleContainer->Size();
const double n = static_cast<double>( nrofsamples );
/** Get the number of parameters. */
const unsigned int P = static_cast<unsigned int>(
this->GetScaledCurrentPosition().GetSize() );
/** Get transform and set current position. */
typename TransformType::Pointer transform = this->GetRegistration()
->GetAsITKBaseType()->GetTransform();
transform->SetParameters( this->GetCurrentPosition() );
const unsigned int outdim = transform->GetOutputSpaceDimension();
/** Get scales vector */
const ScalesType & scales = this->m_ScaledCostFunction->GetScales();
/** Create iterator over the sample container. */
typename ImageSampleContainerType::ConstIterator iter;
typename ImageSampleContainerType::ConstIterator begin = sampleContainer->Begin();
typename ImageSampleContainerType::ConstIterator end = sampleContainer->End();
unsigned int samplenr = 0;
/** Variables for nonzerojacobian indices and the Jacobian. */
const unsigned int sizejacind
= this->m_AdvancedTransform->GetNumberOfNonZeroJacobianIndices();
JacobianType jacj( outdim, sizejacind );
jacj.Fill( 0.0 );
NonZeroJacobianIndicesType jacind( sizejacind );
jacind[ 0 ] = 0;
if ( sizejacind > 1 ) jacind[ 1 ] = 0;
NonZeroJacobianIndicesType prevjacind = jacind;
/** Initialize covariance matrix. Sparse, diagonal, and band form. */
SparseCovarianceMatrixType cov( P, P );
DiagCovarianceMatrixType diagcov( P, 0.0 );
CovarianceMatrixType bandcov;
/** For temporary storage of J'J. */
CovarianceMatrixType jactjac( sizejacind, sizejacind );
jactjac.Fill( 0.0 );
/** Prepare for progress printing. */
ProgressCommandPointer progressObserver = ProgressCommandType::New();
progressObserver->SetUpdateFrequency( nrofsamples * 2, 100 );
progressObserver->SetStartString( " Progress: " );
elxout << " Computing JacobianTerms ..." << std::endl;
/** Variables for the band cov matrix. */
const unsigned int maxbandcovsize = m_MaxBandCovSize;
const unsigned int nrOfBandStructureSamples = m_NumberOfBandStructureSamples;
/** DifHist is a histogram of absolute parameterNrDifferences that
* occur in the nonzerojacobianindex vectors.
* DifHist2 is another way of storing the histogram, as a vector
* of pairs. pair.first = Frequency, pair.second = parameterNrDifference.
* This is useful for sorting.
*/
typedef std::vector<unsigned int> DifHistType;
typedef std::pair<unsigned int, unsigned int> FreqPairType;
typedef std::vector<FreqPairType> DifHist2Type;
DifHistType difHist( P, 0 );
DifHist2Type difHist2;
/** Try to guess the band structure of the covariance matrix.
* A 'band' is a series of elements cov(p,q) with constant q-p.
* In the loop below, on a few positions in the image the Jacobian
* is computed. The nonzerojacobianindices are inspected to figure out
* which values of q-p occur often. This is done by making a histogram.
* The histogram is then sorted and the most occurring bands
* are determined. The covariance elements in these bands will not
* be stored in the sparse matrix structure 'cov', but in the band
* matrix 'bandcov', which is much faster.
* Only after the bandcov and cov have been filled (by looping over
* all Jacobian measurements in the sample container, the bandcov
* matrix is injected in the cov matrix, for easy further calculations,
* and the bandcov matrix is deleted.
*/
unsigned int onezero = 0;
for ( unsigned int s = 0; s < nrOfBandStructureSamples; ++s )
{
/** Semi-randomly get some samples from the sample container. */
const unsigned int samplenr = ( s + 1 ) * nrofsamples
/ ( nrOfBandStructureSamples + 2 + onezero );
onezero = 1 - onezero; // introduces semi-randomness
/** Read fixed coordinates and get Jacobian J_j. */
const FixedImagePointType & point
= sampleContainer->GetElement(samplenr).m_ImageCoordinates;
this->m_AdvancedTransform->GetJacobian( point, jacj, jacind );
/** Skip invalid Jacobians in the beginning, if any. */
if ( sizejacind > 1 )
{
if ( jacind[ 0 ] == jacind[ 1 ] )
{
continue;
}
}
/** Fill the histogram of parameter nr differences. */
for ( unsigned int i = 0; i < sizejacind; ++i )
{
const int jacindi = static_cast<int>( jacind[ i ] );
for ( unsigned int j = i; j < sizejacind; ++j )
{
const int jacindj = static_cast<int>( jacind[ j ] );
difHist[ static_cast<unsigned int>( vcl_abs( jacindj - jacindi ) ) ]++;
}
}
}
/** Copy the nonzero elements of the difHist to a vector pairs. */
for ( unsigned int p = 0; p < P; ++p )
{
const unsigned int freq = difHist[ p ];
if ( freq != 0 )
{
difHist2.push_back( FreqPairType( freq, p ) );
}
}
difHist.resize( 0 );
/** Compute the number of bands. */
elxout << " Estimated band size covariance matrix: " << difHist2.size() << std::endl;
const unsigned int bandcovsize = vnl_math_min( maxbandcovsize,
static_cast<unsigned int>(difHist2.size()) );
elxout << " Used band size covariance matrix: " << bandcovsize << std::endl;
/** Maps parameterNrDifference (q-p) to colnr in bandcov. */
std::vector<unsigned int> bandcovMap( P, bandcovsize );
/** Maps colnr in bandcov to parameterNrDifference (q-p). */
std::vector<unsigned int> bandcovMap2( bandcovsize, P );
/** Sort the difHist2 based on the frequencies. */
std::sort( difHist2.begin(), difHist2.end() );
/** Determine the bands that are expected to be most dominant. */
DifHist2Type::iterator difHist2It = difHist2.end();
for ( unsigned int b = 0; b < bandcovsize; ++b )
{
--difHist2It;
bandcovMap[ difHist2It->second ] = b;
bandcovMap2[ b ] = difHist2It->second;
}
/** Initialize band matrix. */
bandcov = CovarianceMatrixType( P, bandcovsize );
bandcov.Fill( 0.0 );
/**
* TERM 1
*
* Loop over image and compute Jacobian.
* Compute C = 1/n \sum_i J_i^T J_i
* Possibly apply scaling afterwards.
*/
jacind[ 0 ] = 0;
if ( sizejacind > 1 ) jacind[ 1 ] = 0;
for ( iter = begin; iter != end; ++iter )
{
/** Print progress 0-50%. */
progressObserver->UpdateAndPrintProgress( samplenr );
++samplenr;
/** Read fixed coordinates and get Jacobian J_j. */
const FixedImagePointType & point = (*iter).Value().m_ImageCoordinates;
this->m_AdvancedTransform->GetJacobian( point, jacj, jacind );
/** Skip invalid Jacobians in the beginning, if any. */
if ( sizejacind > 1 )
{
if ( jacind[ 0 ] == jacind[ 1 ] )
{
continue;
}
}
if ( jacind == prevjacind )
{
/** Update sum of J_j^T J_j. */
vnl_fastops::inc_X_by_AtA( jactjac, jacj );
}
else
{
/** The following should only be done after the first sample. */
if ( iter != begin )
{
/** Update covariance matrix. */
for ( unsigned int pi = 0; pi < sizejacind; ++pi )
{
const unsigned int p = prevjacind[ pi ];
for ( unsigned int qi = 0; qi < sizejacind; ++qi )
{
const unsigned int q = prevjacind[ qi ];
/** Exploit symmetry: only fill upper triangular part. */
if ( q >= p )
{
const double tempval = jactjac( pi, qi ) / n;
if ( vcl_abs( tempval ) > 1e-14 )
{
const unsigned int bandindex = bandcovMap[ q - p ];
if ( bandindex < bandcovsize )
{
bandcov( p, bandindex ) +=tempval;
}
else
{
cov( p, q ) += tempval;
}
}
}
} // qi
} // pi
} // end if
/** Initialize jactjac by J_j^T J_j. */
vnl_fastops::AtA( jactjac, jacj );
/** Remember nonzerojacobian indices. */
prevjacind = jacind;
} // end else
} // end iter loop: end computation of covariance matrix
/** Update covariance matrix once again to include last jactjac updates
* \todo: a bit ugly that this loop is copied from above.
*/
for ( unsigned int pi = 0; pi < sizejacind; ++pi )
{
const unsigned int p = prevjacind[ pi ];
for ( unsigned int qi = 0; qi < sizejacind; ++qi )
{
const unsigned int q = prevjacind[ qi ];
if ( q >= p )
{
const double tempval = jactjac( pi, qi ) / n;
if ( vcl_abs( tempval ) > 1e-14 )
{
const unsigned int bandindex = bandcovMap[ q - p ];
if ( bandindex < bandcovsize )
{
bandcov( p, bandindex ) +=tempval;
}
else
{
cov( p, q ) += tempval;
}
}
}
} // qi
} // pi
/** Copy the bandmatrix into the sparse matrix and empty the bandcov matrix.
* \todo: perhaps work further with this bandmatrix instead.
*/
for( unsigned int p = 0; p < P; ++p )
{
for ( unsigned int b = 0; b < bandcovsize; ++b )
{
const double tempval = bandcov( p, b );
if ( vcl_abs( tempval ) > 1e-14 )
{
const unsigned int q = p + bandcovMap2[ b ];
cov( p, q ) = tempval;
}
}
}
bandcov.set_size( 0, 0 );
/** Apply scales. */
if ( this->GetUseScales() )
{
for ( unsigned int p = 0; p < P; ++p )
{
cov.scale_row( p, 1.0 / scales[ p ] );
}
/** \todo: this might be faster with get_row instead of the iterator */
cov.reset();
bool notfinished = cov.next();
while ( notfinished )
{
const int col = cov.getcolumn();
cov( cov.getrow(), col ) /= scales[ col ];
notfinished = cov.next();
}
}
/** Compute TrC = trace(C), and diagcov. */
for ( unsigned int p = 0; p < P; ++p )
{
if ( !cov.empty_row( p ) )
{
//avoid creation of element if the row is empty
CovarianceValueType & covpp = cov( p, p );
TrC += covpp;
diagcov[ p ] = covpp;
}
}
/**
* TERM 2
*
* Compute TrCC = ||C||_F^2.
*/
cov.reset();
bool notfinished2 = cov.next();
while ( notfinished2 )
{
TrCC += vnl_math_sqr( cov.value() );
notfinished2 = cov.next();
}
/** Symmetry: multiply by 2 and subtract sumsqr(diagcov). */
TrCC *= 2.0;
TrCC -= diagcov.diagonal().squared_magnitude();
/**
* TERM 3 and 4
*
* Compute maxJJ and maxJCJ
* \li maxJJ = max_j [ ||J_j||_F^2 + 2\sqrt{2} || J_j J_j^T ||_F ]
* \li maxJCJ = max_j [ Tr( J_j C J_j^T ) + 2\sqrt{2} || J_j C J_j^T ||_F ]
*/
maxJJ = 0.0;
maxJCJ = 0.0;
const double sqrt2 = vcl_sqrt( static_cast<double>( 2.0 ) );
JacobianType jacjjacj( outdim, outdim );
JacobianType jacjcov( outdim, sizejacind );
DiagCovarianceMatrixType diagcovsparse( sizejacind );
JacobianType jacjdiagcov( outdim, sizejacind );
JacobianType jacjdiagcovjacj( outdim, outdim );
JacobianType jacjcovjacj( outdim, outdim );
NonZeroJacobianIndicesExpandedType jacindExpanded( P );
samplenr = 0;
for ( iter = begin; iter != end; ++iter )
{
/** Read fixed coordinates and get Jacobian. */
const FixedImagePointType & point = (*iter).Value().m_ImageCoordinates;
this->m_AdvancedTransform->GetJacobian( point, jacj, jacind );
/** Apply scales, if necessary. */
if ( this->GetUseScales() )
{
for ( unsigned int pi = 0; pi < sizejacind; ++pi )
{
const unsigned int p = jacind[ pi ];
jacj.scale_column( pi, 1.0 / scales[ p ] );
}
}
/** Compute 1st part of JJ: ||J_j||_F^2. */
double JJ_j = vnl_math_sqr( jacj.frobenius_norm() );
/** Compute 2nd part of JJ: 2\sqrt{2} || J_j J_j^T ||_F. */
vnl_fastops::ABt( jacjjacj, jacj, jacj );
JJ_j += 2.0 * sqrt2 * jacjjacj.frobenius_norm();
/** Max_j [JJ_j]. */
maxJJ = vnl_math_max( maxJJ, JJ_j );
/** Compute JCJ_j. */
double JCJ_j = 0.0;
/** J_j C = jacjC. */
jacjcov.Fill( 0.0 );
/** Store the nonzero Jacobian indices in a different format
* and create the sparse diagcov.
*/
jacindExpanded.Fill( sizejacind );
for ( unsigned int pi = 0; pi < sizejacind; ++pi )
{
const unsigned int p = jacind[ pi ];
jacindExpanded[ p ] = pi;
diagcovsparse[ pi ] = diagcov[ p ];
}
/** We below calculate jacjC = J_j cov^T, but later we will correct
* for this using:
* J C J' = J (cov + cov' - diag(cov')) J'.
* (NB: cov now still contains only the upper triangular part of C)
*/
for ( unsigned int pi = 0; pi < sizejacind; ++pi )
{
const unsigned int p = jacind[ pi ];
if ( !cov.empty_row( p ) )
{
SparseRowType & covrowp = cov.get_row( p );
typename SparseRowType::iterator covrowpit;
/** Loop over row p of the sparse cov matrix. */
for ( covrowpit = covrowp.begin(); covrowpit != covrowp.end(); ++covrowpit )
{
const unsigned int q = (*covrowpit).first;
const unsigned int qi = jacindExpanded[ q ];
if ( qi < sizejacind )
{
/** If found, update the jacjC matrix. */
const CovarianceValueType covElement = (*covrowpit).second;
for ( unsigned int dx = 0; dx < outdim; ++dx )
{
jacjcov[ dx ][ pi ] += jacj[ dx ][ qi ] * covElement;
} //dx
} // if qi < sizejacind
} // for covrow
} // if not empty row
} // pi
/** J_j C J_j^T = jacjCjacj.
* But note that we actually compute J_j cov' J_j^T
*/
vnl_fastops::ABt( jacjcovjacj, jacjcov, jacj );
/** jacjCjacj = jacjCjacj+ jacjCjacj' - jacjdiagcovjacj */
jacjdiagcov = jacj * diagcovsparse;
vnl_fastops::ABt( jacjdiagcovjacj, jacjdiagcov, jacj );
jacjcovjacj += jacjcovjacj.transpose();
jacjcovjacj -= jacjdiagcovjacj;
/** Compute 1st part of JCJ: Tr( J_j C J_j^T ). */
for ( unsigned int d = 0; d < outdim; ++d )
{
JCJ_j += jacjcovjacj[ d ][ d ];
}
/** Compute 2nd part of JCJ_j: 2 \sqrt{2} || J_j C J_j^T ||_F. */
JCJ_j += 2.0 * sqrt2 * jacjcovjacj.frobenius_norm();
/** Max_j [JCJ_j]. */
maxJCJ = vnl_math_max( maxJCJ, JCJ_j );
/** Show progress 50-100%. */
progressObserver->UpdateAndPrintProgress( samplenr + nrofsamples );
++samplenr;
} // end loop over sample container
/** Finalize progress information. */
progressObserver->PrintProgress( 1.0 );
} // end ComputeJacobianTerms()
/**
* **************** SampleFixedImageForJacobianTerms *******************
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::SampleFixedImageForJacobianTerms(
ImageSampleContainerPointer & sampleContainer )
{
typedef typename ElastixType::MetricBaseType::AdvancedMetricType MetricType;
MetricType * testPtr = dynamic_cast<MetricType *>(
this->GetElastix()->GetElxMetricBase()->GetAsITKBaseType() );
if ( !testPtr )
{
itkExceptionMacro( << "ERROR: AdaptiveStochasticGradientDescent expects "
<< "the metric to be of type AdvancedImageToImageMetric!" );
}
/** Set up grid sampler. */
ImageGridSamplerPointer sampler = ImageGridSamplerType::New();
sampler->SetInput( testPtr->GetFixedImage() );
sampler->SetInputImageRegion( testPtr->GetFixedImageRegion() );
sampler->SetMask( testPtr->GetFixedImageMask() );
/** Determine grid spacing of sampler such that the desired
* NumberOfJacobianMeasurements is achieved approximately.
* Note that the actually obtained number of samples may be lower, due to masks.
* This is taken into account at the end of this function.
*/
unsigned int nrofsamples = this->m_NumberOfJacobianMeasurements;
sampler->SetNumberOfSamples( nrofsamples );
/** Get samples and check the actually obtained number of samples. */
sampler->Update();
sampleContainer = sampler->GetOutput();
nrofsamples = sampleContainer->Size();
if ( nrofsamples == 0 )
{
itkExceptionMacro(
<< "No valid voxels (0/" << this->m_NumberOfJacobianMeasurements
<< ") found to estimate the AdaptiveStochasticGradientDescent parameters." );
}
} // end SampleFixedImageForJacobianTerms()
/**
* **************** PrintSettingsVector **********************
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::PrintSettingsVector( const SettingsVectorType & settings ) const
{
const unsigned long nrofres = settings.size();
/** Print to log file */
elxout << "( SP_a " ;
for ( unsigned int i = 0; i < nrofres; ++i )
{
elxout << settings[ i ].a << " ";
}
elxout << ")\n" ;
elxout << "( SP_A " ;
for ( unsigned int i = 0; i < nrofres; ++i )
{
elxout << settings[ i ].A << " ";
}
elxout << ")\n" ;
elxout << "( SP_alpha " ;
for ( unsigned int i = 0; i < nrofres; ++i )
{
elxout << settings[i].alpha << " ";
}
elxout << ")\n" ;
elxout << "( SigmoidMax " ;
for ( unsigned int i = 0; i < nrofres; ++i )
{
elxout << settings[i].fmax << " ";
}
elxout << ")\n" ;
elxout << "( SigmoidMin " ;
for ( unsigned int i = 0; i < nrofres; ++i )
{
elxout << settings[i].fmin << " ";
}
elxout << ")\n" ;
elxout << "( SigmoidScale " ;
for ( unsigned int i = 0; i < nrofres; ++i )
{
elxout << settings[i].omega << " ";
}
elxout << ")\n" ;
elxout << std::endl;
} // end PrintSettingsVector()
/**
* ****************** CheckForAdvancedTransform **********************
* Check if the transform is of type AdvancedTransform.
* If so, we can speed up derivative calculations by only inspecting
* the parameters in the support region of a point.
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::CheckForAdvancedTransform( void )
{
typename TransformType::Pointer transform = this->GetRegistration()
->GetAsITKBaseType()->GetTransform();
AdvancedTransformType * testPtr = dynamic_cast<AdvancedTransformType *>(
transform.GetPointer() );
if ( !testPtr )
{
this->m_AdvancedTransform = 0;
itkDebugMacro( "Transform is not Advanced" );
itkExceptionMacro( << "The automatic parameter estimation of the ASGD "
<< "optimizer works only with advanced transforms" );
}
else
{
this->m_AdvancedTransform = testPtr;
itkDebugMacro( "Transform is Advanced" );
}
} // end CheckForAdvancedTransform()
/**
* *************** GetScaledDerivativeWithExceptionHandling ***************
* Helper function, used by SampleGradients.
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::GetScaledDerivativeWithExceptionHandling(
const ParametersType & parameters, DerivativeType & derivative )
{
double dummyvalue = 0;
try
{
this->GetScaledValueAndDerivative( parameters, dummyvalue, derivative );
}
catch ( ExceptionObject & err )
{
this->m_StopCondition = MetricError;
this->StopOptimization();
throw err;
}
} // end GetScaledDerivativeWithExceptionHandling()
/**
* *************** AddRandomPerturbation ***************
* Helper function, used by SampleGradients.
*/
template <class TElastix>
void
AdaptiveStochasticGradientDescent<TElastix>
::AddRandomPerturbation( ParametersType & parameters, double sigma )
{
/** Add delta ~ sigma * N(0,I) to the input parameters. */
for ( unsigned int p = 0; p < parameters.GetSize(); ++p )
{
parameters[ p ] += sigma * this->m_RandomGenerator->GetNormalVariate( 0.0, 1.0 );
}
} // end AddRandomPerturbation()
} // end namespace elastix
#endif // end #ifndef __elxAdaptiveStochasticGradientDescent_hxx
| [
"[email protected]"
]
| [
[
[
1,
1434
]
]
]
|
77d0aedacf734c4645417a903db6b7d3a3e3acf8 | 00c36cc82b03bbf1af30606706891373d01b8dca | /OpenGUI/OpenGUI_ContainerControl.cpp | 31480100a54b01dea9bb56cfb5e1a855a0a7f126 | [
"BSD-3-Clause"
]
| permissive | VB6Hobbyst7/opengui | 8fb84206b419399153e03223e59625757180702f | 640be732a25129a1709873bd528866787476fa1a | refs/heads/master | 2021-12-24T01:29:10.296596 | 2007-01-22T08:00:22 | 2007-01-22T08:00:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,745 | cpp | // OpenGUI (http://opengui.sourceforge.net)
// This source code is released under the BSD License
// See LICENSE.TXT for details
#include "OpenGUI_ContainerControl.h"
#include "OpenGUI_Brush_Caching.h"
#include "OpenGUI_Macros.h"
namespace OpenGUI {
SimpleProperty_Float( property_Padding, "Padding", ContainerControl, getPadding, setPadding );
SimpleProperty_Bool( property_ConsumeInput, "ConsumeInput", ContainerControl, getConsumeInput, setConsumeInput );
//############################################################################
class ContainerControl_ObjectAccessorList : public ObjectAccessorList {
public:
ContainerControl_ObjectAccessorList() {
addAccessor( &property_Padding );
addAccessor( &property_ConsumeInput );
}
~ContainerControl_ObjectAccessorList() {}
}
gContainerControl_ObjectAccessorList;
//############################################################################
//############################################################################
//############################################################################
ContainerControl::ContainerControl() {
if ( gContainerControl_ObjectAccessorList.getParent() == 0 )
gContainerControl_ObjectAccessorList.setParent( Control::getAccessors() );
// initialize state variables
Children.setParent( this );
Children.attachListener( this );
mCacheBrush = 0;
m_LayoutSuspended = false; // layouts are instantaneous by default
m_LayoutValid = true; // layout begins valid (as there are no controls to update, it does not matter)
m_InUpdateLayout = false; // we are not in updateLayout() quite yet
m_ClipChildren = false;
mConsumeInput = true; // by default we consume all appropriate input to prevent it from reaching overdrawn widgets
// set up defaults for properties
//Set up events and default bindings
getEvents().createEvent( "DrawBG" );
getEvents()["DrawBG"].add( new EventDelegate( this, &ContainerControl::onDrawBG ) );
getEvents().createEvent( "ChildAttached" );
getEvents().createEvent( "ChildDetached" );
getEvents()["ChildAttached"].add( new EventDelegate( this, &ContainerControl::onChildAttached ) );
getEvents()["ChildDetached"].add( new EventDelegate( this, &ContainerControl::onChildDetached ) );
getEvents().createEvent( "InvalidatedChild" );
getEvents()["InvalidatedChild"].add( new EventDelegate( this, &ContainerControl::onInvalidatedChild ) );
//additional (unblockable) event bindings
getEvents()["Detached"].add( new EventDelegate( this, &ContainerControl::onDetached_BrushCache ) );
}
//############################################################################
ContainerControl::~ContainerControl() {
/**/
if ( mCacheBrush )
delete mCacheBrush;
mCacheBrush = 0;
}
//############################################################################
ObjectAccessorList* ContainerControl::getAccessors() {
return &gContainerControl_ObjectAccessorList;
}
//############################################################################
unsigned int ContainerControl::getObjectType() const {
return OT_CONTAINERCONTROL;
}
//############################################################################
void ContainerControl::onDrawBG( Object* sender, Draw_EventArgs& evtArgs ) {
/*! Default is to do nothing */
}
//############################################################################
void ContainerControl::eventDrawBG( Brush& brush ) {
Draw_EventArgs event( brush );
triggerEvent( "DrawBG", event );
}
//############################################################################
void ContainerControl::onChildAttached( Object* sender, Attach_EventArgs& evtArgs ) {
invalidate(); // need to invalidate caches for hierarchy change
}
//############################################################################
void ContainerControl::eventChildAttached( WidgetCollection* container, Widget* newChild ) {
Attach_EventArgs event( container, newChild );
triggerEvent( "ChildAttached", event );
}
//############################################################################
void ContainerControl::onChildDetached( Object* sender, Attach_EventArgs& evtArgs ) {
invalidate(); // need to invalidate caches for hierarchy change
}
//############################################################################
void ContainerControl::eventChildDetached( WidgetCollection* container, Widget* prevChild ) {
Attach_EventArgs event( container, prevChild );
triggerEvent( "ChildDetached", event );
}
//############################################################################
void ContainerControl::_draw( Brush& brush ) {
if ( getVisible() ) {
Brush_Caching& cacheBrush = _getCacheBrush();
// do we need to rebuild the cache brush?
if ( isCacheDirty() ) {
cacheBrush.pushPosition( -getPosition() ); //offset to parent coords for Container drawing
//draw background
cacheBrush._pushMarker( this );
eventDrawBG( cacheBrush );
cacheBrush._popMarker( this );
cacheBrush.pop(); // pop the parent coords offset
//draw children
if ( m_ClipChildren ) // setup the client area clip if we have one
cacheBrush.pushClippingRect( getClientArea() );
WidgetCollection::reverse_iterator iter, iterend = Children.rend();
for ( iter = Children.rbegin(); iter != iterend; iter++ ) {
iter->_draw( cacheBrush );
}
if ( m_ClipChildren ) // pop the client area clip if we had one
cacheBrush.pop();
cacheBrush.pushPosition( -getPosition() ); //offset to parent coords for Container drawing
//draw foreground
cacheBrush._pushMarker( this );
eventDraw( cacheBrush );
cacheBrush._popMarker( this );
cacheBrush.pop(); // pop the parent coords offset
}
//push cache into output stream
brush.pushAlpha( getAlpha() );
brush.pushPosition( getPosition() );
cacheBrush.emerge( brush );
brush.pop(); // pop position offset
brush.pop(); // pop alpha
}
}
//############################################################################
/*! If layout is not suspended, this triggers an immediate update of the layout.
This function is protected from re-entry when a layout operation is currently
under way. */
void ContainerControl::invalidateLayout() {
if ( !m_InUpdateLayout ) {
m_LayoutValid = false;
if ( !m_LayoutSuspended )
updateLayout();
}
}
//############################################################################
void ContainerControl::suspendLayout() {
m_LayoutSuspended = true;
}
//############################################################################
void ContainerControl::resumeLayout() {
m_LayoutSuspended = false;
if ( !layoutValid() )
updateLayout();
}
//############################################################################
bool ContainerControl::layoutValid() {
return m_LayoutValid;
}
//############################################################################
/*! This is a convenience function that calculates the client area into a rect
from the defined offsets \c m_ClientAreaOffset_UL and \c m_ClientAreaOffset_LR.
*/
const FRect& ContainerControl::getClientArea() {
static FRect retval;
FVector2 size = getSize();
retval.min.x = m_ClientAreaOffset_UL.x;
retval.min.y = m_ClientAreaOffset_UL.y;
retval.max.x = size.x + m_ClientAreaOffset_LR.x;
retval.max.y = size.y + m_ClientAreaOffset_LR.y;
return retval;
}
//############################################################################
/*! The update is performed regardless of layout being currently suspended,
so only call this if you really want the update to occur. Layout validity,
however, is still honored and layouts will not occur unless needed. */
void ContainerControl::updateLayout() {
m_InUpdateLayout = true;
if ( !layoutValid() ) {
_setChildControlLayoutState( true );
_doUpdateLayout();
m_LayoutValid = true;
_setChildControlLayoutState( false );
}
m_InUpdateLayout = false;
}
//############################################################################
void ContainerControl::_setChildControlLayoutState( bool state ) {
WidgetCollection::iterator iter, iterend = Children.end();
for ( iter = Children.begin(); iter != iterend; iter++ ) {
Control* c = dynamic_cast<Control*>( iter.get() );
if ( c )
c->m_InLayout = state;
}
}
//############################################################################
/*! This is virtual in the case that a subclass wishes to perform their own layout logic.
Toolbars and other specialty containers would likely need this functionality. */
void ContainerControl::_doUpdateLayout() {
static FRect oldClntArea = getClientArea();
FRect clntArea = getClientArea();
//update clntArea to respect Padding
clntArea.setWidth( clntArea.getWidth() - ( mPadding * 2.0f ) );
clntArea.setHeight( clntArea.getHeight() - ( mPadding * 2.0f ) );
if ( clntArea.getHeight() < 0.0f ) clntArea.setHeight( 0.0f );
if ( clntArea.getWidth() < 0.0f ) clntArea.setWidth( 0.0f );
clntArea.offset( FVector2( mPadding, mPadding ) );
//update all docked controls
WidgetCollection::iterator iter, iterend = Children.end();
for ( iter = Children.begin(); iter != iterend; iter++ ) {
Control* ctrl = dynamic_cast<Control*>( iter.get() );
if ( ctrl ) {
int dock = ctrl->getDocking();
float margin = ctrl->getMargin();
if ( dock ) {
//Next two IF's cover position and height for 'Fill' as well
if (( dock & Control::Left ) || ( dock & Control::Right ) ) {
ctrl->setTop( clntArea.getPosition().y + margin );
ctrl->setHeight( clntArea.getHeight() - ( margin*2.0f ) );
}
if (( dock & Control::Top ) || ( dock & Control::Bottom ) ) {
ctrl->setLeft( clntArea.getPosition().x + margin );
ctrl->setWidth( clntArea.getWidth() - ( margin*2.0f ) );
}
if ( dock == Control::Left ) {
ctrl->setLeft( clntArea.getPosition().x + margin );
float newwidth = clntArea.getWidth() - ( ctrl->getWidth() + ( margin * 2.0f ) );
clntArea.setWidth( newwidth > 0.0f ? newwidth : 0.0f ); // width can't be less than 0.0f
clntArea.offset( FVector2( ctrl->getWidth() + ( margin*2.0f ), 0.0f ) );
}
if ( dock == Control::Right ) {
float newpos = clntArea.getPosition().x + clntArea.getWidth();
newpos = newpos - ( ctrl->getWidth() + margin );
ctrl->setLeft( newpos );
float newwidth = newpos - margin;
newwidth = newwidth - clntArea.getPosition().x;
clntArea.setWidth( newwidth > 0.0f ? newwidth : 0.0f ); // width can't be less than 0.0f
}
if ( dock == Control::Top ) {
ctrl->setTop( clntArea.getPosition().y + margin );
float newheight = clntArea.getHeight() - ( ctrl->getHeight() + ( margin * 2.0f ) );
clntArea.setHeight( newheight > 0.0f ? newheight : 0.0f ); // height can't be less than 0.0f
clntArea.offset( FVector2( 0.0f, ctrl->getHeight() + ( margin*2.0f ) ) );
}
if ( dock == Control::Bottom ) {
float newtop = clntArea.getPosition().y + clntArea.getHeight();
newtop = newtop - ( ctrl->getHeight() + margin );
ctrl->setTop( newtop );
float newheight = clntArea.getHeight() - ( ctrl->getHeight() + margin * 2.0f );
clntArea.setHeight( newheight > 0.0f ? newheight : 0.0f ); // height can't be less than 0.0f
}
}
}
}
//use difference of new and previous client area space to update anchored controls
float deltaLeft = clntArea.getPosition().x - oldClntArea.getPosition().x;
float deltaTop = clntArea.getPosition().y - oldClntArea.getPosition().y ;
float deltaRight = ( clntArea.getPosition().x + clntArea.getWidth() ) - ( oldClntArea.getPosition().x + oldClntArea.getWidth() ) ;
float deltaBottom = ( clntArea.getPosition().y + clntArea.getHeight() ) - ( oldClntArea.getPosition().y + oldClntArea.getHeight() ) ;
//WidgetCollection::iterator iter, iterend = Children.end(); // done earlier
for ( iter = Children.begin(); iter != iterend; iter++ ) {
Control* ctrl = dynamic_cast<Control*>( iter.get() );
if ( ctrl ) {
int dock = ctrl->getDocking();
if ( dock == Control::None ) {
int anchor = ctrl->getAnchor();
if ( anchor & Control::Left ) {
ctrl->setLeft( ctrl->getLeft() + deltaLeft );
if ( anchor & Control::Right )
ctrl->setWidth(( ctrl->getWidth() - deltaLeft ) + deltaRight );
}
if (( anchor & Control::Left ) == 0 && ( anchor & Control::Right ) ) {
ctrl->setLeft( ctrl->getLeft() + deltaRight );
}
if ( anchor & Control::Top ) {
ctrl->setTop( ctrl->getTop() + deltaTop );
if ( anchor & Control::Bottom )
ctrl->setHeight(( ctrl->getHeight() - deltaTop ) + deltaBottom );
}
if (( anchor & Control::Top ) == 0 && ( anchor & Control::Bottom ) ) {
ctrl->setTop( ctrl->getTop() + deltaBottom );
}
}
}
}
oldClntArea = getClientArea(); // update oldClntArea for next pass
}
//############################################################################
void ContainerControl::_getChildrenAt( const FVector2& position, WidgetPtrList& outList, bool recursive ) {
FVector2 pos = position;
_translatePointIn( pos );
WidgetCollection::iterator iter, iterend = Children.end();
for ( iter = Children.begin(); iter != iterend; iter++ ) {
Widget* child = iter.get();
if ( child->isInside( pos ) ) {
if ( recursive ) {
child->getChildrenAt( pos, outList, true );
}
outList.push_back( child );
}
}
}
//############################################################################
Widget* ContainerControl::_getChildAt( const FVector2& position, bool recursive ) {
FVector2 pos = position;
_translatePointIn( pos );
WidgetCollection::iterator iter, iterend = Children.end();
for ( iter = Children.begin(); iter != iterend; iter++ ) {
Widget* child = iter.get();
if ( child->isInside( pos ) ) {
Widget* ret = child;
if ( recursive ) {
child = child->getChildAt( pos, true );
if ( child )
ret = child;
}
return ret;
}
}
return 0;
}
//############################################################################
void ContainerControl::_invalidatedChild() {
eventInvalidatedChild();
}
//############################################################################
void ContainerControl::dirtyCache() {
if ( mCacheBrush ) {
delete mCacheBrush;
mCacheBrush = 0;
}
}
//############################################################################
bool ContainerControl::isCacheDirty() const {
if ( !mCacheBrush )
return true;
return !mCacheBrush->hasContent();
}
//############################################################################
Brush_Caching& ContainerControl::_getCacheBrush() {
if ( !mCacheBrush ) {
mCacheBrush = new Brush_Caching( getScreen(), getSize() );
}
return *mCacheBrush;
}
//############################################################################
void ContainerControl::_tick( float seconds ) {
Control::_tick( seconds );
WidgetCollection::iterator iter, iterend = Children.end();
for ( iter = Children.begin(); iter != iterend; iter++ ) {
Widget* child = iter.get();
child->_tick( seconds );
}
}
//############################################################################
void ContainerControl::eventInvalidatedChild() {
EventArgs event;
triggerEvent( "InvalidatedChild", event );
}
//############################################################################
void ContainerControl::onInvalidated( Object* sender, EventArgs& evtArgs ) {
dirtyCache();
Control::onInvalidated( sender, evtArgs );
}
//############################################################################
void ContainerControl::onInvalidatedChild( Object* sender, EventArgs& evtArgs ) {
invalidate();
}
//############################################################################
void ContainerControl::onDetached_BrushCache( Object* sender, Attach_EventArgs& evtArgs ) {
dirtyCache();
}
//############################################################################
void ContainerControl::onResized( Object* sender, Resized_EventArgs& evtArgs ) {
invalidate();
Control::onResized( sender, evtArgs );
}
//############################################################################
Widget* ContainerControl::_getChildByName( const String& childName ) const {
return Children.getWidget( childName );
}
//############################################################################
void ContainerControl::_translatePointIn( FVector2& point ) {
const FVector2& pos = getPosition();
point -= pos;
point -= m_ClientAreaOffset_UL;
}
//############################################################################
void ContainerControl::_translatePointOut( FVector2& point ) {
const FVector2& pos = getPosition();
point += m_ClientAreaOffset_UL;
point += pos;
}
//############################################################################
/*! Padding is the distance within the inside of this container to keep children away from the client area edges during auto layout.
The given \c padding cannot be negative, and is clamped to 0.0f if a negative value is given.
*/
void ContainerControl::setPadding( float padding ) {
if ( padding < 0.0f ) padding = 0.0f;
if ( mPadding == padding ) return;
mPadding = padding;
invalidateLayout();
}
//############################################################################
/*! \see setPadding() for description of Padding */
float ContainerControl::getPadding() {
return mPadding;
}
//############################################################################
void ContainerControl::_doflush() {
eventInvalidated();
WidgetCollection::iterator iter, iterend = Children.end();
for ( iter = Children.begin(); iter != iterend; iter++ ) {
Widget* child = iter.get();
child->_doflush();
}
}
//############################################################################
/*! Changing this value to \c false will make the container act as a transparent
entity with regards to cursor input, allowing normally obscured widgets to process
events. This is primarily useful when you use several fully transparent containers
to produce layers that cover the entire Screen for layout purposes. In this case,
you would not want the container to always consume the input, as it would prevent
the lower layers from ever getting input that they should logically receive. */
void ContainerControl::setConsumeInput( bool consume ) {
mConsumeInput = consume;
}
//############################################################################
bool ContainerControl::getConsumeInput() {
return mConsumeInput;
}
//############################################################################
void ContainerControl::_sendToChildren_CursorMove( Cursor_EventArgs& moveEvent ) {
FVector2 point = moveEvent.Position;
_translatePointIn( point );
Cursor_EventArgs localEvent( point.x, point.y );
if ( moveEvent.Consumed ) localEvent.eat();
WidgetCollection::iterator i, ie = Children.end();
for ( i = Children.begin(); i != ie; i++ ) {
i->_injectCursorMove( localEvent );
}
if ( localEvent.Consumed )
moveEvent.eat();
}
//############################################################################
void ContainerControl::_sendToChildren_CursorPress( Cursor_EventArgs& pressEvent ) {
FVector2 point = pressEvent.Position;
_translatePointIn( point );
Cursor_EventArgs localEvent( point.x, point.y );
if ( pressEvent.Consumed ) localEvent.eat();
WidgetCollection::iterator i, ie = Children.end();
for ( i = Children.begin(); i != ie; i++ ) {
i->_injectCursorPress( localEvent );
}
if ( localEvent.Consumed )
pressEvent.eat();
}
//############################################################################
void ContainerControl::_sendToChildren_CursorRelease( Cursor_EventArgs& releaseEvent ) {
FVector2 point = releaseEvent.Position;
_translatePointIn( point );
Cursor_EventArgs localEvent( point.x, point.y );
if ( releaseEvent.Consumed ) localEvent.eat();
WidgetCollection::iterator i, ie = Children.end();
for ( i = Children.begin(); i != ie; i++ ) {
i->_injectCursorRelease( localEvent );
}
if ( localEvent.Consumed )
releaseEvent.eat();
}
//############################################################################
void ContainerControl::onCursorMove( Object* sender, Cursor_EventArgs& evtArgs ) {
if ( mConsumeInput ) {
Control::onCursorMove( sender, evtArgs );
}
}
//############################################################################
void ContainerControl::onCursorPress( Object* sender, Cursor_EventArgs& evtArgs ) {
if ( mConsumeInput ) {
Control::onCursorPress( sender, evtArgs );
}
}
//############################################################################
void ContainerControl::onCursorRelease( Object* sender, Cursor_EventArgs& evtArgs ) {
if ( mConsumeInput ) {
Control::onCursorRelease( sender, evtArgs );
}
}
//############################################################################
} // namespace OpenGUI {
| [
"zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59"
]
| [
[
[
1,
508
]
]
]
|
31ad0bc334d15ed7987259050408064a308a1eec | 52ee98d8e00d66f71139a2e86f1464244eb1616b | /size.cpp | 2d94df6950e6e7b2270604ece11ef46541b4db51 | []
| no_license | shaoyang/algorithm | ea0784e2b92465e54517016a7a8623c109ac9fc1 | 571b6423f5cf7c4bee21ff99b69b972d491c970d | refs/heads/master | 2016-09-05T12:37:14.878376 | 2011-03-22T16:21:58 | 2011-03-22T16:21:58 | 1,502,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | #include<stdio.h>
#include<stdlib.h>
int main(){
char a[30];
char *b = (char *)malloc(20 * sizeof(char));
printf("%d\n", sizeof(a)); //30
printf("%d\n", sizeof(b)); //4
printf("%d\n", sizeof(a[3])); //1
printf("%d\n", sizeof(b+3)); //4
printf("%d\n", sizeof(*(b+4))); //1
system("pause");
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
14
]
]
]
|
f62951ab763d0e6d099786626306af4a6d4b74eb | 38af8ef5939efeb9f98d77756fd54ff8a94985d1 | /TerrainMast/trunk/3rdparty/include/GeographicLib/PolarStereographic.hpp | 960767278cabb5f52483930d382a257817e36adb | []
| no_license | suda-ee/miscprojectsrepo | 16658894d1a3ae5c5900395ce84f519cafc7fd8a | e29d56498910045d97ecc3fd3205b1add4080683 | refs/heads/master | 2021-01-18T15:29:33.618773 | 2011-01-12T06:26:06 | 2011-01-12T06:26:06 | 86,655,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,749 | hpp | /**
* \file PolarStereographic.hpp
* \brief Header for GeographicLib::PolarStereographic class
*
* Copyright (c) Charles Karney (2008, 2009) <[email protected]>
* and licensed under the LGPL. For more information, see
* http://geographiclib.sourceforge.net/
**********************************************************************/
#if !defined(GEOGRAPHICLIB_POLARSTEREOGRAPHIC_HPP)
#define GEOGRAPHICLIB_POLARSTEREOGRAPHIC_HPP "$Id: PolarStereographic.hpp 6720 2009-10-17 23:13:57Z ckarney $"
#include "GeographicLib/Constants.hpp"
namespace GeographicLib {
/**
* \brief Polar Stereographic Projection
*
* Implementation taken from the report,
* - J. P. Snyder,
* <a href="http://pubs.er.usgs.gov/usgspubs/pp/pp1395"> Map Projections: A
* Working Manual</a>, USGS Professional Paper 1395 (1987),
* pp. 160–163.
*
* This is a straightforward implementation of the equations in Snyder except
* that Newton's method is used to invert the projection.
**********************************************************************/
class PolarStereographic {
private:
typedef Math::real real;
const real _a, _f, _k0, _e2, _e, _e2m, _c;
static const real tol;
static const int numit = 5;
static inline real sq(real x) throw() { return x * x; }
// Return e * atanh(e * x) for f >= 0, else return
// - sqrt(-e2) * atan( sqrt(-e2) * x) for f < 0
inline real eatanhe(real x) const throw() {
return _f >= 0 ? _e * Math::atanh(_e * x) : - _e * atan(_e * x);
}
public:
/**
* Constructor for a ellipsoid radius \e a (meters), reciprocal flattening
* \e r, and central scale factor \e k0. Setting \e r <= 0 implies \e r =
* inf or flattening = 0 (i.e., a sphere).
**********************************************************************/
PolarStereographic(real a, real r, real k0) throw();
/**
* Convert from latitude \e lat (degrees) and longitude \e lon (degrees) to
* polar stereographic easting \e x (meters) and northing \e y (meters).
* The projection is about the pole given by \e northp (false means south,
* true means north). Also return the meridian convergence \e gamma
* (degrees) and the scale \e k. No false easting or northing is added.
* \e lat should be in the range (-90, 90] for \e northp = true and in the
* range [-90, 90) for \e northp = false; \e lon should be in the range
* [-180, 360].
**********************************************************************/
void Forward(bool northp, real lat, real lon,
real& x, real& y, real& gamma, real& k) const throw();
/**
* Convert from polar stereogrphic easting \e x (meters) and northing \e y
* (meters) to latitude \e lat (degrees) and longitude \e lon (degrees) .
* The hemisphere is given by \e northp (false means south, true means
* north). Also return the meridian convergence \e gamma (degrees) and the
* scale \e k. No false easting or northing is added. The value of \e lon
* returned is in the range [-180, 180).
**********************************************************************/
void Reverse(bool northp, real x, real y,
real& lat, real& lon, real& gamma, real& k) const throw();
/**
* A global instantiation of PolarStereographic with the WGS84 ellipsoid
* and the UPS scale factor. However, unlike UPS, no false easting or
* northing is added.
**********************************************************************/
const static PolarStereographic UPS;
};
} // namespace GeographicLib
#endif
| [
"cai@localhost"
]
| [
[
[
1,
84
]
]
]
|
15299e3d921b768e508739a6062bd315c8915153 | 17558c17dbc37842111466c43add5b31e3f1b29b | /nav/navinfo.h | ae1e928b5781a27541da5511d50283632720d71d | []
| no_license | AeroWorks/inav | 5c61b6c7a5af1a3f99009de8e177a2ceff3447b0 | 5a97aaca791026d9a09c2273c37e237b18b9cb35 | refs/heads/master | 2020-09-05T23:45:11.561252 | 2011-04-24T01:53:22 | 2011-04-24T01:53:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 434 | h | #ifndef NAVINFO_H
#define NAVINFO_H
#include <QObject>
#include <QString>
class NavInfo
{
public:
static NavInfo* Instance();
QString getSpeedString();
// QString getAltitudeString();
// QString getHeadingString();
protected:
static NavInfo* m_instance;
NavInfo();
~NavInfo();
private:
float heading;
float speed;
float altitude;
};
#endif // NAVINFO_H
| [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
3ef7166ab62997b5a1b51fb3f2f3b3cb15274689 | 974a20e0f85d6ac74c6d7e16be463565c637d135 | /trunk/packages/dScene/dVariable.cpp | 4f8ca1dbde9c3851e75408da4b887aa86de406af | []
| no_license | Naddiseo/Newton-Dynamics-fork | cb0b8429943b9faca9a83126280aa4f2e6944f7f | 91ac59c9687258c3e653f592c32a57b61dc62fb6 | refs/heads/master | 2021-01-15T13:45:04.651163 | 2011-11-12T04:02:33 | 2011-11-12T04:02:33 | 2,759,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,904 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: dVariable.h
// Purpose:
// Author: Julio Jerez
// Modified by:
// Created: 22/05/2010 08:02:08
// RCS-ID:
// Copyright: Copyright (c) <2010> <Newton Game Dynamics>
// License:
// 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
/////////////////////////////////////////////////////////////////////////////
#include "dPluginStdafx.h"
#include "dVariable.h"
dVariable::dVariable ()
{
m_type = m_int;
m_name[0] = 0;
m_integer = 0;
}
dVariable::dVariable (const dVariable& me)
:m_type (me.m_type)
{
strcpy (m_name, me.m_name);
if (m_type == m_string){
SetValue (me.m_data);
} else {
m_integer = me.m_integer;
}
}
dVariable::~dVariable ()
{
if ((m_type == m_string) && m_data){
delete[] m_data;
}
}
void dVariable::SetName (const char* name)
{
strcpy (m_name, name);
}
const char* dVariable::GetName() const
{
return m_name;
}
dVariable::dType dVariable::GetType() const
{
return m_type;
}
void dVariable::SetValue (int value)
{
if ((m_type == m_string) && m_data){
delete[] m_data;
}
m_type = m_int;
m_integer = value;
}
void dVariable::SetValue (float value)
{
if ((m_type == m_string) && m_data){
delete[] m_data;
}
m_type = m_float;
m_real = value;
}
void dVariable::SetValue (const char* value)
{
if ((m_type == m_string) && m_data){
delete[] m_data;
}
m_type = m_string;
m_data = new char[strlen(value) + 1];
strcpy (m_data, value);
}
int dVariable::GetInt () const
{
return (m_type == m_int) ? m_integer : 0;
}
dFloat dVariable::GetFloat () const
{
return (m_type == m_float) ? m_real : 0.0f;
}
const char* dVariable::GetString () const
{
return (m_type == m_string) ? m_data : NULL;
}
dVariableList::dVariableList()
:dTree<dVariable, dCRCTYPE>()
{
}
dVariableList::dVariableList(const dVariableList& me)
:dTree<dVariable, dCRCTYPE>()
{
// for (dListNode* node = me.GetFirst(); node; node = node->GetNext()) {
Iterator iter (me);
for (iter.Begin(); iter; iter++) {
dVariable& var = iter.GetNode()->GetInfo();
Insert(var, iter.GetNode()->GetKey());
}
}
dVariableList::~dVariableList ()
{
}
dVariable* dVariableList::FindVariable(dCRCTYPE crc) const
{
dTreeNode* node = Find (crc);
return node ? &node->GetInfo() : NULL;
}
dVariable* dVariableList::FindVariable(const char* name) const
{
return FindVariable(dCRC64 (name));
}
dVariable* dVariableList::CreateVariable (const char* name)
{
dCRCTYPE crc = dCRC64(name);
dTreeNode* node = Find (crc);
if (!node) {
node = Insert(crc);
dVariable& var = node->GetInfo();
var.SetName (name);
}
return &node->GetInfo();
}
void dVariableList::Serialize(TiXmlElement* const rootNode) const
{
if (GetCount()) {
TiXmlElement* dataNode = new TiXmlElement ("variables");
rootNode->LinkEndChild(dataNode);
Iterator iter (*this);
for (iter.Begin(); iter; iter++) {
dVariable& var = iter.GetNode()->GetInfo();
switch (var.m_type)
{
case dVariable::m_int:
{
TiXmlElement* variable = new TiXmlElement ("integer");
dataNode->LinkEndChild(variable);
variable->SetAttribute("name", var.m_name);
variable->SetAttribute("value", var.m_integer);
break;
}
case dVariable::m_float:
{
TiXmlElement* variable = new TiXmlElement ("float");
dataNode->LinkEndChild(variable);
variable->SetAttribute("name", var.m_name);
variable->SetDoubleAttribute("value", var.m_real);
break;
}
case dVariable::m_string:
{
TiXmlElement* variable = new TiXmlElement ("string");
dataNode->LinkEndChild(variable);
variable->SetAttribute("name", var.m_name);
variable->SetAttribute("value", var.m_data);
break;
}
}
}
}
}
void dVariableList::Deserialize(TiXmlElement* node)
{
TiXmlElement* dataNode = (TiXmlElement*) node->FirstChild ("variables");
if (dataNode) {
for (TiXmlElement* element = (TiXmlElement*) dataNode->FirstChild(); element; element = (TiXmlElement*) element->NextSibling()) {
const char* className = element->Value();
dVariable* var = CreateVariable (element->Attribute ("name"));
if (!strcmp (className, "integer")) {
_ASSERTE (0);
} else if (!strcmp (className, "float")) {
_ASSERTE (0);
} else if (!strcmp (className, "string")) {
var->SetValue(element->Attribute ("value"));
}
}
}
} | [
"[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692"
]
| [
[
[
1,
216
]
]
]
|
a93d06606472e49705f3b3f5bfb4abf4830bc2b3 | bc3073755ed70dd63a7c947fec63ccce408e5710 | /src/Game/Graphics/qd.h | c66277ccf872150394aa20ad5f4c5715749b7f06 | []
| no_license | ptrefall/ste6274gamedesign | 9e659f7a8a4801c5eaa060ebe2d7edba9c31e310 | 7d5517aa68910877fe9aa98243f6bb2444d533c7 | refs/heads/master | 2016-09-07T18:42:48.012493 | 2011-10-13T23:41:40 | 2011-10-13T23:41:40 | 32,448,466 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | h | /* Ken Mazaika
February 23, 2005
Quantum Dynamics Header
Copyright 2005
http://home.comcast.net/~kjmaz
*/
#pragma once
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <GL/glew.h>
#ifdef WIN32
#include <GL/wglew.h>
#endif
#define QD_SUCCESS 1
//For The Particle Engine
namespace Graphics
{
class Qd3dPoint
{
public:
float m_fX;
float m_fY;
float m_fZ;
};
class QdColor
{
public:
float m_fR;
float m_fG;
float m_fB;
float m_fA;
};
}
| [
"[email protected]@2c5777c1-dd38-1616-73a3-7306c0addc79"
]
| [
[
[
1,
40
]
]
]
|
1f37e809aa95c030dc2b63b965b5caaabc99acd7 | 01afd5b6bbab83e1f71a934c838bb87493958c48 | /objects.cpp | c8b937e98dd63839f8a2831ea4f82e30a59ccb6a | []
| no_license | Alyanorno/ray_tracer | b49491ba45d4ba99312e444ec2ba212e31223c71 | 2c38ba2bbf45b97eb601012f3bc005462d95d512 | refs/heads/master | 2016-09-05T15:54:48.796381 | 2011-02-15T21:19:08 | 2011-02-15T21:19:08 | 1,318,240 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,869 | cpp | #include "objects.h"
float Sphere::Intersect( Ray& ray )
{
Vector distans = ray.origion - position;
float dot = - distans.Dot( ray.direction );
if( dot < 0 )
return 0;
float det = dot * dot - distans.Dot( distans ) + radius * radius;
if( det < 0 )
return 0;
else
{
float result1 = dot - sqrt( det );
float result2 = dot + sqrt( det );
return result1 > 0 ? result1 : result2;
}
}
bool Sphere::Refraction( Ray& ray )
{
Vector normal = Normal( ray.origion );
// Change the direction
float n = 1 / material.index;
float c1 = -normal.Dot( ray.direction );
if( c1 < 0 )
return false;
float c2 = 1 - n * n * ( 1 - c1 * c1 );
if( c2 <= 0 )
return false;
ray.direction = ray.direction * n + normal * ( n * c1 - sqrtf( c2 ));
ray.direction.Normalize();
// Calculate new origion
Vector distans = ray.origion - position;
float dot = - distans.Dot( ray.direction );
float differense = 2 * sqrtf( dot * dot - distans.Dot( distans ) + radius * radius );
ray.origion = ray.origion + ray.direction * differense; //(radius * 2);
return true;
}
Vector Sphere::Normal( Vector& intersection )
{
Vector normal = (intersection - position) * radius;
normal.Normalize();
return normal;
}
float inline Length( float x )
{
return x < 0 ? -x : x;
}
float Plane::Intersect( Ray& ray )
{
//(P-P0)*n = 0;
//P = dL+L0
//d = (P0-L0)*n / L*n
float value = point0[2] - ray.origion[2];
float distans = normal[2] * value / normal.Dot( ray.direction );
if( distans < 0 )
return 0;
Vector intersection = ray.origion + ray.direction * distans;
if( Length( point0[0] + intersection[0] ) > Length( point[0] )
|| Length( point0[1] + intersection[1] ) > Length( point[1] ))
return 0;
return distans;
}
Vector Plane::Normal( Vector& intersection )
{
return normal;
}
| [
"[email protected]"
]
| [
[
[
1,
78
]
]
]
|
166c2537e96bc059c4a67babc81632f995d94d75 | f90b1358325d5a4cfbc25fa6cccea56cbc40410c | /src/qwt/src/moc/moc_qwt_abstract_slider.cpp | 9ff6221a2d4ef8a1e7b94d70081744b8420e067f | []
| no_license | ipodyaco/prorata | bd52105499c3fad25781d91952def89a9079b864 | 1f17015d304f204bd5f72b92d711a02490527fe6 | refs/heads/master | 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,479 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'qwt_abstract_slider.h'
**
** Created: ??? ?? 25 15:38:44 2006
** by: The Qt Meta Object Compiler version 59 (Qt 4.1.4)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../include/qwt_abstract_slider.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qwt_abstract_slider.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 59
#error "This file was generated using the moc from 4.1.4. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
static const uint qt_meta_data_QwtAbstractSlider[] = {
// content:
1, // revision
0, // classname
0, 0, // classinfo
8, 10, // methods
4, 50, // properties
0, 0, // enums/sets
// signals: signature, parameters, type, tag, flags
25, 19, 18, 18, 0x05,
46, 18, 18, 18, 0x05,
62, 18, 18, 18, 0x05,
79, 19, 18, 18, 0x05,
// slots: signature, parameters, type, tag, flags
103, 99, 18, 18, 0x0a,
120, 99, 18, 18, 0x0a,
143, 137, 18, 18, 0x0a,
157, 18, 18, 18, 0x0a,
// properties: name, type, flags
180, 175, 0x01095103,
189, 175, 0x01095103,
202, 195, 0x06095103,
223, 207, 0x0009510b,
0 // eod
};
static const char qt_meta_stringdata_QwtAbstractSlider[] = {
"QwtAbstractSlider\0\0value\0valueChanged(double)\0sliderPressed()\0"
"sliderReleased()\0sliderMoved(double)\0val\0setValue(double)\0"
"fitValue(double)\0steps\0incValue(int)\0setReadOnly(bool)\0bool\0"
"readOnly\0valid\0double\0mass\0Qt::Orientation\0orientation\0"
};
const QMetaObject QwtAbstractSlider::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_QwtAbstractSlider,
qt_meta_data_QwtAbstractSlider, 0 }
};
const QMetaObject *QwtAbstractSlider::metaObject() const
{
return &staticMetaObject;
}
void *QwtAbstractSlider::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QwtAbstractSlider))
return static_cast<void*>(const_cast<QwtAbstractSlider*>(this));
if (!strcmp(_clname, "QwtDoubleRange"))
return static_cast<QwtDoubleRange*>(const_cast<QwtAbstractSlider*>(this));
return QWidget::qt_metacast(_clname);
}
int QwtAbstractSlider::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 1: sliderPressed(); break;
case 2: sliderReleased(); break;
case 3: sliderMoved((*reinterpret_cast< double(*)>(_a[1]))); break;
case 4: setValue((*reinterpret_cast< double(*)>(_a[1]))); break;
case 5: fitValue((*reinterpret_cast< double(*)>(_a[1]))); break;
case 6: incValue((*reinterpret_cast< int(*)>(_a[1]))); break;
case 7: setReadOnly((*reinterpret_cast< bool(*)>(_a[1]))); break;
}
_id -= 8;
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty) {
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< bool*>(_v) = isReadOnly(); break;
case 1: *reinterpret_cast< bool*>(_v) = isValid(); break;
case 2: *reinterpret_cast< double*>(_v) = mass(); break;
case 3: *reinterpret_cast< Qt::Orientation*>(_v) = orientation(); break;
}
_id -= 4;
} else if (_c == QMetaObject::WriteProperty) {
void *_v = _a[0];
switch (_id) {
case 0: setReadOnly(*reinterpret_cast< bool*>(_v)); break;
case 1: setValid(*reinterpret_cast< bool*>(_v)); break;
case 2: setMass(*reinterpret_cast< double*>(_v)); break;
case 3: setOrientation(*reinterpret_cast< Qt::Orientation*>(_v)); break;
}
_id -= 4;
} else if (_c == QMetaObject::ResetProperty) {
_id -= 4;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 4;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 4;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 4;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 4;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 4;
}
#endif // QT_NO_PROPERTIES
return _id;
}
// SIGNAL 0
void QwtAbstractSlider::valueChanged(double _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void QwtAbstractSlider::sliderPressed()
{
QMetaObject::activate(this, &staticMetaObject, 1, 0);
}
// SIGNAL 2
void QwtAbstractSlider::sliderReleased()
{
QMetaObject::activate(this, &staticMetaObject, 2, 0);
}
// SIGNAL 3
void QwtAbstractSlider::sliderMoved(double _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 3, _a);
}
| [
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
]
| [
[
[
1,
155
]
]
]
|
dd9a5d559dd8d644a6f9795289c1073829a37865 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestmisccontrol/src/bctestmisccontrolapp.cpp | 8d9b1db52bd8c9f8456c9e8d6651c3adbe0e301b | []
| 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 | 1,998 | cpp | /*
* Copyright (c) 2006 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: Implements main application class.
*
*/
// INCLUDE FILES
#include "bctestmisccontrolapp.h"
#include "bctestmisccontroldocument.h"
#include <eikstart.h>
// ================= MEMBER FUNCTIONS ========================================
// ---------------------------------------------------------------------------
// TUid CBCTestMiscControlApp::AppDllUid()
// Returns application UID.
// ---------------------------------------------------------------------------
//
TUid CBCTestMiscControlApp::AppDllUid() const
{
return KUidBCTestMiscControl;
}
// ---------------------------------------------------------------------------
// CApaDocument* CBCTestMiscControlApp::CreateDocumentL()
// Creates CBCTestMiscControlDocument object.
// ---------------------------------------------------------------------------
//
CApaDocument* CBCTestMiscControlApp::CreateDocumentL()
{
return CBCTestMiscControlDocument::NewL( *this );
}
// ================= OTHER EXPORTED FUNCTIONS ================================
//
// ---------------------------------------------------------------------------
// CApaApplication* NewApplication()
// Constructs CBCTestMiscControlApp.
// Returns: CApaDocument*: created application object
// ---------------------------------------------------------------------------
//
LOCAL_C CApaApplication* NewApplication()
{
return new CBCTestMiscControlApp;
}
GLDEF_C TInt E32Main()
{
return EikStart::RunApplication( NewApplication );
}
| [
"none@none"
]
| [
[
[
1,
62
]
]
]
|
57c0b5fe34067fba571891f491adf7fe8baa84a0 | 9cd3008ba0bcf1c338d4e643f953b7a11b457b15 | /ObjectRightView.cpp | 1a86048624e4bb147e441d6a39a4f723f556eb55 | []
| no_license | R4md4c/CS3D499-Plugin | 099043e103e1d278d30d09b9a462e6225be6c87e | d6bf94e536c35e1bb0ee413728a74e02480550c5 | refs/heads/master | 2020-12-25T00:19:47.967002 | 2010-11-13T11:55:09 | 2010-11-13T11:55:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,199 | cpp | ////////////////////////////////////////////////////////////////////////
// Author: Peter Bonsma
// Date: 31 July 2010
// Project: IFC Engine Series (example using DLL)
//
// This code may be used and edited freely,
// also for commercial projects in open and closed source software
//
// In case of use of the DLL:
// be aware of license fee for use of this DLL when used commercially
// more info for commercial use: [email protected]
//
// more info for using the IFC Engine DLL in other languages
// and creation of specific code examples:
// [email protected]
// [email protected]
////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ObjectViewer.h"
#include "IFCEngineInteract.h"
#include "Camera.h"
#include "ObjectRightView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern STRUCT_INSTANCES * first_instance;
extern int noVertices, noIndices, * pIndices;
extern float * pVertices;
float * pVerticesDeviceBuffer, counter = 0;
bool initialized = false;
int DirectXStatus = 0;
const float kCamMoveAmt = 0.002f; // Amount to move camera by
const float kMaxAngle = 89.0f;
D3DXVECTOR3 m_vecOrigin;
CCamera *g_Camera = new CCamera(D3DXVECTOR3(0,0,-2.5f));
/////////////////////////////////////////////////////////////////////////////
// CObjectRightView
IMPLEMENT_DYNCREATE(CObjectRightView, CFormView)
BEGIN_MESSAGE_MAP(CObjectRightView, CFormView)
ON_WM_SIZE()
END_MESSAGE_MAP()
CObjectRightView::CObjectRightView()
: CFormView(CObjectRightView::IDD), MULTIPLY_RATIO(0.030f)
{
}
CObjectRightView::~CObjectRightView()
{
delete g_Camera;
g_Camera = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// CObjectRightView message handlers
void CObjectRightView::OnSize(UINT nType, int cx, int cy)
{
SetScrollSizes( MM_TEXT, CSize(cx, cy) );
CFormView::OnSize(nType, cx, cy);
if (initialized) {
CRect rc;
m_iWidth = cx;
m_iHeight = cy;
// Save static reference to the render window
CWnd* pGroup = GetDlgItem(IDC_RENDERWINDOW);
pGroup->SetWindowPos(NULL, 0, 0, cx, cy, SWP_NOZORDER);
pGroup->GetClientRect(&rc);
pGroup->MapWindowPoints(this, &rc);
m_hwndRenderWindow = GetDlgItem(IDC_RENDERWINDOW)->GetSafeHwnd();
InitializeDevice();
InitializeDeviceBuffer();
Render();
}
}
int iZoomMouseX, iZoomMouseY;
LRESULT CObjectRightView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
int iMouseX = LOWORD(lParam),
iMouseY = HIWORD(lParam);
switch (message)
{
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
iZoomMouseX = iMouseX;
iZoomMouseY = iMouseY;
break;
case WM_MOUSEMOVE:
//
// Mouse moved
//
if(MK_LBUTTON&wParam)
{
SetCapture();
SetCursor(NULL);
g_Camera->rotateCamera(iMouseY-iZoomMouseY, iMouseX-iZoomMouseX);
if (initialized) {
Render();
}
ReleaseCapture();
iZoomMouseX = iMouseX;
iZoomMouseY = iMouseY;
}
break;
case ID_RESET_FRONT:
//TODO:- Reset to the front of model
if (initialized) {
Render();
}
break;
case ID_RESET_SIDE:
//g_Camera->resetCamera();
if (initialized) {
Render();
}
break;
case WM_KEYDOWN: //If a Key is down
switch(wParam)
{
case 0x57: //W KEY
g_Camera->moveForward(MULTIPLY_RATIO);
if (initialized) {
Render();
}
break;
case 0x53: // S KEY
g_Camera->moveForward(-1.0f * MULTIPLY_RATIO);
if (initialized) {
Render();
}
break;
case 0x41:// A KEY
g_Camera->moveRight(-1.0f * MULTIPLY_RATIO);
if(initialized)
Render();
break;
case 0x44: // D KEY
g_Camera->moveRight( MULTIPLY_RATIO );
if(initialized)
Render();
break;
}
break;
case 7:
case 8:
case 312:
case WM_PAINT:
case ID_UPDATE_RIGHT_VIEW:
if (initialized) {
Render();
}
break;
case ID_INIT_RIGHT_VIEW:
if (g_pd3dDevice == NULL) {
InitializeDevice();
}
InitializeDeviceBuffer();
Render();
break;
default:
break;
}
return CFormView::WindowProc(message, wParam, lParam);
}
/** I have overriden this method to solve the problem of having
to use the SetFocus method to set the keyboard input focus to the RightObjectView
by pretranslating the message that goes to the MessageProc method(above) to process
the WM_KEYDOWN event and sending which key is pressed to the MessageProc method
**/
BOOL CObjectRightView::PreTranslateMessage(MSG *pMSG)
{
/* Send a key down event to the message queue*/
if(pMSG->message == WM_KEYDOWN) {
if(pMSG->wParam == 0x57)
SendMessage(WM_KEYDOWN, 0x57); //Send W key is pressed if the W is pressed
else if( pMSG->wParam == 0x53)
SendMessage(WM_KEYDOWN, 0x53); //Send S key is pressed if the S is pressed
else if( pMSG->wParam == 0x41)
SendMessage(WM_KEYDOWN, 0x41); //Send A key is pressed if the A is pressed
else if( pMSG->wParam == 0x44)
SendMessage(WM_KEYDOWN, 0x44); //Send D key is pressed if the D is pressed
else if( pMSG->wParam == VK_UP)//If UP-Arrow
SendMessage(WM_KEYDOWN, 0x57); //Send as if W
else if( pMSG->wParam == VK_DOWN)//If Down-Arrow
SendMessage(WM_KEYDOWN, 0x53); //Send as if S
else if( pMSG->wParam == VK_LEFT)//If Left-Arrow
SendMessage(WM_KEYDOWN, 0x41); //Send as if A
else if( pMSG->wParam == VK_RIGHT)//If Right-Arrow
SendMessage(WM_KEYDOWN, 0x44); //Send as if D
}
return CView::PreTranslateMessage(pMSG);
}
void CObjectRightView::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
if (!initialized) {
g_pD3D = NULL;
g_pd3dDevice = NULL;
g_pVB = NULL;
GetParentFrame()->RecalcLayout();
ResizeParentToFit();
m_hwndRenderWindow = GetDlgItem(IDC_RENDERWINDOW)->GetSafeHwnd();
CRect rc;
this->GetWindowRect( &rc );
m_iWidth = rc.Width();
m_iHeight = rc.Height();
CWnd* pGroup = GetDlgItem(IDC_RENDERWINDOW);
pGroup->SetWindowPos(NULL, 0, 0, m_iWidth, m_iHeight, SWP_NOZORDER);
InitializeDevice();
initialized = true;
SetFocus();
}
}
void CObjectRightView::InitializeDevice()
{
if (!DirectXStatus) {
// Reset the device
if( g_pVB != NULL ) {
if( FAILED( g_pVB->Release() ) ) {
DirectXStatus = -1;
return;
}
}
if( g_pd3dDevice != NULL ) {
if( FAILED( g_pd3dDevice->Release() ) ) {
DirectXStatus = -1;
return;
}
}
if( g_pD3D != NULL ) {
if( FAILED( g_pD3D->Release() ) ) {
DirectXStatus = -1;
return;
}
}
// Create the D3D object.
if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) ) {
return;
}
//
// Specific for DirectX 8.0
//
D3DDISPLAYMODE d3ddm;
if (FAILED(g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm))) {
DirectXStatus = -1;
return;
}
DWORD quality;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
//Check for hardware antialiasing capabilities
if (SUCCEEDED( g_pD3D->CheckDeviceMultiSampleType(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, TRUE, D3DMULTISAMPLE_NONMASKABLE, &quality) )) {
d3dpp.MultiSampleType = D3DMULTISAMPLE_NONMASKABLE;
d3dpp.MultiSampleQuality = quality - 1;
}
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = d3ddm.Format;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
// Create the D3DDevice
if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_hwndRenderWindow,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&d3dpp, &g_pd3dDevice ) ) )
{
if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_hwndRenderWindow,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp, &g_pd3dDevice ) ) )
{
DirectXStatus = -1;
return;
}
}
//Set the device that the camera operates on
//g_Camera->setDevice(g_pd3dDevice);
// Turn off culling
if( FAILED( g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ) ) ) {
DirectXStatus = -1;
return;
}
if( FAILED( g_pd3dDevice->SetRenderState( D3DRS_MULTISAMPLEANTIALIAS, TRUE) ) ) {
DirectXStatus = -1;
return;
}
// Turn on the zbuffer
if( FAILED( g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ) ) ) {
DirectXStatus = -1;
return;
}
}
}
void CObjectRightView::InitializeDeviceBuffer()
{
if (noVertices) {
if (!DirectXStatus) {
if( FAILED( g_pd3dDevice->CreateVertexBuffer( noIndices * sizeof(CUSTOMVERTEX),
0, D3DFVF_CUSTOMVERTEX,
D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )
{
DirectXStatus = -1;
return;
}
if( FAILED( g_pVB->Lock( 0, 0, (void **)&pVerticesDeviceBuffer, 0 ) ) ) {
DirectXStatus = -1;
return;
}
int i = 0;
while (i < noIndices) {
ASSERT(pIndices[i] < noVertices);
memcpy(&(((CUSTOMVERTEX *) pVerticesDeviceBuffer)[i]), &(((CUSTOMVERTEX *) pVertices)[pIndices[i]]), sizeof(CUSTOMVERTEX));
i++;
}
if (FAILED( g_pVB->Unlock())) {
DirectXStatus = -1;
return;
}
}
}
}
void CObjectRightView::Render()
{
if (!DirectXStatus) {
// Clear the backbuffer and the zbuffer
if( FAILED( g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(0,0,255), 1.0f, 0 ) ) ) {
DirectXStatus = -1;
return;
}
// Begin the scene
if (SUCCEEDED(g_pd3dDevice->BeginScene()))
{
// Setup the lights and materials
if (SetupLights()) {
DirectXStatus = -1;
return;
}
// Setup the world, view, and projection matrices
if (SetupMatrices()) {
DirectXStatus = -1;
return;
}
if (g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX))) {
DirectXStatus = -1;
return;
}
g_pd3dDevice->SetVertexShader(NULL);
g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
D3DMATERIAL9 mtrl;
mtrl.Diffuse.r = mtrl.Ambient.r = mtrl.Specular.r = 0.4f;
mtrl.Diffuse.g = mtrl.Ambient.g = mtrl.Specular.g = 0.1f;
mtrl.Diffuse.b = mtrl.Ambient.b = mtrl.Specular.b = 0.7f;
mtrl.Diffuse.a = mtrl.Ambient.a = mtrl.Specular.a = 1.0f;
mtrl.Emissive.r = 0.1f;
mtrl.Emissive.g = 0.4f;
mtrl.Emissive.b = 0.02f;
mtrl.Emissive.a = 0.5f;
g_pd3dDevice->SetMaterial(&mtrl);
STRUCT_INSTANCES * instance = first_instance;
while (instance) {
if ( (instance->parent) &&
(instance->select == ITEM_CHECKED) ){
g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, instance->startIndex, instance->primitiveCount);
}
instance = instance->next;
}
// End the scene
if( FAILED( g_pd3dDevice->EndScene() ) ) {
DirectXStatus = -1;
return;
}
}
// Present the backbuffer contents to the display
if( FAILED( g_pd3dDevice->Present( NULL, NULL, NULL, NULL ) ) ) {
DirectXStatus = -1;
return;
}
}
}
int CObjectRightView::SetupLights()
{
float max = 1;
// Set up a white, directional light, with an oscillating direction.
// Note that many lights may be active at a time (but each one slows down
// the rendering of our scene). However, here we are just using one. Also,
// we need to set the D3DRS_LIGHTING renderstate to enable lighting
D3DXVECTOR3 vecDir;
D3DLIGHT9 light;
ZeroMemory(&light, sizeof(D3DLIGHT9));
light.Type = D3DLIGHT_DIRECTIONAL;
light.Diffuse.r = 3.4f;
light.Diffuse.g = 3.4f;
light.Diffuse.b = 3.4f;
light.Diffuse.a = 3.4f;
light.Specular.r = 0.1f;
light.Specular.g = 0.1f;
light.Specular.b = 0.1f;
light.Specular.a = 0.5f;
light.Ambient.r = 0.5f;
light.Ambient.g = 0.5f;
light.Ambient.b = 0.5f;
light.Ambient.a = 1.0f;
light.Position.x = (float) -2.0f;
light.Position.y = (float) -2.0f;
light.Position.z = (float) -2.0f;
vecDir.x = -2.0f;
vecDir.y = -6.0f;
vecDir.z = -1.0f;
D3DXVec3Normalize((D3DXVECTOR3*)&light.Direction, &vecDir);
light.Range = 5.0f;
if (FAILED(g_pd3dDevice->SetLight(0, &light))) {
DirectXStatus = -1;
return 1;
}
if (FAILED(g_pd3dDevice->LightEnable(0, TRUE))) {
DirectXStatus = -1;
return 1;
}
D3DLIGHT9 light1;
ZeroMemory(&light1, sizeof(D3DLIGHT9));
light1.Type = D3DLIGHT_DIRECTIONAL;
light1.Diffuse.r = 3.4f;
light1.Diffuse.g = 3.4f;
light1.Diffuse.b = 3.4f;
light1.Diffuse.a = 3.4f;
light1.Specular.r = 0.1f;
light1.Specular.g = 0.1f;
light1.Specular.b = 0.1f;
light1.Specular.a = 0.5f;
light1.Ambient.r = 0.5f;
light1.Ambient.g = 0.5f;
light1.Ambient.b = 0.5f;
light1.Ambient.a = 1.0f;
light1.Position.x = (float) 2.0f;
light1.Position.y = (float) 2.0f;
light1.Position.z = (float) 2.0f;
vecDir.x = 2.0f;
vecDir.y = 6.0f;
vecDir.z = 1.0f;
D3DXVec3Normalize((D3DXVECTOR3*)&light1.Direction, &vecDir);
light1.Range = 5.0f;
if (FAILED(g_pd3dDevice->SetLight(1, &light1))) {
DirectXStatus = -1;
return 1;
}
if (FAILED(g_pd3dDevice->LightEnable(1, TRUE))) {
DirectXStatus = -1;
return 1;
}
if (FAILED(g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, TRUE))) {
DirectXStatus = -1;
return 1;
}
// Finally, turn on some ambient light.
g_pd3dDevice->SetRenderState(D3DRS_AMBIENT, 0x00707070);
return 0;
}
int CObjectRightView::SetupMatrices()
{
// For our world matrix, we will just leave it as the identity
D3DXMATRIX matWorld;
D3DXMatrixIdentity( &matWorld );
matWorld._22 = -1.0f;
D3DXVec3TransformCoord((D3DXVECTOR3 *) &matWorld._41, &m_vecOrigin, &matWorld);
if( FAILED( g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ) ) ) {
DirectXStatus = -1;
return 1;
}
// For the projection matrix, we set up a perspective transform (which
// transforms geometry from 3D view space to 2D viewport space, with
// a perspective divide making objects smaller in the distance). To build
// a perpsective transform, we need the field of view (1/4 pi is common),
// the aspect ratio, and the near and far clipping planes (which define at
// what distances geometry should be no longer be rendered).
D3DXMATRIX matProj;
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, (float) m_iWidth/(float) m_iHeight, 0.03f, 10.0f );
if( FAILED( g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj ) ) ) {
DirectXStatus = -1;
return 1;
}
D3DXMATRIXA16 matrix;
//Calculate the new view matrix for the camera
g_Camera->calculateViewMatrix(&matrix);
if( FAILED( g_pd3dDevice->SetTransform( D3DTS_VIEW, &matrix ) ) ) {
DirectXStatus = -1;
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
595
]
]
]
|
6c2efd2bc1788b2ce2febf9c31c451abf9cae9c7 | f8b364974573f652d7916c3a830e1d8773751277 | /emulator/allegrex/instructions/VSYNC.h | fe14cf038a952ffa12bb27f1fd5535b2fbc4ebe5 | []
| no_license | lemmore22/pspe4all | 7a234aece25340c99f49eac280780e08e4f8ef49 | 77ad0acf0fcb7eda137fdfcb1e93a36428badfd0 | refs/heads/master | 2021-01-10T08:39:45.222505 | 2009-08-02T11:58:07 | 2009-08-02T11:58:07 | 55,047,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,042 | h | template< > struct AllegrexInstructionTemplate< 0xffff0320, 0xffffffff > : AllegrexInstructionUnknown
{
static AllegrexInstructionTemplate &self()
{
static AllegrexInstructionTemplate insn;
return insn;
}
static AllegrexInstruction *get_instance()
{
return &AllegrexInstructionTemplate::self();
}
virtual AllegrexInstruction *instruction(u32 opcode)
{
return this;
}
virtual char const *opcode_name()
{
return "VSYNC";
}
virtual void interpret(Processor &processor, u32 opcode);
virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment);
protected:
AllegrexInstructionTemplate() {}
};
typedef AllegrexInstructionTemplate< 0xffff0320, 0xffffffff >
AllegrexInstruction_VSYNC;
namespace Allegrex
{
extern AllegrexInstruction_VSYNC &VSYNC;
}
#ifdef IMPLEMENT_INSTRUCTION
AllegrexInstruction_VSYNC &Allegrex::VSYNC =
AllegrexInstruction_VSYNC::self();
#endif
| [
"[email protected]"
]
| [
[
[
1,
41
]
]
]
|
de0007b8d1f06fc1c7a804c73f2ad0f571a68368 | f177993b13e97f9fecfc0e751602153824dfef7e | /ImPro/ImProBaseClass/commonLib/MyARTagMediaSample.h | b12eef4f44fe637a179199bba77d7ba16205dcfb | []
| no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,194 | h | #pragma once
#include <initguid.h>
// {D4989B9C-752D-4c2d-8F7F-D4400570F493}
DEFINE_GUID(GUID_ARResult,
0xd4989b9c, 0x752d, 0x4c2d, 0x8f, 0x7f, 0xd4, 0x40, 0x5, 0x70, 0xf4, 0x93);
// {0FB35002-CD0B-46bd-ABE0-EDAA96F722EE}
DEFINE_GUID(GUID_ARLayoutConfigData,
0xfb35002, 0xcd0b, 0x46bd, 0xab, 0xe0, 0xed, 0xaa, 0x96, 0xf7, 0x22, 0xee);
#include "ARToolKitPlus/TrackerMultiMarker.h"
using namespace ARToolKitPlus;
class ARTagResultData
{
public:
const ARMultiMarkerInfoT* m_pMarkerConfig;
const int m_nDetected;
const ARMarkerInfo* m_pDetectedMarks;
const double* m_matARView;
const double* m_matARProj;
double m_basisScale[3];
int m_screenW;
int m_screenH;
public:
ARTagResultData();
ARTagResultData(const ARMultiMarkerInfoT* pMarkerConfig, const int nDetected,
const ARMarkerInfo* pDetectedMarks, const double* matARView, const double* matARProj);
~ARTagResultData();
};
class ARLayoutConfigData
{
public:
ARMultiEachMarkerInfoT* m_ARMarkers;
int m_numMarker;
ARLayoutConfigData();
~ARLayoutConfigData();
ARLayoutConfigData(const ARLayoutConfigData &rhs);
ARLayoutConfigData& operator = (const ARLayoutConfigData &rhs);
}; | [
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
]
| [
[
[
1,
41
]
]
]
|
39607455c5cb8fc04b6e79e2e634fd3b25787104 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/blackberry/Api/WebKitClient.h | f344889842c78ddf2b54a2a68ea0444a2d1e32eb | [
"BSD-2-Clause"
]
| permissive | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | h | /*
* Copyright (C) Research In Motion Limited 2009. All rights reserved.
*/
#ifndef WebKitClient_h
#define WebKitClient_h
#include "BlackBerryGlobal.h"
template<typename T> class SharedArray;
#include "OlympiaPlatformMisc.h"
namespace Olympia {
namespace WebKit {
}
}
#endif // WebKitClient_h
| [
"[email protected]"
]
| [
[
[
1,
18
]
]
]
|
eb8c0e668930ad85002d641382e7055aa54962ad | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/numeric/ublas/bench3/bench32.cpp | 0d0ed8053d61825ee1d2c34b4c919ad73a25d5dc | []
| 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 | 20,169 | cpp | //
// Copyright (c) 2000-2002
// Joerg Walter, Mathias Koch
//
// 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. The authors make no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
//
// The authors gratefully acknowledge the support of
// GeNeSys mbH & Co. KG in producing this work.
//
#include <iostream>
#include <string>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/timer.hpp>
#include "bench3.hpp"
template<class T, int N>
struct bench_c_outer_prod {
typedef T value_type;
void operator () (int runs) const {
try {
static typename c_matrix_traits<T, N, N>::type m;
static typename c_vector_traits<T, N>::type v1, v2;
initialize_c_vector<T, N> () (v1);
initialize_c_vector<T, N> () (v2);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
for (int j = 0; j < N; ++ j) {
for (int k = 0; k < N; ++ k) {
m [j] [k] = - v1 [j] * v2 [k];
}
}
// sink_c_matrix<T, N, N> () (m);
}
footer<value_type> () (N * N, N * N, runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
template<class M, class V, int N>
struct bench_my_outer_prod {
typedef typename M::value_type value_type;
void operator () (int runs, safe_tag) const {
try {
static M m (N, N);
ublas::matrix_range<M> mr (m, ublas::range (0, N), ublas::range (0, N));
static V v1 (N), v2 (N);
ublas::vector_range<V> vr1 (v1, ublas::range (0, N)),
vr2 (v2, ublas::range (0, N));
initialize_vector (vr1);
initialize_vector (vr2);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
mr = - ublas::outer_prod (vr1, vr2);
// sink_matrix (mr);
}
footer<value_type> () (N * N, N * N, runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
void operator () (int runs, fast_tag) const {
try {
static M m (N, N);
ublas::matrix_range<M> mr (m, ublas::range (0, N), ublas::range (0, N));
static V v1 (N), v2 (N);
ublas::vector_range<V> vr1 (v1, ublas::range (0, N)),
vr2 (v2, ublas::range (0, N));
initialize_vector (vr1);
initialize_vector (vr2);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
mr.assign (- ublas::outer_prod (vr1, vr2));
// sink_matrix (mr);
}
footer<value_type> () (N * N, N * N, runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
template<class M, class V, int N>
struct bench_cpp_outer_prod {
typedef typename M::value_type value_type;
void operator () (int runs) const {
try {
static M m (N * N);
static V v1 (N), v2 (N);
initialize_vector (v1);
initialize_vector (v2);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
for (int j = 0; j < N; ++ j) {
for (int k = 0; k < N; ++ k) {
m [N * j + k] = - v1 [j] * v2 [k];
}
}
// sink_vector (m);
}
footer<value_type> () (N * N, N * N, runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
template<class T, int N>
struct bench_c_matrix_vector_prod {
typedef T value_type;
void operator () (int runs) const {
try {
static typename c_matrix_traits<T, N, N>::type m;
static typename c_vector_traits<T, N>::type v1, v2;
initialize_c_matrix<T, N, N> () (m);
initialize_c_vector<T, N> () (v1);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
for (int j = 0; j < N; ++ j) {
v2 [j] = 0;
for (int k = 0; k < N; ++ k) {
v2 [j] += m [j] [k] * v1 [k];
}
}
// sink_c_vector<T, N> () (v2);
}
footer<value_type> () (N * N, N * (N - 1), runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
template<class M, class V, int N>
struct bench_my_matrix_vector_prod {
typedef typename M::value_type value_type;
void operator () (int runs, safe_tag) const {
try {
static M m (N, N);
ublas::matrix_range<M> mr (m, ublas::range (0, N), ublas::range (0, N));
static V v1 (N), v2 (N);
ublas::vector_range<V> vr1 (v1, ublas::range (0, N)),
vr2 (v2, ublas::range (0, N));
initialize_matrix (mr);
initialize_vector (vr1);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
vr2 = ublas::prod (mr, vr1);
// sink_vector (vr2);
}
footer<value_type> () (N * N, N * (N - 1), runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
void operator () (int runs, fast_tag) const {
try {
static M m (N, N);
ublas::matrix_range<M> mr (m, ublas::range (0, N), ublas::range (0, N));
static V v1 (N), v2 (N);
ublas::vector_range<V> vr1 (v1, ublas::range (0, N)),
vr2 (v2, ublas::range (0, N));
initialize_matrix (mr);
initialize_vector (vr1);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
vr2.assign (ublas::prod (mr, vr1));
// sink_vector (vr2);
}
footer<value_type> () (N * N, N * (N - 1), runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
template<class M, class V, int N>
struct bench_cpp_matrix_vector_prod {
typedef typename M::value_type value_type;
void operator () (int runs) const {
try {
static M m (N * N);
static V v1 (N), v2 (N);
initialize_vector (m);
initialize_vector (v1);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
for (int j = 0; j < N; ++ j) {
std::valarray<value_type> row (m [std::slice (N * j, N, 1)]);
v2 [j] = (row * v1).sum ();
}
// sink_vector (v2);
}
footer<value_type> () (N * N, N * (N - 1), runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
template<class T, int N>
struct bench_c_matrix_add {
typedef T value_type;
void operator () (int runs) const {
try {
static typename c_matrix_traits<T, N, N>::type m1, m2, m3;
initialize_c_matrix<T, N, N> () (m1);
initialize_c_matrix<T, N, N> () (m2);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
for (int j = 0; j < N; ++ j) {
for (int k = 0; k < N; ++ k) {
m3 [j] [k] = - (m1 [j] [k] + m2 [j] [k]);
}
}
// sink_c_matrix<T, N, N> () (m3);
}
footer<value_type> () (0, 2 * N * N, runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
template<class M, int N>
struct bench_my_matrix_add {
typedef typename M::value_type value_type;
void operator () (int runs, safe_tag) const {
try {
static M m1 (N, N), m2 (N, N), m3 (N, N);
initialize_matrix (m1);
initialize_matrix (m2);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
m3 = - (m1 + m2);
// sink_matrix (m3);
}
footer<value_type> () (0, 2 * N * N, runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
void operator () (int runs, fast_tag) const {
try {
static M m1 (N, N), m2 (N, N), m3 (N, N);
initialize_matrix (m1);
initialize_matrix (m2);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
m3.assign (- (m1 + m2));
// sink_matrix (m3);
}
footer<value_type> () (0, 2 * N * N, runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
template<class M, int N>
struct bench_cpp_matrix_add {
typedef typename M::value_type value_type;
void operator () (int runs) const {
try {
static M m1 (N * N), m2 (N * N), m3 (N * N);
initialize_vector (m1);
initialize_vector (m2);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
m3 = - (m1 + m2);
// sink_vector (m3);
}
footer<value_type> () (0, 2 * N * N, runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
// Benchmark O (n ^ 2)
template<class T, int N>
void bench_2<T, N>::operator () (int runs) {
header ("bench_2");
header ("outer_prod");
header ("C array");
bench_c_outer_prod<T, N> () (runs);
#ifdef USE_C_ARRAY
header ("c_matrix, c_vector safe");
bench_my_outer_prod<ublas::c_matrix<T, N, N>,
ublas::c_vector<T, N>, N> () (runs, safe_tag ());
header ("c_matrix, c_vector fast");
bench_my_outer_prod<ublas::c_matrix<T, N, N>,
ublas::c_vector<T, N>, N> () (runs, fast_tag ());
#endif
#ifdef USE_BOUNDED_ARRAY
header ("matrix<bounded_array>, vector<bounded_array> safe");
bench_my_outer_prod<ublas::matrix<T, ublas::row_major, ublas::bounded_array<T, N * N> >,
ublas::vector<T, ublas::bounded_array<T, N> >, N> () (runs, safe_tag ());
header ("matrix<bounded_array>, vector<bounded_array> fast");
bench_my_outer_prod<ublas::matrix<T, ublas::row_major, ublas::bounded_array<T, N * N> >,
ublas::vector<T, ublas::bounded_array<T, N> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_UNBOUNDED_ARRAY
header ("matrix<unbounded_array>, vector<unbounded_array> safe");
bench_my_outer_prod<ublas::matrix<T, ublas::row_major, ublas::unbounded_array<T> >,
ublas::vector<T, ublas::unbounded_array<T> >, N> () (runs, safe_tag ());
header ("matrix<unbounded_array>, vector<unbounded_array> fast");
bench_my_outer_prod<ublas::matrix<T, ublas::row_major, ublas::unbounded_array<T> >,
ublas::vector<T, ublas::unbounded_array<T> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_STD_VALARRAY
header ("matrix<std::valarray>, vector<std::valarray> safe");
bench_my_outer_prod<ublas::matrix<T, ublas::row_major, std::valarray<T> >,
ublas::vector<T, std::valarray<T> >, N> () (runs, safe_tag ());
header ("matrix<std::valarray>, vector<std::valarray> fast");
bench_my_outer_prod<ublas::matrix<T, ublas::row_major, std::valarray<T> >,
ublas::vector<T, std::valarray<T> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_STD_VECTOR
header ("matrix<std::vector>, vector<std::vector> safe");
bench_my_outer_prod<ublas::matrix<T, ublas::row_major, std::vector<T> >,
ublas::vector<T, std::vector<T> >, N> () (runs, safe_tag ());
header ("matrix<std::vector>, vector<std::vector> fast");
bench_my_outer_prod<ublas::matrix<T, ublas::row_major, std::vector<T> >,
ublas::vector<T, std::vector<T> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_STD_VALARRAY
header ("std::valarray");
bench_cpp_outer_prod<std::valarray<T>, std::valarray<T>, N> () (runs);
#endif
header ("prod (matrix, vector)");
header ("C array");
bench_c_matrix_vector_prod<T, N> () (runs);
#ifdef USE_C_ARRAY
header ("c_matrix, c_vector safe");
bench_my_matrix_vector_prod<ublas::c_matrix<T, N, N>,
ublas::c_vector<T, N>, N> () (runs, safe_tag ());
header ("c_matrix, c_vector fast");
bench_my_matrix_vector_prod<ublas::c_matrix<T, N, N>,
ublas::c_vector<T, N>, N> () (runs, fast_tag ());
#endif
#ifdef USE_BOUNDED_ARRAY
header ("matrix<bounded_array>, vector<bounded_array> safe");
bench_my_matrix_vector_prod<ublas::matrix<T, ublas::row_major, ublas::bounded_array<T, N * N> >,
ublas::vector<T, ublas::bounded_array<T, N> >, N> () (runs, safe_tag ());
header ("matrix<bounded_array>, vector<bounded_array> fast");
bench_my_matrix_vector_prod<ublas::matrix<T, ublas::row_major, ublas::bounded_array<T, N * N> >,
ublas::vector<T, ublas::bounded_array<T, N> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_UNBOUNDED_ARRAY
header ("matrix<unbounded_array>, vector<unbounded_array> safe");
bench_my_matrix_vector_prod<ublas::matrix<T, ublas::row_major, ublas::unbounded_array<T> >,
ublas::vector<T, ublas::unbounded_array<T> >, N> () (runs, safe_tag ());
header ("matrix<unbounded_array>, vector<unbounded_array> fast");
bench_my_matrix_vector_prod<ublas::matrix<T, ublas::row_major, ublas::unbounded_array<T> >,
ublas::vector<T, ublas::unbounded_array<T> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_STD_VALARRAY
header ("matrix<std::valarray>, vector<std::valarray> safe");
bench_my_matrix_vector_prod<ublas::matrix<T, ublas::row_major, std::valarray<T> >,
ublas::vector<T, std::valarray<T> >, N> () (runs, safe_tag ());
header ("matrix<std::valarray>, vector<std::valarray> fast");
bench_my_matrix_vector_prod<ublas::matrix<T, ublas::row_major, std::valarray<T> >,
ublas::vector<T, std::valarray<T> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_STD_VECTOR
header ("matrix<std::vector>, vector<std::vector> safe");
bench_my_matrix_vector_prod<ublas::matrix<T, ublas::row_major, std::vector<T> >,
ublas::vector<T, std::vector<T> >, N> () (runs, safe_tag ());
header ("matrix<std::vector>, vector<std::vector> fast");
bench_my_matrix_vector_prod<ublas::matrix<T, ublas::row_major, std::vector<T> >,
ublas::vector<T, std::vector<T> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_STD_VALARRAY
header ("std::valarray");
bench_cpp_matrix_vector_prod<std::valarray<T>, std::valarray<T>, N> () (runs);
#endif
header ("matrix + matrix");
header ("C array");
bench_c_matrix_add<T, N> () (runs);
#ifdef USE_C_ARRAY
header ("c_matrix safe");
bench_my_matrix_add<ublas::c_matrix<T, N, N>, N> () (runs, safe_tag ());
header ("c_matrix fast");
bench_my_matrix_add<ublas::c_matrix<T, N, N>, N> () (runs, fast_tag ());
#endif
#ifdef USE_BOUNDED_ARRAY
header ("matrix<bounded_array> safe");
bench_my_matrix_add<ublas::matrix<T, ublas::row_major, ublas::bounded_array<T, N * N> >, N> () (runs, safe_tag ());
header ("matrix<bounded_array> fast");
bench_my_matrix_add<ublas::matrix<T, ublas::row_major, ublas::bounded_array<T, N * N> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_UNBOUNDED_ARRAY
header ("matrix<unbounded_array> safe");
bench_my_matrix_add<ublas::matrix<T, ublas::row_major, ublas::unbounded_array<T> >, N> () (runs, safe_tag ());
header ("matrix<unbounded_array> fast");
bench_my_matrix_add<ublas::matrix<T, ublas::row_major, ublas::unbounded_array<T> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_STD_VALARRAY
header ("matrix<std::valarray> safe");
bench_my_matrix_add<ublas::matrix<T, ublas::row_major, std::valarray<T> >, N> () (runs, safe_tag ());
header ("matrix<std::valarray> fast");
bench_my_matrix_add<ublas::matrix<T, ublas::row_major, std::valarray<T> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_STD_VECTOR
header ("matrix<std::vector> safe");
bench_my_matrix_add<ublas::matrix<T, ublas::row_major, std::vector<T> >, N> () (runs, safe_tag ());
header ("matrix<std::vector> fast");
bench_my_matrix_add<ublas::matrix<T, ublas::row_major, std::vector<T> >, N> () (runs, fast_tag ());
#endif
#ifdef USE_STD_VALARRAY
header ("std::valarray");
bench_cpp_matrix_add<std::valarray<T>, N> () (runs);
#endif
}
#ifdef USE_FLOAT
template struct bench_2<float, 3>;
template struct bench_2<float, 10>;
template struct bench_2<float, 30>;
template struct bench_2<float, 100>;
#endif
#ifdef USE_DOUBLE
template struct bench_2<double, 3>;
template struct bench_2<double, 10>;
template struct bench_2<double, 30>;
template struct bench_2<double, 100>;
#endif
#ifdef USE_STD_COMPLEX
#ifdef USE_FLOAT
template struct bench_2<std::complex<float>, 3>;
template struct bench_2<std::complex<float>, 10>;
template struct bench_2<std::complex<float>, 30>;
template struct bench_2<std::complex<float>, 100>;
#endif
#ifdef USE_DOUBLE
template struct bench_2<std::complex<double>, 3>;
template struct bench_2<std::complex<double>, 10>;
template struct bench_2<std::complex<double>, 30>;
template struct bench_2<std::complex<double>, 100>;
#endif
#endif
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
549
]
]
]
|
bfd0f41ea065a1e026caf085d769c79b590717e2 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /SMDK/TransCritical/TTechQAL/QALPrecip.h | 3d893b8d1af57d74e9aff29732f1edbbb04dc9ac | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,137 | h | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// QAL Classifer Model. Transcritical Technologies Pty Ltd copyright 2004
// Time-stamp: <2007-05-23 01:13:16 Rod Stephenson Transcritical Pty Ltd>
// Copyright (C) 2005 by Transcritical Technologies Pty Ltd and KWA
//===========================================================================
#ifndef __QALPRECIP_H
#define __QALPRECIP_H
#ifndef __MD_HEADERS_H
#include "md_headers.h"
#endif
#ifdef __QALPRECIP_CPP
#define DllImportExport __declspec(dllexport)
#elif !defined(SMDKDemoU)
#define DllImportExport __declspec(dllimport)
#else
#define DllImportExport
#endif
#include <sstream>
#include <iomanip>
#include "QALPSD.h"
#include "..\TTCommon\precip.h"
#include "..\TTCommon\hor.h"
//**/ #define TTDEBUG
#ifdef TTDEBUG
#include "..\TTCommon\ttdbg.h"
#else
#include "..\TTCommon\ttnodbg.h"
#endif
//---------------------------------------------------------------------------
static const double MW_H2O = 18.015;
static const double MW_NaOH = 39.997;
static const double MW_Alumina = 118.001;
static const double MW_THA= 78.084;
static const double MW_Na2CO3 = 105.989;
static const double MW_OrganicSoda = 223.632;
static const double MW_BoundSoda = MW_NaOH;
static const double MW_BoundOrganicSoda = MW_OrganicSoda;
static const double MW_Na2O = 61.9789;
static const double MW_Al2O3 = 101.96;
static const double MW_C = 12.01;
//Alpha Ratio of molecular weights (NaAl[OH]4(l)/Al[OH]3(s))
static const double Alpha = MW_Alumina/MW_THA;
const static int qVal = 1;
const double t0 = 323.15; // Reference temperature for kinetic rate
const double bayerRefTemp = 273.15+25.0; // Bayer liquor reference temperature
double clAE(double);
double wtSub45(MStream &);
class CPrecipitator : public MBaseMethod, CPrecip
{
public:
CPrecipitator(MUnitDefBase *pUnitDef,TaggedObject * pNd);
virtual ~CPrecipitator(void);
void Init();
void BuildDataFields();
bool ValidateDataFields();
void EvalProducts();
void ClosureInfo(MClosureInfo & CI);
protected:
MStreamI Feed;
MStreamI Tank; // Effective Stream for tank, calculations done on this stream
MStreamI Evap;
MStreamI CoolIn;
bool alreadySolved;
void EvalLosses(MStream & Prod); // General routine for finding thermal and evaporative losses
void EvalPrecipRates(MStream & Prod, double t=NAN); // Calculate the precip rates of components in Prod
void AdjustMasses(MStream & Prod); // Adjust the masses of the streams
void AdjustT(MStream & Prod); // Adjust the temperature for heat losses, reaction etc.
void DoPrecip(MStream &);
void DoResults(MStream & Prod);
void AdjustSSA(MStream & Prod);
void AdjustPSD(MStream & Prod);
void AgglomKernel();
void BinFactors(); // Factors for splitting agglomerate between consecutive bins
int q; // Bin *volume* spacing is 2.**(1/q)
double alpha; // Volume ratio of consecutive bins.
int klf(int i, int j) { // Determine which bin an agglomeration from i, j ends up in
return ( (i>j) ? i : i+1);
}
// For QAL SysCAD model, q=1, alpha = 2
// DeGroot original examples, q = 5
bool ConvergenceTest();
bool m_bEvapConnected;
bool m_bCoolerOn;
bool bCoolIn;
bool bCoolOut;
bool bGrowthOn; // Growth
bool bAgglomOn; // Agglom
bool bNuclOn; // Nucleation
bool bAttritionOn;
/// General Precipitation Routines
void PBRates(); // Calculate all the rates
double AgglomRate(); //Number per kg solids /hour
double GrowthRate(); // Microns/hour
double NucleationRate(); // Number per kg slurry per hour
void AttritionRate();
void Growth();
void Nucleation();
void Agglomeration();
void Attrition();
double Soda();
void getN(MStream &); // Get stream to local N
void putN(MStream &); // Put local N to stream
double bsplit[nClasses][nClasses];
double L1; // Size of nucleation bin
double dSALin; // SSA Stuff
double dDiamin;
double m_dOldTotDH;
double dGrowthRate;
double dAgglomRate;
double dNuclRate;
double dSoda;
double dNuclYield;
double dGrowthYield;
double dGrowthRateFactor;
double dAgglRateFactor;
double dNuclRateFactor;
double m_dEvapRateK;
double dSolPrecip;
double dSolConc; // Solids Concentration in outlet
double dTHAPrecip;
double dAlPrecip;
double dTin;
double dTout;
// Common Display stuff
double dACin;
double dACout;
double m_dACeq;
double m_dSSat; // Supersaturation
double m_dHIn;
double m_dHOut;
double m_dHEvap;
double m_dHBal;
double NoPerSec;
double dQvin;
double dQvout;
double m_dUA;
double m_dLMTD;
double m_dLiquorTin;
double m_dLiquorTout;
double dtact; // Actual Time Step
bool m_bByVolFlow;
bool bKernelOK;
double m_dCoolOutTotHz;
double m_dCoolWaterFlowVol;
// Stuff specific to particular model
/// Various precipitation models
/// Worsley
double ER_White;
double K_White;
double gF_White;
double m_dActivationEnergy;
double m_dK0;
double m_dk_TOC;
double m_dn_fc;
double m_dn_eq;
double m_dn_;
double m_dn_s;
double m_dn_sol;
double m_dn_ssa;
double m_dSSAin; // Specific Surface Area, m^2/kg slurry in
double m_dSSA; // Specific Surface Area, m^2/kg slurry tank
double m_dKAgglom;
double m_dSurfaceAct;
double m_dSodaConst; ;
/// Classification Data
double m_dBy_Pass;
double m_dSharp_Index;
double m_dCut_Size;
double m_dSlurry_split;
double m_dOver_pass;
double m_dL0 ;
/// Tank Data
double m_dShort_Circ;
double m_dUFrac;
double m_dGrowth;
double m_dNucleation;
double beta[nClasses+1][nClasses+1]; // Agglomeration Kernel
double Ndot[nClasses+1];
QALPSD fpsd; // Feed PSD
double n[nClasses+1]; // Numbers for bulk slurry in precipitator
double m_dVol, m_dArea, m_dNumber; // Tank Numbers
double NewN[nClasses +1];
double m_dSolidsIn;
double m_dSolidsOut;
double m_dNuclN; // Number of new particles through nucleation
double m_dAgglomN; // Change in number of particles through agglom
double m_ddeltaT; // Quasi - Timestep for solution
double dQmin;
double dQmout;
double m_dsigma;
double dFeedNTot, dProdNTot;
bool m_bUpdateT;
long m_lIterations;
long m_lItermax;
double dAggMinLim;
long iDType;
long iPSD;
void displayStream(MStream &ms, int scrn);
void displayPSD(MStream &ms, int scrn);
void displayPSD(int scrn);
double dd[12][32];
long lPBType; // PSD Model 0: none, 1: SSA, 2: PSD
#ifdef TTDEBUG
bool bTTDebug;
TTDbg dbg;
#endif
};
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
2
],
[
4,
25
],
[
27,
259
],
[
261,
302
]
],
[
[
3,
3
],
[
26,
26
],
[
260,
260
]
]
]
|
9f23cd02a7d29132ddbfb03d0eea875c5d306e05 | 09057f4cce385ad826cf5f61454e85f214e937a8 | /vs2008/testactivex/testactivex/testactivex.h | c773ca874ff3ff02d08bb032f218c9f7ef60a8be | []
| no_license | van-smith/OPBM | 751f8f71e6823b7f1c95e5002909427910479f90 | 69ae167a375dfbfa9552b9bfb388f317447dbd9d | refs/heads/master | 2016-08-07T10:44:54.348257 | 2011-07-28T05:28:59 | 2011-07-28T05:28:59 | 2,143,608 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 888 | h | // The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the TESTACTIVEX_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// TESTACTIVEX_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef TESTACTIVEX_EXPORTS
#define TESTACTIVEX_API __declspec(dllexport)
#else
#define TESTACTIVEX_API __declspec(dllimport)
#endif
// This class is exported from the testactivex.dll
class TESTACTIVEX_API Ctestactivex {
public:
Ctestactivex(void);
// TODO: add your methods here.
};
extern TESTACTIVEX_API int ntestactivex;
TESTACTIVEX_API int fntestactivex(void);
| [
"[email protected]"
]
| [
[
[
1,
22
]
]
]
|
f046240f4cda74153fbc9daf38e4abc03ed5a6c7 | 8c65a88f1d7a28e138f2f4d50477a8f5892b0ac5 | /I2CLCD/I2CLCD.cpp | ad28dad80a4f183dbe896df5b998530816153483 | []
| no_license | jcrouchley/I2CLCD | fffb8098c4a4ba51d5f8c47ec962154bb808d65b | f23f53b1bf8b615886f4aec536884cd3182514ca | refs/heads/master | 2020-04-15T11:13:52.049681 | 2011-07-26T19:32:53 | 2011-07-26T19:32:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,539 | cpp | /*
Uses I2c Wires interface
Uses Analog pin 4 - SDA
Uses Analog pin 5 - SCL
Usage:
see the examples folder of this library distribution.
*/
#include <stdio.h>
#include <string.h>
#include "Wire.h"
#include "I2CLCD.h"
//*******************************************************************
//
// Constructor and Initialisation
//
//*******************************************************************
I2CLCD::I2CLCD(uint8_t adr, uint8_t brows, uint8_t columns)
{
_adr = adr;
_columns = columns; // not yet used
_rows = brows; // not yet used
}
void I2CLCD::init()
{
Wire.begin();
backlight(0x00);
clear();
}
void I2CLCD::command(uint8_t value) {
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(value);
Wire.endTransmission();
delay(1);
}
void I2CLCD::clear()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x01); // clear display, set cursor position to zero
Wire.endTransmission();
delay(2);
}
void I2CLCD::write(const char* b)
{
Wire.beginTransmission(_adr);
while (*b)
{
if (*b == 0xfe || *b == 0xff) Wire.send(0xfe);
Wire.send(*b++); // sends one byte
}
Wire.endTransmission(); // stop transmitting
delay(1);
}
void I2CLCD::write(uint8_t value)
{
Wire.beginTransmission(_adr);
if (value == 0xfe || value == 0xff) Wire.send(0xfe);
Wire.send(value); // sends one byte
Wire.endTransmission(); // stop transmitting
delay(1);
}
void I2CLCD::write(int value)
{
char b[6];
itoa(value, b, 10);
Wire.beginTransmission(_adr);
for(int i=0; i<=6; i++) {
if(b[i] == '\0') {
break;
} else {
if (b[i] == 0xfe || b[i] == 0xff) Wire.send(0xfe);
Wire.send(b[i]); // sends one byte
}
}
Wire.endTransmission(); // stop transmitting
delay(1);
}
void I2CLCD::setCursor(int row, int col)
{
int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 };
command(0x80 | (col + row_offsets[row]));
}
void I2CLCD::backlight(uint8_t value)
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x01);
Wire.send(value);
Wire.endTransmission();
delay(1);
}
void I2CLCD::cursorOff()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x0c);
Wire.endTransmission();
delay(1);
}
void I2CLCD::cursorOn()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x0e);
Wire.endTransmission();
delay(1);
}
void I2CLCD::displayOff()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x08);
Wire.endTransmission();
delay(1);
}
void I2CLCD::displayOn()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x0c);
Wire.endTransmission();
delay(1);
}
void I2CLCD::blinkOn()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x0f);
Wire.endTransmission();
delay(1);
}
void I2CLCD::blinkOff()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x0e);
Wire.endTransmission();
delay(1);
}
void I2CLCD::cursorRight()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x14);
Wire.endTransmission();
delay(1);
}
void I2CLCD::cursorLeft()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x10);
Wire.endTransmission();
delay(1);
}
/*
Sets the display in programmable character mode at CGRAM address
*/
void I2CLCD::progCharMode()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x40);
Wire.endTransmission();
delay(1);
}
void I2CLCD::normalMode()
{
Wire.beginTransmission(_adr);
Wire.send(0xfe);
Wire.send(0x80);
Wire.endTransmission();
delay(1);
}
uint8_t I2CLCD::readEEPROM(uint8_t addr)
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x02);
Wire.send(addr);
Wire.endTransmission();
delay(1);
Wire.requestFrom((int)_adr,1); // ask for the byte
return Wire.receive(); // and return it
}
void I2CLCD::writeEEPROM(uint8_t addr, uint8_t value)
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x03);
Wire.send(addr);
Wire.send(value);
Wire.endTransmission();
delay(1);
}
void I2CLCD::zeroTermString(uint8_t addr)
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x04);
Wire.send(addr);
Wire.endTransmission();
delay(1);
}
void I2CLCD::resetEEPROM()
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0xf0);
Wire.endTransmission();
delay(1);
}
void I2CLCD::reset()
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0xf1);
Wire.endTransmission();
delay(1);
}
/***************
** for some reason this doesn't return a value. Possible firmware bug
****************/
uint8_t I2CLCD::keysInBuffer()
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x10);
Wire.endTransmission();
delay(50);
Wire.requestFrom((int)_adr,1); // ask for the byte
delay(50);
return Wire.receive(); // and return it
}
uint8_t I2CLCD::getKey()
{
uint8_t key = 0x00;
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x11);
Wire.endTransmission();
//needs a higher delay otherwise it won't reliably return the key
delay(40);
Wire.requestFrom((int)_adr, 1); // ask for the byte
if(Wire.available()) {
key = Wire.receive(); // and return it
}
return key;
}
/***************
** for some reason this doesn't return a value. Possible firmware bug
****************/
uint8_t I2CLCD::keyDown()
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x12);
Wire.endTransmission();
delay(1);
Wire.requestFrom((int)_adr,1); // ask for the byte
return Wire.receive(); // and return it
}
void I2CLCD::clearBuffer()
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x13);
Wire.endTransmission();
delay(1);
}
uint8_t I2CLCD::readKeysInBuffer(uint8_t num_keys)
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x14);
Wire.send(num_keys);
Wire.endTransmission();
delay(1);
Wire.requestFrom((int)_adr,1); // ask for the byte
return Wire.receive(); // and return it
}
void I2CLCD::interruptOn()
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x16);
Wire.endTransmission();
delay(1);
}
void I2CLCD::interruptOff()
{
Wire.beginTransmission(_adr);
Wire.send(0xff);
Wire.send(0x16);
Wire.endTransmission();
delay(1);
}
void I2CLCD::backspace()
{
cursorLeft();
write(" ");
cursorLeft();
} | [
"[email protected]"
]
| [
[
[
1,
351
]
]
]
|
f12b822d4c4c91c35fe8b39dac243c6dc58ad5f4 | 216398e30aca5f7874edfb8b72a13f95c22fbb5a | /DBTerm/DBManager/TableManagerDlg.cpp | aa30b172a55cdea0207d9d594526b7b4eb29b680 | []
| no_license | markisme/healthcare | 791813ac6ac811870f3f28d1d31c3d5a07fb2fa2 | 7ab5a959deba02e7637da02a3f3c681548871520 | refs/heads/master | 2021-01-10T07:18:42.195610 | 2009-09-09T13:00:10 | 2009-09-09T13:00:10 | 35,987,767 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 7,776 | cpp | #include "stdafx.h"
#include "TableManagerDlg.h"
IMPLEMENT_DYNAMIC(TableManagerDlg, CDialog)
TableManagerDlg::TableManagerDlg(CWnd* pParent /*=NULL*/) : CDialog(TableManagerDlg::IDD, pParent)
{
}
TableManagerDlg::~TableManagerDlg()
{
}
void TableManagerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT_TABLE_NAME, _tableName);
}
BEGIN_MESSAGE_MAP(TableManagerDlg, CDialog)
ON_WM_CREATE()
ON_WM_SIZE()
ON_WM_DESTROY()
ON_BN_CLICKED(IDOK, &TableManagerDlg::OnBnClickedOk)
END_MESSAGE_MAP()
INT_PTR TableManagerDlg::DoModal( int command, std::string tableName )
{
_command = command;
_tbName = tableName;
return CDialog::DoModal();
}
BOOL TableManagerDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 윈도우 내용 갱신하기
int cnt = _colList.size();
for( int num = 0; num < cnt; num++ )
{
std::string type, length;
BOOL notNull= FALSE, primaryKey= FALSE, autoIncr = FALSE;
std::string buf = _colList[num]._typeList[0];
int index = buf.find('(');
if( index > 0 )
{
type = buf.substr( 0, index );
length = buf.substr( index + 1, buf.size() - index - 2);
}
else
{
type = buf;
}
int count = _colList[num]._typeList.size();
if( count >= 2 )
{
std::string str = _colList[num]._typeList[1];
if( str == "NO" )
{
notNull = TRUE;
}
}
if( count >= 3 )
{
std::string str = _colList[num]._typeList[2];
if( str == "PRI" )
{
primaryKey = TRUE;
}
}
if( count >= 5 )
{
std::string str = _colList[num]._typeList[4];
if( str == "auto_increment" )
{
autoIncr = TRUE;
}
}
TableListItem * item = _dlgList[num];
item->SetFieldName( _colList[num]._name.c_str() );
item->SetFieldType( type );
item->SetFieldLenth( length );
item->SetNotNull( notNull );
item->SetPK( primaryKey );
item->SetAutoIncr( autoIncr );
item->Refresh();
}
if( _command == 1 )
{
_tableName.SetWindowText( _tbName.c_str() );
}
Refresh();
return TRUE; // 컨트롤에 대한 포커스를 설정하지 않을 경우 TRUE를 반환합니다.
}
int TableManagerDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialog::OnCreate(lpCreateStruct) == -1)
return -1;
if( _command == 0 ) // 생성
{
// 생성창을 위해 만들어 둠
TableListItem * item = new TableListItem();
item->Create(IDD_TABLE_LIST_DLG,this);
item->Init( this );
_dlgList.push_back(item);
}
else // 수정
{
// 쿼리 날려서 컬럼정보 얻기
DBConnector::GetInstance().GetColumnsList( _tbName, _colList );
int count = _colList.size();
for( int num = 0; num < count; num++ )
{
TableListItem * item = new TableListItem();
item->Create(IDD_TABLE_LIST_DLG,this);
item->Init( this );
_dlgList.push_back(item);
}
}
}
void TableManagerDlg::OnDestroy()
{
CDialog::OnDestroy();
int count = _dlgList.size();
for( int num = 0; num < count; num++ )
{
TableListItem * item = _dlgList[num];
item->Uninit();
item->DestroyWindow();
SAFE_DELETE(item);
}
}
void TableManagerDlg::AddField( CDialog * child )
{
// 필드 20개 이상 생성 불가
int count = _dlgList.size();
if( count >= 20 )
{
return;
}
// 수정 아이템은 필드 추가 금지
if( _command == 1 )
{
return;
}
// 마지막 아이템인지 검사
TableListItem * item = _dlgList[count-1];
if( item == child )
{
TableListItem * item = new TableListItem();
item->Create(IDD_TABLE_LIST_DLG,this);
item->Init( this );
_dlgList.push_back(item);
Refresh();
}
}
void TableManagerDlg::Refresh()
{
//
int count = _dlgList.size();
for( int num = 0; num < count; num++ )
{
TableListItem * item = _dlgList[num];
item->ShowWindow( SW_SHOW );
item->UpdateWindow();
item->ModifyStyleEx( 0, WS_EX_CONTROLPARENT );
item->ModifyStyle( 0, WS_TABSTOP );
}
// 이동
count = _dlgList.size();
for( int num = 0; num < count; num++ )
{
TableListItem * item = _dlgList[num];
CRect fieldDlgRect;
item->GetClientRect( fieldDlgRect );
uint fieldDlgWidth = (uint)fieldDlgRect.Width();
uint fieldDlgHeight = (uint)fieldDlgRect.Height();
item->MoveWindow( 10, 40+fieldDlgHeight*num, fieldDlgWidth, fieldDlgHeight );
}
}
void TableManagerDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
Refresh();
}
void TableManagerDlg::OnBnClickedOk()
{
// 쿼리 날리기
if( _command == 0 )
{
// 테이블 이름 가져오기
CString tableName;
_tableName.GetWindowText( tableName );
//
std::string fieldList;
// 수정된 정보 긁어 오기
int cnt = _dlgList.size();
for( int num = 0; num < cnt; num++ )
{
TableListItem * item = _dlgList[num];
std::string name = item->GetFieldName();
std::string type = item->GetFieldType();
std::string length = item->GetFieldLenth();
bool notNull = item->IsNotNull();
bool primaryKey = item->IsPK();
bool autoIncr = item->IsAutoIncr();
if( name.length() != 0 )
{
fieldList += name + " ";
}
else
{
continue;
}
if( type.length() != 0 )
{
fieldList += type;
}
else
{
continue;
}
if( length.length() != 0 )
{
fieldList += "(" + length + ")";
fieldList += " ";
}
else
{
fieldList += " ";
}
if( notNull == TRUE )
{
fieldList += "not null";
fieldList += " ";
}
if( primaryKey == TRUE )
{
fieldList += "primary key";
fieldList += " ";
}
if( autoIncr == TRUE )
{
fieldList += "auto_increment";
fieldList += " ";
}
fieldList += ",";
}
fieldList.erase( fieldList.size() - 1 );
char query[1024];
sprintf(query,"CREATE TABLE %s(%s);", tableName, fieldList.c_str() );
if( DBConnector::GetInstance().MysqlQuery( query ) == FALSE )
{
return;
}
}
else
{
// 테이블 이름 가져오기
CString tableName;
_tableName.GetWindowText( tableName );
std::string pkList;
// 수정된 정보 긁어 오기
int cnt = _dlgList.size();
for( int num = 0; num < cnt; num++ )
{
TableListItem * item = _dlgList[num];
std::string name = item->GetFieldName();
std::string type = item->GetFieldType();
std::string length = item->GetFieldLenth();
bool notNull = item->IsNotNull();
bool primaryKey = item->IsPK();
bool autoIncr = item->IsAutoIncr();
if( name.length() == 0 )
{
continue;
}
if( type.length() == 0 )
{
continue;
}
std::string typeOpt;
if( length.length() != 0 )
{
typeOpt += type + "(" + length + ")";
typeOpt += " ";
}
else
{
typeOpt += type + " ";
}
std::string nullOpt;
if( notNull == TRUE )
{
nullOpt += "not null";
nullOpt += " ";
}
if( primaryKey == TRUE )
{
pkList += name;
pkList += ",";
}
std::string incrOpt;
if( autoIncr == TRUE )
{
incrOpt += "auto_increment";
incrOpt += " ";
}
char query[1024];
sprintf(query,"ALTER TABLE %s MODIFY %s %s %s %s;", tableName, name.c_str(), typeOpt.c_str(), nullOpt.c_str(), incrOpt.c_str() );
if( DBConnector::GetInstance().MysqlQuery( query ) == FALSE )
{
return;
}
}
pkList.erase( pkList.size() - 1 );
if( pkList.size() > 0 )
{
char query[1024];
sprintf(query,"ALTER TABLE %s add primary key (%s);", tableName, pkList.c_str() );
if( DBConnector::GetInstance().MysqlQuery( query ) )
{
return;
}
}
}
OnOK();
}
| [
"naidzzang@cc586c1e-b153-0410-8069-cfc9d6f95ec9"
]
| [
[
[
1,
375
]
]
]
|
2997ee35221d1dcdd20773a666f7ef2cc24ce503 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/input/ndi8server_dinput.cc | 9c12683e3c54fb6e4112de0523feb796d609ef55 | []
| no_license | DSPNerd/m-nebula | 76a4578f5504f6902e054ddd365b42672024de6d | 52a32902773c10cf1c6bc3dabefd2fd1587d83b3 | refs/heads/master | 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,418 | cc | #define N_IMPLEMENTS nDI8Server
//------------------------------------------------------------------------------
// ndi8server_dinput.cc
// (C) 2002 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "input/ndi8server.h"
#include "input/ninputdevice.h"
#include "input/njoymousedevice.h"
#include "input/njoystickdevice.h"
#include "input/npadmousedevice.h"
#include "input/nrelmousedevice.h"
#include "input/nkeyboarddevice.h"
#include "kernel/nenv.h"
//------------------------------------------------------------------------------
/**
Initialized DirectInput8 and enumerates the input devices.
*/
bool
nDI8Server::InitDirectInput()
{
HRESULT hr;
// initialize DirectInput
HMODULE instance = GetModuleHandle(NULL);
if (!instance)
{
n_printf("nDI8Server: GetModuleHandle() failed!\n");
return false;
}
hr = DirectInput8Create(instance, DIRECTINPUT_VERSION, IID_IDirectInput8A, (void**) &(this->di8), NULL);
if (FAILED(hr))
{
n_printf("nDI8Server: DirectInput8Create() failed with '%s'!\n", this->Error(hr));
return false;
}
n_assert(this->di8);
// init DirectInput devices
if (!this->InitDevices())
{
n_printf("nDI8Server: Failed to initialize DInput devices!\n");
return false;
}
return true;
}
//------------------------------------------------------------------------------
/**
Destroy DirectInput.
*/
void
nDI8Server::KillDirectInput()
{
n_assert(this->di8);
// shutdown DirectInput devices
this->KillDevices();
// shutdown DirectInput
this->di8->Release();
this->di8 = 0;
}
//------------------------------------------------------------------------------
/**
Set a DWORD property on a DirectInput device.
*/
static
void
di8SetDWordProp(IDirectInputDevice8* dev, REFGUID prop, DWORD val)
{
HRESULT hr;
DIPROPDWORD dpw;
n_memset(&(dpw), 0, sizeof(dpw));
dpw.diph.dwSize = sizeof(DIPROPDWORD);
dpw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dpw.diph.dwHow = DIPH_DEVICE;
dpw.diph.dwObj = NULL;
dpw.dwData = val;
hr = dev->SetProperty(prop, (LPDIPROPHEADER) &dpw);
}
//------------------------------------------------------------------------------
/**
Get a range property from a DirectInput device.
*/
static
void
di8GetRangeProp(IDirectInputDevice8* dev,
REFGUID prop,
DWORD obj,
int& minRange,
int& maxRange)
{
HRESULT hr;
DIPROPRANGE dpr;
n_memset(&(dpr), 0, sizeof(dpr));
dpr.diph.dwSize = sizeof(DIPROPRANGE);
dpr.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dpr.diph.dwHow = DIPH_BYOFFSET;
dpr.diph.dwObj = obj;
hr = dev->GetProperty(prop,(LPDIPROPHEADER)&dpr);
if (SUCCEEDED(hr))
{
minRange = dpr.lMin;
maxRange = dpr.lMax;
}
else
{
minRange = 0;
maxRange = 0;
}
}
//------------------------------------------------------------------------------
/**
Callback procedure for EnumDevices. First checks whether the device
is acceptable to us, then creates a nDI8Device object and adds it to
the device list.
@param lpddi pointer to a DIDEVICEINSTANCE describing the input device
@param pvRef pointer to nDI8Server object
@return DIENUM_CONTINUE continues, DIENUM_STOP stops enumeration
*/
BOOL CALLBACK
di8EnumDevicesCallback(LPCDIDEVICEINSTANCE lpddi, LPVOID pvRef)
{
HRESULT hr;
nDI8Server* diServer = (nDI8Server*) pvRef;
IDirectInput8* di8 = diServer->di8;
n_assert(di8);
// convert device type into general Nebula device type
DWORD devType = lpddi->dwDevType & 0xff;
nDI8Device::DeviceType type;
switch (devType)
{
case DI8DEVTYPE_GAMEPAD:
case DI8DEVTYPE_JOYSTICK:
type = nDI8Device::JOYSTICK;
break;
case DI8DEVTYPE_KEYBOARD:
type = nDI8Device::KEYBOARD;
break;
case DI8DEVTYPE_MOUSE:
type = nDI8Device::MOUSE;
break;
default:
type = nDI8Device::NONE;
break;
}
// ignore if device type not supported
if (nDI8Device::NONE == type)
{
return DIENUM_CONTINUE;
}
// create DirectInput device
IDirectInputDevice8* diDev = 0;
hr = di8->CreateDevice(lpddi->guidInstance, &diDev, 0);
if (FAILED(hr))
{
n_printf("nDI8Server: failed to create device '%s' with '%d'\n",
lpddi->tszInstanceName, diServer->Error(hr));
return DIENUM_CONTINUE;
}
n_assert(diDev);
// get device caps
DIDEVCAPS caps = { sizeof(DIDEVCAPS), 0 };
hr = diDev->GetCapabilities(&caps);
if (FAILED(hr))
{
n_printf("nDI8Server: GetCapabilities() failed!\n");
diDev->Release();
return DIENUM_CONTINUE;
}
// create nDI8Device object and link to device list
nDI8Device* dev = new nDI8Device;
dev->SetDevice(diDev);
dev->SetInstanceName(lpddi->tszInstanceName);
dev->SetProductName(lpddi->tszProductName);
dev->SetDeviceType(type);
dev->SetNumAxes(caps.dwAxes);
dev->SetNumButtons(caps.dwButtons);
dev->SetNumPovs(caps.dwPOVs);
diServer->di8DevList.AddTail(dev);
// initialize the device
HWND hwnd = (HWND) diServer->refHwnd->GetI();
hr = diDev->SetCooperativeLevel(hwnd, (DISCL_FOREGROUND | DISCL_NOWINKEY | DISCL_NONEXCLUSIVE));
if (FAILED(hr))
{
n_printf("SetCooperativeLevel() failed on '%s' with '%s'\n", lpddi->tszInstanceName, diServer->Error(hr));
}
// set data format on DirectInput device
switch(type)
{
int minRange, maxRange;
case nDI8Device::JOYSTICK:
// set data format and axis properties
diDev->SetDataFormat(&c_dfDIJoystick);
di8SetDWordProp(diDev, DIPROP_BUFFERSIZE, nDI8Server::INPUT_BUFFER_SIZE);
di8SetDWordProp(diDev, DIPROP_AXISMODE, DIPROPAXISMODE_ABS);
di8SetDWordProp(diDev, DIPROP_DEADZONE, 500);
di8SetDWordProp(diDev, DIPROP_SATURATION, 9900);
// get the range and store in the device object
di8GetRangeProp(diDev, DIPROP_RANGE, DIJOFS_X, minRange, maxRange);
dev->SetRange(minRange, maxRange);
break;
case nDI8Device::KEYBOARD:
diDev->SetDataFormat(&c_dfDIKeyboard);
break;
case nDI8Device::MOUSE:
// set data format and axis properties
diDev->SetDataFormat(&c_dfDIMouse2);
di8SetDWordProp(diDev, DIPROP_BUFFERSIZE, nDI8Server::INPUT_BUFFER_SIZE);
di8SetDWordProp(diDev, DIPROP_AXISMODE, DIPROPAXISMODE_REL);
dev->SetRange(-50, +50);
break;
default:
break;
}
// acquire the device
diDev->Acquire();
// continue enumeration...
return DIENUM_CONTINUE;
}
//------------------------------------------------------------------------------
/**
Notify the DirectInput devices that the HWND has changed. Called
by Trigger() when window handle has changed since last frame.
*/
void
nDI8Server::HwndChanged()
{
HRESULT hr;
nDI8Device* dev;
for (dev = (nDI8Device*) this->di8DevList.GetHead();
dev;
dev = (nDI8Device*) dev->GetSucc())
{
IDirectInputDevice8* diDev = dev->GetDevice();
n_assert(diDev);
diDev->Unacquire();
hr = diDev->SetCooperativeLevel(this->hwnd, (DISCL_FOREGROUND|DISCL_NOWINKEY|DISCL_NONEXCLUSIVE));
if (FAILED(hr))
{
n_printf("SetCooperativeLevel() failed on '%s' with '%s'\n",
dev->GetInstanceName(),
this->Error(hr));
}
}
}
//------------------------------------------------------------------------------
/**
Enumerate supported DirectInput devices, create a nDI8Device object for each
DirectInput device.
*/
bool
nDI8Server::InitDevices()
{
n_assert(this->di8);
HRESULT hr;
// enumerate devices
hr = this->di8->EnumDevices(DI8DEVCLASS_ALL, di8EnumDevicesCallback, (LPVOID) this, DIEDFL_ATTACHEDONLY);
if (FAILED(hr))
{
n_printf("nDI8Server: EnumDevices() failed with '%s'\n", this->Error(hr));
return false;
}
// export devices into Nebula's input device database
this->ExportDevices();
return true;
}
//------------------------------------------------------------------------------
/**
Kill the devices in the internal device lists
*/
void
nDI8Server::KillDevices()
{
// kill nDI8Device's
nDI8Device* di8Dev;
while (di8Dev = (nDI8Device*) this->di8DevList.RemHead())
{
delete di8Dev;
}
// kill Nebula input device objects
nInputDevice* dev;
while (dev = (nInputDevice*) this->nebDevList.RemHead())
{
delete dev;
}
}
//------------------------------------------------------------------------------
/**
Export recognized devices into the Nebula input device database. This
creates nInputDevice objects, configures them, and asks them to export
themselves.
*/
void
nDI8Server::ExportDevices()
{
this->curJoyMouse = 0;
this->curPadMouse = 0;
this->curRelMouse = 0;
this->curJoystick = 0;
this->curKeyboard = 0;
// scan di8 device list
nDI8Device* di8Dev;
for (di8Dev = (nDI8Device*) this->di8DevList.GetHead();
di8Dev;
di8Dev = (nDI8Device*) di8Dev->GetSucc())
{
// get hardware's number of axes, buttons and povs
int numAxes = di8Dev->GetNumAxes();
int numButtons = di8Dev->GetNumButtons();
int numPovs = di8Dev->GetNumPovs();
// create a nInputDevice object
switch (di8Dev->GetDeviceType())
{
case nDI8Device::MOUSE:
{
// this generates 3 "virtual" mouse devices, a joymouse, a padmouse,
// and a relmouse.
nInputDevice* joyMouse = new nJoyMouseDevice(
kernelServer,
this,
this->curJoyMouse++,
numAxes,
numButtons,
0);
joyMouse->SetSourceDevice(di8Dev);
joyMouse->SetAxisRange(di8Dev->GetMinRange(), di8Dev->GetMaxRange());
joyMouse->Export(this->refDevices.get());
this->nebDevList.AddTail(joyMouse);
nInputDevice* padMouse = new nPadMouseDevice(
kernelServer,
this,
this->curPadMouse++,
numAxes,
numButtons,
0);
padMouse->SetSourceDevice(di8Dev);
padMouse->SetAxisRange(di8Dev->GetMinRange(), di8Dev->GetMaxRange());
padMouse->Export(this->refDevices.get());
this->nebDevList.AddTail(padMouse);
nInputDevice* relMouse = new nRelMouseDevice(
kernelServer,
this,
this->curRelMouse++,
numAxes,
numButtons,
0);
relMouse->SetSourceDevice(di8Dev);
relMouse->SetAxisRange(di8Dev->GetMinRange(), di8Dev->GetMaxRange());
relMouse->Export(this->refDevices.get());
this->nebDevList.AddTail(relMouse);
}
break;
case nDI8Device::JOYSTICK:
{
nInputDevice* joystick = new nJoystickDevice(
kernelServer,
this,
this->curJoystick++,
numAxes,
numButtons,
numPovs);
joystick->SetSourceDevice(di8Dev);
joystick->SetAxisRange(di8Dev->GetMinRange(), di8Dev->GetMaxRange());
joystick->Export(this->refDevices.get());
this->nebDevList.AddTail(joystick);
}
break;
case nDI8Device::KEYBOARD:
{
nInputDevice* keyboard = new nKeyboardDevice(
kernelServer,
this,
this->curKeyboard++,
0,
numButtons,
0);
keyboard->SetSourceDevice(di8Dev);
keyboard->Export(this->refDevices.get());
this->nebDevList.AddTail(keyboard);
}
break;
}
}
}
//------------------------------------------------------------------------------
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
425
]
]
]
|
a45805a80ed24d58490fb031de8efc0970a3333f | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/compatanalysercmd/headeranalyser/src/BBCFileUtils.cpp | ddcbc999df103b83022ced20646c561c1103aafe | []
| 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 | 29,015 | cpp | /*
* Copyright (c) 2006-2009 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:
*
*/
#include "CmdGlobals.h"
#ifdef __WIN__
#pragma warning(disable:4786)
#endif
#include <fstream>
#include <stdlib.h>
#include <string>
#include <map>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef __WIN__
#include <io.h>
#include <windows.h>
#else
#include <unistd.h>
#include <glob.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <unistd.h>
#define _MAX_PATH MAXPATHLEN
#endif
#include "BBCFileUtils.h"
#include "HAException.h"
#include "Utils.h"
#include "XMLUtils.h"
// ----------------------------------------------------------------------------
// BBCFileUtils::BBCFileUtils
// ----------------------------------------------------------------------------
//
BBCFileUtils::BBCFileUtils(string basedir)
{
iBaseDir = basedir;
}
// ----------------------------------------------------------------------------
// BBCFileUtils::~BBCFileUtils
// ----------------------------------------------------------------------------
//
BBCFileUtils::~BBCFileUtils()
{
}
typedef int intptr_t;
// ----------------------------------------------------------------------------
// BBCFileUtils::getFilesInDir
// ----------------------------------------------------------------------------
//
list<pair<string, string> > BBCFileUtils::getFilesInDir(string wildcard, string aRelPath)
{
// START -- Support for multiple header directories
list<pair<string, string> > ret;
list<pair<string, string> > dirs = BBCFileUtils::extractFilenames(iBaseDir);
list<pair<string, string> >::iterator dirbegin = dirs.begin();
for(; dirbegin != dirs.end(); dirbegin++)
{
// END -- Support for multiple header directories
string basedir = BBCFileUtils::getFullPath(dirbegin->first);
if (aRelPath != "")
{
iWildcard = basedir + DIR_SEPARATOR + aRelPath + DIR_SEPARATOR + wildcard;
} else
{
iWildcard = basedir + DIR_SEPARATOR + wildcard;
}
// search for all files which were specified in wildcard string
#ifdef __WIN__
_finddata_t finddata;
intptr_t searchsession =_findfirst(iWildcard.c_str(),&finddata);
int found = -1;
if (searchsession > 0)
{
found = 0;
}
while (found == 0)
{
string path;
if (aRelPath != "")
{
path = DIR_SEPARATOR + aRelPath + DIR_SEPARATOR + string(finddata.name);
} else
{
path = DIR_SEPARATOR + string(finddata.name);
}
string fullpath = basedir + path;
if (isValidFilename(fullpath))
{
pair<string, string> tempval(path, toLowerCaseWin(path));
ret.push_back(tempval);
}
found = _findnext(searchsession, &finddata);
}
_findclose(searchsession);
#else
glob_t p_glob;
glob(iWildcard.c_str() , 0, NULL, &p_glob);
for (unsigned int i = 0; i < p_glob.gl_pathc; i++ )
{
string path = p_glob.gl_pathv[i];
if (isValidFilename(path))
{
path = StripPath(path);
if (aRelPath != "")
{
path = aRelPath + DIR_SEPARATOR + path;
}
path = DIR_SEPARATOR + path;
pair<string, string> tempval(path, toLowerCaseWin(path));
ret.push_back(tempval);
}
}
globfree(&p_glob);
#endif
}
return ret;
}
// ----------------------------------------------------------------------------
// BBCFileUtils::getFilesInDir
// ----------------------------------------------------------------------------
//
list<pair<string,string> > BBCFileUtils::getFilesInDir(list<pair<string, string> >& fileset, string aRelPath, list<pair<string, string> >& aFoundfiles)
{
// START -- Support for multiple header directories
list<pair<string, string> > ret;
list<pair<string, string> > notfound;
list<pair<string, string> > dirs = BBCFileUtils::extractFilenames(iBaseDir);
list<pair<string, string> >::iterator dirbegin = dirs.begin();
for(; dirbegin != dirs.end(); dirbegin++)
{
// END -- Support for multiple header directories
string basedir = BBCFileUtils::getFullPath(dirbegin->first);
if (aRelPath != "")
{
iWildcard = basedir + DIR_SEPARATOR + aRelPath + DIR_SEPARATOR + WILDCARD_ALLFILES;
} else
{
iWildcard = basedir + DIR_SEPARATOR + WILDCARD_ALLFILES;
}
// Search for all files which were specified in wildcard string
#ifdef __WIN__
_finddata_t finddata;
intptr_t searchsession =_findfirst(iWildcard.c_str(),&finddata);
int found = -1;
if (searchsession > 0)
{
found = 0;
}
while (found == 0)
{
string filename = DIR_SEPARATOR + string(finddata.name);
if (aRelPath != "")
{
filename = DIR_SEPARATOR + aRelPath + filename;
}
string fullpath = basedir + filename;
// Check if path is pointing to a file
if (isValidFilename(fullpath))
{
list<pair<string, string> >::iterator file = FindFromList(toLowerCaseWin(filename), fileset, ERightValue);
if (file == fileset.end() && aRelPath != "")
{
file = FindFromList(toLowerCaseWin(finddata.name), fileset, ERightValue);
}
if (file != fileset.end())
{
pair<string, string> tempval;
tempval.first = filename;
tempval.second = toLowerCaseWin(filename);
ret.push_back(tempval);
aFoundfiles.push_back(*file);
fileset.erase(file);
} else if (aRelPath == "")
{
pair<string, string> tempvar(filename, toLowerCaseWin(filename));
notfound.push_back(tempvar);
} else
{
list<pair<string, string> >::iterator alreadyfound = FindFromList(toLowerCaseWin(finddata.name), aFoundfiles, ERightValue);
if (alreadyfound != aFoundfiles.end())
{
cout << "Warning: More than one files matches for the given filename '" << finddata.name;
cout << "' in the file set, only the first file is used." << endl;
aFoundfiles.erase(alreadyfound);
}
}
}
found = _findnext(searchsession, &finddata);
}
_findclose(searchsession);
#else
glob_t p_glob;
int result = glob(iWildcard.c_str() , 0, NULL, &p_glob);
if (result == 0)
{
for ( unsigned int i = 0; i < p_glob.gl_pathc; i++ )
{
string path = p_glob.gl_pathv[i];
// Check if path is pointing to a file
if (isValidFilename(path))
{
string filename = DIR_SEPARATOR + StripPath(path);
string pathfile = "";
if (aRelPath != "")
{
pathfile = DIR_SEPARATOR + aRelPath + filename;
} else
{
pathfile = filename;
}
list<pair<string, string> >::iterator file = FindFromList(toLowerCaseWin(pathfile), fileset,ERightValue);
if (file == fileset.end() && aRelPath != "")
{
file = FindFromList(toLowerCaseWin(filename.substr(1)), fileset,ERightValue);
}
if (file != fileset.end())
{
pair<string, string> tempval;
tempval.first = pathfile;
tempval.second = toLowerCaseWin(pathfile);
ret.push_back(tempval);
aFoundfiles.push_back(*file);
fileset.erase(file);
} else if (aRelPath == "")
{
pair<string, string> tempvar(pathfile, toLowerCaseWin(pathfile));
notfound.push_back(tempvar);
} else
{
list<pair<string, string> >::iterator alreadyfound = FindFromList(toLowerCaseWin(filename.substr(1)), aFoundfiles,ERightValue);
if (alreadyfound != aFoundfiles.end())
{
cout << "Warning: More than one files matches for the given filename '" << filename.substr(1);
cout << "' in the file set, only the first file is used.";
aFoundfiles.erase(alreadyfound);
}
}
}
}
globfree(&p_glob);
}
#endif
}
if (notfound.size() != 0)
{
list<pair<string, string> >::iterator file = notfound.begin();
list<pair<string, string> >::iterator fileend = notfound.end();
for(; file != fileend; file++)
{
string filename = file->second.substr(1);
list<pair<string, string> >::iterator file = FindFromList(filename, fileset, ERightValue);
if (file != fileset.end())
{
pair<string, string> tempval;
tempval.first = DIR_SEPARATOR + file->first;
tempval.second = DIR_SEPARATOR + file->second;
ret.push_back(tempval);
aFoundfiles.push_back(*file);
fileset.erase(file);
} else
{
list<pair<string, string> >::iterator alreadyfound = FindFromList(filename, aFoundfiles, ERightValue);
if (alreadyfound != aFoundfiles.end())
{
cout << "Warning: More than one files matches for the given filename '" << filename;
cout << "' in the file set, only the first file is used." << endl;
aFoundfiles.erase(alreadyfound);
}
}
}
}
ret.sort();
return ret;
}
// ----------------------------------------------------------------------------
// BBCFileUtils::setTemp
// Set temp dir
// ----------------------------------------------------------------------------
//
void BBCFileUtils::setTemp(const string& aTempDir)
{
iTempDir = aTempDir;
}
// ----------------------------------------------------------------------------
// BBCFileUtils::getFilesInDir
// Calculates quite unique fingerprint for a string.
// ----------------------------------------------------------------------------
//
unsigned int BBCFileUtils::quickHash(string str)
{
int ret = 0;
unsigned int len = (unsigned int)str.length();
for (unsigned int i = 0; i < len; i++)
{
ret += (i+1) * str.at(i);
}
return ret;
}
// ----------------------------------------------------------------------------
// BBCFileUtils::trimFilenames
//
// ----------------------------------------------------------------------------
//
/*
string BBCFileUtils::trimFilenames(string aFilenameList)
{
string ret("");
unsigned int i = 0;
for (; i < aFilenameList.length(); i++)
{
char ch = aFilenameList.at(i);
if (ch != ';')
{
ret += ch;
} else
{
ret += ' ';
}
}
return ret;
}
*/
// ----------------------------------------------------------------------------
// BBCFileUtils::extractFilenames
// Extract filenames to string list
// ----------------------------------------------------------------------------
//
list<pair<string, string> > BBCFileUtils::extractFilenames(string aFilenameList)
{
size_t i = 0;
list<pair<string, string> > ret;
string current("");
for (; i < aFilenameList.length(); i++)
{
char ch = aFilenameList.at(i);
if (ch != ';')
{
current += ch;
} else
{
pair<string, string> tempvar(current, toLowerCaseWin(current));
ret.push_back(tempvar);
current = "";
}
}
if (current.length() > 0)
{
pair<string, string> tempvar(current, toLowerCaseWin(current));
ret.push_back(tempvar);
}
return ret;
}
// ----------------------------------------------------------------------------
// BBCFileUtils::isValidFilename
// Check if the given filename is valid
// ----------------------------------------------------------------------------
//
bool BBCFileUtils::isValidFilename(const string& aFilename)
{
bool valid = true;
if (aFilename.length() < 1)
{
valid = false;
}
struct stat stats;
int fSuccess = stat(aFilename.c_str(), &stats);
// Check if path is pointing to a directory
if (fSuccess == -1)
{
valid = false;
} else if ((stats.st_mode & S_IFDIR) != 0)
{
valid = false;
}
return valid;
}
// ----------------------------------------------------------------------------
// BBCFileUtils::isValidDirectory
// Check if the given path is valid directory
// ----------------------------------------------------------------------------
//
bool BBCFileUtils::isValidDirectory(const string& aPath)
{
bool valid = true;
if (aPath.length() < 1)
{
valid = false;
}
struct stat stats;
int fSuccess = stat(aPath.c_str(), &stats);
// Check if path is pointing to a directory
if (fSuccess == -1)
{
valid = false;
} else if ((stats.st_mode & S_IFDIR) == 0)
{
valid = false;
}
return valid;
}
// ----------------------------------------------------------------------------
// BBCFileUtils::getFullPath
// Check if the given path is valid directory
// ----------------------------------------------------------------------------
//
string BBCFileUtils::getFullPath(const string& aPath)
{
string ret;
#ifdef __WIN__
char temppath[_MAX_PATH+2];
char * filepart = NULL;
GetFullPathName(aPath.c_str(), _MAX_PATH, temppath, &filepart);
ret = temppath;
#else
string path = aPath;
string filename;
struct stat statinfo;
if ( 0 != stat(aPath.c_str(),&statinfo) )
{
filename = StripPath(aPath.c_str());
path = aPath.substr(0,aPath.size()-filename.size());
}
if (path.size() == 0)
{
path = ".";
}
if ( !absolutePath(path,ret) )
{
throw HAException("Internal error: Error parsing path.");
}
if (filename.size())
{
ret += DIR_SEPARATOR;
ret += filename;
}
#endif
return ret;
}
#ifdef __UNIX__
// ----------------------------------------------------------------------------
// BBCFileUtils::absolutePath
// Get full path
// ----------------------------------------------------------------------------
//
bool BBCFileUtils::absolutePath(const string& aRelpath, string& aAbspath)
{
char* base = new char[_MAX_PATH+1];
char* home;
getcwd(base, _MAX_PATH);
home = getenv("HOME");
aAbspath = base;
if (aRelpath.length() == 0)
{
aAbspath = "";
return false;
}
vector<string> splittedabspath = splitString(aAbspath, '/');
vector<string> splittedrelpath = splitString(aRelpath, '/');
vector<string> splittedhomepath = splitString(home, '/');
int longest;
if (splittedabspath.size() > splittedhomepath.size())
{
longest = splittedabspath.size();
} else
{
longest = splittedhomepath.size();
}
splittedabspath.reserve(longest + splittedrelpath.size());
if (splittedrelpath.at(0) == "")
{
splittedabspath.clear();
if (splittedrelpath.at(1) == "")
{
splittedabspath.push_back("");
splittedabspath.push_back("");
}
}
if (splittedrelpath.at(0) == "~")
{
splittedabspath = splittedhomepath;
splittedrelpath.erase(splittedrelpath.begin());
}
vector<string>::iterator dir = splittedrelpath.begin();
vector<string>::iterator dirend = splittedrelpath.end();
for(; dir != dirend; dir++)
{
string dirstr = *dir;
if (dirstr == "")
{
// Do nothing
} else if (dirstr == ".")
{
// Do nothing
} else if (dirstr == "..")
{
if (splittedabspath.size() > 1)
{
splittedabspath.pop_back();
}
} else
{
if (dirstr.find_first_not_of('.') == string::npos)
{
throw HAException("Illegal directory: '" + dirstr + "'\n");
}
splittedabspath.push_back(dirstr);
}
}
dir = splittedabspath.begin();
dirend = splittedabspath.end();
if (dir != dirend && *dir == "")
{
dir++;
}
aAbspath = "";
for(; dir != dirend; dir++)
{
aAbspath += '/';
aAbspath += *dir;
}
return true;
}
#endif
// ----------------------------------------------------------------------------
// BBCFileUtils::getDirsInDir
// Get subdirectories in directory
// ----------------------------------------------------------------------------
//
list<pair<string, string> > BBCFileUtils::getDirsInDir(string aRelPath, list<pair<string, string> >& aExcludes)
{
// STRAT -- Support for multiple header directories
list<pair<string, string> > ret;
list<pair<string, string> > dirs = BBCFileUtils::extractFilenames(iBaseDir);
list<pair<string, string> >::iterator dirbegin = dirs.begin();
for(; dirbegin != dirs.end(); dirbegin++)
{
// END -- Support for multiple header directories
string basedir = BBCFileUtils::getFullPath(dirbegin->first);
if (aRelPath != "")
{
iWildcard = basedir + DIR_SEPARATOR + aRelPath + DIR_SEPARATOR + WILDCARD_ALLFILES;
} else
{
iWildcard = basedir + DIR_SEPARATOR + WILDCARD_ALLFILES;
}
// search for all files which were specified in wildcard string
#ifdef __WIN__
_finddata_t finddata;
intptr_t searchsession =_findfirst(iWildcard.c_str(),&finddata);
int found = -1;
if (searchsession > 0)
{
found = 0;
}
while (found == 0)
{
string filename = finddata.name;
if (filename == "." || filename == "..")
{
// Do Nothing
} else
{
if (aRelPath != "")
{
filename = aRelPath + DIR_SEPARATOR + filename;
}
string fullpath = basedir + DIR_SEPARATOR + filename;
// Check if path is pointing to a directory
if (isValidDirectory(fullpath))
{
list<pair<string, string> >::const_iterator filereplace = FindFromList(toLowerCaseWin(filename), aExcludes, ERightValue);
if (filereplace == aExcludes.end())
{
filereplace = FindFromList(toLowerCaseWin(finddata.name), aExcludes, ERightValue);
}
if (filereplace == aExcludes.end())
{
pair<string, string> tempvar(filename, toLowerCaseWin(filename));
ret.push_back(tempvar);
}
}
}
found = _findnext(searchsession, &finddata);
}
_findclose(searchsession);
#else
//Wildcard.c_str());
glob_t p_glob;
int result = glob(iWildcard.c_str() , GLOB_ONLYDIR, NULL, &p_glob);
if (result == 0)
{
for ( unsigned int i = 0; i < p_glob.gl_pathc; i++ )
{
string path = p_glob.gl_pathv[i];
if (path.at(path.length() - 1) == '/')
{
path.resize(path.length() - 1);
}
// Check if path is pointing to a directory
if (isValidDirectory(path))
{
string dirname = BBCFileUtils::StripPath(path);
path = dirname;
if (aRelPath != "")
{
path = aRelPath + DIR_SEPARATOR + dirname;
}
list<pair<string, string> >::const_iterator filereplace = FindFromList(toLowerCaseWin(path), aExcludes,ERightValue);
if (filereplace == aExcludes.end())
{
filereplace = FindFromList(toLowerCaseWin(dirname), aExcludes,ERightValue);
}
if (filereplace == aExcludes.end())
{
pair<string, string> tempvar(path, toLowerCaseWin(path));
ret.push_back(tempvar);
}
}
}
globfree(&p_glob);
}
#endif
}
return ret;
}
// ----------------------------------------------------------------------------
// BBCFileUtils::StripPath
// Strip off path
// ----------------------------------------------------------------------------
//
string BBCFileUtils::StripPath(const string& aFilename)
{
size_t pos = aFilename.find_last_of("\\/");
if (pos != string::npos)
{
return string(aFilename.begin()+pos+1, aFilename.end());
}
return aFilename;
}
// ----------------------------------------------------------------------------
// BBCFileUtils::StripFilenameExtension
// Strip off filename extension
// ----------------------------------------------------------------------------
//
string BBCFileUtils::StripFilenameExtension(string aFilename)
{
string ret(aFilename);
size_t pos = ret.find_last_of("\\/.");
if (pos != string::npos)
{
string::iterator begin = ret.begin() + pos;
string::iterator end = ret.end();
if (*begin == '.')
ret.erase(begin,end);
}
return ret;
}
/**
* This function first splits strings in vectors. Then it finds the
* first part, the common part and the last part of the directories
* and combines them.
*/
// Changes done to this function to Support for multiple header directories. Return type changed to list.
list<pair<string, bool> > BBCFileUtils::MergeDirs(const string& rootDirs, const string& subDir)
{
// START -- Support for multiple header directories --
list<pair<string, bool> > retu;
list<pair<string, string> > dirs = BBCFileUtils::extractFilenames(rootDirs);
list<pair<string, string> >::iterator dirbegin = dirs.begin();
for(; dirbegin != dirs.end(); dirbegin++)
{
string ret;
string rootDir = BBCFileUtils::getFullPath(dirbegin->first);
// END -- Support for multiple header directories --
vector<string> rootVector(splitString(rootDir, DIR_SEPARATOR));
vector<string> subVector(splitString(subDir, DIR_SEPARATOR));
vector<string>::iterator rootIt = rootVector.begin();
vector<string>::iterator subIt = subVector.begin();
bool commonFound = false;
while( rootIt != rootVector.end() || subIt != subVector.end() )
{
string fixedRoot;
string fixedSub;
if( rootIt != rootVector.end() )
{
fixedRoot = *rootIt;
toLower(fixedRoot);
}
if( subIt != subVector.end() )
{
fixedSub = *subIt;
toLower(fixedSub);
}
if( rootIt != rootVector.end() &&
subIt != subVector.end() )
{
if( fixedRoot != fixedSub )
{
if( ret.size() > 0 )
ret += DIR_SEPARATOR;
if( commonFound == false )
{
ret += fixedRoot;
++rootIt;
}
else
{
ret += fixedSub;
++subIt;
}
}
else if( fixedRoot == fixedSub )
{
if( ret.size() > 0 )
ret += DIR_SEPARATOR;
ret += fixedSub;
++subIt;
++rootIt;
commonFound = true;
}
}
else if( subIt != subVector.end() )
{
if( ret.size() > 0 )
ret += DIR_SEPARATOR;
ret += fixedSub;
++subIt;
}
else
{
break;
}
}
#ifndef __WIN__
ret=DIR_SEPARATOR+ret;
#endif
// START -- Support for multiple header directories --
pair<string, bool> tempvar(ret, subIt == subVector.end());
retu.push_back(tempvar);
}
return retu;
// END -- Support for multiple header directories --
}
map<string, bool> BBCFileUtils::fileExistsCache = map<string, bool>();
bool BBCFileUtils::FileExists(const string& fileName)
{
map<string, bool>::const_iterator i = fileExistsCache.find(fileName);
if( i != fileExistsCache.end() )
{
return i->second;
}
fstream fin;
fin.open(fileName.c_str(),ios::in);
bool fileExists = fin.is_open();
fin.close();
fileExistsCache.insert(pair<string, bool>(fileName, fileExists));
return fileExists;
}
string BBCFileUtils::getCompilationError(string filename)
{
//Add compilation error to the report
std::ifstream file(filename.c_str());
string templine;
string compilationError;
int size =0;
int characterLimit = 2000;
// Keep the character count of total line to be displayed in report to 2000.
while(size <= characterLimit && std::getline(file,templine))
{
int index;
string replaceFrom = "\'";
string replaceTo = "`";
size += templine.size();
if(size > characterLimit)
compilationError.append(".........");
else
{
//Replace if any "'" with "`" , to work properly with stylesheet.
if((index = (int)templine.find(replaceFrom))!= string::npos)
templine.replace(index,replaceFrom.size(),replaceTo);
compilationError.append(templine);
compilationError.append("\n");
}
}
return compilationError;
}
// ----------------------------------------------------------------------------------------------------------
string& BBCFileUtils::TrimRight(string& s)
{
int pos(s.size());
for (; pos && (s[pos-1]==' ' || s[pos-1]=='\t' || s[pos-1]=='\r'); --pos);
s.erase(pos, s.size()-pos);
return s;
}
// ----------------------------------------------------------------------------------------------------------
string& BBCFileUtils::TrimLeft(string& s)
{
int pos(0);
for (; s[pos]==' ' || s[pos]=='\t' || s[pos]=='\r'; ++pos);
s.erase(0, pos);
return s;
}
// ----------------------------------------------------------------------------------------------------------
string& BBCFileUtils::TrimAll(string& s)
{
return TrimLeft(TrimRight(s));
}
| [
"none@none"
]
| [
[
[
1,
887
]
]
]
|
326626981360d975311864a60a212bcf3c5929f2 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/NodeViewer/ViewTree.cpp | de44f0a5a8df48fd034f0b8c5a2d0f3aea7a974f | []
| no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 887 | cpp |
#include "NodeViewerPCH.h"
#include "ViewTree.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CViewTree
CViewTree::CViewTree()
{
}
CViewTree::~CViewTree()
{
}
BEGIN_MESSAGE_MAP(CViewTree, CTreeCtrl)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CViewTree message handlers
BOOL CViewTree::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
BOOL bRes = CTreeCtrl::OnNotify(wParam, lParam, pResult);
NMHDR* pNMHDR = (NMHDR*)lParam;
ASSERT(pNMHDR != NULL);
if (pNMHDR && pNMHDR->code == TTN_SHOW && GetToolTips() != NULL)
{
GetToolTips()->SetWindowPos(&wndTop, -1, -1, -1, -1, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE);
}
return bRes;
}
| [
"[email protected]"
]
| [
[
[
1,
41
]
]
]
|
2d2c1edba7e74496e3cc3b987a9436bdb5e1fe3c | 814e67bf5d1c2f2e233b3ec1ee07faaaa65a9951 | /compiladormarvel/Erro.cpp | 1856639c5b8df8433a4aca25d50744cc215edcad | []
| no_license | lsalamon/compiladormarvel | 686a5814e363fee41163d8a447d6753ebe84d220 | 55ea7a3f3cb76ec738e792e608ab01a9f48e5f8b | refs/heads/master | 2021-01-10T08:17:50.321427 | 2009-03-20T14:06:43 | 2009-03-20T14:06:43 | 50,113,476 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 6,061 | cpp | #include "Erro.h"
char *retornaLiteralToken(int token);
/* Definicao das mensagens para erro durante análise léxica */
#define MSG_ERRO_GETTOKEN(linha) fprintf(stderr, "ERRO NO RECONHECIMENTO DO TOKEN NA LINHA %d.\n", linha)
#define MSG_ERRO_NUM_DECIMAL(linha) fprintf(stderr, "\nERRO NO RECONHECIMENTO DE UM NUMERO DECIMAL NA LINHA %d.\n", linha)
#define MSG_ERRO_NUM_REAL(linha) fprintf(stderr, "\nERRO NO RECONHECIMENTO DE UM NUMERO REAL NA LINHA %d.\n", linha)
#define MSG_ERRO_EOF_LITERAL(linha) fprintf(stderr, "\nFIM DE ARQUIVO INESPERADO NO RECONHECIMENTO DE UMA LITERAL NA LINHA %d.\n", linha)
#define MSG_ERRO_EOF_COMENTARIO(linha) fprintf(stderr, "\nFIM DE ARQUIVO INESPERADO DURANTE COMENTARIO INICIADO NA LINHA %d.\n", linha)
#define MSG_ERRO_MEMORIA_INSUF fprintf(stderr, "\nERRO: MEMORIA INSUFICIENTE.\n")
#define MSG_ERRO_PARAM_INVALIDO fprintf(stderr, "\nERRO: PARAMETRO INVALIDO NA ALOCACAO DA TABELA.\n")
#define MSG_ERRO_ABRIR_ARQUIVO fprintf(stderr, "\nERRO AO ABRIR ARQUIVO.\n")
/* Definicao de mensagens para erro durante análise sintática */
#define MSG_TOKEN_ESPERADO(token,linha) fprintf(stderr, "\nERRO: %s ESPERADO E NAO ENCONTRADO NA INSTRUCAO DA LINHA %d.\n",token,linha)
#define MSG_TOKEN_INVALIDO(token,linha) fprintf(stderr, "\nERRO: %s NAO ESPERADO VALIDO NA INSTRUCAO DA LINHA %d.\n",token,linha)
#define MSG_ERRO_EOF_SINTATICO(linha) fprintf(stderr, "\nFIM DE ARQUIVO NAO ESPERADO NA LINHA %d.\n", linha)
/* Definicao de mensagens para erro durante analise semântica */
#define MSG_TIPOS_INCOMPATIVEIS_OPERACAO(string, linha) fprintf(stderr, "\nERRO: TIPO DO IDENTIFICADOR %s NAO E ESPERADO OU E INCOMPATIVEL COM A OPERACAO NA LINHA %d.\n", string, linha)
#define MSG_TIPOS_INCOMPATIVEIS(linha) fprintf(stderr, "\nERRO: TIPOS NAO COMPATIVEIS NA OPERACAO DA LINHA %d.\n", linha)
#define MSG_TIPO_INCOMPATIVEL_INDICE_ARRAY(linha) fprintf(stderr, "\nERRO: TIPO INCOMPATIVEL COM INDICE DE ARRAY SENDO RETORNADO NA EXPRESSAO OU INSTRUCAO DA LINHA %d. O TIPO ESPERADO E INTEIRO.\n", linha)
#define MSG_TIPO_INCOMPATIVEL_ATRIBUICAO(linha) fprintf(stderr, "\nERRO: TIPOS INCOMPATIVEIS COM O IDENTIFICADOR DURANTE A ATRIBUICAO NA LINHA %d.\n", linha)
#define MSG_ERRO_EXPRESSAO_NAO_BOOLEANA(linha) fprintf(stderr, "\nERRO: EXPRESSAO NAO BOOLEANA EM TESTE CONDICIONAL IF NA NA LINHA %d.\n", linha)
#define MSG_ERRO_COMANDO_SEM_EXPRESSAO(string, linha) fprintf(stderr, "\nERRO: COMANDO %s SEM EXPRESSAO NA LINHA %d.\n", string, linha)
#define MSG_ERRO_TIPO_INCOMPATIVEL_CHAMADA_FRAG(linha) fprintf(stderr, "\nERRO: TIPO INCOMPATIVEL NA CHAMADA DO FRAGMENTO, LINHA %d.\n", linha)
#define MSG_ERRO_VARIAVEL_NAO_DECLARADA(linha, string) fprintf(stderr, "\nERRO: VARIAVEL %s NAO DECLARADA NA LINHA %d.\n", string, linha)
#define MSG_ERRO_VARIAVEL_JA_DECLARADA(linha, string) fprintf(stderr, "\nERRO: VARIAVEL %s NA LINHA %d JA DECLARADA ANTES.\n", string, linha)
//Envia uma mensagem de erro para stderr referente a erro lexico
void emiteErroLexico(int codigo, int linha){
switch(codigo) {
case(ERRO_EOF_LITERAL):
MSG_ERRO_EOF_LITERAL(linha);
break;
case(ERRO_GETTOKEN):
MSG_ERRO_GETTOKEN(linha);
break;
case(ERRO_NUM_DECIMAL):
MSG_ERRO_NUM_DECIMAL(linha);
break;
case(ERRO_NUM_REAL):
MSG_ERRO_NUM_REAL(linha);
break;
case(ERRO_EOF_COMENTARIO):
MSG_ERRO_EOF_COMENTARIO(linha);
break;
case(ERRO_MEMORIA_INSUF):
MSG_ERRO_MEMORIA_INSUF;
break;
case(ERRO_PARAM_INVALIDO):
MSG_ERRO_PARAM_INVALIDO;
break;
} // end switch
} // fim funcao
//Envia uma mensagem de erro para stderr referente a erro sintatico
void emiteErroSintatico(int codigo, int token, int linha){
switch(codigo) {
case(ERRO_TOKEN_ESPERADO):
MSG_TOKEN_ESPERADO(retornaLiteralToken(token), linha);
break;
case(ERRO_TOKEN_INVALIDO):
MSG_TOKEN_INVALIDO(retornaLiteralToken(token), linha);
break;
case(ERRO_EOF):
MSG_ERRO_EOF_SINTATICO(linha);
break;
} // end switch
} // fim funcao
// Envia uma mensagem de erro para stderr referente a erro semântico
void emiteErroSemantico(int codigo, char* string, int linha){
switch(codigo) {
case(ERRO_INCOMPATIBILIDADE_TIPO):
MSG_TIPOS_INCOMPATIVEIS(linha);
break;
case(ERRO_TIPO_NAO_ESPERADO_OPERACAO):
MSG_TIPOS_INCOMPATIVEIS_OPERACAO(string, linha);
break;
case(ERRO_TIPO_INCOMPATIVEL_INDICE_ARRAY):
MSG_TIPO_INCOMPATIVEL_INDICE_ARRAY(linha);
break;
case(ERRO_TIPO_INCOMPATIVEL_ATRIBUICAO):
MSG_TIPO_INCOMPATIVEL_ATRIBUICAO(linha);
break;
case(ERRO_EXPRESSAO_NAO_BOOLEANA):
MSG_ERRO_EXPRESSAO_NAO_BOOLEANA(linha);
break;
case(ERRO_COMANDO_SEM_EXPRESSAO):
MSG_ERRO_COMANDO_SEM_EXPRESSAO(string, linha);
break;
case(ERRO_TIPO_INCOMPATIVEL_CHAMADA_FRAG):
MSG_ERRO_TIPO_INCOMPATIVEL_CHAMADA_FRAG(linha);
break;
case(ERRO_VARIAVEL_NAO_DECLARADA):
MSG_ERRO_VARIAVEL_NAO_DECLARADA(linha, string);
break;
case(ERRO_VARIAVEL_JA_DECLARADA):
MSG_ERRO_VARIAVEL_JA_DECLARADA(linha, string);
break;
} // end switch
} // fim da função
| [
"sergiorossini@df256a42-0e3e-0410-b2fe-0dffcef58804",
"cslopes@df256a42-0e3e-0410-b2fe-0dffcef58804"
]
| [
[
[
1,
1
],
[
4,
65
],
[
67,
70
],
[
74,
79
],
[
81,
110
]
],
[
[
2,
3
],
[
66,
66
],
[
71,
73
],
[
80,
80
]
]
]
|
34cf8fa7e83e9adeec182fe6781ebde1faecace2 | 967868cbef4914f2bade9ef8f6c300eb5d14bc57 | /Virtual/VirtualMemory.hpp | 70eb4bcdb2d068aca0f96b567bb72a1bda3a514e | []
| 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 | 5,625 | hpp | /*
© Vestris Inc., Geneva Switzerland
http://www.vestris.com, 1998, All Rights Reserved
__________________________________________________
Virtual Memory Implementation (aka Malloc)
written by Daniel Doubrovkine - [email protected]
*/
#include <platform/include.hpp>
#ifndef BASECLASSES_VIRTUAL_MEMORY_HPP
#define BASECLASSES_VIRTUAL_MEMORY_HPP
#include <Object/Object.hpp>
#include <Mutex/RWMutex.hpp>
//
// an allocated block
//
struct _VMPage;
typedef struct _VMBlock {
size_t m_nSize; // size of block
bool m_fUsed; // used or free
bool m_fLast; // last block in page (to support arbitrary page size)
_VMPage * m_pPage; // page pointer
// allocated memory always starts after sizeof(_VMBlock)
// next block is always after sizeof(_VMBlock) + m_nSize
inline _VMBlock * GetNextBlock(void) const { return m_fLast ? NULL : (_VMBlock *) ((size_t) this + sizeof(_VMBlock) + m_nSize); }
inline void * GetMemory(void) const { return (void *) ((size_t) this + sizeof(_VMBlock)); }
} VMBlock;
//
// an allocated page
//
typedef struct _VMPage {
_VMPage * m_pNext; // next page
CRWMutex m_Mutex;
size_t m_nMaxBlock;
_VMBlock * m_pCacheNextBlock;
#ifdef _DEBUG
size_t m_pLowerBound;
#endif
// memory always starts after sizeof(_VMPage)
inline VMBlock * GetFirstBlock(void) const { return (VMBlock *) ((size_t) this + sizeof(_VMPage)); }
} VMPage;
//
// accounting information
//
typedef struct _VMAccounting {
size_t stUsed; // memory used
size_t stTotal; // total virtual memory usable (pBlock->m_nSize)
size_t stVirtual; // total virtual memory used (pBlock->m_nSize + sizeof(VMBlock)
unsigned int nFragCount; // fragmentation counter
unsigned long nBlockCount; // number of blocks
} VMAccounting;
typedef enum { vsDisabled, vsEnabled, vsTerminating } CVirtualState;
class CVirtualMemory {
protected:
CVirtualState m_bEnabled;
size_t m_PageSize;
VMPage * m_pVirtualMemory;
mutable CRWMutex m_VMMutex;
VMPage * m_pCacheNextPage;
VMBlock * m_pCacheNextBlock;
VMAccounting m_AccountingInfo;
protected:
size_t GetBlockSize(size_t Size) const;
bool AllocatePage(size_t PageSize, VMPage ** pPage);
bool AllocateBlock(size_t Size, VMBlock ** pBlock);
bool AllocateExistingBlock(size_t Size, VMBlock ** pBlock);
bool FreePage(VMPage * pPage);
bool FreePages(void);
bool AllocateBlock(VMPage * pPage, size_t Size, VMBlock ** pBlock);
bool FindPage(VMBlock * pBlock, VMPage ** pPage);
inline static VMBlock * GetBlock(void * pMem) { return (VMBlock *) ((size_t) pMem - sizeof(_VMBlock)); }
protected:
virtual bool AllocateMemory(size_t Size, void ** pMemory);
virtual bool FreeMemory(void * pMemory);
public:
static CVirtualMemory * m_pSwap;
public:
// generic system routines
static size_t GetPageSize(void);
// dump routines
void Dump(void);
CVirtualMemory(void);
virtual ~CVirtualMemory(void);
// allocation routines
void * Allocate(size_t Size);
void Free(void * pMem);
// virtual void GetAccountingInfo(VMPage * pPage, VMAccounting * pAccountingInfo) const;
virtual void GetAccountingInfo(VMAccounting * pAccountingInfo) const;
bool SetEnabled(bool bEnabled);
inline void SetState(CVirtualState State) { m_bEnabled = State; }
virtual void Dispose(void);
};
inline bool CVirtualMemory :: SetEnabled(bool bEnabled) {
m_bEnabled = bEnabled ? vsEnabled : vsDisabled;
return true;
}
inline void CVirtualMemory :: Dispose(void) {
FreePages();
}
inline bool CVirtualMemory :: AllocateMemory(size_t Size, void ** pMemory) {
assert(pMemory);
assert(* pMemory == NULL);
assert(Size);
* pMemory = malloc(Size);
return (* pMemory) ? true : false;
}
inline bool CVirtualMemory :: FreeMemory(void * pMemory) {
assert(pMemory);
free(pMemory);
return true;
}
inline bool CVirtualMemory :: FreePage(VMPage * pPage) {
assert(pPage);
pPage->m_Mutex.~CRWMutex();
if (! FreeMemory((void *) pPage))
return false;
return true;
}
inline size_t CVirtualMemory :: GetPageSize(void) {
#ifdef _UNIX
return (size_t) getpagesize();
#endif
#ifdef _WIN32
SYSTEM_INFO SystemInfo;
GetSystemInfo(&SystemInfo);
return (size_t) SystemInfo.dwAllocationGranularity;
#endif
}
inline bool CVirtualMemory :: AllocateExistingBlock(size_t Size, VMBlock ** pBlock) {
bool bResult = false;
VMPage * pCurrentPage = m_pCacheNextPage ? m_pCacheNextPage : m_pVirtualMemory;
while (pCurrentPage) {
if (AllocateBlock(pCurrentPage, Size, pBlock)) {
bResult = true;
break;
}
pCurrentPage = pCurrentPage->m_pNext;
}
return bResult;
}
inline size_t CVirtualMemory :: GetBlockSize(size_t Size) const {
size_t NewPageSize = m_PageSize;
while (NewPageSize - sizeof(VMPage) - sizeof(VMBlock) < Size)
NewPageSize += m_PageSize;
return NewPageSize;
}
inline void * CVirtualMemory :: Allocate(size_t Size) {
if (m_bEnabled != vsEnabled)
return malloc(Size);
VMBlock * pBlock = NULL;
if (! AllocateBlock(Size, & pBlock)) {
assert(false);
return NULL;
}
return pBlock->GetMemory();
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
202
]
]
]
|
6782f97bdec307e114f3dc2ee66df446604ae7b9 | 25426133cf6405c5cebf4b51c48ff3dce2629ea9 | /gui.cpp | dc3eac017fe5c5273796797a4158ebd341e9324a | []
| no_license | tolhc1234/openglengine | 456fd5a099b30544af1e338fab289402d2b81341 | 6ed525f9a74235605157e68728e36b8b5291b096 | refs/heads/master | 2021-01-10T02:38:58.457222 | 2010-01-12T20:28:21 | 2010-01-12T20:28:21 | 50,214,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,858 | cpp | #include <iostream>
#include <sstream>
#include <gl/gl.h>
#include <list>
#include "gui.h"
#include "../screen/resize.h"
#include "text/font.h"
#include "../mouse/mouseApps.h"
using namespace std;
gui::gui(float possitionX , float PossitionY, float width, float height, char* Text, theme* Options) : basicElem(possitionX,PossitionY,width,height)
{
text = Text;
applyMove = false;
autoSize = false;
options = Options;
focusedOne = this;
}
gui::gui(float possitionX, float PossitionY, float width, float height, char* Text) : basicElem(possitionX,PossitionY,width,height)
{
text = Text;
applyMove = false;
autoSize = false;
options = blueWindow;
focusedOne = this;
}
gui::gui(float possitionX , float PossitionY, char* Text, theme* Options) : basicElem(possitionX,PossitionY,0,0)
{
autoSize = true;
text = Text;
options = Options;
focusedOne = this;
}
gui::gui(float possitionX , float PossitionY, char* Text) : basicElem(possitionX,PossitionY,0,0)
{
autoSize = true;
text = Text;
options = blueWindow;
focusedOne = this;
}
gui::gui(char* Text, theme* Options) : basicElem(200,200,0,0)
{
autoSize = true;
text = Text;
options = Options;
focusedOne = this;
}
gui::gui(char* Text) : basicElem(200,200,0,0)
{
autoSize = 0;
text = Text;
options = blueWindow;
focusedOne = this;
}
gui::gui(theme* Options) : basicElem(200,200,0,0)
{
autoSize = true;
text = "\0";
options = Options;
focusedOne = this;
}
gui::gui() : basicElem(200,200,0,0)
{
autoSize = true;
text = "\0";
options = blueWindow;
focusedOne = this;
}
bool gui::newElem(basicElem * newElement)
{
if(focusedOne == this)
{// is dit de eerste van window?
focusedOne = newElement;
newElement->posY += 5;
scale(newElement->sizeX + 5,0);
elems.push_back(newElement);
return true;//zoja dan hoeft er niks worden berekent.
}
if(!elems.empty())
{//als list niet leeg is
//neem de laatste
std::list<basicElem>::iterator it = elems.end();
it--;
newElement->move(0,(*elems.end())->posY + (*elems.end())->sizeY + 5);
scale(0,(*elems.end())->posY - (*elems.end())->sizeY);
/*
if(tempY > posY + sizeY - 5 && autoSize)
scale(0,newElement->sizeY + 50);
if(newElement->sizeX+newElement->posX > posX + sizeX && autoSize)
scale(newElement->sizeY + 20,0);
*/
newElement->move(posX + 10, 0);
elems.push_back(newElement);
return true;
}
bool gui::mouseUnderBar()
{
if(Mouse.getX() >= posX &&
Mouse.getY() >= posY - 20 &&
Mouse.getX() <= posX + sizeX &&
Mouse.getY() <= posY)
return true;
else return false;
}
void gui::update()
{
if(focusedOne && !focusedOne->isUnderMousePressed())
focusedOne->focus = false;
if(isUnderMousePressed())
{
for(list<basicElem*>::iterator current = elems.begin();current != elems.end();current++)
{
if((*current)->isUnderMousePressed())
{
(*current)->focus = true;
focusedOne = (*current);
}
focusedOne->update();
}
//our update function
//lets make our window move-able
}
if(Mouse.pressedLMB() && applyMove)
{
mouseHelper.update();
posX += mouseHelper.getDiffX();
posY += mouseHelper.getDiffY();
/////////////////
for(list<basicElem*>::iterator current = elems.begin();current != elems.end();current++)
{
(*current)->move(mouseHelper.getDiffX(), mouseHelper.getDiffY());
}
////////////////////////
}
else
{
mouseHelper.reset();
checkMove();
}
}
void gui::checkMove()
{
if(mouseUnderBar())
{
if(Mouse.pressedLMB())
{
applyMove = true;
}
}
else applyMove = false;
}
void gui::render()
{
glDisable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0,getWindowWidth(),getWindowHeight(),0,0,1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glPushAttrib(GL_CURRENT_BIT);
glLoadIdentity();
if(options->useTextures){
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,options->window.windowText->ID);
}
else
glColor4fv(options->window.topColor);
glBegin(GL_QUADS);
glTexCoord2f(0,1); glVertex2f(posX,posY);
glTexCoord2f(1,1); glVertex2f(posX + sizeX, posY);
if(!options->useTextures) glColor4fv(options->window.bottomColor);
glTexCoord2f(1,0); glVertex2f(posX + sizeX, posY + sizeY);
glTexCoord2f(0,0); glVertex2f(posX, posY + sizeY);
glEnd();
if(options->useTextures)
glBindTexture(GL_TEXTURE_2D,options->bar.barText->ID);
else
glColor4fv(options->bar.topColor);
glBegin(GL_QUAD_STRIP);
glTexCoord2f(1,0); glVertex2f(posX,posY);
glTexCoord2f(0,0); glVertex2f(posX + sizeX, posY);
glTexCoord2f(0,25); glVertex2f(posX, posY - 5);
glTexCoord2f(0,25); glVertex2f(posX + sizeX, posY - 5);
if(!options->useTextures) glColor4fv(options->bar.bottomColor);
glTexCoord2f(1,1); glVertex2f(posX, posY - 20);
glTexCoord2f(0,1); glVertex2f(posX + sizeX, posY - 20);
glEnd();
glDisable(GL_TEXTURE_2D);
for(list<basicElem*>::iterator current = elems.begin();current != elems.end();current++)
{
//if((*current)->isUnderMouse())
// glColor3f(0,1,0);
(*current)->render();
}
glColor4f(1,0,0,1);
timesRoman.render(posX + 5,posY - 6,text);
if(enableDebug)
{
std::stringstream numberxyz;
glColor4f(0,8.8,0,0.7);
if(debug.printCoords)
{
numberxyz << (int)posX << ',' << (int)posY << '\0';
timesRoman.render( posX,posY,const_cast<char*>(numberxyz.str().c_str()));
}
if(debug.printx)
{
numberxyz.str("");
numberxyz << sizeX << '\0';
timesRoman.render(posX+sizeX/2,posY,const_cast<char*>(numberxyz.str().c_str()));
}
if(debug.printy)
{
numberxyz.str("");
numberxyz << sizeY << '\0';
timesRoman.render(posX,posY+sizeY/2,const_cast<char*>(numberxyz.str().c_str()));
numberxyz.str("");
}
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPopMatrix();
glPopAttrib();
glDisable(GL_LIGHTING);
return;
}
void gui::handleKey(char key)
{
if(focusedOne != this && focusedOne)
focusedOne->handleKey(key);
}
void gui::handleMouse(int x, int y, int status)
{
if(focusedOne != this && focusedOne)
focusedOne->handleMouse(x,y, status);
}
/*/////////////////////////////////////////////////////////////////
/*GUILIST!
/*
/*////////////////////////////////////////////////////////////////
void guiList::add(gui* theGUI)
{
guilist.push_back(theGUI);
theGUI->focus = true;
if(guilist.size() > 1)
(*(guilist.end()-2))->focus = false;
}
void guiList::dissable(gui* theGUI)
{
return;
}
void guiList::enable(gui* theGUI)
{
return;
}
void guiList::remove(gui* theGUI)
{
vector<gui*>::iterator it = guilist.begin();
for(it;it != guilist.end();it++)
{
if(*it == theGUI)
guilist.erase(it);
}
}
void guiList::renderAll()
{
vector<gui*>::iterator it = guilist.begin();
for(it;it != guilist.end();it++)
{
(*it)->render();
}
}
void guiList::updateAll()
{
vector<gui*>::iterator it = guilist.begin();
for(it;it != guilist.end();it++)
{
if((*it)->focus)
{
(*it)->update();
}
if((*it)->focus == false && (*it)->isUnderMousePressed())
{
(*it)->focus = true;
(*(guilist.end()-1))->focus = false;
gui* it2 = *it;
guilist.erase(it);
guilist.push_back(it2);
// std::swap(*it,*(guilist.end()-1));
break;
}
}
}
void guiList::handleKey(char key)
{
(*(guilist.end()-1))->handleKey(key);
}
void guiList::handleMouse(int x, int y, int status)
{
(*(guilist.end()-1))->handleMouse(x,y, status);
}
guiList GUIList; | [
"[email protected]"
]
| [
[
[
1,
365
]
]
]
|
464b867db739bd5627611227250370961c77a377 | ce10be13a62b6ed6e3ccdd0780fe98e08573166e | /source/save.cpp | 1996bdcb6c0b4c754be2faedd103061c93d19a19 | []
| no_license | pfeyssaguet/afrods | b2d63fd501a60a5c40d2d128bc03820f389c4d59 | df2e85990bac4a2107bba5ad7ba9232753cf7725 | refs/heads/master | 2016-09-06T02:13:26.546098 | 2010-02-07T13:07:01 | 2010-02-07T13:07:01 | 32,130,697 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,724 | cpp | #include "save.h"
#include "itemfactory.h"
#include "itemweapon.h"
#include "itemarmor.h"
#include "constants.h"
#include <fat.h>
using namespace AfroDS;
Save * Save::m_Instance = NULL;
/**
* Constructeur par défaut
*/
Save::Save() {
/*
// Initialisation du filesystem (c'est pas gagné)
PA_OutputText(ECRAN_HAUT, 1, 5, "Init. FAT...");
if (!fatInitDefault()) {
// FAT ne fonctionne pas, on est mal...
PA_OutputText(ECRAN_HAUT, 27, 5, "[KO]");
PA_OutputText(ECRAN_HAUT, 4, 21, "FAT system is down");
} else {
// FAT fonctionne
PA_OutputText(ECRAN_HAUT, 27, 5, "[OK]");
}
// Chargement des persos depuis la sauvegarde
PA_OutputText(ECRAN_HAUT, 1, 6, "Init. personnages...");
*/
loadCreatures();
}
Save * Save::getInstance() {
if (m_Instance == NULL) {
// Initialisation de la sauvegarde
m_Instance = new Save();
}
return m_Instance;
}
/**
* Renvoie le nombre de personnages de la sauvegarde
* @return int nombre de personnages
*/
int Save::getNbCreatures() {
return m_characters.size();
}
/**
* Crée un nouveau personnage
* @param Creature newchar personnage à créer
*/
void Save::addCreature(CreaturePlayer * newchar) {
m_characters.push_back(newchar);
}
/**
* Récupère le personnage n° N
* @param int iNumPerso numéro du personnage
* @return Creature personnage
*/
CreaturePlayer * Save::getCreature(int iNumPerso) {
return m_characters.at(iNumPerso);
}
/**
* Crée un perso de test pour utiliser directement en jeu
*/
CreaturePlayer * Save::getDemoCreature() {
CreaturePlayer * deuspi = new CreaturePlayer("deuspi");
deuspi->addItemToInventory(new Item("Heal Potion", TYPE_POTION_HEAL, 20, 30));
deuspi->addItemToInventory(new Item("Poil de uque", TYPE_OTHER, 0, 1));
deuspi->addItemToInventory(new ItemWeapon("Shortbow", TYPE_RANGEDWEAPON, Coords(1, 6)));
deuspi->addItemToInventory(ItemFactory::generateLoot(LOOT_ARTIFACT_SWORD_OF_BOULBI));
deuspi->addItemToInventory(new ItemArmor("Leather armor", TYPE_ARMOR, 2));
//deuspi->addItemToInventory(new ItemWeapon("Dagger", TYPE_WEAPON_DAGGER, Stats(1, 0, 2, 0, 0, 0), Coords(1, 4)));
//deuspi->addItemToInventory(new ItemWeapon("Greatsword", TYPE_LARGEWEAPON, Coords(2, 6)));
//deuspi->addItemToInventory(new ItemWeapon("Handaxe", TYPE_WEAPON_AXE, Coords(1, 6)));
//deuspi->addItemToInventory(new ItemWeapon("Warhammer", TYPE_WEAPON_HAMMER, Coords(1, 8)));
//deuspi->addItemToInventory(new ItemArmor("Cloak", TYPE_CLOAK));
//deuspi->addItemToInventory(new ItemArmor("Helmet", TYPE_HELMET));
//deuspi->addItemToInventory(new ItemArmor("Shield", TYPE_SHIELD));
deuspi->addItemToInventory(new Item("Mana Potion", TYPE_POTION_MANA, 15));
// équipement
//character.addItemToEquipment(SLOT_RIGHT_WEAPON, new Item("Hache", TYPE_RIGHT_WEAPON, Stats()));
deuspi->addItemToEquipment(SLOT_HELMET, new ItemArmor("Helmet", TYPE_HELMET, 2));
deuspi->addItemToEquipment(SLOT_CLOAK, new ItemArmor("Cloak", TYPE_CLOAK, 1));
deuspi->addItemToEquipment(SLOT_ARMOR, new ItemArmor("Bronze armor", TYPE_ARMOR, 6, Stats(4, 4, 4, 0, 0, 0)));
deuspi->addItemToEquipment(SLOT_RIGHT_WEAPON, new ItemWeapon("Dwarven axe", TYPE_WEAPON_AXE, Coords(1, 10)));
deuspi->addItemToEquipment(SLOT_LEFT_WEAPON, new ItemWeapon("Bastard sword", TYPE_WEAPON_SWORD, Coords(1, 10)));
deuspi->addItemToEquipment(SLOT_BOOTS, new ItemArmor("Boots", TYPE_BOOTS, 2));
deuspi->addItemToEquipment(SLOT_GLOVES, new ItemArmor("Gloves", TYPE_GLOVES));
deuspi->addItemToEquipment(SLOT_RIGHT_RING, new Item("Ring", TYPE_RING));
deuspi->addItemToEquipment(SLOT_LEFT_RING, new Item("The One Ring", TYPE_RING, LARGEICON_RING_GOLD));
deuspi->addItemToEquipment(SLOT_BELT, new Item("Belt", TYPE_BELT));
deuspi->addItemToEquipment(SLOT_NECKLACE, new Item("Necklace", TYPE_NECKLACE));
deuspi->addMoney(564941);
return deuspi;
}
/**
* Charge les personnages depuis la sauvegarde
*/
void Save::loadCreatures() {
/*
FILE* file = fopen(AFRODS_SAVE_FILENAME, "r");
if (file) {
//on cherche la taille du fichier, cela sert apres pour le buffer
u32 size;
fseek(file, 0, SEEK_END);
size = ftell(file);
rewind(file);//on retourne au debut du fichier
// on alloue suffisamment de mémoire et on stocke l'adresse dans buffer
char * buffer;
buffer = (char*) malloc(sizeof(char) * size);
fread(buffer, 1, size, file);
// PA_OutputText(ECRAN_HAUT, 4, 8, "content: [%s]", buffer);
// PA_OutputText(ECRAN_HAUT, 4, 9, "size: %d bytes", size);
free(buffer);
fclose(file);//on ferme le fichier
} else {
// on crée un nouveau fichier
file = fopen(AFRODS_SAVE_FILENAME, "wb");
fclose(file);//on ferme le fichier
}
*/
// pour l'instant j'ajoute quelques persos bidons pour test
createDemoCreatures();
}
/**
* Sauvegarde les personnages
*/
void Save::saveCreatures() {
/*
Creature charac;
for(std::vector<Creature>::iterator it = m_characters.begin(); it != m_characters.end(); ++it)
charac = (Creature)it;
std::string sPath = "/" + charac.getName() + ".dat";
if (m_UseEFS)
sPath = "efs:" + sPath;
FILE * file = fopen(sPath, "wb");
fwrite((void *)charac, 1, sizeof(charac), file);
fclose(file);
}
*/
}
/**
* Crée une liste de persos de test pour utiliser dans le menu
*/
void Save::createDemoCreatures() {
addCreature(getDemoCreature());
addCreature(new CreaturePlayer("Warrior", JOB_WARRIOR));
addCreature(new CreaturePlayer("Wizard", JOB_WIZARD));
addCreature(new CreaturePlayer("Ranger", JOB_RANGER));
addCreature(new CreaturePlayer("Priest", JOB_PRIEST));
addCreature(new CreaturePlayer("Monk", JOB_MONK));
}
| [
"deuspi@fce96c3e-db3a-11de-b64b-7d26b27941e2"
]
| [
[
[
1,
170
]
]
]
|
e826bd60c0e4ac6c4f8675faa3d52a87bac0b56d | 4b61c42390888ca65455051932ddc9f6996b0db4 | /Vector3.h | 938a012164537c8f86ba4c75f793102a4d357c3a | []
| no_license | miyabiarts/math | 916558fb152c67286931494a62909a5bcdf1be0b | eceefff9604f58559eb000876172c4fc3e3ced7c | refs/heads/master | 2016-09-06T16:21:14.864762 | 2011-04-18T13:48:04 | 2011-04-18T13:48:04 | 1,630,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,725 | h | #pragma once
#include <cmath>
template< typename T > struct Matrix4;
//! 3D vector
template< typename T >
struct Vector3
{
Vector3< T >();
Vector3< T >( const Vector3 & );
Vector3< T >( T x ,T y, T z );
virtual ~Vector3< T >(){}
template < typename T2 >
operator Vector3< T2 > () const { return Vector3< T2 >( static_cast< T2 >( x ), static_cast< T2 >( y ), static_cast< T2 >( z ) ); }
Vector3< T > operator + () const;
Vector3< T > operator - () const;
Vector3< T > operator + ( const Vector3< T > &v ) const;
Vector3< T > operator - ( const Vector3< T > &v ) const;
Vector3< T > operator * ( T s ) const;
Vector3< T > operator / ( T s ) const;
Vector3< T > &operator += ( const Vector3 & );
Vector3< T > &operator -= ( const Vector3 & );
Vector3< T > &operator *= ( T );
Vector3< T > &operator /= ( T );
bool operator == ( const Vector3< T >& ) const;
bool operator != ( const Vector3< T >& ) const;
// static function
/*!
@brief normalize vector
*/
static Vector3< T > &normalize(Vector3< T > &v, const Vector3< T > &v0);
/*!
@brief calculate length
*/
static T length(const Vector3< T > &v);
/*!
@brief calculate norm
*/
static T norm(const Vector3< T > &v);
/*!
@brief calculate distance between vectors
*/
static T distance(const Vector3< T > &v1, const Vector3< T > &v2);
/*!
@brief calculate inner product
*/
static T dot(const Vector3 &v1, const Vector3< T > &v2);
/*!
@brief calculate outer product
*/
static Vector3< T > &cross(Vector3< T > &v, const Vector3< T > &v1, const Vector3< T > &v2);
/*!
@brief transformation (homogeneous)
*/
static Vector3< T > &transform( Vector3< T > &v, const Vector3< T > &v0, const Matrix4< T > &m );
/*!
@brief transformation
*/
static Vector3< T > &transformNormal( Vector3< T > &v, const Vector3< T > &v0, const Matrix4< T > &m );
/*!
@brief calculate intersection between ray and triangle
*/
static bool intersectTri( const Vector3< T > &v0, const Vector3< T > &v1, const Vector3< T > &v2, const Vector3< T > &org, const Vector3< T > &dir, T *u = 0, T *v = 0, T *dist = 0 );
union
{
struct
{
T x, y, z;
};
T v[ 3 ];
};
};
template< typename T >
inline Vector3< T >::Vector3()
{
x = y = z = 0;
}
template< typename T >
inline Vector3< T >::Vector3( T x, T y, T z )
{
this->x = x;
this->y = y;
this->z = z;
}
template< typename T >
inline Vector3< T >::Vector3( const Vector3 &v )
{
x = v.x;
y = v.y;
z = v.z;
}
template< typename T >
inline Vector3< T > Vector3< T >::operator +() const
{
return Vector3< T >( x, y, z );
}
template< typename T >
inline Vector3< T > Vector3< T >::operator -() const
{
return Vector3< T >( -x, -y, -z );
}
template< typename T >
inline Vector3< T > Vector3< T >::operator +( const Vector3< T > &v ) const
{
return Vector3< T >( x + v.x, y + v.y,z+ v. z);
}
template< typename T >
inline Vector3< T > Vector3< T >::operator -( const Vector3< T > &v ) const
{
return Vector3< T >( x- v.x, y - v.y, z - v.z );
}
template< typename T >
inline Vector3< T > Vector3< T >::operator * (T s ) const
{
return Vector3< T >( x * s, y * s, z * s );
}
template< typename T >
inline Vector3< T > Vector3< T >::operator /( T s ) const
{
return Vector3< T >( x / s, y / s, z / s );
}
template< typename T >
inline Vector3< T > &Vector3< T >::operator +=( const Vector3< T > &v )
{
x += v.x;
y += v.y;
z += v.z;
return *this;
}
template< typename T >
inline Vector3< T > &Vector3< T >::operator -=( const Vector3< T > &v )
{
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
template< typename T >
inline Vector3< T > &Vector3< T >::operator *=( T s )
{
x *= s;
y *= s;
z *= s;
return *this;
}
template< typename T >
inline Vector3< T > &Vector3< T >::operator /=( T s )
{
x /= s;
y /= s;
z /= s;
return *this;
}
template< typename T >
inline bool Vector3< T >::operator ==( const Vector3< T > &v ) const
{
return (x==v.x && y==v.y && z==v.z);
}
template< typename T >
inline bool Vector3< T >::operator !=( const Vector3< T > &v ) const
{
return !operator==( v );
}
template< typename T >
inline T Vector3< T >::dot( const Vector3< T > &v1, const Vector3< T > &v2 )
{
return ( v1.x * v2.x + v1.y * v2.y + v1.z * v2.z );
}
template< typename T >
inline Vector3< T > &Vector3< T >::cross( Vector3< T > &v, const Vector3< T > &v1, const Vector3< T > &v2 )
{
v = Vector3< T >(v1.y*v2.z - v1.z*v2.y ,v1.z*v2.x - v1.x*v2.z ,v1.x*v2.y - v1.y*v2.x);
return v;
}
//!
template< typename T, typename T2 >
inline Vector3< T > operator * ( T2 s, const Vector3< T > &v )
{
return Vector3< T >(v.x*s,v.y*s,v.z*s);
}
//
template< typename T >
inline Vector3< T > &Vector3< T >::normalize( Vector3< T > &v, const Vector3 &v0 )
{
T l = length(v0);
if(l == 0)
{
v = Vector3();
return v;
}
v = v0 / l;
return v;
}
//
template< typename T >
inline T Vector3< T >::length( const Vector3 &v )
{
return sqrt( v.x * v.x + v.y * v.y + v.z * v.z );
}
//
template< typename T >
inline T Vector3< T >::norm( const Vector3 &v )
{
return ( v.x * v.x + v.y * v.y + v.z * v.z );
}
//
template< typename T >
inline T Vector3< T >::distance( const Vector3 &v1, const Vector3 &v2 )
{
Vector3< T > v = v1 - v2;
return length( v );
}
//
template< typename T >
bool Vector3< T >::intersectTri( const Vector3< T > &v0, const Vector3< T > &v1, const Vector3< T > &v2, const Vector3< T > &org, const Vector3< T > &dir, T *u, T *v, T *dist )
{
// 面の法線を求める
Vector3< T > t1 = v1 - v0;
Vector3< T > t2 = v2 - v0;
Vector3< T > N;
Vector3< T >::cross( N, t1, t2 );
Vector3::normalize( N, N );
Vector3< T > va = org - v0;
T t = -Vector3< T >::dot(va,N) / Vector3< T >::dot( dir,N );
Vector3< T > p = org + t * dir;
Vector3< T > vp0 = v0 - p;
Vector3< T > vp1 = v1 - p;
Vector3< T > vp2 = v2 - p;
Vector3< T > d1 = v1 - v0;
Vector3< T > c;
Vector3< T >::cross( c, vp0, d1 );
double c0 = Vector3< T >::dot( c, N );
d1 = v2 - v1;
Vector3< T >::cross( c, vp1, d1 );
double c1 = Vector3< T >::dot( c, N );
d1 = v0 - v2;
Vector3< T >::cross( c, vp2, d1 );
double c2 = Vector3< T >::dot( c, N );
if( c0 >= 0.0 && c1 >= 0.0 && c2 >= 0.0 )
{
if( dist )
{
*dist = t;
}
if(u && v)
{
T l1 = Vector3< T >::norm( t1 );
T l2 = Vector3< T >::norm( t2 );
T c12 = Vector3< T >::dot( t1, t2 );
T S = static_cast< T >( sqrt( static_cast< double >( l1 * l2 - c12 * c12 ) ) ) / 2;
T l2p = Vector3< T >::norm( vp2 );
T c2p = Vector3< T >::dot( vp2 , t2 );
T Su = static_cast< T >( sqrt( static_cast< double >( l2 * l2p - c2p * c2p ) ) ) / 2;
T l1p = Vector3< T >::norm( vp1 );
T c1p = Vector3< T >::dot( vp1, t1 );
T Sv = static_cast< T >( sqrt( static_cast< double >( l1 * l1p - c1p * c1p ) ) ) / 2;
*u = Su / S;
*v = Sv / S;
}
return true;
}
return false;
}
#include "Matrix4.h"
template< typename T >
Vector3< T > &Vector3< T >::transform( Vector3< T > &v, const Vector3< T > &v0, const Matrix4< T > &m )
{
Vector3< T > t;
t.x = v0.x * m._11 + v0.y * m._21 + v0.z * m._31 + m._41;
t.y = v0.x * m._12 + v0.y * m._22 + v0.z * m._32 + m._42;
t.z = v0.x * m._13 + v0.y * m._23 + v0.z * m._33 + m._43;
T w = v0.x * m._14 + v0.y * m._24 + v0.z * m._34 + m._44;
if( w == 0 )
{
return v;
}
t.x /= w;
t.y /= w;
t.z /= w;
v = t;
return v;
}
template< typename T >
Vector3< T > &Vector3< T >::transformNormal( Vector3< T > &v, const Vector3< T > &v0, const Matrix4< T > &m )
{
Vector3< T > t;
t.x = v0.x * m._11 + v0.y * m._21 + v0.z * m._31;
t.y = v0.x * m._12 + v0.y * m._22 + v0.z * m._32;
t.z = v0.x * m._13 + v0.y * m._23 + v0.z * m._33;
T w = v0.x * m._14 + v0.y * m._24 + v0.z * m._34;
if( w == 0 )
{
return v;
}
t.x /= w;
t.y /= w;
t.z /= w;
v = t;
return v;
}
/*!
出力
*/
template< typename T >
std::ostream &operator<<( std::ostream &os, const Vector3< T > &v )
{
os << v.x << ", " << v.y << ", " << v.z;
return os;
}
typedef Vector3< unsigned char > Vector3UC;
typedef Vector3< int > Vector3I;
typedef Vector3<float> Vector3F;
typedef Vector3<double> Vector3D;
| [
"[email protected]"
]
| [
[
[
1,
379
]
]
]
|
54509dca2b48e56523ac9dcc5f17c4e13160c55e | ef8e875dbd9e81d84edb53b502b495e25163725c | /classifier/classifier.h | 49b8f4c1541f46c704b7ea6cec415353f11e637b | []
| no_license | panone/litewiz | 22b9d549097727754c9a1e6286c50c5ad8e94f2d | e80ed9f9d845b08c55b687117acb1ed9b6e9a444 | refs/heads/master | 2021-01-10T19:54:31.146153 | 2010-10-01T13:29:38 | 2010-10-01T13:29:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,406 | h | /*******************************************************************************
*******************************************************************************/
#ifndef CLASSIFIER_H
#define CLASSIFIER_H
/******************************************************************************/
#include <QList>
#include <QString>
/******************************************************************************/
class ClassifierImplementation;
class QStringList;
/*******************************************************************************
*******************************************************************************/
class ClusterInfo
{
public:
QString name;
QString stem;
QList< int > files;
};
/*******************************************************************************
*******************************************************************************/
class ItemInfo : public ClusterInfo
{
};
/*******************************************************************************
*******************************************************************************/
class VariantInfo : public ClusterInfo
{
public:
bool reference;
};
/*******************************************************************************
*******************************************************************************/
class ClassificationInfo
{
public:
QList< ItemInfo > items;
QList< VariantInfo > variants;
};
/*******************************************************************************
*******************************************************************************/
class Classifier
{
public:
Classifier
(
void
);
~Classifier
(
void
);
public:
void classify
(
QStringList const & fileNames
);
QList< int > getPossibleVariance
(
void
);
int getDefaultVariance
(
void
);
ClassificationInfo getClassification
(
int variance
);
private:
ClassifierImplementation * implementation;
};
/******************************************************************************/
#endif /* CLASSIFIER_H */
| [
"[email protected]"
]
| [
[
[
1,
98
]
]
]
|
cf73c07a2a4c6e0e6069a16316fbe6444bb7ea5b | de2f72b217bc8a9b1f780090bedf425a2ad9587a | /Pangea/Physics/include/world/ParticleWorld.h | ce190d644040971aa56060b76e078028c850c588 | []
| no_license | axelwass/oliveira | 65b32a7f16cb7e00a95cdf3051a731a2004aaf5f | 4c34730a720465311e367f8e25cc1cced46801c7 | refs/heads/master | 2021-01-18T14:18:42.622080 | 2011-04-18T18:39:08 | 2011-04-18T18:39:08 | 32,120,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | h | /*
* ParticleWorld.h
*
* Created on: 25/09/2010
* Author: Mariano
*/
#include "../../../Generic/Generic.h"
#include "../particle/Particle.h"
#include "../particle/ParticleGroup.h"
#include "../particle/ParticleInteraction.h"
#include "../force/InterParticleForce.h"
#include "../force/SpringForce.h"
#include "../octree/Octree.h"
#include <list>
#include <vector>
using namespace std;
class Emitter;
#ifndef PARTICLEWORLD_H_
#define PARTICLEWORLD_H_
// Useful for all particle related
typedef tr1::shared_ptr<Octree<ParticleGroup> > OctreePtr;
class ParticleWorld {
protected:
list<Emitter *> emitters;
list<ParticleGroupPtr> groups;
OctreePtr groupsOctree;
real precision;
real time;
Particle worldParticle;
int particlesPerThread;
void resolveGroupCollisions();
public:
ParticleWorld(real precision = 0.5);
void addParticleGroup(ParticleGroupPtr group);
void removeParticleGroup(ParticleGroupPtr group);
void particleEmission();
void addField(Force * field);
void addEmitter(Emitter * emitter);
void runPhysics();
void updateForces();
real getTime();
void integrate();
// PARA TESTEAR NOMAS
void render();
};
#endif /* PARTICLEWORLD_H_ */
| [
"merchante.mariano@d457d4b0-f835-b411-19da-99c4f284aa10"
]
| [
[
[
1,
70
]
]
]
|
7e901536f470936857a56b5552fa050d88a4bcc3 | 60365cfb5278ec1dfcc07a5b3e07f3c9d680fa2a | /xlview/CachedImage.h | fcec2ff0b6a287f0b0545b6e9e3ab87d62376b86 | []
| no_license | cyberscorpio/xlview | 6c01e96dbf225cfbc2be1cc15a8b70c61976eb46 | a4b5088ce049695de2ed7ed191162e6034326381 | refs/heads/master | 2021-01-01T16:34:47.787022 | 2011-04-28T13:34:25 | 2011-04-28T13:34:25 | 38,444,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,046 | h | #ifndef XL_VIEW_CACHED_IMAGE_H
#define XL_VIEW_CACHED_IMAGE_H
#include <memory>
#include "libxl/include/lockable.h"
#include "libxl/include/interfaces.h"
#include "Image.h"
#include "ImageLoader.h"
class CCachedImage;
typedef std::tr1::shared_ptr<CCachedImage> CCachedImagePtr;
class CCachedImage
: public xl::CUserLock
{
xl::tstring m_fileName;
CSize m_szImage;
CImagePtr m_suitableImage;
CImagePtr m_thumbnailImage;
public:
CCachedImage (const xl::tstring &fileName);
virtual ~CCachedImage ();
bool loadSuitable (CSize szView, xl::ILongTimeRunCallback *pCallback = NULL);
bool loadThumbnail (bool fastOnly, xl::ILongTimeRunCallback *pCallback = NULL);
void setSuitableImage (CImagePtr image, CSize realSize);
void clear (bool clearThumbnail = false);
xl::tstring getFileName () const;
CSize getImageSize () const;
CImagePtr getCachedImage () const;
CImagePtr getSuitableImage () const;
CImagePtr getThumbnailImage () const;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
faaadb9d0c1b4a84f27c96fd8d1d8926e1ffbefb | 388d7d901492224b76919af3be6d1210362444e1 | /tio/VectorStorage.h | 8a9c9b50099fd9615811f91fb0f841d6d0a26fb5 | []
| no_license | ederfreire/tio | 159e958a9e98dd4686b9363b1dd459f3b27215c9 | 9040d8c7241ea713f3f6a60983ac3de50282f21c | refs/heads/master | 2020-04-10T09:25:42.301209 | 2011-03-22T21:34:18 | 2011-03-22T21:34:18 | 1,518,698 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,479 | h | /*
Tio: The Information Overlord
Copyright 2010 Rodrigo Strauss (http://www.1bit.com.br)
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.
*/
#pragma once
namespace tio {
namespace MemoryStorage
{
class VectorStorage :
boost::noncopyable,
public boost::enable_shared_from_this<VectorStorage>,
public ITioStorage
{
private:
vector<ValueAndMetadata> data_;
string name_, type_;
EventDispatcher dispatcher_;
inline ValueAndMetadata& GetInternalRecord(const TioData& key)
{
return data_.at(GetRecordNumber(key));
}
inline ValueAndMetadata& GetInternalRecord(const TioData* key)
{
return GetInternalRecord(*key);
}
inline size_t GetRecordNumber(int index)
{
//
// python like index (-1 for last, -2 for before last, so on)
//
if(index < 0)
{
if(-index > (int)data_.size())
throw std::invalid_argument("invalid subscript");
index = data_.size() + index;
}
return static_cast<size_t>(index);
}
inline size_t GetRecordNumber(const TioData& td)
{
return GetRecordNumber(td.AsInt());
}
inline size_t GetRecordNumber(const TioData* td)
{
return GetRecordNumber(*td);
}
public:
VectorStorage(const string& name, const string& type) :
name_(name),
type_(type)
{}
~VectorStorage()
{
return;
}
virtual string GetName()
{
return name_;
}
virtual string GetType()
{
return type_;
}
virtual string Command(const string& command)
{
throw std::invalid_argument("command not supported");
}
virtual size_t GetRecordCount()
{
return data_.size();
}
virtual void PushBack(const TioData& key, const TioData& value, const TioData& metadata)
{
CheckValue(value);
data_.push_back(ValueAndMetadata(value, metadata));
dispatcher_.RaiseEvent("push_back", static_cast<int>(data_.size() - 1), value, metadata);
}
virtual void PushFront(const TioData& key, const TioData& value, const TioData& metadata)
{
CheckValue(value);
data_.insert(data_.begin(), ValueAndMetadata(value, metadata));
dispatcher_.RaiseEvent("push_front", key, value, metadata);
}
private:
void _Pop(vector<ValueAndMetadata>::iterator i, TioData* value, TioData* metadata)
{
ValueAndMetadata& data = *i;
if(value)
*value = data.value;
if(metadata)
*metadata = data.metadata;
data_.erase(i);
}
public:
virtual void PopBack(TioData* key, TioData* value, TioData* metadata)
{
if(data_.empty())
throw std::invalid_argument("empty");
_Pop(data_.end() - 1, value, metadata);
dispatcher_.RaiseEvent("pop_back",
key ? *key : TIONULL,
value ? *value : TIONULL,
metadata ? *metadata : TIONULL);
}
virtual void PopFront(TioData* key, TioData* value, TioData* metadata)
{
if(data_.empty())
throw std::invalid_argument("empty");
_Pop(data_.begin(), value, metadata);
dispatcher_.RaiseEvent("pop_front",
key ? *key : TIONULL,
value ? *value : TIONULL,
metadata ? *metadata : TIONULL);
}
void CheckValue(const TioData& value)
{
if(value.Empty())
throw std::invalid_argument("value??");
}
virtual void Set(const TioData& key, const TioData& value, const TioData& metadata)
{
CheckValue(value);
ValueAndMetadata& data = GetInternalRecord(key);
data = ValueAndMetadata(value, metadata);
dispatcher_.RaiseEvent("set", key, value, metadata);
}
virtual void Insert(const TioData& key, const TioData& value, const TioData& metadata)
{
CheckValue(value);
size_t recordNumber = GetRecordNumber(key);
// check out of bounds
GetRecord(key, NULL, NULL, NULL);
data_.insert(data_.begin() + recordNumber, ValueAndMetadata(value, metadata));
dispatcher_.RaiseEvent("insert", key, value, metadata);
}
virtual void Delete(const TioData& key, const TioData& value, const TioData& metadata)
{
size_t recordNumber = GetRecordNumber(key);
// check out of bounds
GetRecord(key, NULL, NULL, NULL);
data_.erase(data_.begin() + recordNumber);
dispatcher_.RaiseEvent("delete", key, value, metadata);
}
virtual void Clear()
{
data_.clear();
dispatcher_.RaiseEvent("clear", TIONULL, TIONULL, TIONULL);
}
virtual shared_ptr<ITioResultSet> Query(int startOffset, int endOffset, const TioData& query)
{
if(!query.IsNull())
throw std::runtime_error("this container doesn't support query strings");
NormalizeQueryLimits(&startOffset, &endOffset, GetRecordCount());
return shared_ptr<ITioResultSet>(
new GenericResultSet<ITioStorage>(query, shared_from_this(), startOffset, endOffset));
}
virtual void GetRecord(const TioData& searchKey, TioData* key, TioData* value, TioData* metadata)
{
const ValueAndMetadata& data = GetInternalRecord(searchKey);
if(key)
*key = searchKey;
if(value)
*value = data.value;
if(metadata)
*metadata = data.metadata;
}
virtual unsigned int Subscribe(EventSink sink, const string& start)
{
unsigned int cookie = 0;
size_t startIndex = 0;
if(!start.empty())
{
try
{
startIndex = GetRecordNumber(lexical_cast<int>(start));
//
// if client asks to start at index 0, it's never
// an error, even if the vector is empty. So, we'll
// not test out of bounds if zero
//
if(startIndex != 0)
data_.at(startIndex);
}
catch(std::exception&)
{
throw std::invalid_argument("invalid start index");
}
}
cookie = dispatcher_.Subscribe(sink);
if(start.empty())
return cookie;
//
// key is the start index to send
//
for(size_t x = startIndex ; x < data_.size() ; x++)
{
const ValueAndMetadata& data = data_[x];
sink("push_back", (int)x, data.value, data.metadata);
}
return cookie;
}
virtual void Unsubscribe(unsigned int cookie)
{
dispatcher_.Unsubscribe(cookie);
}
};
}}
| [
"[email protected]"
]
| [
[
[
1,
282
]
]
]
|
f51054c6c5b2a52de947692bffe197e13dba45a3 | 1caba14ec096b36815b587f719dda8c963d60134 | /tags/start/smx/libsmx/tabpre.h | 7abf3f888dae7f8c7623e770c5e72777d12d11c3 | []
| no_license | BackupTheBerlios/smx-svn | 0502dff1e494cffeb1c4a79ae8eaa5db647e5056 | 7955bd611e88b76851987338b12e47a97a327eaf | refs/heads/master | 2021-01-10T19:54:39.450497 | 2009-03-01T12:24:56 | 2009-03-01T12:24:56 | 40,749,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | h | #ifndef _TABPRE_H_
#define _TABPRE_H_
class CTabPre : public CTabFmt
{
int m_pRgb;
public:
CTabPre(OUTSTREAM *pStream) {Init(pStream); m_pRgb = 0;}
void ColV(ColFmt &col, const char **data, double value, int rgb, char **bufp);
void ColN(ColFmt &col, int rgb, char **bufp);
void RowB(char **bufp);
void RowE(char **bufp);
};
#endif //#ifndef _TABPRE_H_
| [
"(no author)@407f561b-fe63-0410-8234-8332a1beff53"
]
| [
[
[
1,
17
]
]
]
|
1ebb20ecf1e055242fbbfcdd75a745e7cc6d2c24 | 339ca2c8c3407ee4254c2f93632f823861afe51c | /tinytetris/main.cpp | 4284003a105f55fe453c489c7a1e77556eff1f13 | []
| no_license | nangaidesuka/consoletetris | 95370167877931bf450b2bda419ff15657edfc07 | 9f7a2f5497567a9a7a9a86bf41abf6e7e6a49664 | refs/heads/master | 2021-01-10T07:00:42.793940 | 2008-06-21T13:14:36 | 2008-06-21T13:14:36 | 55,165,355 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,975 | cpp | #include <time.h>
#include "console.h"
#include "fpsctl.h"
#include "tinytetris.h"
void main()
{try{
using namespace console;
using namespace tetris;
SetConsoleTitleW(L"Tiny Tetris by Jin Sun");
srand((UINT)time(0));
fpsctl thefpsctl;
draw con(size(COL, ROW));
input in;
block blk;
panel pnl;
int score;
blk.reborn();
pnl.clear();
score = 0;
/* 游戏开始 */
con.clear();
con.drawtext(L"==================", position(0, 0), white_i);
con.drawtext(L"=超迷你俄罗斯方块=", position(0, 1), white_i);
con.drawtext(L"==================", position(0, 2), white_i);
con.drawtext(L" 左: A", position(2, 4), green);
con.drawtext(L" 右: D", position(2, 5), green);
con.drawtext(L" 下: S", position(2, 6), green);
con.drawtext(L"变形: W", position(2, 7), green);
con.drawtext(L"慢下: U", position(2, 8), green);
con.drawtext(L"开始: 回车", position(2, 10), green_i);
con.flip();
while (1) {
Sleep(100);
in.update();
if (in.keydown(VK_RETURN))
break;
}
/* 游戏主循环 */
while (1) {
con.clear();
in.update();
bool gameover = false;
bool leavegame = false;
const int frametoupinput = 2;
if (in.keydown('A')) {
static int i = 0;
if (i++ == frametoupinput) {
if (pnl.canmove(&blk, moveleft))
blk.move(moveleft);
i = 0;
}
}
if (in.keydown('D')) {
static int i = 0;
if (i++ == frametoupinput) {
if (pnl.canmove(&blk, moveright))
blk.move(moveright);
i = 0;
}
}
if (in.keyclick('W')) {
if (pnl.cantransform(&blk))
blk.transform();
}
bool domovedown = false;
static int downtimer = 30;
if (--downtimer == 0) {
domovedown = true;
downtimer = 30;
}
if (in.keydown('U')) {
static int i = 0;
if (i++ == frametoupinput) {
domovedown = true;
i = 0;
}
}
if (domovedown) {
if (pnl.canmove(&blk, movedown))
blk.move(movedown);
else {
score += pnl.land(&blk);
blk.reborn();
if (pnl.collision(&blk))
gameover = true;
}
}
if (in.keyclick('S')) {
score += pnl.fallatonce(&blk);
blk.reborn();
if (pnl.collision(&blk))
gameover = true;
}
/* 处理游戏失败 */
if (gameover) {
con.clear();
con.drawtext(L"失败! 继续(Y/N)?", draw::homepos(), red_i);
con.flip();
while (1) {
Sleep(100);
in.update();
if (in.keydown('Y'))
break;
if (in.keydown('N')) {
leavegame = true;
break;
}
}
con.clear();
blk.reborn();
pnl.clear();
}
/* 离开游戏 */
if (leavegame)
break;
/* 绘图 */
wchar_t buf[100];
wsprintf(buf, L"得分: %d", score);
con.drawtext(buf, draw::homepos(), green_i);
pnl.draw(&con);
blk.draw(&con);
con.flip();
thefpsctl.wait();
}
}catch(const std::exception& e){
MessageBoxA(0,e.what(),0,0);
}
} | [
"bidepan2023@9e7edf01-a44e-0410-9491-a5bc24264e2e"
]
| [
[
[
1,
145
]
]
]
|
214b46762b5cdc5f90f9ffcf317d15388d73f3c6 | 102d8810abb4d1c8aecb454304ec564030bf2f64 | /TP3/Tanque/Tanque/Tanque/BattleCityEngine.h | 7f2da66fac0adb8d7089e7b25a3ea5fa84f4ad11 | []
| no_license | jfacorro/tp-taller-prog-1-fiuba | 2742d775b917cc6df28188ecc1f671d812017a0a | a1c95914c3be6b1de56d828ea9ff03e982560526 | refs/heads/master | 2016-09-14T04:32:49.047792 | 2008-07-15T20:17:27 | 2008-07-15T20:17:27 | 56,912,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,743 | h | #ifndef BattleCityEngine_h
#define BattleCityEngine_h
#define BATTLECITYENGINE_WALL_TEST
#define FRAMES_PER_SECOND 20
#include "BattleCityTypes.h"
#include "BattleCityWall.h"
#include "windows.h"
typedef struct _BattleCityParameters
{
unsigned int ArenaWidth;
unsigned int ArenaHeight;
unsigned int TankRadius;
unsigned int BulletRadius;
unsigned int BombRadius;
unsigned int PixelsPerUM;
char BackGroundTextureId[TEXTURE_NAME_MAX_LENGTH];
char ExplosionTextureId[TEXTURE_NAME_MAX_LENGTH];
vector<BattleCityTank> Tanks;
vector<BattleCityWall> Walls;
vector<BattleCityTexture> Textures;
unsigned int MaxBullets;
double BulletSpeed;
unsigned int BulletScope;
unsigned int MaxBombs;
unsigned int BombDelay;
unsigned int BombBlastDelay;
unsigned int BombBlastRadius;
}
BattleCityParameters;
typedef struct _BattleCityClientParameters
{
unsigned int ArenaWidth;
unsigned int ArenaHeight;
unsigned int TankRadius;
unsigned int BulletRadius;
unsigned int BombRadius;
unsigned int PixelsPerUM;
char BackGroundTextureId[TEXTURE_NAME_MAX_LENGTH];
char ExplosionTextureId[TEXTURE_NAME_MAX_LENGTH];
unsigned int MaxBullets;
double BulletSpeed;
unsigned int BulletScope;
unsigned int MaxBombs;
unsigned int BombDelay;
unsigned int BombBlastDelay;
unsigned int BombBlastRadius;
}
BattleCityClientParameters;
BattleCityClientParameters GetBattleCityClientParameters(BattleCityParameters params);
typedef struct _BattleCityState
{
vector<BattleCityTank> Tanks;
vector<BattleCityBomb> Bombs;
vector<BattleCityBullet> Bullets;
vector<BattleCityWall> Walls;
}
BattleCityState;
class BattleCityEngine
{
public:
BattleCityEngine(BattleCityParameters parameters);
virtual ~BattleCityEngine();
bool GetDirty();
bool GetFinished();
BattleCityState GetState();
void Start();
void Tick();
int GetNextTickInterval();
void TurnTank(unsigned int tank,Direction direction);
bool DropBomb(unsigned int tank);
bool ShootBullet(unsigned int tank);
private:
void UpdateNextTick();
void UpdateBombs();
void UpdateTankPos(unsigned int tank,double nextX, double nextY);
bool UpdateBulletPos(unsigned int bullet,double currentX,double currentY,double nextX,double nextY,bool check=true);
void HitTank(unsigned int tank, int decrementedEnergy);
bool FindTankCollition(unsigned int tank,int x, int y);
BattleCityParameters parameters;
bool dirty;
bool finished;
DWORD lastTick;
DWORD nextTick;
vector<BattleCityTank> tanks;
vector<BattleCityBomb> bombs;
vector<BattleCityBullet> bullets;
vector<BattleCityWall> walls;
};
#endif
| [
"juan.facorro@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb",
"nahuelgonzalez@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb"
]
| [
[
[
1,
4
],
[
6,
84
],
[
86,
107
],
[
109,
118
]
],
[
[
5,
5
],
[
85,
85
],
[
108,
108
]
]
]
|
8fb00bec7e8e529e8ac5e2cf9eda81e91924d75c | 028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32 | /src/drivers/psychic5.cpp | 3aceb837a1f9a478fa46a78578aaf27d1d078afe | []
| no_license | neonichu/iMame4All-for-iPad | 72f56710d2ed7458594838a5152e50c72c2fb67f | 4eb3d4ed2e5ccb5c606fcbcefcb7c5a662ace611 | refs/heads/master | 2020-04-21T07:26:37.595653 | 2011-11-26T12:21:56 | 2011-11-26T12:21:56 | 2,855,022 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,808 | cpp | #include "../vidhrdw/psychic5.cpp"
/**************************
*** PSYCHIC 5 hardware *** (by Roberto Ventura)
**************************
Psychic 5 (c) JALECO (early 1987)
driver by Jarek Parchanski
0) GENERAL.
The game has two Z80s.
The second CPU controls the two YM2203 sound chips.
Screen resolution is 224x256 (vertical CRT).
768 colors on screen.
96 sprites (16x16 or 32x32).
Some hardware features description is arbitrary since I
guessed their hardware implementation trusting what
I can recall of the 'real' arcade game.
1) ROM CONTENTS.
P5A 256 Kbit Sound program ROM
P5B 512 Kbit Sprites data ROM 0
P5C 512 Kbit Sprites data ROM 1
P5D 256 Kbit Main CPU program ROM
P5E 512 Kbit Banked CPU data ROM (banks 0,1,2 and 3)
P5F 256 Kbit Foreground data ROM
P5G 512 Kbit Background data ROM 0
P5H 512 Kbit Background data ROM 1
ROM banks 2 and 3 contain the eight level maps only.
Graphics format is pretty simple,each nibble contains information
for one pixel (4 planes packed).
All graphics is made of 8x8 tiles (32 consecutive bytes),16x16 tiles
are composed of 4 consecutive 8x8 tiles,while 32x32 sprites can be
considered as four 16x16 tiles assembled in the same way 8x8 tiles produce
one 16x16 tile.
Tile composition follows this scheme:
These are 4 consecutive tiles as stored in ROM - increasing memory
(the symbol ">" means the tiles are rotated 270 degrees):
A>;B>;C>;D>
This is the composite tile.
A> C>
B> D>
This is the way tile looks on the effective CRT after 90 deg rotation.
C^ D^
A^ B^
2) CPU.
The board mounts two crystals, 12.000 Mhz and 5.000 Mhz.
The possible effective main CPU clock may be 6 Mhz (12/2).
The main Z80 runs in Interrupt mode 0 (IM0),the game program expects
execution of two different restart (RST) instructions.
RST 10,the main IRQ,is to be triggered each time the screen is refreshed.
RST 08 must be triggered in order to make the game work properly
(e.g. demo game),I guess sound has something to do with this IRQ,but I
don't know whether it is sinchronized with video beam neither I know whether
it can be disabled.
Sound CPU runs in IM1.
The main CPU lies idle waiting the external IRQ occurrence executing code
from 012d to 0140.
Game data is paged,level maps and other data fit in ROM space
8000-bfff.
Video RAM is also banked at locations from c000 to dfff.
3) MAIN CPU MEMORY MAP.
0000-7fff ROM
8000-bfff paged ROM
c000-dfff paged RAM (RAM/VRAM/IO)
f000-f1ff I/O
f200-f7ff Sprites registers (misc RAM)
f800-ffff Work RAM
-paged RAM memory map
Bank 0
c000-cfff Background tile buffer
e000-dfff RAM (dummy background image for software collisions)
Bank 1
c000-c3ff I/O
c400-cbff Palette RAM
d000-d800 Foreground tile buffer
4) I/O
-VRAM bank 1
c000 COIN SLOTS and START BUTTONS
76543210
|| ||
|| |^-- coin 1
|| ^--- coin 2
||
|^-------- start 1
^--------- start 2
c001 PLAYER 1 CONTROLS
c002 PLAYER 2 CONTROLS
76543210
||||||
|||||^-- right
||||^--- left
|||^---- down
||^----- up
|^------ fire 0
^------- fire 1
c003 DIPSWITCH 0
76543210
||
^^-------- number of player's espers
c004 DIPSWITCH 1
76543210
||| |
||| ^-- player's immortality
^^^------- coin/credit configurations
c308 BACKGROUND SCROLL Y least significant 8 bits
c309 BACKGROUND SCROLL Y most significant 2 bits
76543210
||
|^-- Y scroll bit 8
^--- Y scroll bit 9
c30A BACKGROUND SCROLL X least significant 8 bits
c30B BACKGROUND SCROLL X MSB
76543210
||||||||
|||||||^-- X scroll bit 8
||||||^--- Unknown (title screen)
^^^^^^---- Unknown (title screen: 0xff)
c30C SCREEN MODE
76543210
||
|^-- background enable bit (0 means black BG)
^--- grey background enable bit
c5fe BACKGROUND PALETTE INTENSITY (red and green)
76543210
||||||||
||||^^^^-- green intensity
^^^^------ red intensity
c5ff BACKGROUND PALETTE INTENSITY (blue)
76543210
||||||||
||||^^^^-- unknown (?)
^^^^------ blue intensity
-RAM f000-f1ff
f000 SOUND COMMAND (?)
f001 UNKNOWN
maybe some external HW like a flashing light
when a coin falls in slot (?)
f002 ROM PAGE SELECTOR
select four (0-3) ROM pages at 8000-bfff.
f003 VRAM PAGE SELECTOR
selects two (0-1) VRAM pages at c000-dfff.
f004 UNKNOWN
f005 UNKNOWN
5) COLOR RAM
The palette system is dynamic,the game can show up to 768 different
colors on screen.
Each color component (RGB) depth is 4 bits,two consecutive bytes are used
for each color code (12 bits).
format: RRRRGGGGBBBB0000
Colors are organized in palettes,since graphics is 4 bits (16 colors)
each palette takes 32 bytes;the three different layers (background,sprites
and foreground) don't share any color,each has its own 256 color space,hence
the 768 colors on screen.
c400-c5ff Sprites palettes
c800-c9ff Background palettes
ca00-cbff Foreground palettes
The last palette colors for sprites and foreground are transparent
colors,these colors aren't displayed on screen so the actual maximum
color output is 736 colors.
Some additional palette effects are provided for background.
Sprite palette 15's transparent color (c5fe-c5ff) is the global
background intensity.
Background Intensity is encoded in the same way of colors,and
affects the intensity of each color component (BGR).
The least significant nibble of c5ff is unknown,it assumes value
0xf occasionaly when the other nibbles are changed.The only
value which is not 0 neither 0xf is 2 and it is assumed by this nibble
during the ride on the witches' broom.
When bit 1 of c30c (VRAM bank 1) is set background screen turns
grey.Notice the output of this function is passed to the palette
intensity process.
When you hit the witch the screen gets purple,this is done via
setting grey screen and scaling color components.
(BTW,I haven't seen a Psychic5 machine for about 10 years but
I think the resulting purple tonality in my emulator is way off...)
Palette intensity acts badly during title screen,when the game
scenario rapidly shows up under the golden logo;the problem is value
0xffff causes the background to be displayed as black.
6) TILE-BASED LAYERS
The tile format for background and foreground is the same,the
only difference is that background tiles are 16x16 pixels while foreground
tiles are only 8x8.
Background virtual screen is 1024 pixels tall and 512 pixel wide.
Two consecutive bytes identify one tile.
O7 O6 O5 O4 O3 O2 O1 O0 gfx Offset
O9 O8 FX FY C3 C2 C1 C0 Attibute
O= GFX offset (1024 tiles)
F= Flip X and Y
C= Color palette selector
Tile layers are to be displayed 'bottom-up' (eg. c000-c040
is row 63 of background screen)
Both background and foreground playfields can scroll; background tiles
are arranged in a rotational (wrap-around) buffer; window can be scrolled
vertically by an eight pixel offset (i.e. enough to scroll a single tile
smoothly),the game has to copy in new tiles every time a row is scrolled
(this feature is only used in the credits section at the end of the game).
I haven't provided the address for this feature, since I don't
know where it is mapped.
7) SPRITES
Five bytes identify each sprite,but the registers actually used
are placed at intervals of 16.
The remaining bytes are used as backup sprite coordinates and
attributes,not real sprites.
Sprites are provided in 2 different sizes,16x16 and 32x32.
Larger sprites are addressed as 16x16 sprites,but they are all
aligned by 4.
The first sprite data is located at f20b,then f21b and so on.
0b X7 X6 X5 X4 X3 X2 X1 X0 X coord (on screen)
0c Y7 Y6 Y5 Y5 Y3 Y2 Y1 Y0 X coord (on screen)
0d O9 O8 FX FY SZ X8 -- Y8 hi gfx - FLIP - hi X - hi Y
0e O7 O6 O5 O4 O3 O2 O1 O0 gfx - offset
0f -- -- -- -- C3 C2 C1 C0 color
Y= Y coordinate (two's complemented) (Y8 is used to clip sprite on top border)
X= X coordinate (X8 is used to clip 32x32 sprites on left border)
O= Gfx offset (1024 sprites)
F= Flip
SZ=Size 0=16x16 sprite,1=32x32 sprite
C= Color palette selector
*/
#include "driver.h"
#include "vidhrdw/generic.h"
void psychic5_init_machine(void);
int psychic5_vh_start(void);
void psychic5_vh_stop(void);
void psychic5_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
WRITE_HANDLER( psychic5_paged_ram_w );
READ_HANDLER( psychic5_paged_ram_r );
WRITE_HANDLER( psychic5_vram_page_select_w );
READ_HANDLER( psychic5_vram_page_select_r );
static int psychic5_bank_latch = 0x0;
READ_HANDLER( psychic5_bankselect_r )
{
return psychic5_bank_latch;
}
WRITE_HANDLER( psychic5_bankselect_w )
{
unsigned char *RAM = memory_region(REGION_CPU1);
int bankaddress;
if (data != psychic5_bank_latch)
{
psychic5_bank_latch = data;
bankaddress = 0x10000 + ((data & 3) * 0x4000);
cpu_setbank(1,&RAM[bankaddress]); /* Select 4 banks of 16k */
}
}
int psychic5_interrupt(void)
{
if (cpu_getiloops() == 0)
return 0xd7; /* RST 10h */
else
return 0xcf; /* RST 08h */
}
static struct MemoryReadAddress readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0xbfff, MRA_BANK1 },
{ 0xc000, 0xdfff, psychic5_paged_ram_r },
{ 0xe000, 0xefff, MRA_RAM },
{ 0xf000, 0xf000, MRA_RAM },
{ 0xf001, 0xf001, MRA_RAM }, // unknown
{ 0xf002, 0xf002, psychic5_bankselect_r },
{ 0xf003, 0xf003, psychic5_vram_page_select_r },
{ 0xf004, 0xf004, MRA_RAM }, // unknown
{ 0xf005, 0xf005, MRA_RAM }, // unknown
{ 0xf006, 0xf1ff, MRA_NOP },
{ 0xf200, 0xf7ff, MRA_RAM },
{ 0xf800, 0xffff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress writemem[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0x8000, 0xbfff, MWA_BANK1 },
{ 0xc000, 0xdfff, psychic5_paged_ram_w },
{ 0xe000, 0xefff, MWA_RAM },
{ 0xf000, 0xf000, soundlatch_w },
{ 0xf001, 0xf001, MWA_RAM }, // unknown
{ 0xf002, 0xf002, psychic5_bankselect_w },
{ 0xf003, 0xf003, psychic5_vram_page_select_w },
{ 0xf004, 0xf004, MWA_RAM }, // unknown
{ 0xf005, 0xf005, MWA_RAM }, // unknown
{ 0xf006, 0xf1ff, MWA_NOP },
{ 0xf200, 0xf7ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xf800, 0xffff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress sound_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0xc000, 0xc7ff, MRA_RAM },
{ 0xe000, 0xe000, soundlatch_r },
{ -1 }
};
static struct MemoryWriteAddress sound_writemem[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0xc000, 0xc7ff, MWA_RAM },
{ -1 }
};
static struct IOWritePort sound_writeport[] =
{
{ 0x00, 0x00, YM2203_control_port_0_w },
{ 0x01, 0x01, YM2203_write_port_0_w },
{ 0x80, 0x80, YM2203_control_port_1_w },
{ 0x81, 0x81, YM2203_write_port_1_w },
{ -1 }
};
INPUT_PORTS_START( psychic5 )
PORT_START
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_START /* player 1 controls */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* player 2 controls */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* dsw0 */
PORT_DIPNAME( 0x01, 0x00, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x04, 0x00, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x08, "Normal" )
PORT_DIPSETTING( 0x00, "Hard" )
PORT_DIPNAME( 0x10, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x10, DEF_STR( Cocktail ) )
PORT_DIPNAME( 0x20, 0x20, DEF_STR( Demo_Sounds ) )
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x20, DEF_STR( On ) )
PORT_DIPNAME( 0xc0, 0xc0, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x80, "2" )
PORT_DIPSETTING( 0xc0, "3" )
PORT_DIPSETTING( 0x40, "4" )
PORT_DIPSETTING( 0x00, "5" )
PORT_START /* dsw1 */
PORT_BITX( 0x01, 0x01, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0xe0, 0xe0, DEF_STR( Coin_A ) )
PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x20, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x40, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x60, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0xe0, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0xc0, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0xa0, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x80, DEF_STR( 1C_4C ) )
PORT_DIPNAME( 0x1c, 0x1c, DEF_STR( Coin_B ) )
PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x1c, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x18, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x14, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x10, DEF_STR( 1C_4C ) )
INPUT_PORTS_END
static struct GfxLayout charlayout =
{
8,8, /* 8x8 characters */
1024, /* 1024 characters */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 }, /* the four bitplanes for pixel are packed into one nibble */
{ 0, 4, 8, 12, 16, 20, 24, 28 },
{ 0*8, 4*8, 8*8, 12*8, 16*8, 20*8, 24*8, 28*8 },
32*8 /* every char takes 32 consecutive bytes */
};
static struct GfxLayout spritelayout =
{
16,16, /* 16x16 characters */
1024, /* 1024 characters */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 }, /* the four bitplanes for pixel are packed into one nibble */
{ 0, 4, 8, 12, 16, 20, 24, 28, 64*8, 64*8+4, 64*8+8, 64*8+12, 64*8+16, 64*8+20, 64*8+24, 64*8+28 },
{ 0*8, 4*8, 8*8, 12*8, 16*8, 20*8, 24*8, 28*8, 32*8, 36*8, 40*8, 44*8, 48*8, 52*8, 56*8, 60*8 },
128*8 /* every char takes 128 consecutive bytes */
};
static struct GfxDecodeInfo gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &spritelayout, 0*16, 16 },
{ REGION_GFX2, 0, &spritelayout, 16*16, 16 },
{ REGION_GFX3, 0, &charlayout, 32*16, 16 },
{ -1 } /* end of array */
};
static void irqhandler(int irq)
{
cpu_set_irq_line(1,0,irq ? ASSERT_LINE : CLEAR_LINE);
}
static struct YM2203interface ym2203_interface =
{
2, /* 2 chips */
6000000/4, /* 1.5 MHz */
{ YM2203_VOL(50,15), YM2203_VOL(50,15) },
{ 0 },
{ 0 },
{ 0 },
{ 0 },
{ irqhandler }
};
static struct MachineDriver machine_driver_psychic5 =
{
/* basic machine hardware */
{
{
CPU_Z80,
6000000,
readmem,writemem,0,0,
psychic5_interrupt,2
},
{
CPU_Z80 | CPU_AUDIO_CPU,
6000000,
sound_readmem,sound_writemem,0,sound_writeport,
ignore_interrupt,0 /* IRQs are generated by the YM2203 */
}
},
53.8, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
/* frames per second hand tuned to match game and music speed */
10, /* Allow time for 2nd cpu to interleave*/
psychic5_init_machine,
/* video hardware */
32*8, 32*8,
{ 0*8, 32*8-1, 2*8, 30*8-1 },
gfxdecodeinfo,
48*16,48*16,
0,
VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE,
0,
psychic5_vh_start,
psychic5_vh_stop,
psychic5_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_YM2203,
&ym2203_interface
}
}
};
/***************************************************************************
Game driver(s)
***************************************************************************/
ROM_START( psychic5 )
ROM_REGION( 0x20000, REGION_CPU1 ) /* 2*64K for main CPU, Z80 */
ROM_LOAD( "p5d", 0x00000, 0x08000, 0x90259249 )
ROM_LOAD( "p5e", 0x10000, 0x10000, 0x72298f34 )
ROM_REGION( 0x10000, REGION_CPU2 ) /*64K for 2nd z80 CPU*/
ROM_LOAD( "p5a", 0x00000, 0x08000, 0x50060ecd )
ROM_REGION( 0x20000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "p5b", 0x00000, 0x10000, 0x7e3f87d4 ) /* sprite tiles */
ROM_LOAD( "p5c", 0x10000, 0x10000, 0x8710fedb )
ROM_REGION( 0x20000, REGION_GFX2 | REGIONFLAG_DISPOSE )
ROM_LOAD( "p5g", 0x00000, 0x10000, 0xf9262f32 ) /* background tiles */
ROM_LOAD( "p5h", 0x10000, 0x10000, 0xc411171a )
ROM_REGION( 0x08000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "p5f", 0x00000, 0x08000, 0x04d7e21c ) /* foreground tiles */
ROM_END
GAMEX( 1987, psychic5, 0, psychic5, psychic5, 0, ROT270, "Jaleco", "Psychic 5", GAME_NO_COCKTAIL )
| [
"[email protected]"
]
| [
[
[
1,
623
]
]
]
|
91261d1324b7d157820cecd8a0b22741884878af | 33b5565fb265463ed201c31f38ba3bd305a4e5d9 | /FLHook/tags/Latest/src/source/HkTimers.cpp | 66288830517f49314abf9aa97f387a3704a58644 | []
| no_license | HeIIoween/FLHook-And-88-Flak-m0tah | be1ee2fa0e240c24160dda168b8b23ad6aec2b48 | 3f0737f7456ef3eed5dd67cfec1b838d32b8b5e1 | refs/heads/master | 2021-05-07T14:00:34.880461 | 2011-01-28T00:21:41 | 2011-01-28T00:21:41 | 109,712,726 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,762 | cpp | #include <winsock2.h>
#include "wildcards.hh"
#include "hook.h"
/**************************************************************************************************************
Update average ping data
**************************************************************************************************************/
void HkTimerUpdatePingData()
{
try {
// for all players
struct PlayerData *pPD = 0;
while(pPD = Players.traverse_active(pPD))
{
uint iClientID = HkGetClientIdFromPD(pPD);
if(ClientInfo[iClientID].tmF1TimeDisconnect)
continue;
// CDPClientProxy *cdpClient = g_cClientProxyArray[iClientID - 1];
// u_long pPingPacket[2] = {3, 4, 5, 6, 7};
// cdpClient->Send(&pPingPacket, sizeof(pPingPacket));
// CDPServer::getServer()->SendTo(cdpClient, &pPingPacket, sizeof(pPingPacket));
DPN_CONNECTION_INFO ci;
if(HkGetConnectionStats(iClientID, ci) != HKE_OK)
continue;
///////////////////////////////////////////////////////////////
// update ping data
if(ClientInfo[iClientID].lstPing.size() >= set_iPingKickFrame)
{
// calculate average loss
ClientInfo[iClientID].iAveragePing = 0;
foreach(ClientInfo[iClientID].lstPing, uint, it)
ClientInfo[iClientID].iAveragePing += (*it);
ClientInfo[iClientID].iAveragePing /= (uint)ClientInfo[iClientID].lstPing.size();
}
// remove old pingdata
while(ClientInfo[iClientID].lstPing.size() >= set_iPingKickFrame)
ClientInfo[iClientID].lstPing.pop_back();
ClientInfo[iClientID].lstPing.push_front(ci.dwRoundTripLatencyMS);
}
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
/**************************************************************************************************************
Update average loss data
**************************************************************************************************************/
void HkTimerUpdateLossData()
{
try {
// for all players
struct PlayerData *pPD = 0;
while(pPD = Players.traverse_active(pPD))
{
uint iClientID = HkGetClientIdFromPD(pPD);
if(ClientInfo[iClientID].tmF1TimeDisconnect)
continue;
DPN_CONNECTION_INFO ci;
if(HkGetConnectionStats(iClientID, ci) != HKE_OK)
continue;
///////////////////////////////////////////////////////////////
// update loss data
if(ClientInfo[iClientID].lstLoss.size() >= (set_iLossKickFrame / (LOSS_INTERVALL / 1000)))
{
// calculate average loss
ClientInfo[iClientID].iAverageLoss = 0;
foreach(ClientInfo[iClientID].lstLoss, uint, it)
ClientInfo[iClientID].iAverageLoss += (*it);
ClientInfo[iClientID].iAverageLoss /= (uint)ClientInfo[iClientID].lstLoss.size();
}
// remove old lossdata
while(ClientInfo[iClientID].lstLoss.size() >= (set_iLossKickFrame / (LOSS_INTERVALL / 1000)))
ClientInfo[iClientID].lstLoss.pop_back();
// CDPClientProxy *cdpClient = g_cClientProxyArray[iClientID - 1];
// double d = cdpClient->GetLinkSaturation();
// ClientInfo[iClientID].lstLoss.push_front((uint)(cdpClient->GetLinkSaturation() * 100)); // loss per sec
ClientInfo[iClientID].lstLoss.push_front(ci.dwBytesRetried - ClientInfo[iClientID].iLastLoss); // loss per sec
ClientInfo[iClientID].iLastLoss = ci.dwBytesRetried;
}
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
/**************************************************************************************************************
check if players should be kicked
**************************************************************************************************************/
void HkTimerCheckKick()
{
try {
// for all players
struct PlayerData *pPD = 0;
while(pPD = Players.traverse_active(pPD))
{
uint iClientID = HkGetClientIdFromPD(pPD);
if(ClientInfo[iClientID].tmKickTime)
{
if(timeInMS() >= ClientInfo[iClientID].tmKickTime)
HkKick(ARG_CLIENTID(iClientID)); // kick time expired
continue; // player will be kicked anyway
}
if(set_iAntiBaseIdle)
{ // anti base-idle check
uint iBaseID;
pub::Player::GetBase(iClientID, iBaseID);
if(iBaseID && ClientInfo[iClientID].iBaseEnterTime)
{
if((time(0) - ClientInfo[iClientID].iBaseEnterTime) >= set_iAntiBaseIdle)
{
HkAddKickLog(iClientID, L"Base idling");
HkMsgAndKick(iClientID, L"Base idling", set_iKickMsgPeriod);
}
}
}
if(set_iAntiCharMenuIdle)
{ // anti charmenu-idle check
if(HkIsInCharSelectMenu(iClientID)) {
if(!ClientInfo[iClientID].iCharMenuEnterTime)
ClientInfo[iClientID].iCharMenuEnterTime = (uint)time(0);
else if((time(0) - ClientInfo[iClientID].iCharMenuEnterTime) >= set_iAntiCharMenuIdle) {
HkAddKickLog(iClientID, L"Charmenu idling");
HkKick(ARG_CLIENTID(iClientID));
continue;
}
} else
ClientInfo[iClientID].iCharMenuEnterTime = 0;
}
if(set_iLossKick)
{ // check if loss is too high
if(ClientInfo[iClientID].iAverageLoss > set_iLossKick)
{
HkAddKickLog(iClientID, L"High loss");
HkMsgAndKick(iClientID, L"High loss", set_iKickMsgPeriod);
}
}
if(set_iPingKick)
{ // check if ping is too high
if(ClientInfo[iClientID].iAveragePing > set_iPingKick)
{
HkAddKickLog(iClientID, L"High ping");
HkMsgAndKick(iClientID, L"High ping", set_iKickMsgPeriod);
}
}
}
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
/**************************************************************************************************************
Check if NPC spawns should be disabled
**************************************************************************************************************/
void HkTimerNPCAndF1Check()
{
try {
struct PlayerData *pPD = 0;
while(pPD = Players.traverse_active(pPD))
{
uint iClientID = HkGetClientIdFromPD(pPD);
if(ClientInfo[iClientID].tmF1Time && (timeInMS() >= ClientInfo[iClientID].tmF1Time)) { // f1
Server.CharacterInfoReq(iClientID, false);
ClientInfo[iClientID].tmF1Time = 0;
} else if(ClientInfo[iClientID].tmF1TimeDisconnect && (timeInMS() >= ClientInfo[iClientID].tmF1TimeDisconnect)) {
ulong lArray[64] = {0};
lArray[26] = iClientID;
__asm
{
pushad
lea ecx, lArray
mov eax, [hModRemoteClient]
add eax, ADDR_RC_DISCONNECT
call eax ; disconncet
popad
}
ClientInfo[iClientID].tmF1TimeDisconnect = 0;
continue;
}
}
// npc
if(!g_bNPCForceDisabled)
{
if(set_iDisableNPCSpawns && (g_iServerLoad >= set_iDisableNPCSpawns))
HkChangeNPCSpawn(true); // serverload too high, disable npcs
else
HkChangeNPCSpawn(false);
}
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
/**************************************************************************************************************
**************************************************************************************************************/
void HkTimerSolarRepair()
{
try {
if(!btSolarList->Count())
{
return;
}
BinaryTreeIterator<SOLAR_REPAIR> *solarIter = new BinaryTreeIterator<SOLAR_REPAIR>(btSolarList);
solarIter->First();
for(long i=0; i<btSolarList->Count(); i++)
{
if(solarIter->Curr()->iTimeAfterDestroyed<0) //solar is alive
{
float fRelativeHealth;
pub::SpaceObj::GetRelativeHealth(solarIter->Curr()->iObjectID, fRelativeHealth);
if(fRelativeHealth<=set_fBaseDockDmg)
{
solarIter->Curr()->iTimeAfterDestroyed = 0;
}
}
else //dead or being repaired
{
if(solarIter->Curr()->iTimeAfterDestroyed>((int)(set_iRepairBaseTime*set_fRepairBaseRatio)))
{
float fRelativeHealth;
pub::SpaceObj::GetRelativeHealth(solarIter->Curr()->iObjectID, fRelativeHealth);
if(fRelativeHealth<set_fRepairBaseMaxHealth)
{
pub::SpaceObj::SetRelativeHealth(solarIter->Curr()->iObjectID, fRelativeHealth + (1.0f/(set_iRepairBaseTime*set_fRepairBaseRatio))*set_fRepairBaseMaxHealth + 0.000001f);
}
else
solarIter->Curr()->iTimeAfterDestroyed = -2;
}
else if(solarIter->Curr()->iTimeAfterDestroyed>set_iRepairBaseTime)
{
solarIter->Curr()->iTimeAfterDestroyed = -2;
}
solarIter->Curr()->iTimeAfterDestroyed++;
}
solarIter->Next();
}
delete solarIter;
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
/**************************************************************************************************************
**************************************************************************************************************/
CRITICAL_SECTION csIPResolve;
list<RESOLVE_IP> g_lstResolveIPs;
list<RESOLVE_IP> g_lstResolveIPsResult;
HANDLE hThreadResolver;
void HkThreadResolver()
{
try {
while(1)
{
EnterCriticalSection(&csIPResolve);
list<RESOLVE_IP> lstMyResolveIPs = g_lstResolveIPs;
g_lstResolveIPs.clear();
LeaveCriticalSection(&csIPResolve);
foreach(lstMyResolveIPs, RESOLVE_IP, it)
{
ulong addr = inet_addr(wstos(it->wscIP).c_str());
hostent *host = gethostbyaddr((const char*)&addr, sizeof(addr), AF_INET);
if(host)
it->wscHostname = stows(host->h_name);
}
EnterCriticalSection(&csIPResolve);
foreach(lstMyResolveIPs, RESOLVE_IP, it2)
{
if(it2->wscHostname.length())
g_lstResolveIPsResult.push_back(*it2);
}
LeaveCriticalSection(&csIPResolve);
Sleep(50);
}
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
/**************************************************************************************************************
**************************************************************************************************************/
void HkTimerCheckResolveResults()
{
try {
EnterCriticalSection(&csIPResolve);
foreach(g_lstResolveIPsResult, RESOLVE_IP, it)
{
if(it->iConnects != ClientInfo[it->iClientID].iConnects)
continue; // outdated
// check if banned
foreach(set_lstBans, wstring, itb)
{
if(Wildcard::wildcardfit(wstos(*itb).c_str(), wstos(it->wscHostname).c_str()))
{
HkAddKickLog(it->iClientID, L"IP/Hostname ban(%s matches %s)", it->wscHostname.c_str(), (*itb).c_str());
if(set_bBanAccountOnMatch)
HkBan(ARG_CLIENTID(it->iClientID), true);
HkKick(ARG_CLIENTID(it->iClientID));
}
}
ClientInfo[it->iClientID].wscHostname = it->wscHostname;
}
g_lstResolveIPsResult.clear();
LeaveCriticalSection(&csIPResolve);
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
/**************************************************************************************************************
**************************************************************************************************************/
void HkTimerCloakHandler()
{
try {
// for all players
struct PlayerData *pPD = 0;
while(pPD = Players.traverse_active(pPD))
{
uint iClientID = HkGetClientIdFromPD(pPD);
if (ClientInfo[iClientID].bCanCloak)
{
// send cloak state for uncloaked cloak-able players (only for them in space)
// this is the code to fix the bug where players wouldnt always see uncloaked players
uint iShip = 0;
pub::Player::GetShip(iClientID, iShip);
if (iShip)
{
if(!ClientInfo[iClientID].bCloaked && !ClientInfo[iClientID].bIsCloaking)
{
XActivateEquip ActivateEq;
ActivateEq.bActivate = false;
ActivateEq.l1 = iShip;
ActivateEq.sID = ClientInfo[iClientID].iCloakSlot;
Server.ActivateEquip(iClientID,ActivateEq);
}
// check cloak timings
mstime tmTimeNow = timeInMS();
if(ClientInfo[iClientID].bWantsCloak && (tmTimeNow - ClientInfo[iClientID].tmCloakTime) > ClientInfo[iClientID].iCloakWarmup)
HkCloak(iClientID);
if(ClientInfo[iClientID].bIsCloaking && (tmTimeNow - ClientInfo[iClientID].tmCloakTime) > ClientInfo[iClientID].iCloakingTime)
{
ClientInfo[iClientID].bIsCloaking = false;
ClientInfo[iClientID].bCloaked = true;
ClientInfo[iClientID].tmCloakTime = tmTimeNow;
}
mstime tmCloakRemaining = tmTimeNow - ClientInfo[iClientID].tmCloakTime;
if(ClientInfo[iClientID].bCloaked && ClientInfo[iClientID].iCloakingTime && tmCloakRemaining > 0)
{
HkUnCloak(iClientID);
}
/*if(ClientInfo[iClientID].iCloakingTime)
{
PrintUserCmdText(iClientID, L"tmCloakRemaining: %I64d, %i, %i", tmCloakRemaining, (ClientInfo[iClientID].iCloakingTime - (set_iCloakExpireWarnTime - 500)), (ClientInfo[iClientID].iCloakingTime - set_iCloakExpireWarnTime));
}*/
//Does not work, dunno why
/*if(ClientInfo[iClientID].bCloaked && ClientInfo[iClientID].iCloakingTime && tmCloakRemaining < (mstime)(ClientInfo[iClientID].iCloakingTime - (set_iCloakExpireWarnTime - 500)) && tmCloakRemaining >= (mstime)(ClientInfo[iClientID].iCloakingTime - set_iCloakExpireWarnTime))
{
PrintUserCmdText(iClientID, L"Warning: cloak will expire in %i seconds", set_iCloakExpireWarnTime/1000);
}*/
if(!ClientInfo[iClientID].bCloaked && tmCloakRemaining < (ClientInfo[iClientID].iCloakCooldown + 500) && tmCloakRemaining >= ClientInfo[iClientID].iCloakCooldown)
{
PrintUserCmdText(iClientID, L"Cloak has cooled down and is ready to be used!");
}
}
}
}
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
/**************************************************************************************************************
**************************************************************************************************************/
void HkTimerSpaceObjMark()
{
try {
if(set_fAutoMarkRadius<=0.0f) //automarking disabled
return;
struct PlayerData *pPD = 0;
while(pPD = Players.traverse_active(pPD))
{
uint iShip, iClientID = HkGetClientIdFromPD(pPD);
pub::Player::GetShip(iClientID, iShip);
if(!iShip || ClientInfo[iClientID].fAutoMarkRadius<=0.0f) //docked or does not want any marking
continue;
uint iSystem;
pub::Player::GetSystem(iClientID, iSystem);
Vector VClientPos;
Matrix MClientOri;
pub::SpaceObj::GetLocation(iShip, VClientPos, MClientOri);
for(uint i=0; i<ClientInfo[iClientID].vAutoMarkedObjs.size(); i++)
{
Vector VTargetPos;
Matrix MTargetOri;
pub::SpaceObj::GetLocation(ClientInfo[iClientID].vAutoMarkedObjs[i], VTargetPos, MTargetOri);
if(HkDistance3D(VTargetPos, VClientPos)>ClientInfo[iClientID].fAutoMarkRadius)
{
pub::Player::MarkObj(iClientID, ClientInfo[iClientID].vAutoMarkedObjs[i], 0);
ClientInfo[iClientID].vDelayedAutoMarkedObjs.push_back(ClientInfo[iClientID].vAutoMarkedObjs[i]);
if(i!=ClientInfo[iClientID].vAutoMarkedObjs.size()-1)
{
ClientInfo[iClientID].vAutoMarkedObjs[i] = ClientInfo[iClientID].vAutoMarkedObjs[ClientInfo[iClientID].vAutoMarkedObjs.size()-1];
i--;
}
ClientInfo[iClientID].vAutoMarkedObjs.pop_back();
}
}
for(uint i=0; i<ClientInfo[iClientID].vDelayedAutoMarkedObjs.size(); i++)
{
if(pub::SpaceObj::ExistsAndAlive(ClientInfo[iClientID].vDelayedAutoMarkedObjs[i]))
{
if(i!=ClientInfo[iClientID].vDelayedAutoMarkedObjs.size()-1)
{
ClientInfo[iClientID].vDelayedAutoMarkedObjs[i] = ClientInfo[iClientID].vDelayedAutoMarkedObjs[ClientInfo[iClientID].vDelayedAutoMarkedObjs.size()-1];
i--;
}
ClientInfo[iClientID].vDelayedAutoMarkedObjs.pop_back();
continue;
}
Vector VTargetPos;
Matrix MTargetOri;
pub::SpaceObj::GetLocation(ClientInfo[iClientID].vDelayedAutoMarkedObjs[i], VTargetPos, MTargetOri);
if(!(HkDistance3D(VTargetPos, VClientPos)>ClientInfo[iClientID].fAutoMarkRadius))
{
pub::Player::MarkObj(iClientID, ClientInfo[iClientID].vDelayedAutoMarkedObjs[i], 1);
ClientInfo[iClientID].vAutoMarkedObjs.push_back(ClientInfo[iClientID].vDelayedAutoMarkedObjs[i]);
if(i!=ClientInfo[iClientID].vDelayedAutoMarkedObjs.size()-1)
{
ClientInfo[iClientID].vDelayedAutoMarkedObjs[i] = ClientInfo[iClientID].vDelayedAutoMarkedObjs[ClientInfo[iClientID].vDelayedAutoMarkedObjs.size()-1];
i--;
}
ClientInfo[iClientID].vDelayedAutoMarkedObjs.pop_back();
}
}
for(uint i=0; i<vMarkSpaceObjProc.size(); i++)
{
uint iMarkSpaceObjProcShip = vMarkSpaceObjProc[i];
if(set_bFlakVersion)
{
uint iType;
pub::SpaceObj::GetType(iMarkSpaceObjProcShip, iType);
if(iType!=OBJ_CAPITAL && ((ClientInfo[iClientID].bMarkEverything && iType==OBJ_FIGHTER)/* || iType==OBJ_FREIGHTER*/))
{
uint iSpaceObjSystem;
pub::SpaceObj::GetSystem(iMarkSpaceObjProcShip, iSpaceObjSystem);
Vector VTargetPos;
Matrix MTargetOri;
pub::SpaceObj::GetLocation(iMarkSpaceObjProcShip, VTargetPos, MTargetOri);
if(iSpaceObjSystem!=iSystem || HkDistance3D(VTargetPos, VClientPos)>ClientInfo[iClientID].fAutoMarkRadius)
{
ClientInfo[iClientID].vDelayedAutoMarkedObjs.push_back(iMarkSpaceObjProcShip);
}
else
{
pub::Player::MarkObj(iClientID, iMarkSpaceObjProcShip, 1);
ClientInfo[iClientID].vAutoMarkedObjs.push_back(iMarkSpaceObjProcShip);
}
}
}
else //just mark everything
{
uint iSpaceObjSystem;
pub::SpaceObj::GetSystem(iMarkSpaceObjProcShip, iSpaceObjSystem);
Vector VTargetPos;
Matrix MTargetOri;
pub::SpaceObj::GetLocation(iMarkSpaceObjProcShip, VTargetPos, MTargetOri);
if(iSpaceObjSystem!=iSystem || HkDistance3D(VTargetPos, VClientPos)>ClientInfo[iClientID].fAutoMarkRadius)
{
ClientInfo[iClientID].vDelayedAutoMarkedObjs.push_back(iMarkSpaceObjProcShip);
}
else
{
pub::Player::MarkObj(iClientID, iMarkSpaceObjProcShip, 1);
ClientInfo[iClientID].vAutoMarkedObjs.push_back(iMarkSpaceObjProcShip);
}
}
}
vMarkSpaceObjProc.clear();
}
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
list<DELAY_MARK> g_lstDelayedMarks;
void HkTimerMarkDelay()
{
if(!g_lstDelayedMarks.size())
return;
float fMaxDistance = *(float*)SRV_ADDR(0x86AF0); //"square of player disappear distance in MP"
mstime tmTimeNow = timeInMS();
for(list<DELAY_MARK>::iterator mark = g_lstDelayedMarks.begin(); mark != g_lstDelayedMarks.end(); )
{
if(tmTimeNow-mark->time > 50)
{
Matrix mTemp;
Vector vItem, vPlayer;
pub::SpaceObj::GetLocation(mark->iObj, vItem, mTemp);
uint iItemSystem;
pub::SpaceObj::GetSystem(mark->iObj, iItemSystem);
// for all players
struct PlayerData *pPD = 0;
while(pPD = Players.traverse_active(pPD))
{
uint iClientID = HkGetClientIdFromPD(pPD);
if(Players[iClientID].iSystemID == iItemSystem)
{
pub::SpaceObj::GetLocation(Players[iClientID].iSpaceObjID, vPlayer, mTemp);
if(HkDistance3D(vPlayer, vItem) <= fMaxDistance)
{
HkMarkObject(iClientID, mark->iObj);
}
}
}
mark = g_lstDelayedMarks.erase(mark);
}
else
{
mark++;
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
void HkTimerNPCDockHandler()
{
try {
for(uint i=0; i<vDelayedNPCDocks.size(); i++)
{
float fRelativeHealth;
pub::SpaceObj::GetRelativeHealth(vDelayedNPCDocks[i].iDockTarget, fRelativeHealth);
if(fRelativeHealth>=set_fBaseDockDmg)
{
pub::SpaceObj::Dock(vDelayedNPCDocks[i].iShip, vDelayedNPCDocks[i].iDockTarget, 0, vDelayedNPCDocks[i].dockResponse);
if(i!=vDelayedNPCDocks.size()-1)
{
vDelayedNPCDocks[i] = vDelayedNPCDocks[vDelayedNPCDocks.size()-1];
i--;
}
vDelayedNPCDocks.pop_back();
}
}
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
list<SHIP_REPAIR> g_lstRepairShips;
void HkTimerRepairShip()
{
try {
for(list<SHIP_REPAIR>::iterator ship = g_lstRepairShips.begin(); ship != g_lstRepairShips.end(); )
{
if(!pub::SpaceObj::ExistsAndAlive(ship->iObjID))
{
float fHealth, fMaxHealth;
pub::SpaceObj::GetHealth(ship->iObjID, fHealth, fMaxHealth);
if(fHealth && fHealth != fMaxHealth)
{
fHealth += ship->fIncreaseHealth;
if(fHealth > fMaxHealth)
pub::SpaceObj::SetRelativeHealth(ship->iObjID, 1.0f);
else
pub::SpaceObj::SetRelativeHealth(ship->iObjID, fHealth/fMaxHealth);
}
ship++;
}
else
{
ship = g_lstRepairShips.erase(ship);
}
}
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
list< pair<IObjInspectImpl*, DAMAGE_INFO> > lstSolarDestroyDelay;
void HkTimerSolarDestroyDelay()
{
try {
foreach(lstSolarDestroyDelay, pair<IObjInspectImpl* COMMA DAMAGE_INFO>, damage)
{
float fHealth, fMaxHealth;
damage->first->get_status(fHealth, fMaxHealth);
if(!fHealth)
{
uint iSpaceObj = damage->first->get_id();
pair< map<uint, list<DAMAGE_INFO> >::iterator, bool> findSpaceObj = mapSpaceObjDmgRec.insert(make_pair(iSpaceObj, list<DAMAGE_INFO>()));
findSpaceObj.first->second.push_back(damage->second);
SpaceObjDestroyed(iSpaceObj, true);
}
}
lstSolarDestroyDelay.clear();
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**************************************************************************************************************
Called when _SendMessage is sent
NOT USED ATM
**************************************************************************************************************/
struct MSGSTRUCT
{
uint iShipID; // ? or charid? or archetype?
uint iClientID;
};
void __stdcall HkCb_Message(uint iMsg, MSGSTRUCT *msg)
{
try {
uint i = msg->iClientID;
FILE *f = fopen("msg.txt", "at");
fprintf(f, "%.4d %.4d\n", iMsg, i);
fclose(f);
} catch(...) { AddLog("Exception in %s", __FUNCTION__); }
}
__declspec(naked) void _SendMessageHook()
{
__asm
{
push [esp+0Ch]
push [esp+0Ch]
call HkCb_Message
ret
}
}
| [
"M0tah@62241663-6891-49f9-b8c1-0f2e53ca0faf"
]
| [
[
[
1,
669
]
]
]
|
dac5442dc4124bfecdbee9d180c0e50e740ac2d8 | 444a151706abb7bbc8abeb1f2194a768ed03f171 | /trunk/ENIGMAsystem/SHELL/Universal_System/var4.cpp | c0aefbe64b62be2dba9c7e5b885d9da4d4f648fb | []
| no_license | amorri40/Enigma-Game-Maker | 9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6 | c6b701201b6037f2eb57c6938c184a5d4ba917cf | refs/heads/master | 2021-01-15T11:48:39.834788 | 2011-11-22T04:09:28 | 2011-11-22T04:09:28 | 1,855,342 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 29,100 | cpp | /** Copyright (C) 2011 Josh Ventura
***
*** This file is a part of the ENIGMA Development Environment.
***
*** ENIGMA 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, version 3 of the license or any later version.
***
*** This application and its source code is distributed AS-IS, 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 code. If not, see <http://www.gnu.org/licenses/>
**/
#include <map>
#include <string>
#include <math.h>
using namespace std;
#include "var4.h"
#undef string
#include "var_te.h"
variant::operator int() { return int (rval.d); }
variant::operator bool() { return lrint(rval.d) > 0; }
variant::operator char() { return char (rval.d); }
variant::operator long() { return long (rval.d); }
variant::operator short() { return short(rval.d); }
variant::operator unsigned() { return (unsigned int) (rval.d); }
variant::operator unsigned char() { return (unsigned char) (rval.d); }
variant::operator unsigned short() { return (unsigned short) (rval.d); }
variant::operator unsigned long() { return (unsigned long) (rval.d); }
variant::operator unsigned long long() { return (unsigned long long) (rval.d); }
variant::operator long long() { return (long long)(rval.d); }
variant::operator double() { return double (rval.d); }
variant::operator float() { return float (rval.d); }
variant::operator string() { return sval; }
variant::operator int() const { return int (rval.d); }
variant::operator bool() const { return lrint(rval.d) > 0; }
variant::operator char() const { return char (rval.d); }
variant::operator long() const { return long (rval.d); }
variant::operator short() const { return short(rval.d); }
variant::operator unsigned() const { return (unsigned int) (rval.d); }
variant::operator unsigned char() const { return (unsigned char) (rval.d); }
variant::operator unsigned short() const { return (unsigned short) (rval.d); }
variant::operator unsigned long() const { return (unsigned long) (rval.d); }
variant::operator unsigned long long() const { return (unsigned long long) (rval.d); }
variant::operator long long() const { return (long long)(rval.d); }
variant::operator double() const { return double (rval.d); }
variant::operator float() const { return float (rval.d); }
variant::operator string() const { return sval; }
#define real enigma::vt_real
#define tstr enigma::vt_tstr
types_extrapolate_real_p (variant::variant,: rval(x), sval( ), type(real) {})
types_extrapolate_string_p(variant::variant,: rval(0), sval(x), type(tstr) {})
//variant::variant(var x): rval(x[0].rval), sval(x[0].sval) { }
variant::variant(const variant& x): rval(x.rval.d), sval(x.sval), type(x.type) { }
variant::variant(): rval(0), sval( ), type(0) { }
types_extrapolate_real_p (variant& variant::operator=, { rval.d = x; type = real; return *this; })
types_extrapolate_string_p(variant& variant::operator=, { sval = x; type = tstr; return *this; })
variant& variant::operator=(const variant x) { rval.d = x.rval.d; if ((type = x.type) == tstr) sval = x.sval; return *this; }
variant& variant::operator=(const var &x) { return *this = *x; }
types_extrapolate_real_p (variant& variant::operator+=, { terror(real); rval.d += x; return *this; })
types_extrapolate_string_p(variant& variant::operator+=, { terror(tstr); sval += x; return *this; })
variant& variant::operator+=(const variant x) { terror(x.type); if (x.type == real) rval.d += x.rval.d; else sval += x.sval; return *this; }
variant& variant::operator+=(const var &x) { return *this += *x; }
types_extrapolate_real_p (variant& variant::operator-=, { terror(real); rval.d -= x; return *this; })
types_extrapolate_string_p(variant& variant::operator-=, { terrortrue(); return *this; })
variant& variant::operator-=(const variant x) { terror2(real); rval.d -= x.rval.d; return *this; }
variant& variant::operator-=(const var &x) { return *this -= *x; }
types_extrapolate_real_p (variant& variant::operator*=, { terror(real); rval.d *= x; return *this; })
types_extrapolate_string_p(variant& variant::operator*=, { terrortrue(); return *this; })
variant& variant::operator*=(const variant x) { terror2(real); rval.d *= x.rval.d; return *this; }
variant& variant::operator*=(const var &x) { return *this *= *x; }
types_extrapolate_real_p (variant& variant::operator/=, { terror(real); div0c(x); rval.d /= x; return *this; })
types_extrapolate_string_p(variant& variant::operator/=, { terrortrue(); return *this; })
variant& variant::operator/=(const variant x) { terror2(real); div0c(x.rval.d); rval.d /= x.rval.d; return *this; }
variant& variant::operator/=(const var &x) { return *this /= *x; }
types_extrapolate_real_p (variant& variant::operator%=, { terror(real); div0c(x); rval.d = fmod(rval.d, x); return *this; })
types_extrapolate_string_p(variant& variant::operator%=, { terrortrue(); return *this; })
variant& variant::operator%=(const variant x) { terror2(real); div0c(x.rval.d); rval.d = fmod(rval.d, x.rval.d); return *this; }
variant& variant::operator%=(const var &x) { div0c((*x).rval.d) rval.d = fmod(rval.d, (*x).rval.d); return *this; }
types_extrapolate_real_p (variant& variant::operator<<=, { terror(real); rval.d = long(rval.d) << int(x); return *this; })
types_extrapolate_string_p(variant& variant::operator<<=, { terrortrue(); return *this; })
variant& variant::operator<<=(const variant x) { terror2(real); rval.d = long(rval.d) << long(x.rval.d); return *this; }
variant& variant::operator<<=(const var &x) { return *this <<= *x; }
types_extrapolate_real_p (variant& variant::operator>>=, { terror(real); rval.d = long(rval.d) >> int(x); return *this; })
types_extrapolate_string_p(variant& variant::operator>>=, { terrortrue(); return *this; })
variant& variant::operator>>=(const variant x) { terror2(real); rval.d = long(rval.d) >> long(x.rval.d); return *this; }
variant& variant::operator>>=(const var &x) { return *this >>= *x; }
types_extrapolate_real_p (variant& variant::operator&=, { terror(real); rval.d = long(rval.d) & long(x); return *this; })
types_extrapolate_string_p(variant& variant::operator&=, { terrortrue(); return *this; })
variant& variant::operator&=(const variant x) { terror2(real); rval.d = long(rval.d) & long(x.rval.d); return *this; }
variant& variant::operator&=(const var &x) { return *this &= *x; }
types_extrapolate_real_p (variant& variant::operator|=, { terror(real); rval.d = long(rval.d) | long(x); return *this; })
types_extrapolate_string_p(variant& variant::operator|=, { terrortrue(); return *this; })
variant& variant::operator|=(const variant x) { terror2(real); rval.d = long(rval.d) | long(x.rval.d); return *this; }
variant& variant::operator|=(const var &x) { return *this |= *x; }
types_extrapolate_real_p (variant& variant::operator^=, { terror(real); rval.d = long(rval.d) ^ long(x); return *this; })
types_extrapolate_string_p(variant& variant::operator^=, { terrortrue(); return *this; })
variant& variant::operator^=(const variant x) { terror2(real); rval.d = long(rval.d) ^ long(x.rval.d); return *this; }
variant& variant::operator^=(const var &x) { return *this ^= *x; }
#undef EVCONST
#define EVCONST const
types_extrapolate_real_p (variant variant::operator+, { terror(real); return rval.d + x; })
types_extrapolate_string_p(variant variant::operator+, { terror(tstr); return sval + x; })
variant variant::operator+(const variant x) EVCONST { terror(x.type); if (x.type == real) return rval.d + x.rval.d; return sval + x.sval; }
variant variant::operator+(const var &x) EVCONST { return *this + *x; }
types_extrapolate_real_p (double variant::operator-, { terror(real); return rval.d - x; })
types_extrapolate_string_p(double variant::operator-, { terrortrue(); return rval.d; })
double variant::operator-(const variant x) EVCONST { terror2(real); return rval.d - x.rval.d; }
double variant::operator-(const var &x) EVCONST { return *this - *x; }
types_extrapolate_real_p (double variant::operator*, { terror(real); return rval.d * x; })
types_extrapolate_string_p(double variant::operator*, { terrortrue(); return rval.d; })
double variant::operator*(const variant x) EVCONST { terror2(real); return rval.d * x.rval.d; }
double variant::operator*(const var &x) EVCONST { return *this * *x; }
types_extrapolate_real_p (double variant::operator/, { terror(real); div0c(x); return rval.d / x; })
types_extrapolate_string_p(double variant::operator/, { terrortrue(); return rval.d; })
double variant::operator/(const variant x) EVCONST { terror2(real); return rval.d / x.rval.d; }
double variant::operator/(const var &x) EVCONST { return *this / *x; }
types_extrapolate_real_p (double variant::operator%, { terror(real); div0c(x); return fmod(rval.d, x); })
types_extrapolate_string_p(double variant::operator%, { terrortrue(); return rval.d; })
double variant::operator%(const variant x) EVCONST { terror2(real); div0c(x.rval.d); return fmod(rval.d, x.rval.d); }
double variant::operator%(const var &x) EVCONST { div0c((*x).rval.d); return fmod(this->rval.d, (*x).rval.d); }
types_extrapolate_real_p (long variant::operator<<, { terror(real); return long(rval.d) << long(x); })
types_extrapolate_string_p(long variant::operator<<, { terrortrue(); return long(rval.d); })
long variant::operator<<(const variant x) EVCONST { terror2(real); return long(rval.d) << long(x.rval.d); }
long variant::operator<<(const var &x) EVCONST { return *this << *x; }
types_extrapolate_real_p (long variant::operator>>, { terror(real); return long(rval.d) >> long(x); })
types_extrapolate_string_p(long variant::operator>>, { terrortrue(); return long(rval.d); })
long variant::operator>>(const variant x) EVCONST { terror2(real); return long(rval.d) >> long(x.rval.d); }
long variant::operator>>(const var &x) EVCONST { return *this >> *x; }
types_extrapolate_real_p (long variant::operator&, { terror(real); return long(rval.d) & long(x); })
types_extrapolate_string_p(long variant::operator&, { terrortrue(); return long(rval.d); })
long variant::operator&(const variant x) EVCONST { terror2(real); return long(rval.d) & long(x.rval.d); }
long variant::operator&(const var &x) EVCONST { return *this & *x; }
types_extrapolate_real_p (long variant::operator|, { terror(real); return long(rval.d) | long(x); })
types_extrapolate_string_p(long variant::operator|, { terrortrue(); return long(rval.d);})
long variant::operator|(const variant x) EVCONST { terror2(real); return long(rval.d) | long(x.rval.d); }
long variant::operator|(const var &x) EVCONST { return *this | *x; }
types_extrapolate_real_p (long variant::operator^, { terror(real); return long(rval.d) ^ long(x); })
types_extrapolate_string_p(long variant::operator^, { terrortrue(); return long(rval.d); })
long variant::operator^(const variant x) EVCONST { terror2(real); return long(rval.d) ^ long(x.rval.d); }
long variant::operator^(const var &x) EVCONST { return *this ^ *x; }
// STANDARD: In all cases, string > real
types_extrapolate_real_p (bool variant::operator==, { return type == real and rval.d == x; })
types_extrapolate_string_p(bool variant::operator==, { return type == tstr and sval == x; })
bool variant::operator==(const variant &x) EVCONST { return type == x.type and ((x.type == real) ? rval.d == x.rval.d : sval == x.sval); }
//bool variant::operator==(const variant x) { return type == x.type and ((x.type == real) ? rval.d == x.rval.d : sval == x.sval); }
bool variant::operator==(const var &x) EVCONST { return *this == *x; }
types_extrapolate_real_p (bool variant::operator!=, { return type != real or rval.d != x; })
types_extrapolate_string_p(bool variant::operator!=, { return type != tstr or sval != x; })
bool variant::operator!=(const variant &x) EVCONST { return type != x.type or ((x.type == real) ? rval.d != x.rval.d : sval != x.sval); }
//bool variant::operator!=(const variant x) { return type != x.type or ((x.type == real) ? rval.d != x.rval.d : sval != x.sval); }
bool variant::operator!=(const var &x) EVCONST { return *this != *x; }
types_extrapolate_real_p (bool variant::operator>=, { return type != real or rval.d >= x; }) //type != real, then we're string and a priori greater.
types_extrapolate_string_p(bool variant::operator>=, { return type == tstr and sval >= x; }) //To be more, we must be string anyway.
bool variant::operator>=(const variant &x) EVCONST { return !(type < x.type) and (type > x.type or ((x.type == real) ? rval.d >= x.rval.d : sval >= x.sval)); }
//bool variant::operator>=(const variant x) { return !(type < x.type) and (type > x.type or ((x.type == real) ? rval.d >= x.rval.d : sval >= x.sval)); }
bool variant::operator>=(const var &x) EVCONST { return *this >= *x; }
types_extrapolate_real_p (bool variant::operator<=, { return type == real and rval.d <= x; }) //To be less, we must be real anyway.
types_extrapolate_string_p(bool variant::operator<=, { return type != tstr or sval <= x; }) //type != tstr, then we're real and a priori less.
bool variant::operator<=(const variant &x) EVCONST { return !(type > x.type) and (type < x.type or ((x.type == real) ? rval.d <= x.rval.d : sval <= x.sval)); }
//bool variant::operator<=(const variant x) { return !(type > x.type) and (type < x.type or ((x.type == real) ? rval.d <= x.rval.d : sval <= x.sval)); }
bool variant::operator<=(const var &x) EVCONST { return *this <= *x; }
types_extrapolate_real_p (bool variant::operator>, { return type != real or rval.d > x; }) //type != real, then we're string and a priori greater.
types_extrapolate_string_p(bool variant::operator>, { return type == tstr and sval > x; }) //To be more, we must be string anyway.
bool variant::operator>(const variant &x) EVCONST { return !(type < x.type) and (type > x.type or ((x.type == real) ? rval.d > x.rval.d : sval > x.sval)); }
//bool variant::operator>(const variant x) { return !(type < x.type) and (type > x.type or ((x.type == real) ? rval.d > x.rval.d : sval > x.sval)); }
bool variant::operator>(const var &x) EVCONST { return *this > *x; }
types_extrapolate_real_p (bool variant::operator<, { return type == real and rval.d < x; }) //To be less, we must be real anyway.
types_extrapolate_string_p(bool variant::operator<, { return type != tstr or sval < x; }) //type != tstr, then we're real and a priori less.
bool variant::operator<(const variant &x) EVCONST { return !(type > x.type) and (type < x.type or ((x.type == real) ? rval.d < x.rval.d : sval < x.sval)); }
//bool variant::operator<(const variant x) { return !(type > x.type) and (type < x.type or ((x.type == real) ? rval.d < x.rval.d : sval < x.sval)); }
bool variant::operator<(const var &x) EVCONST { return *this < *x; }
variant::~variant() { }
#undef EVCONST
#define EVCONST
/*
* Var implementation
*/
var::operator variant&() { return **this; }
var::operator const variant&() const { return **this; }
var::var() { initialize(); }
var::var(variant x) { initialize(); **this = x; }
types_extrapolate_real_p (var::var, { initialize(); **this = x; })
types_extrapolate_string_p(var::var, { initialize(); **this = x; })
var::operator int() { return int (**this); }
var::operator bool() { return bool (**this); }
var::operator char() { return char (**this); }
var::operator long() { return long (**this); }
var::operator short() { return short(**this); }
var::operator unsigned() { return (unsigned int) (**this); }
var::operator unsigned char() { return (unsigned char) (**this); }
var::operator unsigned short() { return (unsigned short) (**this); }
var::operator unsigned long() { return (unsigned long) (**this); }
var::operator unsigned long long() { return (unsigned long long) (**this); }
var::operator long long() { return (long long)(**this); }
var::operator double() { return double (**this); }
var::operator float() { return float (**this); }
var::operator string() { return string(**this); }
var::operator int() const { return int (**this); }
var::operator bool() const { return bool (**this); }
var::operator char() const { return char (**this); }
var::operator long() const { return long (**this); }
var::operator short() const { return short(**this); }
var::operator unsigned() const { return (unsigned int) (**this); }
var::operator unsigned char() const { return (unsigned char) (**this); }
var::operator unsigned short() const { return (unsigned short) (**this); }
var::operator unsigned long() const { return (unsigned long) (**this); }
var::operator unsigned long long() const { return (unsigned long long) (**this); }
var::operator long long() const { return (long long)(**this); }
var::operator double() const { return double (**this); }
var::operator float() const { return float (**this); }
var::operator string() const { return string(**this); }
types_extrapolate_real_p (variant& var::operator=, { return **this = x; })
types_extrapolate_string_p(variant& var::operator=, { return **this = x; })
variant& var::operator= (const variant x) { return **this = x; }
#define types_extrapolate_all_fromvariant(type, op)\
types_extrapolate_real_p (type var::operator op, { return **this op x; })\
types_extrapolate_string_p(type var::operator op, { return **this op x; })\
type var::operator op(const variant x) EVCONST { return **this op x; }\
type var::operator op(const var &x) EVCONST { return **this op *x; }
types_extrapolate_all_fromvariant(variant& , +=)
types_extrapolate_all_fromvariant(variant& , -=)
types_extrapolate_all_fromvariant(variant& , *=)
types_extrapolate_all_fromvariant(variant& , /=)
types_extrapolate_all_fromvariant(variant& , <<=)
types_extrapolate_all_fromvariant(variant& , >>=)
types_extrapolate_all_fromvariant(variant& , &=)
types_extrapolate_all_fromvariant(variant& , |=)
types_extrapolate_all_fromvariant(variant& , ^=)
#undef EVCONST
#define EVCONST const
types_extrapolate_all_fromvariant(variant , +)
types_extrapolate_all_fromvariant(double , -)
types_extrapolate_all_fromvariant(double , *)
types_extrapolate_all_fromvariant(double , /)
types_extrapolate_all_fromvariant(double , %)
types_extrapolate_all_fromvariant(long , <<)
types_extrapolate_all_fromvariant(long , >>)
types_extrapolate_all_fromvariant(long , &)
types_extrapolate_all_fromvariant(long , |)
types_extrapolate_all_fromvariant(long , ^)
#undef types_extrapolate_all_fromvariant
#define types_extrapolate_all_fromvariant(type, op)\
types_extrapolate_real_p (type var::operator op, { return **this op x; })\
types_extrapolate_string_p(type var::operator op, { return **this op x; })\
type var::operator op(const variant &x) const { return **this op x; }\
type var::operator op(const var &x) const { return **this op *x; }
types_extrapolate_all_fromvariant(bool , ==)
types_extrapolate_all_fromvariant(bool , !=)
types_extrapolate_all_fromvariant(bool , >=)
types_extrapolate_all_fromvariant(bool , <=)
types_extrapolate_all_fromvariant(bool , >)
types_extrapolate_all_fromvariant(bool , <)
#undef EVCONST
#define EVCONST
var::~var() { cleanup(); }
/*
This part is about ass-backwards. But we'll go along with it. For science. You monster.
*/
types_binary_assign_extrapolate_implement(+, const variant&, terror(real);)
types_binary_assign_extrapolate_implement(-, const variant&, terror(real);)
types_binary_assign_extrapolate_implement(*, const variant&, terror(real);)
types_binary_assign_extrapolate_implement(/, const variant&, terror(real);)
types_binary_bitwise_assign_extrapolate_implement(<<, const variant&, terror(real);)
types_binary_bitwise_assign_extrapolate_implement(>>, const variant&, terror(real);)
types_binary_bitwise_assign_extrapolate_implement(&, const variant&, terror(real);)
types_binary_bitwise_assign_extrapolate_implement(|, const variant&, terror(real);)
types_binary_bitwise_assign_extrapolate_implement(^, const variant&, terror(real);)
types_binary_extrapolate_real_p (double operator+, const variant&, { terror(real); return x + y.rval.d; })
types_binary_extrapolate_string_p(string operator+, const variant&, { terror(tstr); return x + y.sval; })
types_binary_extrapolate_real_p (double operator-, const variant&, { terror(real); return x - y.rval.d; })
types_binary_extrapolate_string_p(string operator-, const variant&, { terrortrue(); return 0; })
types_binary_extrapolate_real_p (double operator*, const variant&, { terror(real); return x * y.rval.d; })
types_binary_extrapolate_string_p(string operator*, const variant&, { terrortrue(); return 0; })
types_binary_extrapolate_real_p (double operator/, const variant&, { terror(real); div0c(y.rval.d); return x / y.rval.d; })
types_binary_extrapolate_string_p(string operator/, const variant&, { terrortrue(); return 0; })
types_binary_extrapolate_real_p (double operator%, const variant&, { terror(real); div0c(y.rval.d); return fmod(x, y.rval.d); })
types_binary_extrapolate_string_p(string operator%, const variant&, { terrortrue(); return 0; })
types_binary_bitwise_extrapolate_real_p(<<, const variant&, terror(real); )
//types_binary_extrapolate_string_p (string operator<<, const variant&, { terrortrue(); return 0; })
types_binary_bitwise_extrapolate_real_p(>>, const variant&, terror(real); )
//types_binary_extrapolate_string_p (string operator>>, const variant&, { terrortrue(); return 0; })
types_binary_bitwise_extrapolate_real_p(&, const variant&, terror(real); )
//types_binary_extrapolate_string_p (string operator&, const variant&, { terrortrue(); return 0; })
types_binary_bitwise_extrapolate_real_p(|, const variant&, terror(real); )
//types_binary_extrapolate_string_p (string operator|, const variant&, { terrortrue(); return 0; })
types_binary_bitwise_extrapolate_real_p(^, const variant&, terror(real); )
//types_binary_extrapolate_string_p (string operator^, const variant&, { terrortrue(); return 0; })
// I have no fucking idea why C++0x can't do this for me.
types_binary_extrapolate_real_p (bool operator==, const variant&, { return y == x; })
types_binary_extrapolate_string_p(bool operator==, const variant&, { return y == x; })
types_binary_extrapolate_real_p (bool operator!=, const variant&, { return y != x; })
types_binary_extrapolate_string_p(bool operator!=, const variant&, { return y != x; })
types_binary_extrapolate_real_p (bool operator>=, const variant&, { return y <= x; })
types_binary_extrapolate_string_p(bool operator>=, const variant&, { return y <= x; })
types_binary_extrapolate_real_p (bool operator<=, const variant&, { return y >= x; })
types_binary_extrapolate_string_p(bool operator<=, const variant&, { return y >= x; })
types_binary_extrapolate_real_p (bool operator>, const variant&, { return y < x; })
types_binary_extrapolate_string_p(bool operator>, const variant&, { return y < x; })
types_binary_extrapolate_real_p (bool operator<, const variant&, { return y > x; })
types_binary_extrapolate_string_p(bool operator<, const variant&, { return y > x; })
types_binary_assign_extrapolate_implement(+, const var&, )
types_binary_assign_extrapolate_implement(-, const var&, )
types_binary_assign_extrapolate_implement(*, const var&, )
types_binary_assign_extrapolate_implement(/, const var&, )
types_binary_bitwise_assign_extrapolate_implement(<<, const var&, )
types_binary_bitwise_assign_extrapolate_implement(>>, const var&, )
types_binary_bitwise_assign_extrapolate_implement(&, const var&, )
types_binary_bitwise_assign_extrapolate_implement(|, const var&, )
types_binary_bitwise_assign_extrapolate_implement(^, const var&, )
types_binary_extrapolate_real_p (double operator+, const var&, { return x + (*y).rval.d; })
types_binary_extrapolate_string_p(string operator+, const var&, { terror(tstr); return x + (*y).sval; })
types_binary_extrapolate_real_p (double operator-, const var&, { return x - (*y).rval.d; })
types_binary_extrapolate_string_p(string operator-, const var&, { terrortrue(); return 0; })
types_binary_extrapolate_real_p (double operator*, const var&, { return x * (*y).rval.d; })
types_binary_extrapolate_string_p(string operator*, const var&, { terrortrue(); return 0; })
types_binary_extrapolate_real_p (double operator/, const var&, { div0c((*y).rval.d); return x / (*y).rval.d; })
types_binary_extrapolate_string_p(string operator/, const var&, { terrortrue(); return 0; })
types_binary_extrapolate_real_p (double operator%, const var&, { div0c((*y).rval.d); return fmod(x, (*y).rval.d); })
types_binary_extrapolate_string_p(string operator%, const var&, { terrortrue(); return 0; })
types_binary_bitwise_extrapolate_real_p(<<, const var&, )
//types_binary_extrapolate_string_p (string operator<<, const var&, { terrortrue(); return 0; })
types_binary_bitwise_extrapolate_real_p(>>, const var&, )
//types_binary_extrapolate_string_p (string operator>>, const var&, { terrortrue(); return 0; })
types_binary_bitwise_extrapolate_real_p(&, const var&, )
//types_binary_extrapolate_string_p (string operator&, const var&, { terrortrue(); return 0; })
types_binary_bitwise_extrapolate_real_p(|, const var&, )
//types_binary_extrapolate_string_p (string operator|, const var&, { terrortrue(); return 0; })
types_binary_bitwise_extrapolate_real_p(^, const var&, )
//types_binary_extrapolate_string_p (string operator^, const var&, { terrortrue(); return 0; })
// I have no fucking idea why C++0x can't do this for me.
types_binary_extrapolate_real_p (bool operator==, const var&, { return y == x; })
types_binary_extrapolate_string_p(bool operator==, const var&, { return y == x; })
types_binary_extrapolate_real_p (bool operator!=, const var&, { return y != x; })
types_binary_extrapolate_string_p(bool operator!=, const var&, { return y != x; })
types_binary_extrapolate_real_p (bool operator>=, const var&, { return y <= x; })
types_binary_extrapolate_string_p(bool operator>=, const var&, { return y <= x; })
types_binary_extrapolate_real_p (bool operator<=, const var&, { return y >= x; })
types_binary_extrapolate_string_p(bool operator<=, const var&, { return y >= x; })
types_binary_extrapolate_real_p (bool operator>, const var&, { return y < x; })
types_binary_extrapolate_string_p(bool operator>, const var&, { return y < x; })
types_binary_extrapolate_real_p (bool operator<, const var&, { return y > x; })
types_binary_extrapolate_string_p(bool operator<, const var&, { return y > x; })
/*
Unary nonsense for either party
*/
char& variant::operator[] (int x) { return sval[x]; }
variant& variant::operator++ () { return ++rval.d, *this; }
double variant::operator++ (int) { return rval.d++; }
variant& variant::operator-- () { return --rval.d, *this; }
double variant::operator-- (int) { return rval.d--; }
variant& variant::operator* () { return *this; }
#undef EVCONST
#define EVCONST const
bool variant::operator! () EVCONST { return !bool(*this); }
long variant::operator~ () EVCONST { return ~long(*this); }
double variant::operator- () EVCONST { return -rval.d; }
double variant::operator+ () EVCONST { return rval.d; }
#undef EVCONST
#define EVCONST
// Same thing for var, other than dereference ops such as * and []: those are implementation specific.
// See var_lua.cpp for default sample.
variant& var::operator++ () { return ++(**this); }
double var::operator++ (int) { return (**this)++; }
variant& var::operator-- () { return --(**this); }
double var::operator-- (int) { return (**this)--; }
bool var::operator! () const { return !bool(**this); }
long var::operator~ () const { return ~long(**this); }
double var::operator- () const { return -(double)(**this); }
double var::operator+ () const { return +(double)(**this); }
#include <stdio.h>
#include "../libEGMstd.h"
string toString(const variant &a)
{
char buf[32];
if (a.type == real)
return string(buf,sprintf(buf,"%g",a.rval.d));
return a.sval;
}
string toString(const var &a) {
return toString(*a);
}
| [
"[email protected]"
]
| [
[
[
1,
480
]
]
]
|
94f455d2725109f45b59d9a22ea48254ce60f91b | 559770fbf0654bc0aecc0f8eb33843cbfb5834d9 | /haina/codes/beluga/client/moblie/3rdParty/libxml2-2.6.19/wince/libxml_ce/StdAfx.cpp | 2a32f87fbb9f049400f84f47054c6f2b97d68fb7 | [
"MIT",
"LicenseRef-scancode-x11-xconsortium-veillard"
]
| permissive | CMGeorge/haina | 21126c70c8c143ca78b576e1ddf352c3d73ad525 | c68565d4bf43415c4542963cfcbd58922157c51a | refs/heads/master | 2021-01-11T07:07:16.089036 | 2010-08-18T09:25:07 | 2010-08-18T09:25:07 | 49,005,284 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | // stdafx.cpp : source file that includes just the standard includes
// libxml_ce.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"shaochuan.yang@6c45ac76-16e4-11de-9d52-39b120432c5d"
]
| [
[
[
1,
8
]
]
]
|
4279112ecaeb5606ac76b72163f43a0ff35bf177 | 3182b05c41f13237825f1ee59d7a0eba09632cd5 | /T3D/gameConnectionEvents.cpp | 94f174b2828d4d8162232a8b2b9950205f892308 | []
| no_license | adhistac/ee-client-2-0 | 856e8e6ce84bfba32ddd8b790115956a763eec96 | d225fc835fa13cb51c3e0655cb025eba24a8cdac | refs/heads/master | 2021-01-17T17:13:48.618988 | 2010-01-04T17:35:12 | 2010-01-04T17:35:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,094 | cpp | //-----------------------------------------------------------------------------
// Torque 3D
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "core/dnet.h"
#include "core/stream/bitStream.h"
#include "console/consoleTypes.h"
#include "console/simBase.h"
#include "sceneGraph/pathManager.h"
#include "sceneGraph/sceneGraph.h"
#include "sfx/sfxSystem.h"
#include "app/game.h"
#include "T3D/gameConnection.h"
#include "T3D/gameConnectionEvents.h"
#define DebugChecksum 0xF00DBAAD
//--------------------------------------------------------------------------
IMPLEMENT_CO_CLIENTEVENT_V1(SimDataBlockEvent);
IMPLEMENT_CO_CLIENTEVENT_V1(Sim2DAudioEvent);
IMPLEMENT_CO_CLIENTEVENT_V1(Sim3DAudioEvent);
IMPLEMENT_CO_CLIENTEVENT_V1(SetMissionCRCEvent);
//----------------------------------------------------------------------------
SimDataBlockEvent::~SimDataBlockEvent()
{
delete mObj;
}
SimDataBlockEvent::SimDataBlockEvent(SimDataBlock* obj, U32 index, U32 total, U32 missionSequence)
{
mObj = NULL;
mIndex = index;
mTotal = total;
mMissionSequence = missionSequence;
mProcess = false;
if(obj)
{
id = obj->getId();
AssertFatal(id >= DataBlockObjectIdFirst && id <= DataBlockObjectIdLast,
"Out of range event data block id... check simBase.h");
// Con::printf("queuing data block: %d", mIndex);
}
}
#ifdef TORQUE_DEBUG_NET
const char *SimDataBlockEvent::getDebugName()
{
SimObject *obj = Sim::findObject(id);
static char buffer[256];
dSprintf(buffer, sizeof(buffer), "%s [%s - %s]",
getClassName(),
obj ? obj->getName() : "",
obj ? obj->getClassName() : "NONE");
return buffer;
}
#endif // TORQUE_DEBUG_NET
void SimDataBlockEvent::notifyDelivered(NetConnection *conn, bool )
{
// if the modified key for this event is not the current one,
// we've already resorted and resent some blocks, so fall out.
if(conn->isRemoved())
return;
GameConnection *gc = (GameConnection *) conn;
if(gc->getDataBlockSequence() != mMissionSequence)
return;
U32 nextIndex = mIndex + DataBlockQueueCount;
SimDataBlockGroup *g = Sim::getDataBlockGroup();
if(mIndex == g->size() - 1)
{
gc->setDataBlockModifiedKey(gc->getMaxDataBlockModifiedKey());
gc->sendConnectionMessage(GameConnection::DataBlocksDone, mMissionSequence);
}
if(g->size() <= nextIndex)
return;
SimDataBlock *blk = (SimDataBlock *) (*g)[nextIndex];
gc->postNetEvent(new SimDataBlockEvent(blk, nextIndex, g->size(), mMissionSequence));
}
void SimDataBlockEvent::pack(NetConnection *conn, BitStream *bstream)
{
#ifdef AFX_CAP_DATABLOCK_CACHE // AFX CODE BLOCK (db-cache) <<
((GameConnection *)conn)->tempDisableStringBuffering(bstream);
#endif // AFX CODE BLOCK (db-cache) >>
SimDataBlock* obj;
Sim::findObject(id,obj);
GameConnection *gc = (GameConnection *) conn;
if(bstream->writeFlag(gc->getDataBlockModifiedKey() < obj->getModifiedKey()))
{
if(obj->getModifiedKey() > gc->getMaxDataBlockModifiedKey())
gc->setMaxDataBlockModifiedKey(obj->getModifiedKey());
AssertFatal(obj,
"SimDataBlockEvent:: Data blocks cannot be deleted");
bstream->writeInt(id - DataBlockObjectIdFirst,DataBlockObjectIdBitSize);
S32 classId = obj->getClassId(conn->getNetClassGroup());
bstream->writeClassId(classId, NetClassTypeDataBlock, conn->getNetClassGroup());
bstream->writeInt(mIndex, DataBlockObjectIdBitSize);
bstream->writeInt(mTotal, DataBlockObjectIdBitSize + 1);
obj->packData(bstream);
#ifdef TORQUE_DEBUG_NET
bstream->writeInt(classId ^ DebugChecksum, 32);
#endif
}
#ifdef AFX_CAP_DATABLOCK_CACHE // AFX CODE BLOCK (db-cache) <<
((GameConnection *)conn)->restoreStringBuffering(bstream);
#endif // AFX CODE BLOCK (db-cache) >>
}
void SimDataBlockEvent::unpack(NetConnection *cptr, BitStream *bstream)
{
#ifdef AFX_CAP_DATABLOCK_CACHE // AFX CODE BLOCK (db-cache) <<
// stash the stream position prior to unpacking
S32 start_pos = bstream->getCurPos();
((GameConnection *)cptr)->tempDisableStringBuffering(bstream);
#endif // AFX CODE BLOCK (db-cache) >>
if(bstream->readFlag())
{
mProcess = true;
id = bstream->readInt(DataBlockObjectIdBitSize) + DataBlockObjectIdFirst;
S32 classId = bstream->readClassId(NetClassTypeDataBlock, cptr->getNetClassGroup());
mIndex = bstream->readInt(DataBlockObjectIdBitSize);
mTotal = bstream->readInt(DataBlockObjectIdBitSize + 1);
SimObject* ptr = (SimObject *) ConsoleObject::create(cptr->getNetClassGroup(), NetClassTypeDataBlock, classId);
if ((mObj = dynamic_cast<SimDataBlock*>(ptr)) != 0)
{
//Con::printf(" - SimDataBlockEvent: unpacking event of type: %s", mObj->getClassName());
mObj->unpackData(bstream);
}
else
{
//Con::printf(" - SimDataBlockEvent: INVALID PACKET! Could not create class with classID: %d", classId);
delete ptr;
cptr->setLastError("Invalid packet in SimDataBlockEvent::unpack()");
}
#ifdef TORQUE_DEBUG_NET
U32 checksum = bstream->readInt(32);
AssertISV( (checksum ^ DebugChecksum) == (U32)classId,
avar("unpack did not match pack for event of class %s.",
mObj->getClassName()) );
#endif
}
#ifdef AFX_CAP_DATABLOCK_CACHE // AFX CODE BLOCK (db-cache) <<
// rewind to stream position and then process raw bytes for caching
((GameConnection *)cptr)->repackClientDatablock(bstream, start_pos);
((GameConnection *)cptr)->restoreStringBuffering(bstream);
#endif // AFX CODE BLOCK (db-cache) >>
}
void SimDataBlockEvent::write(NetConnection *cptr, BitStream *bstream)
{
if(bstream->writeFlag(mProcess))
{
bstream->writeInt(id - DataBlockObjectIdFirst,DataBlockObjectIdBitSize);
S32 classId = mObj->getClassId(cptr->getNetClassGroup());
bstream->writeClassId(classId, NetClassTypeDataBlock, cptr->getNetClassGroup());
bstream->writeInt(mIndex, DataBlockObjectIdBitSize);
bstream->writeInt(mTotal, DataBlockObjectIdBitSize + 1);
mObj->packData(bstream);
}
}
void SimDataBlockEvent::process(NetConnection *cptr)
{
if(mProcess)
{
//call the console function to set the number of blocks to be sent
Con::executef("onDataBlockObjectReceived", Con::getIntArg(mIndex), Con::getIntArg(mTotal));
SimDataBlock* obj = NULL;
String &errorBuffer = NetConnection::getErrorBuffer();
if( Sim::findObject( id,obj ) && dStrcmp( obj->getClassName(),mObj->getClassName() ) == 0 )
{
U8 buf[1500];
BitStream stream(buf, 1500);
mObj->packData(&stream);
stream.setPosition(0);
obj->unpackData(&stream);
obj->preload(false, errorBuffer);
}
else
{
if( obj != NULL )
{
Con::warnf( "A '%s' datablock with id: %d already existed. "
"Clobbering it with new '%s' datablock from server.",
obj->getClassName(), id, mObj->getClassName() );
obj->deleteObject();
}
bool ret = mObj->registerObject(id);
if(ret)
{
cptr->addObject(mObj);
GameConnection *conn = dynamic_cast<GameConnection *>(cptr);
if(conn)
{
conn->preloadDataBlock(mObj);
mObj = NULL;
}
}
}
}
}
//----------------------------------------------------------------------------
Sim2DAudioEvent::Sim2DAudioEvent(SFXProfile *profile)
{
mProfile = profile;
}
void Sim2DAudioEvent::pack(NetConnection *, BitStream *bstream)
{
bstream->writeInt( mProfile->getId() - DataBlockObjectIdFirst, DataBlockObjectIdBitSize);
}
void Sim2DAudioEvent::write(NetConnection *, BitStream *bstream)
{
bstream->writeInt( mProfile->getId() - DataBlockObjectIdFirst, DataBlockObjectIdBitSize);
}
void Sim2DAudioEvent::unpack(NetConnection *, BitStream *bstream)
{
SimObjectId id = bstream->readInt(DataBlockObjectIdBitSize) + DataBlockObjectIdFirst;
Sim::findObject(id, mProfile);
}
void Sim2DAudioEvent::process(NetConnection *)
{
if (mProfile)
SFX->playOnce( mProfile );
}
//----------------------------------------------------------------------------
static F32 SoundPosAccuracy = 0.5;
static S32 SoundRotBits = 8;
Sim3DAudioEvent::Sim3DAudioEvent(SFXProfile *profile,const MatrixF* mat)
{
mProfile = profile;
if (mat)
mTransform = *mat;
}
void Sim3DAudioEvent::pack(NetConnection *con, BitStream *bstream)
{
bstream->writeInt(mProfile->getId() - DataBlockObjectIdFirst, DataBlockObjectIdBitSize);
// If the sound has cone parameters, the orientation is
// transmitted as well.
SFXDescription* ad = mProfile->getDescription();
if ( bstream->writeFlag( ad->mConeInsideAngle || ad->mConeOutsideAngle ) )
{
QuatF q(mTransform);
q.normalize();
// LH - we can get a valid quat that's very slightly over 1 in and so
// this fails (barely) check against zero. So use some error-
AssertFatal((1.0 - ((q.x * q.x) + (q.y * q.y) + (q.z * q.z))) >= (0.0 - 0.001),
"QuatF::normalize() is broken in Sim3DAudioEvent");
bstream->writeFloat(q.x,SoundRotBits);
bstream->writeFloat(q.y,SoundRotBits);
bstream->writeFloat(q.z,SoundRotBits);
bstream->writeFlag(q.w < 0.0);
}
Point3F pos;
mTransform.getColumn(3,&pos);
bstream->writeCompressedPoint(pos,SoundPosAccuracy);
}
void Sim3DAudioEvent::write(NetConnection *con, BitStream *bstream)
{
// Just do the normal pack...
pack(con,bstream);
}
void Sim3DAudioEvent::unpack(NetConnection *con, BitStream *bstream)
{
SimObjectId id = bstream->readInt(DataBlockObjectIdBitSize) + DataBlockObjectIdFirst;
Sim::findObject(id, mProfile);
if (bstream->readFlag()) {
QuatF q;
q.x = bstream->readFloat(SoundRotBits);
q.y = bstream->readFloat(SoundRotBits);
q.z = bstream->readFloat(SoundRotBits);
F32 value = ((q.x * q.x) + (q.y * q.y) + (q.z * q.z));
// #ifdef __linux
// Hmm, this should never happen, but it does...
if ( value > 1.f )
value = 1.f;
// #endif
q.w = mSqrt(1.f - value);
if (bstream->readFlag())
q.w = -q.w;
q.setMatrix(&mTransform);
}
else
mTransform.identity();
Point3F pos;
bstream->readCompressedPoint(&pos,SoundPosAccuracy);
mTransform.setColumn(3, pos);
}
void Sim3DAudioEvent::process(NetConnection *)
{
if (mProfile)
SFX->playOnce( mProfile, &mTransform );
}
| [
"[email protected]"
]
| [
[
[
1,
334
]
]
]
|
7fc3fa4e7364a52e6bcdd9a32cc18550b1773486 | d866ee0dee1e0db90bcfb6bb03b155411ace6db0 | /cob_common/canopen_motor/common/src/CanDriveHarmonica.cpp | 11969be95e3564113d225a5d03e085af7d97f20a | []
| no_license | Kuhn1981/care-o-bot | a0a31e8bbe8823f4dcfdeef3830eba777cd9987f | 2797166dd4252040b0f9dfa1918483956be4c2b7 | refs/heads/master | 2020-12-24T10:58:10.792578 | 2010-03-24T14:49:07 | 2010-03-24T14:49:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,377 | cpp | /****************************************************************
*
* Copyright (c) 2010
*
* Fraunhofer Institute for Manufacturing Engineering
* and Automation (IPA)
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Project name: care-o-bot
* ROS stack name: cob3_common
* ROS package name: canopen_motor
* Description:
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Author: Christian Connette, email:[email protected]
* Supervised by: Christian Connette, email:[email protected]
*
* Date of creation: Feb 2009
* ToDo: - Assign Adsress of digital input for homing switch "iHomeDigIn" via parameters (in evalReceived Message, Line 116).
* - Homing Event should be defined by a parameterfile and handed to CanDrive... e.g. via the DriveParam.h (in inithoming, Line 531).
* - Check whether "requestStatus" can/should be done in the class implementing the component
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* 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 Fraunhofer Institute for Manufacturing
* Engineering and Automation (IPA) nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL 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 Lesser General Public License LGPL for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************/
#include <assert.h>
#include <canopen_motor/CanDriveHarmonica.h>
//-----------------------------------------------
CanDriveHarmonica::CanDriveHarmonica()
{
// Parameter
m_Param.iDivForRequestStatus = 10;
m_Param.dCanTimeout = 6;
// Variables
m_pCanCtrl = NULL;
m_iStatusCtrl = 0;
m_dPosGearMeasRad = 0;
m_dAngleGearRadMem = 0;
m_dVelGearMeasRadS = 0;
m_VelCalcTime.SetNow();
m_bLimSwLeft = false;
m_bLimSwRight = false;
m_bLimitSwitchEnabled = false;
m_iCountRequestDiv = 0;
m_iMotorState = ST_PRE_INITIALIZED;
m_bCurrentLimitOn = false;
m_iNumAttempsRecFail = 0;
m_SendTime.SetNow();
m_StartTime.SetNow();
m_bOutputOfFailure = false;
m_bIsInitialized = false;
}
//-----------------------------------------------
void CanDriveHarmonica::setCanOpenParam( int iTxPDO1, int iTxPDO2, int iRxPDO2, int iTxSDO, int iRxSDO )
{
m_ParamCanOpen.iTxPDO1 = iTxPDO1;
m_ParamCanOpen.iTxPDO2 = iTxPDO2;
m_ParamCanOpen.iRxPDO2 = iRxPDO2;
m_ParamCanOpen.iTxSDO = iTxSDO;
m_ParamCanOpen.iRxSDO = iRxSDO;
}
//-----------------------------------------------
bool CanDriveHarmonica::evalReceivedMsg(CanMsg& msg)
{
bool bRet = false;
int iDigIn;
int iFailure;
int iPara;
int iHomeDigIn = 0x0001; // 0x0001 for CoB3 steering drive homing input; 0x0400 for Scara
int iTemp1, iTemp2;
m_CanMsgLast = msg;
//-----------------------
// eval answers from PDO1 - transmitted on SYNC msg
if (msg.m_iID == m_ParamCanOpen.iTxPDO1)
{
iTemp1 = (msg.getAt(3) << 24) | (msg.getAt(2) << 16)
| (msg.getAt(1) << 8) | (msg.getAt(0) );
m_dPosGearMeasRad = m_DriveParam.getSign() * m_DriveParam.
PosMotIncrToPosGearRad(iTemp1);
iTemp2 = (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4) );
m_dVelGearMeasRadS = m_DriveParam.getSign() * m_DriveParam.
VelMotIncrPeriodToVelGearRadS(iTemp2);
m_WatchdogTime.SetNow();
}
//-----------------------
// eval answers from binary interpreter
if (msg.m_iID == m_ParamCanOpen.iTxPDO2)
{
if( (msg.getAt(0) == 'P') && (msg.getAt(1) == 'X') ) // current pos
{
}
else if( (msg.getAt(0) == 'P') && (msg.getAt(1) == 'A') ) // position absolute
{
}
else if( (msg.getAt(0) == 'J') && (msg.getAt(1) == 'V') ) // current velocity
{
}
else if( (msg.getAt(0) == 'B') && (msg.getAt(1) == 'G') ) // begin motion
{
}
else if( (msg.getAt(0) == 'U') && (msg.getAt(1) == 'M') ) // user mode
{
iDigIn = 0x1FFFFF & ( (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4)) );
}
else if( (msg.getAt(0) == 'I') && (msg.getAt(1) == 'P') ) // digital in == limit switches
{
iDigIn = 0x1FFFFF & ( (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4)) );
iDigIn = 0x1FFFFF & ( (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4)) );
if( (iDigIn & iHomeDigIn) != 0x0000 )
{
m_bLimSwRight = true;
}
}
else if( (msg.getAt(0) == 'S') && (msg.getAt(1) == 'R') ) // status
{
m_iStatusCtrl = (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4) );
evalStatusRegister(m_iStatusCtrl);
}
else if( (msg.getAt(0) == 'M') && (msg.getAt(1) == 'F') ) // motor failure
{
iFailure = (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4) );
evalMotorFailure(iFailure);
}
// debug eval
else if( (msg.getAt(0) == 'U') && (msg.getAt(1) == 'M') )
{
iPara = (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4) );
std::cout << "um " << iPara << std::endl;
}
else if( (msg.getAt(0) == 'P') && (msg.getAt(1) == 'M') )
{
iPara = (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4) );
std::cout << "pm " << iPara << std::endl;
}
else if( (msg.getAt(0) == 'A') && (msg.getAt(1) == 'C') )
{
iPara = (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4) );
std::cout << "ac " << iPara << std::endl;
}
else if( (msg.getAt(0) == 'D') && (msg.getAt(1) == 'C') )
{
iPara = (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4) );
std::cout << "dc " << iPara << std::endl;
}
else if( (msg.getAt(0) == 'H') && (msg.getAt(1) == 'M') )
{
// status message (homing armed = 1 / disarmed = 0) is encoded in 5th byte
if(msg.getAt(4) == 0)
{
// if 0 received: elmo disarmed homing after receiving the defined event
m_bLimSwRight = true;
}
}
else if( (msg.getAt(0) == 'I') && (msg.getAt(1) == 'Q') )
{
int iVal=0;
iVal = (msg.getAt(7) << 24) | (msg.getAt(6) << 16)
| (msg.getAt(5) << 8) | (msg.getAt(4) );
float* pfVal;
pfVal=(float*)&iVal;
m_dMotorCurr = *pfVal;
}
else
{
}
m_WatchdogTime.SetNow();
bRet = true;
}
//-----------------------
// eval answer from SDO
if (msg.m_iID == m_ParamCanOpen.iTxSDO)
{
m_WatchdogTime.SetNow();
bRet = true;
}
return bRet;
}
//-----------------------------------------------
bool CanDriveHarmonica::init()
{
int iCnt, iPosCnt;
bool bRet = true;
CanMsg Msg;
m_iMotorState = ST_PRE_INITIALIZED;
// Set Values for Modulo-Counting. Neccessary to preserve absolute position for homed motors (after encoder overflow)
int iIncrRevWheel = int( (double)m_DriveParam.getGearRatio() * (double)m_DriveParam.getBeltRatio()
* (double)m_DriveParam.getEncIncrPerRevMot() * 3 );
IntprtSetInt(8, 'M', 'O', 0, 0);
usleep(20000);
IntprtSetInt(8, 'X', 'M', 2, iIncrRevWheel * 5000);
usleep(20000);
IntprtSetInt(8, 'X', 'M', 1, -iIncrRevWheel * 5000);
usleep(20000);
setTypeMotion(MOTIONTYPE_VELCTRL);
// ---------- set position counter to zero
IntprtSetInt(8, 'P', 'X', 0, 0);
iCnt = 0;
while(true)
{
m_pCanCtrl->receiveMsg(&Msg);
if( (Msg.getAt(0) == 'P') && (Msg.getAt(1) == 'X') )
{
iPosCnt = (Msg.getAt(7) << 24) | (Msg.getAt(6) << 16)
| (Msg.getAt(5) << 8) | (Msg.getAt(4) );
m_dPosGearMeasRad = m_DriveParam.getSign() * m_DriveParam.PosMotIncrToPosGearRad(iPosCnt);
m_dAngleGearRadMem = m_dPosGearMeasRad;
break;
}
if ( iCnt > 300 )
{
std::cout << "CanDriveHarmonica: initial position not set" << std::endl;
bRet = false;
break;
}
usleep(10000);
iCnt++;
}
// ---------- set PDO mapping
// Mapping of TPDO1:
// - position
// - velocity
// stop all emissions of TPDO1
sendSDODownload(0x1A00, 0, 0);
// position 4 byte of TPDO1
sendSDODownload(0x1A00, 1, 0x60640020);
// velocity 4 byte of TPDO1
sendSDODownload(0x1A00, 2, 0x60690020);
// transmission type "synch"
sendSDODownload(0x1800, 2, 1);
// activate mapped objects
sendSDODownload(0x1A00, 0, 2);
m_bWatchdogActive = false;
if( bRet )
m_bIsInitialized = true;
return bRet;
}
//-----------------------------------------------
bool CanDriveHarmonica::stop()
{
bool bRet = true;
// motor off
IntprtSetInt(8, 'M', 'O', 0, 0);
usleep(20000);
return bRet;
}
//-----------------------------------------------
bool CanDriveHarmonica::start()
{
// motor on
IntprtSetInt(8, 'M', 'O', 0, 1);
usleep(20000);
// ------------------- request status
int iCnt;
bool bRet = true;
int iStatus;
CanMsg Msg;
// clear the can buffer
do
{
bRet = m_pCanCtrl->receiveMsg(&Msg);
}
while(bRet == true);
// send request
IntprtSetInt(4, 'S', 'R', 0, 0);
iCnt = 0;
while(true)
{
m_pCanCtrl->receiveMsg(&Msg);
if( (Msg.getAt(0) == 'S') && (Msg.getAt(1) == 'R') )
{
iStatus = (Msg.getAt(7) << 24) | (Msg.getAt(6) << 16)
| (Msg.getAt(5) << 8) | (Msg.getAt(4) );
bRet = evalStatusRegister(iStatus);
break;
}
if ( iCnt > 300 )
{
std::cout << "CanDriveHarmonica::enableMotor(): No answer on status request" << std::endl;
bRet = false;
break;
}
usleep(10000);
iCnt++;
}
// ------------------- start watchdog timer
m_WatchdogTime.SetNow();
m_SendTime.SetNow();
return bRet;
}
//-----------------------------------------------
bool CanDriveHarmonica::reset()
{
// repeat initialization
// start network
CanMsg msg;
msg.m_iID = 0;
msg.m_iLen = 2;
msg.set(1,0,0,0,0,0,0,0);
m_pCanCtrl->transmitMsg(msg);
// init and start
bool bRet = init();
bRet |= start();
return bRet;
}
//-----------------------------------------------
bool CanDriveHarmonica::shutdown()
{
std::cout << "shutdown drive " << m_DriveParam.getDriveIdent() << std::endl;
IntprtSetInt(8, 'M', 'O', 0, 0);
return true;
}
//-----------------------------------------------
bool CanDriveHarmonica::startWatchdog(bool bStarted)
{
if (bStarted == true)
{
//save Watchdog state into member variable
m_bWatchdogActive = true;
// ------- init watchdog
// Harmonica checks PC hearbeat
// note: the COB-ID for a heartbeat message = 0x700 + Device ID
const int c_iHeartbeatTimeMS = 1000;
const int c_iNMTNodeID = 0x00;
// consumer (PC) heartbeat time
sendSDODownload(0x1016, 1, (c_iNMTNodeID << 16) | c_iHeartbeatTimeMS);
// error behavior after failure: 0=pre-operational, 1=no state change, 2=stopped"
sendSDODownload(0x1029, 1, 2);
// motor behavior after heartbeat failre: "quick stop"
sendSDODownload(0x6007, 0, 3);
// acivate emergency events: "heartbeat event"
// Object 0x2F21 = "Emergency Events" which cause an Emergency Message
// Bit 3 is responsible for Heartbeart-Failure.--> Hex 0x08
sendSDODownload(0x2F21, 0, 0x08);
usleep(20000);
}
else
{
//save Watchdog state into member variable
m_bWatchdogActive = false;
//Motor action after Hearbeat-Error: No Action
sendSDODownload(0x6007, 0, 0);
//Error Behavior: No state change
sendSDODownload(0x1029, 1, 1);
// Deacivate emergency events: "heartbeat event"
// Object 0x2F21 = "Emergency Events" which cause an Emergency Message
// Bit 3 is responsible for Heartbeart-Failure.
sendSDODownload(0x2F21, 0, 0x00);
usleep(25000);
}
return true;
}
//-----------------------------------------------
bool CanDriveHarmonica::disableBrake(bool bDisabled)
{
return true;
}
//-----------------------------------------------
double CanDriveHarmonica::getTimeToLastMsg()
{
m_CurrentTime.SetNow();
return m_CurrentTime - m_WatchdogTime;
}
//-----------------------------------------------
bool CanDriveHarmonica::getStatusLimitSwitch()
{
return m_bLimSwRight;
}
//-----------------------------------------------
bool CanDriveHarmonica::initHoming()
{
const int c_iPosRef = m_DriveParam.getEncOffset();
// 1. make sure that, if on elmo controller still a pending homing from a previous startup is running (in case of warm-start without switching of the whole robot), this old sequence is disabled
// disarm homing process
IntprtSetInt(8, 'H', 'M', 1, 0);
// always give can and controller some time to understand the command
usleep(20000);
// 2. configure the homing sequence
// 2.a set the value to which the increment counter shall be reseted as soon as the homing event occurs
// value to load at homing event
IntprtSetInt(8, 'H', 'M', 2, c_iPosRef);
usleep(20000);
// 2.b choose the chanel/switch on which the controller listens for a change or defined logic level (the homing event) (high/low/falling/rising)
// home event
// iHomeEvent = 5 : event according to defined FLS switch (for scara arm)
// iHomeEvent = 9 : event according to definded DIN1 switch (for full steerable wheels COb3)
// ToDo: this should be defined by a parameterfile and handed to CanDrive... e.g. via the DriveParam.h
IntprtSetInt(8, 'H', 'M', 3, 9);
usleep(20000);
// 2.c choose the action that the controller shall perform after the homing event occured
// HM[4] = 0 : after Event stop immediately
// HM[4] = 2 : Do nothing!
IntprtSetInt(8, 'H', 'M', 4, 2);
usleep(20000);
// 2.d choose the setting of the position counter (i.e. to the value defined in 2.a) after the homing event occured
// HM[5] = 0 : absolute setting of position counter: PX = HM[2]
IntprtSetInt(8, 'H', 'M', 5, 0);
usleep(20000);
// 3. let the motor turn some time to give him the possibility to escape the approximation sensor if accidently in home position already at the beginning of the sequence (done in CanCtrlPltf...)
return true;
}
//-----------------------------------------------
bool CanDriveHarmonica::execHoming()
{
int iCnt;
CanMsg Msg;
bool bRet = true;
int iNrDrive = m_DriveParam.getDriveIdent();
// 4. arm the homing process -> as soon as the approximation sensor is reached and the homing event occurs the commands set in 2. take effect
// arm homing process
IntprtSetInt(8, 'H', 'M', 1, 1);
// 5. clear the can buffer to get rid of all uneccessary and potentially disturbing commands still floating through the wires
do
{
// read from can
bRet = m_pCanCtrl->receiveMsg(&Msg);
}
while(bRet == true);
// 6. now listen for status of homing, to synchronize program flow -> proceed only after homing was succesful (homing disarmed by elmo) or timeout occured
// set timeout counter to zero
iCnt = 0;
do
{
// 6.a ask for status of homing process (armed/disarmed)
// ask for first byte in Homing Configuration
IntprtSetInt(4, 'H', 'M', 1, 0);
// 6.b read message from can
m_pCanCtrl->receiveMsgRetry(&Msg, 10);
// 6.c see if received message is answer of request and if so what is the status
if( (Msg.getAt(0) == 'H') && (Msg.getAt(1) == 'M') )
{
// status message (homing armed = 1 / disarmed = 0) is encoded in 5th byte
if(Msg.getAt(4) == 0)
{
// if 0 received: elmo disarmed homing after receiving the defined event
m_bLimSwRight = true;
break;
}
}
// increase count for timeout
usleep(10000);
iCnt++;
}
while((m_bLimSwRight == false) && (iCnt<1000)); // wait some time
// 7. see why finished (homed or timeout) and log out
if(iCnt>=1000)
{
std::cout << "Homing failed - limit switch " << iNrDrive << " not reached" << std::endl;
}
else
{
std::cout << "Homing successful - limit switch " << iNrDrive << " ok" << std::endl;
}
return true;
}
//-----------------------------------------------
void CanDriveHarmonica::setGearPosVelRadS(double dPosGearRad, double dVelGearRadS)
{
int iPosEncIncr;
int iVelEncIncrPeriod;
m_DriveParam.PosVelRadToIncr(dPosGearRad, dVelGearRadS, &iPosEncIncr, &iVelEncIncrPeriod);
if(iVelEncIncrPeriod > m_DriveParam.getVelMax())
{
iVelEncIncrPeriod = (int)m_DriveParam.getVelMax();
}
if(iVelEncIncrPeriod < -m_DriveParam.getVelMax())
{
iVelEncIncrPeriod = (int)-m_DriveParam.getVelMax();
}
if(m_iTypeMotion == MOTIONTYPE_POSCTRL)
{
//new: set VELOCITY for PTP Motion
IntprtSetInt(8, 'S', 'P', 0, iVelEncIncrPeriod);
// Position Relativ ("PR") , because of positioning of driving wheel
// which is not initialized to zero on a specific position
// only when command is for homed steering wheel set absolute
if (m_DriveParam.getIsSteer() == true)
IntprtSetInt(8, 'P', 'A', 0, iPosEncIncr);
else
IntprtSetInt(8, 'P', 'R', 0, iPosEncIncr);
IntprtSetInt(4, 'B', 'G', 0, 0);
}
if(m_iTypeMotion == MOTIONTYPE_VELCTRL)
{
iVelEncIncrPeriod *= m_DriveParam.getSign();
IntprtSetInt(8, 'J', 'V', 0, iVelEncIncrPeriod);
IntprtSetInt(4, 'B', 'G', 0, 0);
}
// request pos and vel by TPDO1, triggered by SYNC msg
// (to request pos by SDO usesendSDOUpload(0x6064, 0) )
CanMsg msg;
msg.m_iID = 0x80;
msg.m_iLen = 0;
msg.set(0,0,0,0,0,0,0,0);
m_pCanCtrl->transmitMsg(msg);
}
//-----------------------------------------------
void CanDriveHarmonica::setGearVelRadS(double dVelGearRadS)
{
int iVelEncIncrPeriod;
// calc motor velocity from joint velocity
iVelEncIncrPeriod = m_DriveParam.getSign() * m_DriveParam.VelGearRadSToVelMotIncrPeriod(dVelGearRadS);
if(iVelEncIncrPeriod > m_DriveParam.getVelMax())
{
std::cout << "SteerVelo asked for " << iVelEncIncrPeriod << " EncIncrements" << std::endl;
iVelEncIncrPeriod = (int)m_DriveParam.getVelMax();
}
if(iVelEncIncrPeriod < -m_DriveParam.getVelMax())
{
std::cout << "SteerVelo asked for " << iVelEncIncrPeriod << " EncIncrements" << std::endl;
iVelEncIncrPeriod = -1 * (int)m_DriveParam.getVelMax();
}
IntprtSetInt(8, 'J', 'V', 0, iVelEncIncrPeriod);
IntprtSetInt(4, 'B', 'G', 0, 0);
// request pos and vel by TPDO1, triggered by SYNC msg
// (to request pos by SDO use sendSDOUpload(0x6064, 0) )
// sync msg is: iID 0x08 with msg (0,0,0,0,0,0,0,0)
CanMsg msg;
msg.m_iID = 0x80;
msg.m_iLen = 0;
msg.set(0,0,0,0,0,0,0,0);
m_pCanCtrl->transmitMsg(msg);
// send heartbeat to keep watchdog inactive
msg.m_iID = 0x700;
msg.m_iLen = 5;
msg.set(0x00,0,0,0,0,0,0,0);
m_pCanCtrl->transmitMsg(msg);
m_CurrentTime.SetNow();
double dt = m_CurrentTime - m_SendTime;
if ((dt > 1.0) && m_bWatchdogActive)
{
std::cout << "Time between send velocity of motor " << m_DriveParam.getDriveIdent()
<< " is too large: " << dt << " s" << std::endl;
}
m_SendTime.SetNow();
// request status
m_iCountRequestDiv++;
if (m_iCountRequestDiv > m_Param.iDivForRequestStatus)
{
requestStatus();
m_iCountRequestDiv = 0;
}
}
//-----------------------------------------------
void CanDriveHarmonica::getGearPosRad(double* dGearPosRad)
{
*dGearPosRad = m_dPosGearMeasRad;
}
//-----------------------------------------------
void CanDriveHarmonica::getGearPosVelRadS(double* pdAngleGearRad, double* pdVelGearRadS)
{
*pdAngleGearRad = m_dPosGearMeasRad;
*pdVelGearRadS = m_dVelGearMeasRadS;
}
//-----------------------------------------------
void CanDriveHarmonica::getGearDeltaPosVelRadS(double* pdAngleGearRad, double* pdVelGearRadS)
{
*pdAngleGearRad = m_dPosGearMeasRad - m_dAngleGearRadMem;
*pdVelGearRadS = m_dVelGearMeasRadS;
m_dAngleGearRadMem = m_dPosGearMeasRad;
}
//-----------------------------------------------
void CanDriveHarmonica::getData(double* pdPosGearRad, double* pdVelGearRadS,
int* piTorqueCtrl, int* piStatusCtrl)
{
*pdPosGearRad = m_dPosGearMeasRad;
*pdVelGearRadS = m_dVelGearMeasRadS;
*piTorqueCtrl = m_iTorqueCtrl;
*piStatusCtrl = m_iStatusCtrl;
}
//-----------------------------------------------
void CanDriveHarmonica::requestPosVel()
{
// request pos and vel by TPDO1, triggered by SYNC msg
CanMsg msg;
msg.m_iID = 0x80;
msg.m_iLen = 0;
msg.set(0,0,0,0,0,0,0,0);
m_pCanCtrl->transmitMsg(msg);
// (to request pos by SDO use sendSDOUpload(0x6064, 0) )
}
//-----------------------------------------------
void CanDriveHarmonica::requestStatus()
{
IntprtSetInt(4, 'S', 'R', 0, 0);
}
//-----------------------------------------------
void CanDriveHarmonica::requestMotorTorque()
{
// send command for requesting motor current:
IntprtSetInt(4, 'I', 'Q', 0, 0); // active current
//IntprtSetInt(4, 'I', 'D', 0, 0); // reactive current
}
//-----------------------------------------------
bool CanDriveHarmonica::isError()
{
if (m_iMotorState != ST_MOTOR_FAILURE)
{
// Check timeout of can communication
double dWatchTime = getTimeToLastMsg();
if (dWatchTime>m_Param.dCanTimeout)
{
if ( m_bOutputOfFailure == false)
{
std::cout << "Motor " << m_DriveParam.getDriveIdent() <<
" has no can communiction for " << dWatchTime << " s." << std::endl;
}
m_iMotorState = ST_MOTOR_FAILURE;
m_FailureStartTime.SetNow();
}
}
return (m_iMotorState == ST_MOTOR_FAILURE);
}
//-----------------------------------------------
bool CanDriveHarmonica::setTypeMotion(int iType)
{
int iMaxAcc = int(m_DriveParam.getMaxAcc());
int iMaxDcc = int(m_DriveParam.getMaxDec());
CanMsg Msg;
if (iType == MOTIONTYPE_POSCTRL)
{
// 1.) Switch to UnitMode = 5 (Single Loop Position Control) //
// switch off Motor to change Unit-Mode
IntprtSetInt(8, 'M', 'O', 0, 0);
usleep(20000);
// switch Unit-Mode
IntprtSetInt(8, 'U', 'M', 0, 5);
// set Target Radius to X Increments
IntprtSetInt(8, 'T', 'R', 1, 15);
// set Target Time to X ms
IntprtSetInt(8, 'T', 'R', 2, 100);
// set maximum Acceleration to X Incr/s^2
IntprtSetInt(8, 'A', 'C', 0, iMaxAcc);
// set maximum decceleration to X Incr/s^2
IntprtSetInt(8, 'D', 'C', 0, iMaxDcc);
usleep(100000);
}
else if (iType == MOTIONTYPE_TORQUECTRL)
{
// Switch to TorqueControll-Mode
// switch off Motor to change Unit-Mode
IntprtSetInt(8, 'M', 'O', 0, 0);
usleep(50000);
// switch Unit-Mode 1: Torque Controlled
IntprtSetInt(8, 'U', 'M', 0, 1);
// disable external compensation input
// to avoid noise from that input pin
IntprtSetInt(8, 'R', 'M', 0, 0);
// debugging:
std::cout << "Motor"<<m_DriveParam.getDriveIdent()<<" Unit Mode switched to: TORQUE controlled" << std::endl;
usleep(100000);
}
else
{
//Default Motion Type = VelocityControled
// switch off Motor to change Unit-Mode
IntprtSetInt(8, 'M', 'O', 0, 0);
// switch Unit-Mode
IntprtSetInt(8, 'U', 'M', 0, 2);
// set profiler Mode (only if Unit Mode = 2)
IntprtSetInt(8, 'P', 'M', 0, 1);
// set maximum Acceleration to X Incr/s^2
IntprtSetInt(8, 'A', 'C', 0, iMaxAcc);
// set maximum decceleration to X Incr/s^2
IntprtSetInt(8, 'D', 'C', 0, iMaxDcc);
usleep(100000);
}
m_iTypeMotion = iType;
return true;
}
//-----------------------------------------------
void CanDriveHarmonica::IntprtSetInt(int iDataLen, char cCmdChar1, char cCmdChar2, int iIndex, int iData)
{
char cIndex[2];
char cInt[4];
CanMsg CMsgTr;
CMsgTr.m_iID = m_ParamCanOpen.iRxPDO2;
CMsgTr.m_iLen = iDataLen;
cIndex[0] = iIndex;
cIndex[1] = (iIndex >> 8) & 0x3F; // The two MSB must be 0. Cf. DSP 301 Implementation guide p. 39.
cInt[0] = iData;
cInt[1] = iData >> 8;
cInt[2] = iData >> 16;
cInt[3] = iData >> 24;
CMsgTr.set(cCmdChar1, cCmdChar2, cIndex[0], cIndex[1], cInt[0], cInt[1], cInt[2], cInt[3]);
m_pCanCtrl->transmitMsg(CMsgTr);
}
//-----------------------------------------------
void CanDriveHarmonica::IntprtSetFloat(int iDataLen, char cCmdChar1, char cCmdChar2, int iIndex, float fData)
{
char cIndex[2];
char cFloat[4];
CanMsg CMsgTr;
char* pTempFloat = NULL;
CMsgTr.m_iID = m_ParamCanOpen.iRxPDO2;
CMsgTr.m_iLen = iDataLen;
cIndex[0] = iIndex;
// for sending float values bit 6 has to be zero and bit 7 one (according to Elmo Implementation guide)
cIndex[1] = (iIndex >> 8) & 0x3F; // setting bit 6 to zero with mask 0b10111111->0xBF
cIndex[1] = cIndex[1] | 0x80; // setting bit 7 to one with mask 0b10000000 ->0x80
pTempFloat = (char*)&fData;
for( int i=0; i<4; i++ )
cFloat[i] = pTempFloat[i];
CMsgTr.set(cCmdChar1, cCmdChar2, cIndex[0], cIndex[1], cFloat[0], cFloat[1], cFloat[2], cFloat[3]);
m_pCanCtrl->transmitMsg(CMsgTr);
}
//-----------------------------------------------
void CanDriveHarmonica::sendSDOUpload(int iObjIndex, int iObjSubIndex)
{
CanMsg CMsgTr;
const int ciInitUploadReq = 0x40;
CMsgTr.m_iLen = 8;
CMsgTr.m_iID = m_ParamCanOpen.iRxSDO;
unsigned char cMsg[8];
cMsg[0] = ciInitUploadReq;
cMsg[1] = iObjIndex;
cMsg[2] = iObjIndex >> 8;
cMsg[3] = iObjSubIndex;
cMsg[4] = 0x00;
cMsg[5] = 0x00;
cMsg[6] = 0x00;
cMsg[7] = 0x00;
CMsgTr.set(cMsg[0], cMsg[1], cMsg[2], cMsg[3], cMsg[4], cMsg[5], cMsg[6], cMsg[7]);
m_pCanCtrl->transmitMsg(CMsgTr);
}
//-----------------------------------------------
void CanDriveHarmonica::sendSDODownload(int iObjIndex, int iObjSubIndex, int iData)
{
CanMsg CMsgTr;
const int ciInitDownloadReq = 0x20;
const int ciNrBytesNoData = 0x00;
const int ciExpedited = 0x02;
const int ciDataSizeInd = 0x01;
CMsgTr.m_iLen = 8;
CMsgTr.m_iID = m_ParamCanOpen.iRxSDO;
unsigned char cMsg[8];
cMsg[0] = ciInitDownloadReq | (ciNrBytesNoData << 2) | ciExpedited | ciDataSizeInd;
cMsg[1] = iObjIndex;
cMsg[2] = iObjIndex >> 8;
cMsg[3] = iObjSubIndex;
cMsg[4] = iData;
cMsg[5] = iData >> 8;
cMsg[6] = iData >> 16;
cMsg[7] = iData >> 24;
CMsgTr.set(cMsg[0], cMsg[1], cMsg[2], cMsg[3], cMsg[4], cMsg[5], cMsg[6], cMsg[7]);
m_pCanCtrl->transmitMsg(CMsgTr);
}
//-----------------------------------------------
void CanDriveHarmonica::evalSDO(CanMsg& CMsg, int* pIndex, int* pSubindex)
{
*pIndex = (CMsg.getAt(2) << 8) | CMsg.getAt(1);
*pSubindex = CMsg.getAt(3);
}
//-----------------------------------------------
int CanDriveHarmonica::getSDODataInt32(CanMsg& CMsg)
{
int iData = (CMsg.getAt(7) << 24) | (CMsg.getAt(6) << 16) |
(CMsg.getAt(5) << 8) | CMsg.getAt(4);
return iData;
}
//-----------------------------------------------
double CanDriveHarmonica::estimVel(double dPos)
{
double dVel;
double dt;
m_CurrentTime.SetNow();
dt = m_CurrentTime - m_VelCalcTime;
dVel = (dPos - m_dOldPos)/dt;
m_dOldPos = dPos;
m_VelCalcTime.SetNow();
return dVel;
}
//-----------------------------------------------
bool CanDriveHarmonica::evalStatusRegister(int iStatus)
{
bool bNoError;
// --------- Error status
if( isBitSet(iStatus, 0) )
{
// ------------ Error
if ( m_bOutputOfFailure == false )
{
std::cout << "Error of drive: " << m_DriveParam.getDriveIdent() << std::endl;
if( (iStatus & 0x0000000E) == 2)
std::cout << "- drive error under voltage" << std::endl;
if( (iStatus & 0x0000000E) == 4)
std::cout << "- drive error over voltage" << std::endl;
if( (iStatus & 0x0000000E) == 10)
std::cout << "- drive error short circuit" << std::endl;
if( (iStatus & 0x0000000E) == 12)
std::cout << "- drive error overheating" << std::endl;
// Request detailed description of failure
IntprtSetInt(4, 'M', 'F', 0, 0);
}
m_iNewMotorState = ST_MOTOR_FAILURE;
bNoError = false;
}
else if ( isBitSet(iStatus, 6) )
{
// General failure
if ( m_bOutputOfFailure == false )
{
std::cout << "Motor " << m_DriveParam.getDriveIdent() << " failure latched" << std::endl;
// Request detailed description of failure
IntprtSetInt(4, 'M', 'F', 0, 0);
m_FailureStartTime.SetNow();
}
m_iNewMotorState = ST_MOTOR_FAILURE;
bNoError = false;
}
else
{
// ---------- No error
bNoError = true;
// Clear flag for failure output only if at least one
// status message without error has been received.
// Printing an error message on recovery is avoided.
m_bOutputOfFailure = false;
// --------- General status bits
// check if Bit 4 (-> Motor is ON) ist set
if( isBitSet(iStatus, 4) )
{
if (m_iMotorState != ST_OPERATION_ENABLED)
{
std::cout << "Motor " << m_DriveParam.getDriveIdent() << " operation enabled" << std::endl;
m_FailureStartTime.SetNow();
}
m_iNewMotorState = ST_OPERATION_ENABLED;
}
else
{
if (m_iMotorState != ST_OPERATION_DISABLED)
{
std::cout << "Motor " << m_DriveParam.getDriveIdent() << " operation disabled" << std::endl;
}
m_iNewMotorState = ST_OPERATION_DISABLED;
}
// Current limit
if( isBitSet(iStatus, 13) )
{
if (m_bCurrentLimitOn == false)
std::cout << "Motor " << m_DriveParam.getDriveIdent() << "current limit on" << std::endl;
m_bCurrentLimitOn = true;
}
else
m_bCurrentLimitOn = false;
}
// Change state
m_iMotorState = m_iNewMotorState;
if (m_iMotorState == ST_MOTOR_FAILURE)
m_bOutputOfFailure = true;
return bNoError;
}
//-----------------------------------------------
void CanDriveHarmonica::evalMotorFailure(int iFailure)
{
std::cout << "Motor " << m_DriveParam.getDriveIdent() << " has a failure:" << std::endl;
if( isBitSet(iFailure, 2) )
{
std::cout << "- feedback loss" << std::endl;
}
if( isBitSet(iFailure, 3) )
{
std::cout << "- peak current excced" << std::endl;
}
if( isBitSet(iFailure, 7) )
{
std::cout << "- speed track error" << std::endl;
}
if( isBitSet(iFailure, 8) )
{
std::cout << "- position track error" << std::endl;
}
if( isBitSet(iFailure, 17) )
{
std::cout << "- speed limit exceeded" << std::endl;
}
if( isBitSet(iFailure, 21) )
{
std::cout << "- motor stuck" << std::endl;
}
}
//-----------------------------------------------
void CanDriveHarmonica::setMotorTorque(double dTorqueNm)
{
// convert commanded motor current into amperes
float fMotCurr = m_DriveParam.getSign() * dTorqueNm / m_DriveParam.getCurrToTorque();
// check for limitations
if (fMotCurr > m_DriveParam.getCurrMax())
{
fMotCurr = m_DriveParam.getCurrMax();
std::cout << "Torque command too high: " << fMotCurr << " Nm. Torque has been limitited." << std::endl;
}
if (fMotCurr < -m_DriveParam.getCurrMax())
{
fMotCurr = -m_DriveParam.getCurrMax();
std::cout << "Torque command too high: " << fMotCurr << " Nm. Torque has been limitited." << std::endl;
}
// send Command
IntprtSetFloat(8, 'T', 'C', 0, fMotCurr);
// request pos and vel by TPDO1, triggered by SYNC msg
CanMsg msg;
msg.m_iID = 0x80;
msg.m_iLen = 0;
msg.set(0,0,0,0,0,0,0,0);
m_pCanCtrl->transmitMsg(msg);
// send heartbeat to keep watchdog inactive
msg.m_iID = 0x700;
msg.m_iLen = 5;
msg.set(0x00,0,0,0,0,0,0,0);
m_pCanCtrl->transmitMsg(msg);
m_CurrentTime.SetNow();
double dt = m_CurrentTime - m_SendTime;
if (dt > 1.0)
{
std::cout << "Time between send current/torque of motor " << m_DriveParam.getDriveIdent()
<< " is too large: " << dt << " s" << std::endl;
}
m_SendTime.SetNow();
// request status
m_iCountRequestDiv++;
if (m_iCountRequestDiv > m_Param.iDivForRequestStatus)
{
requestStatus();
m_iCountRequestDiv = 0;
}
}
//-----------------------------------------------
void CanDriveHarmonica::getMotorTorque(double* dTorqueNm)
{
// With motor sign:
*dTorqueNm = m_DriveParam.getSign() * m_dMotorCurr * m_DriveParam.getCurrToTorque();
}
| [
"cpc@okeanos.(none)",
"[email protected]"
]
| [
[
[
1,
57
],
[
59,
1206
]
],
[
[
58,
58
]
]
]
|
eee15b410eba5e89eb49980e5130922337123e80 | 22b6d8a368ecfa96cb182437b7b391e408ba8730 | /engine/include/qvPrerequisites.h | f6f08dbe1f7daebb925c0c051a0e7843d2772efa | [
"MIT"
]
| permissive | drr00t/quanticvortex | 2d69a3e62d1850b8d3074ec97232e08c349e23c2 | b780b0f547cf19bd48198dc43329588d023a9ad9 | refs/heads/master | 2021-01-22T22:16:50.370688 | 2010-12-18T12:06:33 | 2010-12-18T12:06:33 | 85,525,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,990 | h | /**************************************************************************************************
//This code is part of QuanticVortex for latest information, see http://www.quanticvortex.org
//
//Copyright (c) 2009-2010 QuanticMinds Software Ltda.
//
//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.
**************************************************************************************************/
#ifndef __QV_PREREQUISITES_H_
#define __QV_PREREQUISITES_H_
#ifdef _MSC_VER
# pragma warning (disable : 4275) // non dll-interface class used as base
// // for dll-interface class
//
# pragma warning (disable : 4661) // no suitable definition provided for
// // explicit template instantiation request
//
# pragma warning (disable : 4221) // private dependency
# pragma warning (disable : 4251) //needs to have dll-interface to be used by clients
# pragma warning( disable : 4244 ) // possible loss of data in converversion - small number of places
#endif
//#include "irrlicht.h"
//#include "IReferenceCounted.h"
//#include "irrArray.h"
//#include "irrList.h"
//#include "irrMap.h"
//#include "irrMath.h"
//#include "irrString.h"
//#include "irrTypes.h"
//using namespace irr;
//using namespace irr::core;
//#include "qvSuperFastHash.h"
//math types
#include "LinearMath/btTransform.h"
#include "LinearMath/btQuickprof.h" //for btClock portable timing class
#include "LinearMath/btList.h"
#include "LinearMath/btHashMap.h"
#include "qvTypes.h"
namespace qv
{
typedef btScalar real; //single ou double precision
//game constants
const u32 GC_GAME_FRAMERATE(16);
const u32 GC_ANIMATION_FRAMERATE(16); // 1/30
const u32 GF_RENDER_FRAMERATE(16); // 1/60
const u32 GF_GAME_PHYSICS_FRAMERATE(16); // 1/60
//const f32 GamePhysicsFramerate(16.666667f);
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
86
]
]
]
|
44d056c93c90bd1ae000f22605b0a6f82e48fed9 | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /nanobots/src/demo/Demo.h | 34341355f54c26a9015547dc1677ae741c097663 | [
"MIT"
]
| permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 842 | h | #ifndef __DEMO_H
#define __DEMO_H
#include "../system/System.h"
class CDemo : public CSystem, public IInputListener {
public:
CDemo( const std::string& serverName, int serverPort, const std::string& recordFileName, bool writeRecord );
// IDingusApplication
virtual bool checkDevice( const CD3DDeviceCaps& caps, CD3DDeviceCaps::eVertexProcessing vproc, CD3DEnumErrors& errors );
virtual void initD3DSettingsPref( SD3DSettingsPref& pref );
virtual void initialize( IDingusAppContext& appContext );
virtual void shutdown();
virtual bool shouldFinish();
virtual bool shouldShowStats();
virtual void perform();
virtual bool msgProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam );
// IInputListener
virtual void onInputEvent( const CInputEvent& event );
virtual void onInputStage();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
28
]
]
]
|
cb26c65b4eaff5e30b9d3a5061848e16fccb5d84 | 2ca3ad74c1b5416b2748353d23710eed63539bb0 | /Pilot/Lokapala_Neverdie/Operator/Operator.cpp | 72d07ca6829a79366f1630e2701ff1ee60d07ddc | []
| 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 | 2,110 | cpp | // Operator.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "Operator.h"
#include "OperatorDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// COperatorApp
BEGIN_MESSAGE_MAP(COperatorApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// COperatorApp construction
COperatorApp::COperatorApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only COperatorApp object
COperatorApp theApp;
// COperatorApp initialization
BOOL COperatorApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
COperatorDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
]
| [
[
[
1,
78
]
]
]
|
7881609a8a4523e79e4206f5526dfd8076f01255 | 1d0aaab36740e9117022b3cf03029cede9f558ab | /Physics.h | 56730269919b2e52d7a7e104a090de49401ef0dc | []
| no_license | mikeqcp/superseaman | 76ac7c4b4a19a705880a078ca66cfd8976fc07d1 | bebeb48e90270dd94bb1c85090f12c4123002815 | refs/heads/master | 2021-01-25T12:09:29.096901 | 2011-09-13T21:44:33 | 2011-09-13T21:44:33 | 32,287,575 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,093 | h | #pragma once
#include "includes.h"
#include "Boat.h"
#include "PhysicalObject.h"
#include <cmath>
const double PI = 3.141592653589793;
class Physics
{
public:
static Physics *instance(); //zwraca wskaźnik (jeśli trzeba tworzy obiekt klasy)
glm::vec4 getWind() { return wind; };
glm::mat4 getWindScaleMatrix()
{
return glm::scale(glm::mat4(1), glm::vec3(0.7,0.7,0.7));
};
glm::mat4 getWindMatrix() { return windM; };
void setTargets(PhysicalObject **objArray, int size);
PhysicalObject **getTargets(){return targets; };
void update();
Result *getStates();
protected:
Physics(void);
~Physics(void);
private:
static Physics *instance_pointer; //wskaźnik na instacje singletona
PhysicalObject **targets;
Result *states;
int targetNum;
glm::vec4 speed; //predkosc łódki
glm::vec4 wind; //wiatr
glm::mat4 windM; //macierz transformacji wiatru (dla strzałki)
GLfloat windStr; //siła wiatru
GLfloat sailAngle; //kąt bomu (względem osi łódki)
void updateWind();
};
GLfloat degToRad(GLfloat val); | [
"[email protected]@a54423c0-632b-0463-fc5f-a1ef5643ace0"
]
| [
[
[
1,
52
]
]
]
|
38236b22d860a9f2ff5e0f3d1199c0330ff12c97 | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Graphics/WS/VectorSprite/Base.h | 37054219ffe40e63b3667ee0ff10d8c020d249c3 | []
| no_license | huellif/symbian-example | 72097c9aec6d45d555a79a30d576dddc04a65a16 | 56f6c5e67a3d37961408fc51188d46d49bddcfdc | refs/heads/master | 2016-09-06T12:49:32.021854 | 2010-10-14T06:31:20 | 2010-10-14T06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,697 | h | // Base.h
//
// Copyright (c) 2005 Symbian Softwares Ltd. All rights reserved.
//
#if !defined(__VECTORSPRITES_H__)
#define __VECTORSPRITES_H__
// Forward declarations
class CWsRedrawer;
class CWindow;
/////////////////////////////////////////////////////////////////////////
// Declaration of CWsClient
/////////////////////////////////////////////////////////////////////////
class CWsClient : public CActive
{
public:
void ConstructL();
// destruct
~CWsClient();
// main window
virtual void ConstructMainWindowL();
// terminate cleanly
void Exit();
// active object protocol
void IssueRequest(); // request an event
void DoCancel(); // cancel the request
virtual void RunL() = 0; // handle completed request
virtual void HandleKeyEventL(TKeyEvent& aKeyEvent) = 0;
protected:
//construct
CWsClient();
CWsScreenDevice* iScreen;
CWsRedrawer* iRedrawer;
RWsSession iWs;
TWsEvent iWsEvent;
private:
RWindowGroup iGroup;
CWindowGc* iGc;
friend class CWsRedrawer; // needs to get at session
friend class CWindow; // needs to get at session
friend class CSprite;
friend class CPointerCursor;
};
////////////////////////////////////////////////////////////////////////////
// CWsRedrawer declaration
////////////////////////////////////////////////////////////////////////////
class CWsRedrawer : public CActive
{
public:
// construct/destruct
CWsRedrawer();
void ConstructL(CWsClient* aClient);
~CWsRedrawer();
// drawing
void IssueRequest();
void DoCancel();
void RunL();
protected:
CWsClient* iClient;
};
//////////////////////////////////////////////////////////////////////////////
// CWindow declaration
//////////////////////////////////////////////////////////////////////////////
class CWindow : public CBase
{
public:
enum
{
KPointerMoveBufferSize = 32
};
CWindow(CWsClient* aClient);
void ConstructL(const TRect& aRect, const TRgb& aColor, CWindow* aParent =
0);
~CWindow();
// access
RWindow& Window(); // our own window
CWindowGc* SystemGc(); // system graphics context
CWsScreenDevice* Screen();
CFont* Font();
// drawing
virtual void Draw(const TRect& aRect) = 0;
virtual void HandlePointerEvent(TPointerEvent& aPointerEvent) = 0;
protected:
RWindow iWindow; // window server window
TRect iRect; // window's extent
private:
CWsClient* iClient; // client including session and group
CFont* iFont;
};
#endif
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
]
| [
[
[
1,
99
]
]
]
|
355ee6f6535fa83d2702eff88356ebaff7cd1e57 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/singleplayer/ricochet/dlls/disc_arena.cpp | a2ffa5fcfd8b301852b54751270765e9a0fe187b | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,892 | cpp | //=========== (C) Copyright 1999 Valve, L.L.C. All rights reserved. ===========
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose: Handles the arena portion of discwar
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "player.h"
#include "gamerules.h"
#include "weapons.h"
#include "discwar.h"
#include "disc_arena.h"
#include "disc_objects.h"
int g_iNextArenaGroupInfo = 0;
void ClientUserInfoChanged( edict_t *pEntity, char *infobuffer );
edict_t *EntSelectSpawnPoint( CBaseEntity *pPlayer );
void respawn(entvars_t* pev, BOOL fCopyCorpse);
extern int gmsgStartRnd;
extern int gmsgEndRnd;
extern int gmsgTeamInfo;
extern int g_iPlayersPerTeam;
extern int g_iMapTurnedOffArena;
CDiscArena *g_pArenaList[ MAX_ARENAS ];
char *g_szCountDownVox[6] =
{
"die",
"one",
"two",
"three",
"four",
};
char *g_szTeamNames[3] =
{
"",
"red",
"blue",
};
int InArenaMode()
{
if ( g_iMapTurnedOffArena )
return FALSE;
if ( gpGlobals->maxClients == 1 || (CVAR_GET_FLOAT("rc_arena") == 0) )
return FALSE;
return TRUE;
}
LINK_ENTITY_TO_CLASS( disc_arena, CDiscArena );
// NOTE:
// We store queue position in pev->playerclass, so it's automatically pushed
// down to the client. The scoreboard uses pev->playerclass to display the
// positions of the players in the queue.
void CDiscArena::Spawn( void )
{
pev->groupinfo = 1 << (g_iNextArenaGroupInfo++);
Reset();
// Initialize
m_iMaxRounds = CVAR_GET_FLOAT("rc_rounds");
m_iPlayersPerTeam = g_iPlayersPerTeam;
SetThink( NULL );
}
void CDiscArena::Reset( void )
{
// Remove all clients in the queue
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( i );
if (pPlayer && (pPlayer->m_pCurrentArena == this) && pPlayer->m_bHasDisconnected != TRUE )
{
RemoveClient( pPlayer );
// Move her into spectator mode
//MoveToSpectator( pPlayer );
}
}
m_pPlayerQueue = NULL;
m_iPlayers = 0;
m_flTimeLimitOver = 0;
m_bShownTimeWarning = FALSE;
m_iArenaState = ARENA_WAITING_FOR_PLAYERS;
memset( m_hCombatants, 0, sizeof( m_hCombatants ) );
SetThink( NULL );
pev->nextthink = 0;
}
//-----------------------------------------------------------------------------
// Purpose: Start a battle. Spawn all the players, and begin the countdown.
//-----------------------------------------------------------------------------
void CDiscArena::StartBattle( void )
{
m_iCurrRound = 0;
m_iTeamOneScore = m_iTeamTwoScore = 0;
// First, set all players in this arena to "didn't play"
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( i );
if (pPlayer && (pPlayer->m_pCurrentArena == this) && pPlayer->m_bHasDisconnected != TRUE )
pPlayer->m_iLastGameResult = GAME_DIDNTPLAY;
}
// Get the players in the battle
for ( i = 0; i < (m_iPlayersPerTeam * 2); i++ )
{
CBasePlayer *pCurr;
// Check to see if this slot's already full
if ( m_hCombatants[ i ] )
{
pCurr = (CBasePlayer*)(CBaseEntity*)m_hCombatants[ i ];
}
else
{
// Pop a new player from the queue
pCurr = GetNextPlayer();
if (!pCurr)
{
// Couldnt get enough players. Reset.
Reset();
return;
}
}
// Set her team number
if ( i < m_iPlayersPerTeam )
pCurr->pev->team = 1;
else
pCurr->pev->team = 2;
pCurr->pev->iuser4 = pCurr->pev->team;
char sz[128];
sprintf(sz, "Arena %d", pev->groupinfo );
MESSAGE_BEGIN( MSG_ALL, gmsgTeamInfo );
WRITE_BYTE( pCurr->entindex() );
WRITE_STRING( sz );
MESSAGE_END();
// Add her to the list of combatants
m_hCombatants[ i ] = pCurr;
// Force her to update her clientinfo, so her colors match her team
ClientUserInfoChanged( pCurr->edict(), g_engfuncs.pfnGetInfoKeyBuffer( pCurr->edict() ) );
}
// Start the first round
StartRound();
}
//-----------------------------------------------------------------------------
// Purpose: Start the next round in the match
//-----------------------------------------------------------------------------
void CDiscArena::StartRound( void )
{
m_iCurrRound++;
m_iSecondsTillStart = ARENA_TIME_PREBATTLE;
m_flTimeLimitOver = gpGlobals->time + ARENA_TIME_ROUNDLIMIT;
RestoreWorldObjects();
// Tell the clients
for ( int iPlayerNum = 1; iPlayerNum <= gpGlobals->maxClients; iPlayerNum++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( iPlayerNum );
if (pPlayer && (pPlayer->pev->groupinfo & pev->groupinfo) && (pPlayer->m_bHasDisconnected != TRUE) )
{
MESSAGE_BEGIN( MSG_ONE, gmsgStartRnd, NULL, pPlayer->edict() );
WRITE_BYTE( m_iCurrRound );
WRITE_BYTE( m_iSecondsTillStart );
WRITE_BYTE( (m_iPlayersPerTeam * 2) );
// Send down all the players in the round
for ( int j = 0; j < (m_iPlayersPerTeam * 2); j++ )
{
if (m_hCombatants[j])
WRITE_SHORT( ((CBaseEntity*)m_hCombatants[j])->entindex() );
}
MESSAGE_END();
}
}
// Spawn all the players in the round
for ( int i = 0; i < (m_iPlayersPerTeam * 2); i++ )
{
CBasePlayer *pPlayer = ((CBasePlayer*)(CBaseEntity*)m_hCombatants[i]);
if ( pPlayer )
{
// make sure the player's groupinfo is set the arena's groupinfo
pPlayer->pev->groupinfo = pev->groupinfo;
// is the player an observer?
if ( pPlayer->IsObserver() )
{
SpawnCombatant( pPlayer );
}
// Remove any powerups
pPlayer->RemoveAllPowerups();
}
}
// Start counting down
m_iArenaState = ARENA_COUNTDOWN;
pev->nextthink = gpGlobals->time + 0.1;
SetThink( CountDownThink );
}
//-----------------------------------------------------------------------------
// Purpose: Make sure all the Combatants in the game a valid. Return FALSE if not.
//-----------------------------------------------------------------------------
int CDiscArena::ValidateCombatants( void )
{
for ( int i = 0; i < (m_iPlayersPerTeam * 2); i++ )
{
CBasePlayer *pPlayer = ((CBasePlayer*)(CBaseEntity*)m_hCombatants[i]);
if ( !pPlayer )
return FALSE;
if ( pPlayer->m_bHasDisconnected )
return FALSE;
}
return TRUE;
}
//-----------------------------------------------------------------------------
// Purpose: Restore all the world objects
//-----------------------------------------------------------------------------
void CDiscArena::RestoreWorldObjects( void )
{
CBaseEntity *pFunc = NULL;
while ((pFunc = UTIL_FindEntityByClassname( pFunc, "func_plat_toggleremove" )) != NULL)
{
((CPlatToggleRemove*)pFunc)->Reset();
}
while ((pFunc = UTIL_FindEntityByClassname( pFunc, "func_disctoggle" )) != NULL)
{
((CDiscTarget*)pFunc)->Reset();
}
// Disable powerups
while ((pFunc = UTIL_FindEntityByClassname( pFunc, "item_powerup" )) != NULL)
{
((CDiscwarPowerup*)pFunc)->Disable();
}
}
void CDiscArena::BattleThink( void )
{
if ( gpGlobals->time >= m_flTimeLimitOver - 1.0 )
{
pev->nextthink = gpGlobals->time + 1.0;
SetThink( TimeOver );
return;
}
if ( !CheckBattleOver() )
{
pev->nextthink = gpGlobals->time + 1.0;
}
}
//-----------------------------------------------------------------------------
// Purpose: Countdown to the round start
//-----------------------------------------------------------------------------
void CDiscArena::CountDownThink( void )
{
// Freeze everyone until there's 3 seconds to go
if ( m_iSecondsTillStart == 3 )
{
for ( int i = 0; i < (m_iPlayersPerTeam * 2); i++ )
{
if (m_hCombatants[i])
((CBaseEntity*)m_hCombatants[i])->pev->maxspeed = 320;
}
}
m_iSecondsTillStart--;
// Play countdown VOX
if (m_iSecondsTillStart < 5)
{
// Speech
for ( int i = 0; i < (m_iPlayersPerTeam * 2); i++ )
{
if (m_hCombatants[i])
((CBasePlayer*)(CBaseEntity*)m_hCombatants[i])->ClientHearVox( g_szCountDownVox[ m_iSecondsTillStart ] );
}
}
// Send the message to the clients in the arena
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( i );
if (pPlayer && (pPlayer->pev->groupinfo & pev->groupinfo) && pPlayer->m_bHasDisconnected != TRUE)
{
MESSAGE_BEGIN( MSG_ONE, gmsgStartRnd, NULL, pPlayer->edict() );
WRITE_BYTE( m_iCurrRound );
WRITE_BYTE( m_iSecondsTillStart );
WRITE_BYTE( 0 );
MESSAGE_END();
}
}
if (m_iSecondsTillStart)
{
pev->nextthink = gpGlobals->time + 1.0;
}
else
{
m_iArenaState = ARENA_BATTLE_IN_PROGRESS;
// Enable powerups
CBaseEntity *pFunc = NULL;
while ((pFunc = UTIL_FindEntityByClassname( pFunc, "item_powerup" )) != NULL)
{
((CDiscwarPowerup*)pFunc)->Enable();
}
pev->nextthink = gpGlobals->time + 1.0;
SetThink( BattleThink );
}
}
//-----------------------------------------------------------------------------
// Purpose: A player in the battle has died. See if we need to restart the battle.
//-----------------------------------------------------------------------------
void CDiscArena::PlayerKilled( CBasePlayer *pPlayer )
{
// Check to see if the battle's over in 5 seconds
if ( m_iArenaState == ARENA_BATTLE_IN_PROGRESS || m_iArenaState == ARENA_COUNTDOWN )
{
if ( !CheckBattleOver() )
{
pev->nextthink = gpGlobals->time + 0.5;
SetThink( CheckOverThink );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: A player in the battle has respawned. Move them to observer mode.
//-----------------------------------------------------------------------------
void CDiscArena::PlayerRespawned( CBasePlayer *pPlayer )
{
if ( m_iArenaState == ARENA_BATTLE_IN_PROGRESS )
{
// Move the player into Spectator mode
MoveToSpectator( pPlayer );
}
else if ( m_iArenaState == ARENA_SHOWING_SCORES && ( m_iTeamOneScore >= m_iMaxRounds || m_iTeamTwoScore >= m_iMaxRounds ) )
{
// Battle is over. If there's only 2 players in the game, just respawn.
// Otherwise, move to spectator.
int iNumPlayers = 0;
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( i );
if (pPlayer && pPlayer->m_bHasDisconnected != TRUE)
iNumPlayers++;
}
// Move the player into Spectator mode if there are more players
if ( iNumPlayers > 2 )
MoveToSpectator( pPlayer );
}
}
//-----------------------------------------------------------------------------
// Purpose: Move the player to a spectating position
//-----------------------------------------------------------------------------
void CDiscArena::MoveToSpectator( CBasePlayer *pPlayer )
{
// Find the spectator spawn position
CBaseEntity *pSpot = UTIL_FindEntityByClassname( NULL, "info_player_spectator");
if ( pSpot )
{
pPlayer->StartObserver( pSpot->pev->origin, pSpot->pev->angles);
}
else
{
// Find any spawn point
edict_t *pentSpawnSpot = EntSelectSpawnPoint( pPlayer );
pPlayer->StartObserver( VARS(pentSpawnSpot)->origin, VARS(pentSpawnSpot)->angles);
}
pPlayer->pev->team = 0;
pPlayer->Observer_SetMode( OBS_LOCKEDVIEW );
}
//-----------------------------------------------------------------------------
// Purpose: Battle is over.
//-----------------------------------------------------------------------------
void CDiscArena::BattleOver( void )
{
pev->nextthink = gpGlobals->time + 3;
SetThink( FinishedThink );
m_iSecondsTillStart = ARENA_TIME_VIEWSCORES;
m_iArenaState = ARENA_SHOWING_SCORES;
RestoreWorldObjects();
}
//-----------------------------------------------------------------------------
// Purpose: Round timelimit has been hit
//-----------------------------------------------------------------------------
void CDiscArena::TimeOver( void )
{
// Display the 10 second warning first
if ( !m_bShownTimeWarning )
{
m_bShownTimeWarning = TRUE;
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( i );
if (pPlayer && (pPlayer->pev->groupinfo & pev->groupinfo) && pPlayer->m_bHasDisconnected != TRUE)
ClientPrint( pPlayer->pev, HUD_PRINTCENTER, "#Time_Warning" );
}
pev->nextthink = gpGlobals->time + 10;
}
else
{
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( i );
if (pPlayer && (pPlayer->pev->groupinfo & pev->groupinfo) && (pPlayer->m_bHasDisconnected != TRUE) )
ClientPrint( pPlayer->pev, HUD_PRINTCENTER, "#Time_Over" );
}
// Increment both scores to force the game to end
m_iTeamOneScore++;
m_iTeamTwoScore++;
BattleOver();
}
}
bool CDiscArena::CheckBattleOver( void )
{
bool bTeamOneAlive = false;
bool bTeamTwoAlive = false;
// See if the battle is finished
for ( int i = 0; i < (m_iPlayersPerTeam * 2); i++ )
{
if ( m_hCombatants[i] != NULL && ((CBasePlayer*)(CBaseEntity*)m_hCombatants[i])->IsAlive() )
{
if ( ((CBaseEntity*)m_hCombatants[i])->pev->team == 1 )
bTeamOneAlive = true;
else if ( ((CBaseEntity*)m_hCombatants[i])->pev->team == 2 )
bTeamTwoAlive = true;
}
}
if ( !bTeamOneAlive || !bTeamTwoAlive )
{
// Battle is finished.
if (bTeamOneAlive)
{
m_iWinningTeam = 1;
m_iTeamOneScore++;
}
else
{
m_iWinningTeam = 2;
m_iTeamTwoScore++;
}
int iTeamInTheLead = 0;
if ( m_iTeamOneScore > m_iTeamTwoScore )
iTeamInTheLead = 1;
else if ( m_iTeamOneScore < m_iTeamTwoScore )
iTeamInTheLead = 2;
// Send the message to the clients in the arena
for ( int iPlayerNum = 1; iPlayerNum <= gpGlobals->maxClients; iPlayerNum++ )
{
CBasePlayer *pPlayer = (CBasePlayer*)UTIL_PlayerByIndex( iPlayerNum );
if (pPlayer && (pPlayer->pev->groupinfo & pev->groupinfo) && (pPlayer->m_bHasDisconnected != TRUE) )
{
MESSAGE_BEGIN( MSG_ONE, gmsgEndRnd, NULL, pPlayer->edict() );
WRITE_BYTE( m_iCurrRound );
WRITE_BYTE( 1 );
WRITE_BYTE( m_iPlayersPerTeam );
// Send down the winners of this round
for (i = 0; i < (m_iPlayersPerTeam * 2); i++)
{
CBasePlayer *pPlayer = (CBasePlayer*)(CBaseEntity*)m_hCombatants[i];
if ( !pPlayer || pPlayer->pev->team != m_iWinningTeam )
continue;
WRITE_SHORT( pPlayer->entindex() );
}
// Send down the team who's winning the battle now
if ( iTeamInTheLead == 0 )
{
// It's a draw at the moment.
// No need to send down player data.
WRITE_BYTE( 0 );
}
else
{
WRITE_BYTE( m_iPlayersPerTeam );
// Send down the winners of this round
for (i = 0; i < (m_iPlayersPerTeam * 2); i++)
{
CBasePlayer *pPlayer = (CBasePlayer*)(CBaseEntity*)m_hCombatants[i];
if ( !pPlayer || pPlayer->pev->team != iTeamInTheLead )
continue;
WRITE_SHORT( ((CBaseEntity*)m_hCombatants[i])->entindex() );
}
}
// Send down the scores
if ( iTeamInTheLead == 1 )
{
WRITE_BYTE( m_iTeamOneScore );
WRITE_BYTE( m_iTeamTwoScore );
}
else
{
WRITE_BYTE( m_iTeamTwoScore );
WRITE_BYTE( m_iTeamOneScore );
}
// Send down over or not
if ( m_iTeamOneScore == m_iMaxRounds || m_iTeamTwoScore == m_iMaxRounds )
WRITE_BYTE( 1 );
else
WRITE_BYTE( 0 );
MESSAGE_END();
}
}
BattleOver();
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Check to see if the Battle is over
//-----------------------------------------------------------------------------
void CDiscArena::CheckOverThink( void )
{
if ( !CheckBattleOver() )
{
if ( m_iArenaState == ARENA_COUNTDOWN )
{
pev->nextthink = gpGlobals->time + 0.1;
SetThink( CountDownThink );
}
else
{
pev->nextthink = gpGlobals->time + 0.1;
SetThink( BattleThink );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Show who won, and then restart the round
//-----------------------------------------------------------------------------
void CDiscArena::FinishedThink( void )
{
m_iSecondsTillStart--;
if (m_iSecondsTillStart)
{
pev->nextthink = gpGlobals->time + 1.0;
}
else
{
SetThink( NULL );
// Tell the clients to remove the "Won" window
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( i );
if (pPlayer && (pPlayer->pev->groupinfo & pev->groupinfo) && pPlayer->m_bHasDisconnected != TRUE)
{
MESSAGE_BEGIN( MSG_ONE, gmsgEndRnd, NULL, pPlayer->edict() );
WRITE_BYTE( m_iCurrRound );
WRITE_BYTE( 0 );
WRITE_BYTE( 0 );
MESSAGE_END();
}
}
// Round is over. See if the match is over too.
if ( m_iTeamOneScore >= m_iMaxRounds || m_iTeamTwoScore >= m_iMaxRounds )
{
// Remove the losers from the combatants list
for (int i = 0; i < (m_iPlayersPerTeam * 2); i++)
{
CBasePlayer *pPlayer = (CBasePlayer*)(CBaseEntity*)m_hCombatants[i];
if (!pPlayer)
continue;
if ( pPlayer->pev->team == m_iWinningTeam )
{
pPlayer->m_iDeaths += 1;
pPlayer->m_iLastGameResult = GAME_WON;
continue;
}
pPlayer->m_iLastGameResult = GAME_LOST;
m_hCombatants[i] = NULL;
}
// Then start the next Battle
PostBattle();
}
else
{
// Start the next round
StartRound();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Spawn a player in this battle
//-----------------------------------------------------------------------------
void CDiscArena::SpawnCombatant( CBasePlayer *pPlayer )
{
// Make sure she's out of spectator mode
pPlayer->StopObserver();
// Spawn
g_pGameRules->GetPlayerSpawnSpot( pPlayer );
// Prevent movement for a couple of seconds
pPlayer->pev->maxspeed = 1;
}
//-----------------------------------------------------------------------------
// Purpose: Start a Battle
//-----------------------------------------------------------------------------
void CDiscArena::StartBattleThink( void )
{
StartBattle();
}
//-----------------------------------------------------------------------------
// Purpose: Prevent firing during prematch
//-----------------------------------------------------------------------------
bool CDiscArena::AllowedToFire( void )
{
return ( m_iArenaState == ARENA_BATTLE_IN_PROGRESS );
}
//-----------------------------------------------------------------------------
// Purpose: New client was added to the arena
//-----------------------------------------------------------------------------
void CDiscArena::AddClient( CBasePlayer *pPlayer, BOOL bCheckStart )
{
// Remove them from any arena they're currently in
if ( pPlayer->m_pCurrentArena != NULL )
pPlayer->m_pCurrentArena->RemoveClient( pPlayer );
m_iPlayers++;
pPlayer->pev->groupinfo = pev->groupinfo;
// Add her to the queue
AddPlayerToQueue( pPlayer );
pPlayer->m_pCurrentArena = this;
// Only check a restart if the flag is set
if ( bCheckStart )
{
// Start a game if there's none going, and we now have enough players
// Allow starting of games if there aren't enough players, but there's more than 1 on the svr.
//if ( (m_iPlayersPerTeam > 1) && (m_iPlayers > 1) && (m_iPlayers < (m_iPlayersPerTeam * 2)) )
//m_iPlayersPerTeam = 1;
// If we're in a battle, and the players-per-team isn't the map's setting, restart the battle
if ( (m_iArenaState == ARENA_WAITING_FOR_PLAYERS) && ( m_iPlayers >= (m_iPlayersPerTeam * 2) ) )
{
// Start a battle in a second to let the clients learn about this new player
SetThink( StartBattleThink );
pev->nextthink = gpGlobals->time + 1.0;
}
else
{
// Move her into spectator mode
MoveToSpectator( pPlayer );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Client was removed from the arena
//-----------------------------------------------------------------------------
void CDiscArena::RemoveClient( CBasePlayer *pPlayer )
{
m_iPlayers--;
pPlayer->pev->groupinfo = 0;
pPlayer->m_pCurrentArena = NULL;
// Is she in the current battle?
if ( pPlayer->pev->playerclass != 0 )
{
// No, she's in the queue, so remove her.
RemovePlayerFromQueue( pPlayer );
}
else if ( m_iArenaState != ARENA_WAITING_FOR_PLAYERS )
{
// This team loses
m_iWinningTeam = (pPlayer->pev->team == 1) ? 2 : 1;
if ( m_iWinningTeam == 1 )
m_iTeamOneScore = m_iMaxRounds - 1; // -1 because we'll get 1 point for winning this round in CheckOverThink
else
m_iTeamTwoScore = m_iMaxRounds - 1; // -1 because we'll get 1 point for winning this round in CheckOverThink
// Find the player in the combatant list
for ( int i = 0; i < (m_iPlayersPerTeam * 2); i++ )
{
// Check to see if this slot's already full
if ( m_hCombatants[ i ] == pPlayer )
{
m_hCombatants[i] = NULL;
break;
}
}
CheckOverThink();
}
}
//-----------------------------------------------------------------------------
// Purpose: Add a player to the end of the queue
//-----------------------------------------------------------------------------
void CDiscArena::AddPlayerToQueue( CBasePlayer *pPlayer )
{
if ( !pPlayer )
return;
if ( m_pPlayerQueue )
{
CBasePlayer *pCurr = (CBasePlayer*)(CBaseEntity*)m_pPlayerQueue;
while ( pCurr->m_pNextPlayer )
{
pCurr = (CBasePlayer*)(CBaseEntity*)pCurr->m_pNextPlayer;
}
pCurr->m_pNextPlayer = pPlayer;
pPlayer->pev->playerclass = pCurr->pev->playerclass + 1;
}
else
{
m_pPlayerQueue = pPlayer;
pPlayer->pev->playerclass = 1;
}
pPlayer->m_pNextPlayer = NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Remove a player from the queue
//-----------------------------------------------------------------------------
void CDiscArena::RemovePlayerFromQueue( CBasePlayer *pPlayer )
{
bool bFoundHer = false;
if ( !pPlayer )
return;
CBasePlayer *pCurr = (CBasePlayer*)(CBaseEntity*)m_pPlayerQueue;
CBasePlayer *pPrev = NULL;
while ( pCurr )
{
if (pCurr == pPlayer )
{
bFoundHer = true;
if (pPrev)
pPrev->m_pNextPlayer = pCurr->m_pNextPlayer;
else
m_pPlayerQueue = pCurr->m_pNextPlayer;
}
else
{
pPrev = pCurr;
// Adjust all the following player's queue positions
if (bFoundHer)
pCurr->pev->playerclass--;
}
pCurr = (CBasePlayer*)(CBaseEntity*)pCurr->m_pNextPlayer;
}
pPlayer->m_pNextPlayer = NULL;
pPlayer->pev->playerclass = 0;
}
//-----------------------------------------------------------------------------
// Purpose: Get the next player from the queue, and shuffle the rest up
//-----------------------------------------------------------------------------
CBasePlayer *CDiscArena::GetNextPlayer( void )
{
if ( m_pPlayerQueue == NULL )
return NULL;
CBasePlayer *pCurr = (CBasePlayer*)(CBaseEntity*)m_pPlayerQueue;
RemovePlayerFromQueue( (CBasePlayer*)(CBaseEntity*)m_pPlayerQueue );
return pCurr;
}
//-----------------------------------------------------------------------------
// Returns TRUE if the Arena is full
int CDiscArena::IsFull( void )
{
if ( m_iPlayers < (m_iPlayersPerTeam * 2) )
return FALSE;
return TRUE;
}
//-----------------------------------------------------------------------------
// Returns the first player in the Arena's queue, if any
CBasePlayer *CDiscArena::GetFirstSparePlayer( void )
{
if ( m_pPlayerQueue == NULL )
return NULL;
return (CBasePlayer*)(CBaseEntity*)m_pPlayerQueue;
}
//-----------------------------------------------------------------------------
// Add a client to an Arena. Find the first arena that doesn't have two
// players in it, and add this player to that. If we find a third player
// Spectating another arena, grab them and add them to this player's arena.
void AddClientToArena( CBasePlayer *pPlayer )
{
// First, find an arena for this player to be put into
for (int i = 0; i < MAX_ARENAS; i++)
{
if ( g_pArenaList[i]->IsFull() == FALSE )
{
int iArenaNumber = i;
g_pArenaList[iArenaNumber]->AddClient( pPlayer, TRUE );
bool bFoundOne = TRUE;
// Now, if this arena's not full, try to find more player to join her
while ( (g_pArenaList[iArenaNumber]->IsFull() == FALSE) && bFoundOne )
{
bFoundOne = FALSE;
// Cycle through all the arenas and find a spare player
for (int j = 0; j < MAX_ARENAS; j++)
{
CBasePlayer *pSparePlayer = g_pArenaList[j]->GetFirstSparePlayer();
if (pSparePlayer && pSparePlayer != pPlayer)
{
g_pArenaList[j]->RemoveClient( pSparePlayer );
g_pArenaList[iArenaNumber]->AddClient( pSparePlayer, TRUE );
bFoundOne = TRUE;
break;
}
}
}
// If we couldn't find another player for this arena, just add them to an existing arena
if ( g_pArenaList[iArenaNumber]->IsFull() == FALSE )
{
// Add to the first full arena
for (int j = 0; j < MAX_ARENAS; j++)
{
if ( g_pArenaList[j]->IsFull() )
{
// Remove from current
g_pArenaList[iArenaNumber]->RemoveClient( pPlayer );
// Add to full one
iArenaNumber = j;
g_pArenaList[iArenaNumber]->AddClient( pPlayer, TRUE );
break;
}
}
}
//ALERT( at_console, "ADDED %s to Arena %d\n", STRING(pPlayer->pev->netname), iArenaNumber );
return;
}
}
}
//-----------------------------------------------------------------------------
// Put the specified group of players into the current arena
int AddPlayers( int iPlayers, int iArenaNum )
{
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( i );
if (pPlayer && (pPlayer->m_pCurrentArena == NULL) && (pPlayer->m_bHasDisconnected != TRUE) )
{
if ( pPlayer->m_iLastGameResult != iPlayers )
continue;
g_pArenaList[iArenaNum]->AddClient( pPlayer, FALSE );
if ( g_pArenaList[iArenaNum]->IsFull() )
iArenaNum++;
}
}
return iArenaNum;
}
//-----------------------------------------------------------------------------
// Take all the players not in battles and shuffle them into new groups
void ShufflePlayers( void )
{
int iArenaNum = 0;
// Reset all Arenas
for ( int i = 0; i < MAX_ARENAS; i++)
{
g_pArenaList[i]->Reset();
}
// Play the winners off against the other winners first
iArenaNum = AddPlayers( GAME_WON, iArenaNum );
// First, add the players who didn't play at all
iArenaNum = AddPlayers( GAME_DIDNTPLAY, iArenaNum );
// Then add the losers
iArenaNum = AddPlayers( GAME_LOST, iArenaNum );
// Then tell all full arenas to start
for (i = 0; i < MAX_ARENAS; i++)
{
if ( g_pArenaList[i]->IsFull() )
{
g_pArenaList[i]->StartBattle();
}
else
{
// If the arena has players in it, move them to the first full arena
if ( g_pArenaList[i]->m_iPlayers != 0 )
{
for ( int j = 1; j <= gpGlobals->maxClients; j++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( j );
if (pPlayer && (pPlayer->m_pCurrentArena == g_pArenaList[i]) && (pPlayer->m_bHasDisconnected != TRUE) )
{
// Add to the first arena
g_pArenaList[0]->AddClient( pPlayer, TRUE );
pPlayer->m_iLastGameResult = GAME_DIDNTPLAY;
}
}
}
}
}
}
//-----------------------------------------------------------------------------
// The Battle is over. First, check to see if there are games going on in
// other arenas. If there are, these players go watch one of them for a bit.
// If all games finish in that time, shuffle all the players and start new
// games. Otherwise, shuffle all the players who aren't still playing, and
// start new games with them.
void CDiscArena::PostBattle( void )
{
int iOtherGame = -1;
// First, see if there are any other games going on in other arenas
for (int i = 0; i < MAX_ARENAS; i++)
{
if ( g_pArenaList[i]->m_iArenaState != ARENA_WAITING_FOR_PLAYERS && g_pArenaList[i] != this )
{
iOtherGame = i;
break;
}
}
// If there are no other games, just shuffle and start again
if ( iOtherGame == -1 )
{
ShufflePlayers();
return;
}
// There's another game going on. Move all the players from this arena to it to spectate.
for ( i = 1; i <= gpGlobals->maxClients; i++ )
{
CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( i );
if (pPlayer && (pPlayer->pev->groupinfo & pev->groupinfo) && (pPlayer->m_bHasDisconnected != TRUE) )
{
g_pArenaList[ iOtherGame ]->AddClient( (CBasePlayer*)pPlayer, TRUE );
}
}
m_iArenaState = ARENA_WAITING_FOR_PLAYERS;
} | [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
1044
]
]
]
|
5dd526773efff3f547c75a80811eda8eb53a930e | 3eae8bea68fd2eb7965cca5afca717b86700adb5 | /Engine/Project/Core/GnMain/Source/GnColor.h | d97d70795ba946a7159c6cc8727500290b75e1ba | []
| no_license | mujige77/WebGame | c0a218ee7d23609076859e634e10e29c92bb595b | 73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd | refs/heads/master | 2021-01-01T15:51:20.045414 | 2011-10-03T01:02:59 | 2011-10-03T01:02:59 | 455,950 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,875 | h | #ifndef GNCOLOR_H
#define GNCOLOR_H
#include <GnMemoryObject.h>
class GNMAIN_ENTRY GnColorA : public GnMemoryObject
{
public:
float r, g, b, a;
inline GnColorA (float fR = 0.0f, float fG = 0.0f,
float fB = 0.0f, float fA = 1.0f);
inline GnColorA& operator= (float fScalar);
inline bool operator== (const GnColorA& c) const;
inline bool operator!= (const GnColorA& c) const;
inline GnColorA operator+ (const GnColorA& c) const;
inline GnColorA operator- (const GnColorA& c) const;
inline GnColorA operator* (float fScalar) const;
inline GnColorA operator* (const GnColorA& c) const;
inline GnColorA operator/ (float fScalar) const;
inline GnColorA operator/ (const GnColorA& c) const;
inline GnColorA operator- () const;
GNMAIN_ENTRY friend GnColorA operator* (float fScalar, const GnColorA& c);
inline GnColorA& operator+= (const GnColorA& c);
inline GnColorA& operator-= (const GnColorA& c);
inline GnColorA& operator*= (float fScalar);
inline GnColorA& operator*= (const GnColorA& c);
inline GnColorA& operator/= (float fScalar);
inline GnColorA& operator/= (const GnColorA& c);
// map (r,g,b,a) to unit hypercube
inline void Clamp();
inline void Scale();
// Function to return the color as an unsigned integer.
inline guint32 GetRGBA() const;
inline void GetRGBA(guint8& outR, guint8& outG, guint8& outB, guint8& outA);
};
inline GnColorA::GnColorA(float fR, float fG, float fB, float fA)
{
r = fR;
g = fG;
b = fB;
a = fA;
}
inline GnColorA& GnColorA::operator= (float fScalar)
{
r = fScalar;
g = fScalar;
b = fScalar;
a = fScalar;
return *this;
}
inline bool GnColorA::operator== (const GnColorA& c) const
{
return (r == c.r && g == c.g && b == c.b && a == c.a);
}
inline bool GnColorA::operator!= (const GnColorA& c) const
{
return !(*this == c);
}
inline GnColorA GnColorA::operator+ (const GnColorA& c) const
{
GnColorA result = *this;
result.r += c.r;
result.g += c.g;
result.b += c.b;
result.a += c.a;
return result;
}
inline GnColorA GnColorA::operator- (const GnColorA& c) const
{
GnColorA result = *this;
result.r -= c.r;
result.g -= c.g;
result.b -= c.b;
result.a -= c.a;
return result;
}
inline GnColorA GnColorA::operator* (float fScalar) const
{
GnColorA result = *this;
result.r *= fScalar;
result.g *= fScalar;
result.b *= fScalar;
result.a *= fScalar;
return result;
}
inline GnColorA GnColorA::operator* (const GnColorA &c) const
{
GnColorA result = *this;
result.r *= c.r;
result.g *= c.g;
result.b *= c.b;
result.a *= c.a;
return result;
}
inline GnColorA GnColorA::operator/ (float fScalar) const
{
GnColorA result = *this;
result.r /= fScalar;
result.g /= fScalar;
result.b /= fScalar;
result.a /= fScalar;
return result;
}
inline GnColorA GnColorA::operator/ (const GnColorA &c) const
{
GnColorA result = *this;
result.r /= c.r;
result.g /= c.g;
result.b /= c.b;
result.a /= c.a;
return result;
}
inline GnColorA GnColorA::operator- () const
{
return GnColorA(-r,-g,-b,-a);
}
inline GnColorA operator* (float fScalar, const GnColorA& c)
{
return c*fScalar;
}
inline GnColorA& GnColorA::operator+= (const GnColorA& c)
{
r += c.r;
g += c.g;
b += c.b;
a += c.a;
return *this;
}
inline GnColorA& GnColorA::operator-= (const GnColorA& c)
{
r -= c.r;
g -= c.g;
b -= c.b;
a -= c.a;
return *this;
}
inline GnColorA& GnColorA::operator*= (float fScalar)
{
r *= fScalar;
g *= fScalar;
b *= fScalar;
a *= fScalar;
return *this;
}
inline GnColorA& GnColorA::operator*= (const GnColorA &c)
{
r *= c.r;
g *= c.g;
b *= c.b;
a *= c.a;
return *this;
}
inline GnColorA& GnColorA::operator/= (float fScalar)
{
r /= fScalar;
g /= fScalar;
b /= fScalar;
a /= fScalar;
return *this;
}
inline GnColorA& GnColorA::operator/= (const GnColorA &c)
{
r /= c.r;
g /= c.g;
b /= c.b;
a /= c.a;
return *this;
}
inline void GnColorA::Clamp()
{
// Clamp to [0,1]^4. Assumes that (r,g,b,a) >= (0,0,0). This is a
// reasonable assumption since colors are only added or multiplied in
// the lighting system. Note that clamping can cause significant
// changes in the final color.
if ( r > 1.0f )
r = 1.0f;
if ( g > 1.0f )
g = 1.0f;
if ( b > 1.0f )
b = 1.0f;
if ( a > 1.0f )
a = 1.0f;
}
inline void GnColorA::Scale()
{
// Scale down by maximum component (preserves the final color).
float fMax = r;
if ( g > fMax )
fMax = g;
if ( b > fMax )
fMax = b;
if ( fMax > 1.0f )
{
float fInvMax = 1.0f/fMax;
r *= fInvMax;
g *= fInvMax;
b *= fInvMax;
}
if ( a > 1.0f )
a = 1.0f;
}
inline guint32 GnColorA::GetRGBA() const
{
return ((int)(a * 255.0f) << 24 ) | ((int)(r * 255.0f) << 16) | ((int)(g * 255.0f) << 8 ) | (int)(b * 255.0f);
}
inline void GnColorA::GetRGBA(guint8& outR, guint8& outG, guint8& outB, guint8& outA)
{
outR = (int)(r * 255.0f);
outG = (int)(g * 255.0f);
outB = (int)(b * 255.0f);
outA = (int)(a * 255.0f);
}
class GNMAIN_ENTRY GnColor : public GnMemoryObject
{
public:
static const GnColor Red;
static const GnColor Blue;
static const GnColor Green;
static const GnColor Black;
static const GnColor White;
float r, g, b;
inline GnColor (float fR = 0.0f, float fG = 0.0f, float fB = 0.0f);
inline GnColor& operator= (float fScalar);
inline bool operator== (const GnColor& c) const;
inline bool operator!= (const GnColor& c) const;
inline GnColor operator+ (const GnColor& c) const;
inline GnColor operator- (const GnColor& c) const;
inline GnColor operator* (float fScalar) const;
inline GnColor operator* (const GnColor& c) const;
inline GnColor operator/ (float fScalar) const;
inline GnColor operator/ (const GnColor& c) const;
inline GnColor operator- () const;
GNMAIN_ENTRY friend GnColor operator* (float fScalar, const GnColor& c);
inline GnColor& operator+= (const GnColor& c);
inline GnColor& operator-= (const GnColor& c);
inline GnColor& operator*= (float fScalar);
inline GnColor& operator*= (const GnColor& c);
inline GnColor& operator/= (float fScalar);
inline GnColor& operator/= (const GnColor& c);
// map (r,g,b,a) to unit hypercube
inline void Clamp();
inline void Scale();
// Function to return the color as an unsigned integer.
inline guint32 GetRGB() const;
inline void GetRGB(guint8& outR, guint8& outG, guint8& outB);
};
inline GnColor::GnColor(float fR, float fG, float fB)
{
r = fR;
g = fG;
b = fB;
}
inline GnColor& GnColor::operator= (float fScalar)
{
r = fScalar;
g = fScalar;
b = fScalar;
return *this;
}
inline bool GnColor::operator== (const GnColor& c) const
{
return ( r == c.r && g == c.g && b == c.b );
}
inline bool GnColor::operator!= (const GnColor& c) const
{
return !(*this == c);
}
inline GnColor GnColor::operator+ (const GnColor& c) const
{
GnColor result = *this;
result.r += c.r;
result.g += c.g;
result.b += c.b;
return result;
}
inline GnColor GnColor::operator- (const GnColor& c) const
{
GnColor result = *this;
result.r -= c.r;
result.g -= c.g;
result.b -= c.b;
return result;
}
inline GnColor GnColor::operator* (float fScalar) const
{
GnColor result = *this;
result.r *= fScalar;
result.g *= fScalar;
result.b *= fScalar;
return result;
}
inline GnColor GnColor::operator* (const GnColor &c) const
{
GnColor result = *this;
result.r *= c.r;
result.g *= c.g;
result.b *= c.b;
return result;
}
inline GnColor GnColor::operator/ (float fScalar) const
{
GnColor result = *this;
result.r /= fScalar;
result.g /= fScalar;
result.b /= fScalar;
return result;
}
inline GnColor GnColor::operator/ (const GnColor &c) const
{
GnColor result = *this;
result.r /= c.r;
result.g /= c.g;
result.b /= c.b;
return result;
}
inline GnColor GnColor::operator- () const
{
return GnColor(-r,-g,-b);
}
inline GnColor operator* (float fScalar, const GnColor& c)
{
return c*fScalar;
}
inline GnColor& GnColor::operator+= (const GnColor& c)
{
r += c.r;
g += c.g;
b += c.b;
return *this;
}
inline GnColor& GnColor::operator-= (const GnColor& c)
{
r -= c.r;
g -= c.g;
b -= c.b;
return *this;
}
inline GnColor& GnColor::operator*= (float fScalar)
{
r *= fScalar;
g *= fScalar;
b *= fScalar;
return *this;
}
inline GnColor& GnColor::operator*= (const GnColor &c)
{
r *= c.r;
g *= c.g;
b *= c.b;
return *this;
}
inline GnColor& GnColor::operator/= (float fScalar)
{
r /= fScalar;
g /= fScalar;
b /= fScalar;
return *this;
}
inline GnColor& GnColor::operator/= (const GnColor &c)
{
r /= c.r;
g /= c.g;
b /= c.b;
return *this;
}
inline void GnColor::Clamp()
{
// Clamp to [0,1]^4. Assumes that (r,g,b,a) >= (0,0,0). This is a
// reasonable assumption since colors are only added or multiplied in
// the lighting system. Note that clamping can cause significant
// changes in the final color.
if ( r > 1.0f )
r = 1.0f;
if ( g > 1.0f )
g = 1.0f;
if ( b > 1.0f )
b = 1.0f;
}
inline void GnColor::Scale()
{
// Scale down by maximum component (preserves the final color).
float fMax = r;
if ( g > fMax )
fMax = g;
if ( b > fMax )
fMax = b;
if ( fMax > 1.0f )
{
float fInvMax = 1.0f/fMax;
r *= fInvMax;
g *= fInvMax;
b *= fInvMax;
}
}
inline guint32 GnColor::GetRGB() const
{
return ( ((int)(r * 255.0f) << 16) | ((int)(g * 255.0f) << 8 ) | (int)(b * 255.0f) );
}
inline void GnColor::GetRGB(guint8& outR, guint8& outG, guint8& outB)
{
outR = (int)(r * 255.0f);
outG = (int)(g * 255.0f);
outB = (int)(b * 255.0f);
}
#endif // GNCOLOR_H | [
"[email protected]"
]
| [
[
[
1,
468
]
]
]
|
3ac8269c2577570087c4c4fceba37eab81375e04 | f6c641b102ebbffb48e93dd554a0b7eb7e639be7 | /Source/Base/Base Compute Library/Compute.hpp | 871264d474a1616b16acc8b0353a78d326a128a4 | []
| no_license | ZAsprose/rtrt-on-gpu | e3ca4921a3429cbc72e0cee8afd946200b83573d | 4949e373c273f963467658ca25d39244da7fb4e6 | refs/heads/master | 2021-01-10T14:42:45.293509 | 2010-08-25T18:37:19 | 2010-08-25T18:37:19 | 53,016,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,774 | hpp | /*
-----------------------------------------------------------------------------
| B A S E C O M P U T E L I B R A R Y |
-----------------------------------------------------------------------------
Copyright (c) 2009 - 2010 Denis Bogolepov ( denisbogol @ gmail.com )
This library 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 library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _OPENCL_TOOLS_
#define _OPENCL_TOOLS_
#include <vector>
#include <Graphics.hpp>
#include <CL/cl_gl.h>
#include "Util.hpp"
/*
* ------------------------------ NOTE -----------------------------
* | |
* | All functions perform check of errors and print result in log |
* | ( text file in the folder with a program executable ). If an |
* | error occurred the program finishes with code #1. |
* | |
* -----------------------------------------------------------------
*/
/*
* Use this macro to set vector class.
*/
#define VECTOR std :: vector
/***************************************************************************************/
/*
* Use this function to check errors.
*/
void cltCheckError ( cl_int error );
/***************************************************************************************/
/*
* Obtain the list of platforms available.
*/
VECTOR < cl_platform_id > cltGetPlatforms ( void );
/*
* Obtain the list of devices available on a platform.
*/
VECTOR < cl_device_id > cltGetDevices ( cl_platform_id platform,
cl_device_type type = CL_DEVICE_TYPE_GPU );
/*
* Obtain the list of devices available on a context.
*/
VECTOR < cl_device_id > cltGetDevices ( cl_context context );
/***************************************************************************************/
/*
* Create an OpenCL context from a device type.
*/
cl_context cltCreateContext ( cl_platform_id platform,
cl_device_type type = CL_DEVICE_TYPE_GPU );
/*
* Create an OpenCL context from a device type
* based on current OpenGL context.
*/
cl_context cltCreateContextFromOpenGL ( cl_platform_id platform,
cl_device_type type = CL_DEVICE_TYPE_GPU );
/*
* Create an OpenCL context with one or more devices.
*/
cl_context cltCreateContext ( cl_platform_id platform,
VECTOR < cl_device_id > & devices );
/*
* Create an OpenCL context with one or more devices
* based on current OpenGL context.
*/
cl_context cltCreateContextFromOpenGL ( cl_platform_id platform,
VECTOR < cl_device_id > & devices );
/***************************************************************************************/
/*
* Create a program object for a context and loads the
* source code from a specified file.
*/
cl_program cltLoadProgram ( cl_context context,
const char * filename,
const char * prefix = NULL );
/*
* Builds a program executable from a program source.
*/
void cltBuildProgram ( cl_program program,
VECTOR < cl_device_id > & devices,
const char * options = NULL );
/***************************************************************************************/
/*
* Create an OpenCL buffer object with specified data type.
* ( template function must be implemented in header file ).
*/
template < class T >
cl_mem cltCreateBuffer ( cl_context context,
cl_mem_flags flags,
size_t count,
T * data = NULL )
{
cl_int error = CL_SUCCESS;
cl_mem buffer = clCreateBuffer (
context /* context */,
flags /* flags */,
count * sizeof ( T ) /* size */,
data /* host_ptr */,
&error /* errcode_ret */ );
if ( error != CL_SUCCESS )
{
EZLOGGERSTREAM << "ERROR: clCreateBuffer failed" << std :: endl;
switch ( error )
{
case CL_INVALID_CONTEXT:
EZLOGGERSTREAM << "CL_INVALID_CONTEXT" << std :: endl; break;
case CL_INVALID_VALUE:
EZLOGGERSTREAM << "CL_INVALID_VALUE" << std :: endl; break;
case CL_INVALID_BUFFER_SIZE:
EZLOGGERSTREAM << "CL_INVALID_BUFFER_SIZE" << std :: endl; break;
case CL_INVALID_HOST_PTR:
EZLOGGERSTREAM << "CL_INVALID_HOST_PTR" << std :: endl; break;
case CL_MEM_OBJECT_ALLOCATION_FAILURE:
EZLOGGERSTREAM << "CL_MEM_OBJECT_ALLOCATION_FAILURE" << std :: endl; break;
case CL_OUT_OF_HOST_MEMORY:
EZLOGGERSTREAM << "CL_OUT_OF_HOST_MEMORY" << std :: endl; break;
default:
EZLOGGERSTREAM << "UNKNOWN_ERROR" << std :: endl;
}
exit ( EXIT_FAILURE );
}
return buffer;
}
/*
* Create an OpenCL 2D image object from an OpenGL 2D texture object.
*/
cl_mem cltCreateImageFromTexture ( cl_context context,
cl_mem_flags flags,
graphics :: Texture2D * texture );
/*
* Create an OpenCL 3D image object from an OpenGL 3D texture object.
*/
cl_mem cltCreateImageFromTexture ( cl_context context,
cl_mem_flags flags,
graphics :: Texture3D * texture );
/*
* Create an OpenCL 2D image object from an OpenGL renderbuffer object.
*/
cl_mem cltCreateImageFromRenderbuffer ( cl_context context,
cl_mem_flags flags,
graphics :: RenderBuffer * buffer );
/***************************************************************************************/
/*
* NOTE: How we can share textures with OpenCL
*
*----------------------------
*
* We start in OpenGL land
*
* do some GL stuff
*
* clEnqueueAcquireGLObjects
*
* Now we are in OpenCL land
*
* do some CL stuff
*
* clEnqueueReleaseGLObjects
*
* back to OpenGL land
*
*----------------------------
*
* clEnqueueAcquireGLObjects and clEnqueueReleaseGLObjects do not do any
* really heavy handed synchronization they are more of a spec thing.
*/
/*
* Acquire OpenCL memory object that has been created from OpenGL
* object. These objects need to be acquired before they can be used
* by any OpenCL commands queued to a command-queue.
*/
void cltAcquireGraphicsObject ( cl_command_queue queue,
const cl_mem & memory,
cl_event * event = NULL );
/*
* Release OpenCL memory objects that have been created from OpenGL
* objects. These objects need to be released before they can be used
* by OpenGL.
*/
void cltReleaseGraphicsObject ( cl_command_queue queue,
const cl_mem & memory,
cl_event * event = NULL );
/***************************************************************************************/
/*
* Create a command-queue on a specific device.
*/
cl_command_queue cltCreateQueue ( cl_context context,
cl_device_id device,
cl_command_queue_properties properties = NULL );
/***************************************************************************************/
/*
* Create a kernel object for a function declared in a program.
*/
cl_kernel cltCreateKernel ( cl_program program, const char * name );
/***************************************************************************************/
/*
* Set the argument value for a specific argument of a kernel
* ( template function must be implemented in header file ).
*/
template < class T >
void cltSetArgument ( cl_kernel kernel,
cl_uint index,
const T * value )
{
cl_int error = clSetKernelArg (
kernel /* kernel */,
index /* arg_index */,
sizeof ( T ) /* arg_size */,
value /* arg_value */ );
if ( error != CL_SUCCESS )
{
EZLOGGERSTREAM << "ERROR: clSetKernelArg failed" << std :: endl;
EZLOGGERVAR ( index );
switch ( error )
{
case CL_INVALID_KERNEL:
EZLOGGERSTREAM << "CL_INVALID_KERNEL" << std :: endl; break;
case CL_INVALID_ARG_INDEX:
EZLOGGERSTREAM << "CL_INVALID_ARG_INDEX" << std :: endl; break;
case CL_INVALID_ARG_VALUE:
EZLOGGERSTREAM << "CL_INVALID_ARG_VALUE" << std :: endl; break;
case CL_INVALID_MEM_OBJECT:
EZLOGGERSTREAM << "CL_INVALID_MEM_OBJECT" << std :: endl; break;
case CL_INVALID_SAMPLER:
EZLOGGERSTREAM << "CL_INVALID_SAMPLER" << std :: endl; break;
case CL_INVALID_ARG_SIZE:
EZLOGGERSTREAM << "CL_INVALID_ARG_SIZE" << std :: endl; break;
default:
EZLOGGERSTREAM << "UNKNOWN_ERROR" << std :: endl;
}
exit ( EXIT_FAILURE );
}
}
/***************************************************************************************/
/*
* Enqueues a command to execute a kernel on a device for 1D index space.
*/
void cltRunKernel1D ( cl_command_queue queue,
cl_kernel kernel,
size_t X, /* global size */
size_t x, /* local size */
cl_event * event = NULL );
/*
* Enqueues a command to execute a kernel on a device for 2D index space.
*/
void cltRunKernel2D ( cl_command_queue queue,
cl_kernel kernel,
size_t X, size_t Y, /* global size */
size_t x, size_t y, /* local size */
cl_event * event = NULL );
/*
* Enqueues a command to execute a kernel on a device for 3D index space.
*/
void cltRunKernel3D ( cl_command_queue queue,
cl_kernel kernel,
size_t X, size_t Y, size_t Z, /* global size */
size_t x, size_t y, size_t z, /* local size */
cl_event * event = NULL );
/***************************************************************************************/
/*
* Issues all previously queued OpenCL commands in a command-queue to
* the device associated with the command-queue.
*/
void cltFlush ( cl_command_queue queue );
/*
* Blocks until all previously queued OpenCL commands in a command-queue
* are issued to the associated device and have completed.
*/
void cltFinish ( cl_command_queue queue );
#endif | [
"[email protected]"
]
| [
[
[
1,
348
]
]
]
|
afcdbc78572e8a0358edf9ae48c244c08c532fd8 | a405cf24ef417f6eca00c688ceb9008d80f84e1a | /trunk/commands.cpp | ca9192b9978816f753c9fb8053fd3d0bb0719871 | []
| no_license | BackupTheBerlios/nassiplugin-svn | 186ac2b1ded4c0bf7994e6309150aa23bc70b644 | abd9d809851d58d7206008b470680a23d0548ef6 | refs/heads/master | 2020-06-02T21:23:32.923994 | 2010-02-23T21:37:37 | 2010-02-23T21:37:37 | 40,800,406 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,847 | cpp | #ifdef __GNUG__
// #pragma implementation
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/txtstrm.h>
#include "commands.h"
/// this command will insert a brick before any other Brick
/// it will check if:
/// - the brick has a brick before,
/// - the Brick is the first of a list of child (a leaf in composite), or
/// - the brick is the first of a diagram.
NassiInsertBrickBefore::NassiInsertBrickBefore(NassiFileContent *nfc, NassiBrick *brick, NassiBrick *InsrBrick)
:wxCommand(true, _T("Insert Brick") )
{
m_nfc = nfc;
m_brick = brick;
m_done = false;
m_nbrk = InsrBrick;
m_nlbrk = m_nbrk;
while ( m_nlbrk->GetNext() )
m_nlbrk = m_nlbrk->GetNext();
}
NassiInsertBrickBefore::~NassiInsertBrickBefore(void)
{
if ( !m_done )
{
if ( m_nbrk != (NassiBrick *)NULL )
delete m_nbrk;
}
}
bool NassiInsertBrickBefore::Do(void)
{
if ( m_done )
return(false);
if (!m_brick)
return(false);
if ( !m_nbrk )
return(false);
NassiBrick *prev = m_brick->GetPrevious();
if ( prev )
{
prev->SetNext(m_nbrk);
//m_nbrk->SetNext(m_brick);
m_nlbrk->SetNext(m_brick);
m_nbrk->SetParent((NassiBrick *)NULL);
m_done = true;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
NassiBrick *par = m_brick->GetParent();
if ( par )
{
//wxMessageDialog dlg(NULL, _T("has Parent"), _T("Info"));
//tdlg.ShowModal();
for ( wxUint32 n = 0 ; n < par->GetChildCount() ; n++ )
{
if ( par->GetChild(n) == m_brick ) // both pointers point to the same brick
{
par->SetChild(m_nbrk, n);
//m_nbrk->SetNext(m_brick);
m_nlbrk->SetNext(m_brick);
m_nbrk->SetPrevious((NassiBrick *)NULL);
m_nbrk->SetParent(par);
m_brick->SetParent((NassiBrick *)NULL);
m_done = true;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
}
return(false);
}
if ( m_nfc->GetFirstBrick() == m_brick ) // no previos and no parent
{
m_nfc->SetFirstBrick(m_nbrk);
//m_nbrk->SetNext(m_brick);
m_nlbrk->SetNext(m_brick);
m_nbrk->SetParent((NassiBrick *)NULL);
m_nbrk->SetPrevious((NassiBrick *)NULL);
//m_brick->SetParent((NassiBrick *)NULL);
m_done = true;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
return(false);
}
bool NassiInsertBrickBefore::Undo(void)
{
if ( !m_done)
return(false);
if ( !m_brick )
return(false);
NassiBrick *prev = m_nbrk->GetPrevious();
if ( prev )
{
prev->SetNext(m_brick);
m_brick->SetParent((NassiBrick *)NULL);
//m_nbrk->SetNext((NassiBrick *)NULL);
m_nlbrk->SetNext((NassiBrick *)NULL);
m_nbrk->SetPrevious((NassiBrick *)NULL);
m_nbrk->SetParent((NassiBrick *)NULL);
m_done = false;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
NassiBrick *par = m_nbrk->GetParent();
if ( par )
{
for ( wxUint32 n = 0 ; n < par->GetChildCount() ; n++ )
{
if ( par->GetChild(n) == m_nbrk )
{
par->SetChild(m_brick,n);
m_brick->SetPrevious((NassiBrick *)NULL);
m_nbrk->SetPrevious((NassiBrick *)NULL);
m_nbrk->SetParent((NassiBrick *)NULL);
//m_nbrk->SetNext((NassiBrick *)NULL);
m_nlbrk->SetNext((NassiBrick *)NULL);
m_done = false;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
}
return(false);
}
if ( m_nfc->GetFirstBrick() == m_nbrk )
{
m_nfc->SetFirstBrick(m_brick);
m_brick->SetPrevious((NassiBrick *)NULL);
m_brick->SetParent((NassiBrick *)NULL);
//m_nbrk->SetNext((NassiBrick *)NULL);
m_nlbrk->SetNext((NassiBrick *)NULL);
m_nbrk->SetPrevious((NassiBrick *)NULL);
m_nbrk->SetParent((NassiBrick *)NULL);
m_done = false;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
return(false);
}
/// this command will insert a brick after another brick
/// nothing to check
NassiInsertBrickAfter::NassiInsertBrickAfter( NassiFileContent *nfc, NassiBrick *brick, NassiBrick *InsrBrick)
: wxCommand(true, _T("Insert Brick") )
{
m_nfc = nfc;
m_brick = brick;
//m_tool = tool;
m_done = false;
m_nbrk = InsrBrick;
m_nlbrk = m_nbrk;
while ( m_nlbrk->GetNext() != (NassiBrick *)NULL )
m_nlbrk = m_nlbrk->GetNext();
}
NassiInsertBrickAfter::~NassiInsertBrickAfter(void)
{
if ( !m_done )
{
if ( m_nbrk != (NassiBrick *)NULL )
delete m_nbrk;
}
}
bool NassiInsertBrickAfter::Do(void)
{
if ( m_done )
return(false);
if ( !m_brick )
return(false);
NassiBrick *next = m_brick->GetNext();
if ( next != (NassiBrick *)NULL )
{
m_brick->SetNext(m_nbrk);
//m_nbrk->SetNext(next);
m_nlbrk->SetNext(next);
m_nbrk->SetParent((NassiBrick *)NULL);
}
else
{
m_brick->SetNext(m_nbrk);
//m_nbrk->SetNext((NassiBrick *)NULL);
m_nlbrk->SetNext((NassiBrick *)NULL);
m_nbrk->SetParent((NassiBrick *)NULL);
}
m_done = true;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
bool NassiInsertBrickAfter::Undo(void)
{
if ( !m_done )
return(false);
if ( !m_brick )
return(false);
//m_brick->SetNext(m_nbrk->GetNext());
m_brick->SetNext(m_nlbrk->GetNext());
//m_nbrk->SetNext((NassiBrick *)NULL);
m_nlbrk->SetNext((NassiBrick *)NULL);
m_done = false;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
///this command will insert a brick as the first of a diagram
NassiInsertFirstBrick::NassiInsertFirstBrick( NassiFileContent *nfc, NassiBrick *InsrBrick, bool CanUndo)
:wxCommand(CanUndo, _T("Insert Brick") )
{
m_nfc = nfc;
//m_tool = tool;
m_done = false;
m_nbrk = InsrBrick;
m_nlbrk = m_nbrk;
while ( m_nlbrk->GetNext() )
m_nlbrk = m_nlbrk->GetNext();
}
NassiInsertFirstBrick::~NassiInsertFirstBrick(void)
{
if ( !m_done )
{
if ( m_nbrk != (NassiBrick *)NULL )
delete m_nbrk;
}
}
bool NassiInsertFirstBrick::Do(void)
{
if ( m_done )
return(false);
if ( m_nbrk == (NassiBrick *)NULL )
return(false);
m_nbrk->SetPrevious((NassiBrick *)NULL);
m_nbrk->SetParent((NassiBrick *)NULL);
m_nfc->SetFirstBrick(m_nbrk);
//m_nbrk->SetNext((NassiBrick *)NULL);
m_nbrk = (NassiBrick *)NULL;
m_done = true;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
bool NassiInsertFirstBrick::Undo(void)
{
if ( !m_done )
return(false);
m_nbrk = m_nfc->GetFirstBrick();
m_nfc->SetFirstBrick((NassiBrick *)NULL);
//m_nbrk->SetNext((NassiBrick *)NULL);
//m_nbrk->SetPrevious((NassiBrick *)NULL);
//m_nbrk->SetParent((NassiBrick *)NULL);
m_done = false;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
///this command will add a child a new case of a switch command
NassiAddChildIndicatorCommand::NassiAddChildIndicatorCommand( NassiFileContent *nfc, NassiBrick *brick, NassiBrick *InsrBrick, wxUint32 ChildAddNumber, wxString _strc, wxString _strs )
:wxCommand(true, _T("Insert Brick") ),
m_nfc(nfc),
m_brick(brick),
m_done(false),
m_ChildAddNumber(ChildAddNumber),
m_nbrk(InsrBrick),
m_nlbrk(InsrBrick),
strc(_strc),
strs(_strs)
{
if ( m_nlbrk )
while ( m_nlbrk->GetNext() )
m_nlbrk = m_nlbrk->GetNext();
}
NassiAddChildIndicatorCommand::~NassiAddChildIndicatorCommand(void)
{
if ( !m_done && m_nbrk )
delete m_nbrk;
}
bool NassiAddChildIndicatorCommand::Do(void)
{
if ( m_done || !m_brick || (m_ChildAddNumber > m_brick->GetChildCount()) ) return false;
m_brick->AddChild( m_ChildAddNumber );
m_brick->SetChild( m_nbrk, m_ChildAddNumber );
m_brick->SetTextByNumber( strc , 2*(m_ChildAddNumber+1) );
m_brick->SetTextByNumber( strs , 2*(m_ChildAddNumber+1)+1 );
m_done = true;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return true ;
}
bool NassiAddChildIndicatorCommand::Undo(void)
{
if ( !m_done || !m_brick || m_ChildAddNumber >= m_brick->GetChildCount() ) return false;
m_brick->SetChild((NassiBrick *)NULL, m_ChildAddNumber);
m_brick->RemoveChild(m_ChildAddNumber);
m_done = false;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return true;
}
NassiInsertChildBrickCommand::NassiInsertChildBrickCommand( NassiFileContent *nfc, NassiBrick *brick, NassiBrick *InsrBrick, wxUint32 ChildNumber):
wxCommand(true, _T("Insert Brick") ),
m_nfc(nfc),
m_brick(brick),
m_done(false),
m_nbrk(InsrBrick),
m_nlbrk(InsrBrick),
m_childNumber(ChildNumber)
{
if ( m_nlbrk )
while ( m_nlbrk->GetNext() )
m_nlbrk = m_nlbrk->GetNext();
}
NassiInsertChildBrickCommand::~NassiInsertChildBrickCommand(void)
{
if ( !m_done && m_nbrk != (NassiBrick *)NULL )
delete m_nbrk;
}
bool NassiInsertChildBrickCommand::Do(void)
{
if ( m_done || !m_brick || m_childNumber >= m_brick->GetChildCount() )
return false;
m_brick->SetChild( m_nbrk, m_childNumber );
m_nbrk->SetParent(m_brick);
m_nlbrk->SetNext((NassiBrick *)NULL);
m_nbrk->SetPrevious((NassiBrick *)NULL);
m_done = true;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
bool NassiInsertChildBrickCommand::Undo(void)
{
if ( ! m_done )
return(false);
if ( !m_brick )
return(false);
if ((m_childNumber >= m_brick->GetChildCount()) || (m_childNumber < 0) )
return(false);
m_brick->SetChild((NassiBrick *)NULL, m_childNumber);
m_done = false;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return(true);
}
/// used command to change text
NassiEditTextCommand::NassiEditTextCommand( NassiFileContent *nfc, NassiBrick *brick, const wxString &str, wxInt32 nmbr)
:wxCommand(true, _T("Change Text") )
{
m_nfc = nfc;
m_str = str;
m_brick = brick;
m_nmbr = nmbr;
}
NassiEditTextCommand::~NassiEditTextCommand(void)
{}
bool NassiEditTextCommand::Do(void)
{
if ( m_brick )
{
wxString str;
str = *(m_brick->GetTextByNumber(m_nmbr));
m_brick->SetTextByNumber(m_str,m_nmbr);
m_str = str;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return true;
}
return false;
}
bool NassiEditTextCommand::Undo(void)
{
return(Do());
}
/// will delete a brick (and the following ,first till (including) last )
NassiDeleteCommand::NassiDeleteCommand( NassiFileContent *nfc, NassiBrick *first, NassiBrick *last)
: wxCommand(true, _T("Delete selected bricks"))
{
m_nfc = nfc;
m_first = first;
m_last = last;
m_done = false;
//m_isdndmove = isDnDMoveInOneView;
parPrev = (NassiBrick*)NULL;
m_childnmbr = -1;
strc.Empty();
strs.Empty();
firstCall = true;
}
NassiDeleteCommand::~NassiDeleteCommand(void)
{
if ( m_done )
{
m_last->SetNext((NassiBrick *)NULL);
if ( m_first )
delete m_first;
}
}
bool NassiDeleteCommand::Do(void)
{
if ( !m_done && m_first && m_last )
{
if ( m_first->GetPrevious() )
{
m_childnmbr = -1;
parPrev = m_first->GetPrevious();
parPrev->SetNext( m_last->GetNext() );
m_last->SetNext((NassiBrick *)NULL);
m_nfc->Modify(true);
m_nfc->NotifyObservers();
m_done = true;
return(true);
}
else
{
if ( m_first->GetParent() )
{
parPrev = m_first->GetParent();
for ( wxUint32 n = 0 ; n < parPrev->GetChildCount() ; n++ )
{
if ( parPrev->GetChild(n) == m_first)
{
m_childnmbr = n;
strc = *(parPrev->GetTextByNumber( 2*(n+1) ));
strs = *(parPrev->GetTextByNumber( 2*(n+1)+1 ));
parPrev->SetChild(m_last->GetNext(), n);
if ( ! m_last->GetNext() ) // for a switch Brick:
{
//parPrev->RemoveChild(n);
}
m_last->SetNext((NassiBrick *)NULL);
m_nfc->Modify(true);
m_nfc->NotifyObservers();
m_done = true;
return(true);
}
}
}
else
{
m_childnmbr = -1;
NassiBrick *newfirst = m_last->GetNext();
if ( newfirst )
{
newfirst->SetPrevious( (NassiBrick *)NULL );
newfirst->SetParent( (NassiBrick *)NULL );
}
m_nfc->SetFirstBrick( newfirst );
m_last->SetNext((NassiBrick *)NULL);
m_nfc->Modify(true);
m_nfc->NotifyObservers();
m_done = true;
return(true);
}
}
}
m_done = false;
return false ;
}
bool NassiDeleteCommand::Undo(void)
{
if ( m_done )
{
if ( m_first->GetPrevious() && parPrev )
{
m_last->SetNext(parPrev->GetNext());
parPrev->SetNext(m_first);
m_nfc->Modify(true);
m_nfc->NotifyObservers();
m_done = false;
return(true);
}
else if ( m_first->GetParent() && parPrev )
{
if ( ! m_last->GetNext() )
{
//parPrev->AddChild(m_childnmbr);
}
m_last->SetNext(parPrev->GetChild(m_childnmbr));
parPrev->SetChild( m_first, m_childnmbr);
parPrev->SetTextByNumber(strc, 2*(m_childnmbr+1) );
parPrev->SetTextByNumber(strs, 2*(m_childnmbr+1)+1 );
m_nfc->Modify(true);
m_nfc->NotifyObservers();
m_done = false;
return(true);
}
else
{
NassiBrick *oldfirst = m_nfc->GetFirstBrick();
m_last->SetNext(oldfirst);
m_nfc->SetFirstBrick(m_first);
m_nfc->Modify(true);
m_nfc->NotifyObservers();
m_done = false;
return(true);
}
}
return( false );
}
NassiDeleteChildRootCommand::NassiDeleteChildRootCommand(
NassiFileContent *nfc, NassiBrick *parent, wxInt32 childNumber):
wxCommand(true, _T("Delete selected bricks")),
m_nfc(nfc),
m_parent(parent),
m_done(false),
m_delcmd(NULL),
m_childNmbr(childNumber)
{
m_strC = *parent->GetTextByNumber( 2*(childNumber+1) );
m_strS = *parent->GetTextByNumber( 2*(childNumber+1)+1 );
}
NassiDeleteChildRootCommand::~NassiDeleteChildRootCommand(void)
{
if ( m_delcmd )
delete m_delcmd;
}
bool NassiDeleteChildRootCommand::Do(void)
{
if ( !m_done )
{
m_done = true;
if ( !m_delcmd )
{
delete m_delcmd;
m_delcmd = NULL;
}
NassiBrick *first = m_parent->GetChild(m_childNmbr);
NassiBrick *last = first;
if ( first )
{
while ( last->GetNext() ) last = last->GetNext();
m_delcmd = new NassiDeleteCommand( m_nfc, first, last);
m_done = m_delcmd->Do();
}
m_parent->RemoveChild(m_childNmbr);
m_nfc->Modify(true);
m_nfc->NotifyObservers();
}
return m_done;
}
bool NassiDeleteChildRootCommand::Undo(void)
{
if ( m_done )
{
m_parent->AddChild(m_childNmbr);
m_parent->SetTextByNumber(m_strC, 2*( m_childNmbr + 1 ) );
m_parent->SetTextByNumber(m_strS, 2*( m_childNmbr + 1 ) + 1 );
m_nfc->Modify(true);
m_nfc->NotifyObservers();
m_done = false;
if ( m_delcmd )
return m_delcmd->Undo();
return true;
}
return false;
}
/// moving a brick will add a copy of the brick to move and
/// deletes the original brick.
///////////////////////////
NassiMoveBrick::NassiMoveBrick( wxCommand *addCmd, wxCommand *delCmd)
:wxCommand(true, _T("Drag n Drop Brick"))
{
m_delCmd = delCmd;
m_addCmd = addCmd;
}
NassiMoveBrick::~NassiMoveBrick()
{
if ( m_addCmd )
delete m_addCmd;
if ( m_delCmd )
delete m_delCmd;
}
bool NassiMoveBrick::Do(void)
{
if ( ! m_addCmd )
return(false);
bool res = true;
if ( res )
res = m_addCmd->Do();
if ( m_delCmd )
res = m_delCmd->Do();
return( res );
}
bool NassiMoveBrick::Undo(void)
{
if ( ! m_addCmd )
return(false);
bool res = true;
if ( m_delCmd )
res = m_delCmd->Undo();
if ( res )
res = m_addCmd->Undo();
return( res );
}
/*NassiAddFunctionCommand::NassiAddFunctionCommand( NassiDocument *doc, wxInt32 nmbr):
wxCommand(true, _T("Add Function") )
{
m_nfc = doc;
functionNumber = nmbr;
}
NassiAddFunctionCommand::~NassiAddFunctionCommand(void)
{}
bool NassiAddFunctionCommand::Do(void)
{
//m_nfc->AddFirstBrick(functionNumber, (NassiBrick *)NULL );
//m_nfc->Modify(true);
//m_nfc->NotifyObservers();
return true;
}
bool NassiAddFunctionCommand::Undo(void)
{
//m_nfc->RemoveFirstBrick(functionNumber);
//m_nfc->Modify(true);
//m_nfc->NotifyObservers();
return true;
}*/
/*NassiRenameFunctionCommand::NassiRenameFunctionCommand( NassiDocument *doc, wxInt32 nmbr, wxString newName)
:wxCommand(true, _T("Rename function"))
{
m_nfc = doc;
fname = newName;
functionNumber = nmbr;
}
NassiRenameFunctionCommand::~NassiRenameFunctionCommand(void)
{}
bool NassiRenameFunctionCommand::Do(void)
{
wxString oldName = m_nfc->GetFunctionName(functionNumber);
wxInt32 n = oldName.Find('\n');
if ( n != -1 )
{
fname += oldName.Mid(n+1);
}
m_nfc->SetFunctionName(functionNumber, fname);
fname = oldName;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return true;
}
bool NassiRenameFunctionCommand::Undo(void)
{
return Do();
}
*/
/*NassiDeleteFunctionCommand::NassiDeleteFunctionCommand(NassiDocument *doc, wxInt32 nmbr)
: wxCommand(true, _T("Remove Function"))
{
m_nfc = doc;
m_done = false;
firstbrick = (NassiBrick *)NULL;
m_nmbr = nmbr;
}
NassiDeleteFunctionCommand::~NassiDeleteFunctionCommand(void)
{
if ( m_done )
{
if ( firstbrick )
delete firstbrick;
}
}
bool NassiDeleteFunctionCommand::Do(void)
{
if ( ! m_done )
{
Name = m_nfc->GetFunctionName(m_nmbr);
otherSrc = m_nfc->GetOtherText(m_nmbr);
//firstbrick = m_nfc->RemoveFirstBrick(m_nmbr);
m_done = true;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return true;
}
else
return false;
}
bool NassiDeleteFunctionCommand::Undo(void)
{
if ( m_done )
{
//m_nfc->AddFirstBrick(m_nmbr, firstbrick);
m_nfc->SetFunctionName(m_nmbr, Name);
m_nfc->SetOtherText(m_nmbr, otherSrc);
firstbrick = (NassiBrick *)NULL;
m_done = false;
m_nfc->Modify(true);
m_nfc->NotifyObservers();
return true;
}
else
return false;
}*/
| [
"danselmi@1ca45b2e-1973-0410-a226-9012aad761af"
]
| [
[
[
1,
748
]
]
]
|
a89b75fb7e0ce4ff3ec58b96bca8671f31681906 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Common/Compat/Deprecated/UnitTest/Xml/StressTest.h | 3433e38eb6ab74efaec6f3c5b52c86e41acaaaf1 | []
| 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 | 1,865 | 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.
*
*/
#include <Common/Base/hkBase.h>
#include <Common/Serialize/Util/hkStructureLayout.h>
class hkStressTestCinfo;
class StressTest : public hkReferencedObject
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_DEMO);
enum DuplicateEnumName
{
VALUE_FOO
};
StressTest( const hkStressTestCinfo& info ) { }
void getCinfo(hkStressTestCinfo&) const { }
void updateFromCinfo(const hkStressTestCinfo&) { }
const hkClass* getClass() const;
public:
hkStructureLayout m_layout;
};
class StressTest2 : public hkReferencedObject
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_DEMO);
enum DuplicateEnumName
{
VALUE_FOO
};
};
/*
* 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,
59
]
]
]
|
2b5a465d501a47bd6b7e5917d44c3bf7ea282ec3 | c175910763a4ed175cdbfc58f539aece471f5256 | /truck/3d-cg/3DCG/glib/Math/Matrix4x4_Reference.h | dd2a93d8b15f3a38bb23d34692fc6e8dec58d5ed | []
| no_license | KiraiChang/3d-cg | 357c8315a349653a6cbe7a339cefa04078db4b3d | dbbd66c4331f117857dbfa660991c2ded01d3738 | refs/heads/master | 2021-01-22T09:32:10.976546 | 2010-04-27T06:59:57 | 2010-04-27T06:59:57 | 32,336,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,712 | h | #ifndef _MATRIX4x4_GENERAL_
#define _MATRIX4x4_GENERAL_
#if !defined(_ENABLE_GENERALCPU_)
#define _ENABLE_GENERALCPU_
#endif
#include "Vector4.h"
class Matrix4x4CPU;
extern Matrix4x4CPU g_MatrixCPU_Identity;
inline Vector4CPU operator*(Vector4CPU &v, Matrix4x4CPU &matrix);
inline Matrix4x4CPU operator*(Matrix4x4CPU &a, Matrix4x4CPU &b);
class Matrix4x4CPU
{
public:
union
{
struct
{
float m_00, m_01, m_02, m_03;
float m_10, m_11, m_12, m_13;
float m_20, m_21, m_22, m_23;
float m_30, m_31, m_32, m_33;
};
struct
{
Vector4CPU m_Vec0, m_Vec1, m_Vec2, m_Vec3;
};
};
public:
inline Matrix4x4CPU()
{
}
inline Matrix4x4CPU(
float f00, float f01, float f02, float f03,
float f10, float f11, float f12, float f13,
float f20, float f21, float f22, float f23,
float f30, float f31, float f32, float f33
)
{
m_00 = f00; m_01 = f01; m_02 = f02; m_03 = f03;
m_10 = f10; m_11 = f11; m_12 = f12; m_13 = f13;
m_20 = f20; m_21 = f21; m_22 = f22; m_23 = f23;
m_30 = f30; m_31 = f31; m_32 = f32; m_33 = f33;
}
inline void Identity(void)
{
/*
m_00 = 1.0f; m_01 = 0.0f; m_02 = 0.0f; m_03 = 0.0f;
m_10 = 0.0f; m_11 = 1.0f; m_12 = 0.0f; m_13 = 0.0f;
m_20 = 0.0f; m_21 = 0.0f; m_22 = 1.0f; m_23 = 0.0f;
m_30 = 0.0f; m_31 = 0.0f; m_32 = 0.0f; m_33 = 1.0f;
*/
*this = g_MatrixCPU_Identity;
}
static Matrix4x4CPU &IdentityMatrix(void)
{
return g_MatrixCPU_Identity;
}
inline void SetRow(int row, Vector4CPU &vec)
{
assert(row>=0 && row<4);
Vector4CPU *rows = &m_Vec0;
rows[row] = vec;
}
inline void SetColumn(int column, Vector4CPU &vec)
{
assert(column>=0 && column<4);
float *p = &m_00 + column;
p[0] = vec.GetX();
p[4] = vec.GetY();
p[8] = vec.GetZ();
p[12] = vec.GetW();
}
inline Vector4CPU &GetRow(int row)
{
assert(row>=0 && row<4);
Vector4CPU *rows = &m_Vec0;
return rows[row];
}
inline Vector4CPU GetColumn(int column)
{
assert(column>=0 && column<4);
Vector4CPU vec;
float *p = &m_00 + column;
vec.SetX(p[0]);
vec.SetY(p[4]);
vec.SetZ(p[8]);
vec.SetW(p[12]);
return vec;
}
inline Matrix4x4CPU &Transpose(void)
{
FastMath::Swap(m_01,m_10);
FastMath::Swap(m_02,m_20);
FastMath::Swap(m_03,m_30);
FastMath::Swap(m_12,m_21);
FastMath::Swap(m_13,m_31);
FastMath::Swap(m_23,m_32);
return *this;
}
// assume input vec.w equals 1
// result.w is garbage
inline Vector4CPU TransformVec3(Vector4CPU &vec)
{
Vector4CPU result = vec * (*this);
return result;
}
void Rotate( Vector4CPU &v, float radian)
{
float x = v.x;
float y = v.y;
float z = v.z;
float w = v.w;
float fSin, fCos;
FastMath::SinCos(radian, fSin, fCos);
Matrix4x4CPU local, final;
local.m_00 = ( x * x ) * ( 1.0f - fCos ) + fCos;
local.m_01 = ( x * y ) * ( 1.0f - fCos ) + (z * fSin);
local.m_02 = ( x * z ) * ( 1.0f - fCos ) - (y * fSin);
local.m_03 = 0.0f;
local.m_10 = ( y * x ) * ( 1.0f - fCos ) - (z * fSin);
local.m_11 = ( y * y ) * ( 1.0f - fCos ) + fCos ;
local.m_12 = ( y * z ) * ( 1.0f - fCos ) + (x * fSin);
local.m_13 = 0.0f;
local.m_20 = ( z * x ) * ( 1.0f - fCos ) + (y * fSin);
local.m_21 = ( z * y ) * ( 1.0f - fCos ) - (x * fSin);
local.m_22 = ( z * z ) * ( 1.0f - fCos ) + fCos;
local.m_23 = 0.0f;
local.m_30 = 0.0f;
local.m_31 = 0.0f;
local.m_32 = 0.0f;
local.m_33 = 1.0f;
final = local * (*this);
*this = final;
}
void Rotate_Replace( Vector4CPU &v, float radian)
{
float x = v.x;
float y = v.y;
float z = v.z;
float w = v.w;
float fSin, fCos;
FastMath::SinCos(radian, fSin, fCos);
m_00 = ( x * x ) * ( 1.0f - fCos ) + fCos;
m_01 = ( x * y ) * ( 1.0f - fCos ) + (z * fSin);
m_02 = ( x * z ) * ( 1.0f - fCos ) - (y * fSin);
m_03 = 0.0f;
m_10 = ( y * x ) * ( 1.0f - fCos ) - (z * fSin);
m_11 = ( y * y ) * ( 1.0f - fCos ) + fCos ;
m_12 = ( y * z ) * ( 1.0f - fCos ) + (x * fSin);
m_13 = 0.0f;
m_20 = ( z * x ) * ( 1.0f - fCos ) + (y * fSin);
m_21 = ( z * y ) * ( 1.0f - fCos ) - (x * fSin);
m_22 = ( z * z ) * ( 1.0f - fCos ) + fCos;
m_23 = 0.0f;
m_30 = 0.0f;
m_31 = 0.0f;
m_32 = 0.0f;
m_33 = 1.0f;
}
void Rotate( float x, float y, float z, float radian )
{
Vector4CPU v(x, y, z, 0.0f);
Rotate(v, radian);
}
void Rotate_Replace(float x, float y, float z, float radian)
{
Vector4CPU v(x, y, z, 0.0f);
Rotate_Replace(v, radian);
}
// this = Rx * this
void RotateX( const float radian )
{
float Sin, Cos;
FastMath::SinCos(radian, Sin, Cos);
float Temp10, Temp11, Temp12, Temp13;
float Temp20, Temp21, Temp22, Temp23;
Temp10 = m_10 * Cos + m_20 * Sin;
Temp11 = m_11 * Cos + m_21 * Sin;
Temp12 = m_12 * Cos + m_22 * Sin;
Temp13 = m_13 * Cos + m_23 * Sin;
Temp20 = m_10 *-Sin + m_20 * Cos;
Temp21 = m_11 *-Sin + m_21 * Cos;
Temp22 = m_12 *-Sin + m_22 * Cos;
Temp23 = m_13 *-Sin + m_23 * Cos;
m_10 = Temp10;
m_11 = Temp11;
m_12 = Temp12;
m_13 = Temp13;
m_20 = Temp20;
m_21 = Temp21;
m_22 = Temp22;
m_23 = Temp23;
}
void RotateX_Replace( const float radian )
{
float fSin, fCos;
FastMath::SinCos(radian, fSin, fCos);
m_Vec0.Set(1.0f, 0.0f, 0.0f, 0.0f);
m_Vec1.Set(0.0f, fCos, fSin, 0.0f);
m_Vec2.Set(0.0f, -fSin, fCos, 0.0f);
m_Vec3.Set(0.0f, 0.0f, 0.0f, 1.0f);
}
// this = Ry * this
void RotateY( const float radian )
{
float Temp00, Temp01, Temp02, Temp03;
float Temp20, Temp21, Temp22, Temp23;
float Sin, Cos;
FastMath::SinCos(radian, Sin, Cos);
Temp00 = m_00 * Cos - m_20 * Sin;
Temp01 = m_01 * Cos - m_21 * Sin;
Temp02 = m_02 * Cos - m_22 * Sin;
Temp03 = m_03 * Cos - m_23 * Sin;
Temp20 = m_00 * Sin + m_20 * Cos;
Temp21 = m_01 * Sin + m_21 * Cos;
Temp22 = m_02 * Sin + m_22 * Cos;
Temp23 = m_03 * Sin + m_23 * Cos;
m_00 = Temp00;
m_01 = Temp01;
m_02 = Temp02;
m_03 = Temp03;
m_20 = Temp20;
m_21 = Temp21;
m_22 = Temp22;
m_23 = Temp23;
}
void RotateY_Replace( const float radian )
{
float fSin, fCos;
FastMath::SinCos(radian, fSin, fCos);
m_Vec0.Set( fCos, 0.0f, -fSin, 0.0f);
m_Vec1.Set( 0.0f, 1.0f, 0.0f, 0.0f);
m_Vec2.Set(-fSin, 0.0f, fCos, 0.0f);
m_Vec3.Set( 0.0f, 0.0f, 0.0f, 1.0f);
}
// this = Rx * this
void RotateZ( const float radian )
{
float Temp00, Temp01, Temp02, Temp03;
float Temp10, Temp11, Temp12, Temp13;
float Sin, Cos;
FastMath::SinCos(radian, Sin, Cos);
Temp00 = m_00 * Cos + m_10 * Sin;
Temp01 = m_01 * Cos + m_11 * Sin;
Temp02 = m_02 * Cos + m_12 * Sin;
Temp03 = m_03 * Cos + m_13 * Sin;
Temp10 = m_00 *-Sin + m_10 * Cos;
Temp11 = m_01 *-Sin + m_11 * Cos;
Temp12 = m_02 *-Sin + m_12 * Cos;
Temp13 = m_03 *-Sin + m_13 * Cos;
m_00 = Temp00;
m_01 = Temp01;
m_02 = Temp02;
m_03 = Temp03;
m_10 = Temp10;
m_11 = Temp11;
m_12 = Temp12;
m_13 = Temp13;
}
void RotateZ_Replace( const float radian )
{
float fSin, fCos;
FastMath::SinCos(radian, fSin, fCos);
m_Vec0.Set( fCos, fSin, 0.0f, 0.0f);
m_Vec1.Set(-fSin, fCos, 0.0f, 0.0f);
m_Vec2.Set( 0.0f, 0.0f, 1.0f, 0.0f);
m_Vec3.Set( 0.0f, 0.0f, 0.0f, 1.0f);
}
void Scale(Vector4CPU &scale)
{
Scale(scale[0], scale[1], scale[2]);
}
void Scale(float x, float y, float z)
{
m_Vec0 *= x;
m_Vec1 *= y;
m_Vec2 *= z;
}
void Scale_Replace(Vector4CPU &scale)
{
Scale_Replace(scale[0], scale[1], scale[2]);
}
void Scale_Replace(float x, float y, float z)
{
m_Vec0.Set(x, 0, 0, 0);
m_Vec1.Set(0, y, 0, 0);
m_Vec2.Set(0, 0, z, 0);
m_Vec3.Set(0, 0, 0, 1);
}
inline Matrix4x4CPU &FastInvert(void)
{
Vector4CPU pos = VectorInvertSign(m_Vec3);
m_Vec3 = g_MatrixCPU_Identity.m_Vec3;
Transpose();
Translate(pos);
return *this;
}
Matrix4x4CPU &Invert(void);
// this = T * this
void Translate(float x, float y, float z)
{
m_Vec3 += m_Vec0 * x + m_Vec1 * y + m_Vec2 * z;
}
void Translate(Vector4CPU &v)
{
m_Vec3 += m_Vec0 * v.GetX() + m_Vec1 * v.GetY() + m_Vec2 * v.GetZ();
}
void Translate_Replace(float x, float y, float z)
{
Identity();
m_Vec3[0] = x;
m_Vec3[1] = y;
m_Vec3[2] = z;
}
void Translate_Replace(Vector4CPU &v)
{
Identity();
m_Vec3 = v;
}
void TranslateX(float d)
{
Vector4CPU dddd(d);
m_Vec3 += m_Vec0 * dddd;
}
void TrsnalteY(float d)
{
Vector4CPU dddd(d);
m_Vec3 += m_Vec1 * dddd;
}
void TranslateZ(float d)
{
Vector4CPU dddd(d);
m_Vec3 += m_Vec2 * dddd;
}
Vector4CPU RotateVector(Vector4CPU &v)
{
Vector4CPU result;
result.x = v.x*m_00 + v.y*m_10 + v.z*m_20;
result.y = v.x*m_01 + v.y*m_11 + v.z*m_21;
result.z = v.x*m_02 + v.y*m_12 + v.z*m_22;
result.w = 1.0f;
return result;
}
void NoTranslate(void)
{
m_Vec3 = IdentityMatrix()[3];
}
void NoRotate(void)
{
m_Vec0 = IdentityMatrix()[0];
m_Vec1 = IdentityMatrix()[1];
m_Vec2 = IdentityMatrix()[2];
}
void SetMatrix3x4(Matrix4x4CPU &mat)
{
m_Vec0 = mat[0];
m_Vec1 = mat[1];
m_Vec2 = mat[2];
}
void ConsoleOutput(void);
// operator
inline float &operator() (int i, int j)
{
assert(i>=0 && i<4);
assert(j>=0 && j<4);
return GetRow(i)[j];
}
inline Vector4CPU &operator[](int row)
{
return GetRow(row);
}
inline Matrix4x4CPU &operator=(Matrix4x4CPU &rhs)
{
m_Vec0 = rhs.m_Vec0;
m_Vec1 = rhs.m_Vec1;
m_Vec2 = rhs.m_Vec2;
m_Vec3 = rhs.m_Vec3;
return *this;
}
inline Matrix4x4CPU &operator=(float f)
{
Vector4CPU ffff(f);
m_Vec0 = ffff;
m_Vec1 = ffff;
m_Vec2 = ffff;
m_Vec3 = ffff;
return *this;
}
inline Matrix4x4CPU &operator+=(float f)
{
Vector4CPU ffff(f);
m_Vec0 += ffff;
m_Vec1 += ffff;
m_Vec2 += ffff;
m_Vec3 += ffff;
return *this;
}
inline Matrix4x4CPU &operator+=(Matrix4x4CPU &rhs)
{
m_Vec0 += rhs.m_Vec0;
m_Vec1 += rhs.m_Vec1;
m_Vec2 += rhs.m_Vec2;
m_Vec3 += rhs.m_Vec3;
return *this;
}
inline Matrix4x4CPU &operator-=(float f)
{
Vector4CPU ffff(f);
m_Vec0 -= f;
m_Vec1 -= f;
m_Vec2 -= f;
m_Vec3 -= f;
return *this;
}
inline Matrix4x4CPU &operator-=(Matrix4x4CPU &rhs)
{
m_Vec0 -= rhs.m_Vec0;
m_Vec1 -= rhs.m_Vec1;
m_Vec2 -= rhs.m_Vec2;
m_Vec3 -= rhs.m_Vec3;
return *this;
}
inline Matrix4x4CPU &operator*=(float f)
{
m_Vec0 *= f;
m_Vec1 *= f;
m_Vec2 *= f;
m_Vec3 *= f;
return *this;
}
inline Matrix4x4CPU &operator*=(Matrix4x4CPU &rhs)
{
m_Vec0 = m_Vec0 * rhs;
m_Vec1 = m_Vec1 * rhs;
m_Vec2 = m_Vec2 * rhs;
m_Vec3 = m_Vec3 * rhs;
return *this;
}
inline Matrix4x4CPU &operator/=(float f)
{
m_Vec0 /= f;
m_Vec1 /= f;
m_Vec2 /= f;
m_Vec3 /= f;
return *this;
}
};
inline bool operator==(Matrix4x4CPU &a, Matrix4x4CPU &b)
{
// true if all vectors equal to each other
bool result = a.m_Vec0==b.m_Vec0 && a.m_Vec1==b.m_Vec1 && a.m_Vec2==b.m_Vec2 && a.m_Vec3==b.m_Vec3;
return result;
}
inline bool operator!=(Matrix4x4CPU &a, Matrix4x4CPU &b)
{
// true if any one vector not-equal
bool result = a.m_Vec0!=b.m_Vec0 || a.m_Vec1!=b.m_Vec1 || a.m_Vec2!=b.m_Vec2 || a.m_Vec3!=b.m_Vec3;
return result;
}
inline Matrix4x4CPU operator+(Matrix4x4CPU &a, float f)
{
Matrix4x4CPU result = a;
result += f;
return result;
}
inline Matrix4x4CPU operator+(float f, Matrix4x4CPU &a)
{
Matrix4x4CPU result = a;
result += f;
return result;
}
inline Matrix4x4CPU operator+(Matrix4x4CPU &a, Matrix4x4CPU &b)
{
Matrix4x4CPU result;
result.m_Vec0 = a.m_Vec0 + b.m_Vec0;
result.m_Vec1 = a.m_Vec1 + b.m_Vec1;
result.m_Vec2 = a.m_Vec2 + b.m_Vec2;
result.m_Vec3 = a.m_Vec3 + b.m_Vec3;
return result;
}
inline Matrix4x4CPU operator-(Matrix4x4CPU &a, float f)
{
Matrix4x4CPU result = a;
result -= f;
return result;
}
inline Matrix4x4CPU operator-(float f, Matrix4x4CPU &a)
{
Matrix4x4CPU result = a;
result -= f;
return result;
}
inline Matrix4x4CPU operator-(Matrix4x4CPU &a, Matrix4x4CPU &b)
{
Matrix4x4CPU result;
result.m_Vec0 = a.m_Vec0 - b.m_Vec0;
result.m_Vec1 = a.m_Vec1 - b.m_Vec1;
result.m_Vec2 = a.m_Vec2 - b.m_Vec2;
result.m_Vec3 = a.m_Vec3 - b.m_Vec3;
return result;
}
inline Vector4CPU operator*(Vector4CPU &v, Matrix4x4CPU &m)
{
Vector4CPU result;
result.x = v.x*m.m_00 + v.y*m.m_10 + v.z*m.m_20 + v.w*m.m_30;
result.y = v.x*m.m_01 + v.y*m.m_11 + v.z*m.m_21 + v.w*m.m_31;
result.z = v.x*m.m_02 + v.y*m.m_12 + v.z*m.m_22 + v.w*m.m_32;
result.w = v.x*m.m_03 + v.y*m.m_13 + v.z*m.m_23 + v.w*m.m_33;
return result;
}
inline Vector4CPU operator*(Matrix4x4CPU &matrix, Vector4CPU &vec)
{
Vector4CPU result;
result[0] = VectorDot(vec, matrix[0]).GetX();
result[1] = VectorDot(vec, matrix[1]).GetX();
result[2] = VectorDot(vec, matrix[2]).GetX();
result[3] = VectorDot(vec, matrix[3]).GetX();
return result;
}
inline Matrix4x4CPU operator*(Matrix4x4CPU &a, Matrix4x4CPU &b)
{
Matrix4x4CPU result;
result.m_Vec0 = a.m_Vec0 * b;
result.m_Vec1 = a.m_Vec1 * b;
result.m_Vec2 = a.m_Vec2 * b;
result.m_Vec3 = a.m_Vec3 * b;
return result;
}
inline Matrix4x4CPU operator*(Matrix4x4CPU &a, float f)
{
Matrix4x4CPU result;
result.m_Vec0 = a.m_Vec0 * f;
result.m_Vec1 = a.m_Vec1 * f;
result.m_Vec2 = a.m_Vec2 * f;
result.m_Vec3 = a.m_Vec3 * f;
return result;
}
inline Matrix4x4CPU operator*(float f, Matrix4x4CPU &a)
{
Matrix4x4CPU result;
result.m_Vec0 = a.m_Vec0 * f;
result.m_Vec1 = a.m_Vec1 * f;
result.m_Vec2 = a.m_Vec2 * f;
result.m_Vec3 = a.m_Vec3 * f;
return result;
}
inline Matrix4x4CPU operator/(Matrix4x4CPU &a, float f)
{
Matrix4x4CPU result;
result.m_Vec0 = a.m_Vec0 / f;
result.m_Vec1 = a.m_Vec1 / f;
result.m_Vec2 = a.m_Vec2 / f;
result.m_Vec3 = a.m_Vec3 / f;
return result;
return result;
}
inline Matrix4x4CPU Matrix4x4Transpose(Matrix4x4CPU &matrix)
{
Matrix4x4CPU result = matrix;
result.Transpose();
return result;
}
void Matrix4x4FromQuaternion(Matrix4x4CPU &matrix, Vector4CPU &v);
void Matrix4x4FromQuaternionAndTransform(Matrix4x4CPU &matrix, Vector4CPU &q, Vector4CPU &t = g_MatrixCPU_Identity.m_Vec3 );
void QuaternionFromMatrix4x4(Matrix4x4CPU &matrix, Vector4CPU &quaternion);
#endif // _MATRIX4x4_GENERAL_
| [
"[email protected]@d0fecb8e-c161-339a-4e07-94e11f48a80e"
]
| [
[
[
1,
702
]
]
]
|
4ccd24def6476129194e62f58f6ca972dbb153ee | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/src/pthread_attr_getstacksize.cpp | c3aee8cf3ab8c0ade6dcb53c131d459711e716ce | []
| 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 | 1,380 | cpp | /*
* Copyright (c) 2005-2006 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: pthread_attr_getstacksize call implementation.
*
*
*
*/
#include <pthread.h>
#include <errno.h>
#include "threadglobals.h"
#include "threadcreate.h"
EXPORT_C int pthread_attr_getstacksize(const pthread_attr_t *attrib,
size_t *stkSize)
{
THR_PRINTF("[pthread] Begin pthread_attr_getstacksize\n");
_pthread_attr *thAttrPtr;
if ((NULL == attrib) || (NULL == stkSize))
{
THR_PRINTF("[pthread] End of pthread_attr_getstacksize\n");
return EINVAL;
}
thAttrPtr = (_pthread_attr*) attrib;
if (thAttrPtr->stackSize < PTHREAD_STACK_MIN)
{
THR_PRINTF("[pthread] End of pthread_attr_getstacksize\n");
return EINVAL;
}
*stkSize = thAttrPtr->stackSize;
THR_PRINTF("[pthread] End pthread_attr_getstacksize\n");
return 0;
}
// End of File
| [
"none@none"
]
| [
[
[
1,
56
]
]
]
|
882b93348447c16afcc6a76bbe662d0f9f0a5acc | 6d680e20e4a703f0aa0d4bb5e50568143241f2d5 | /src/MobiHealth/moc_CreditsFooterWidget.cpp | 04d56ed9a1fd1fa41eb0a747c655ce415b8c69da | []
| no_license | sirnicolaz/MobiHealt | f7771e53a4a80dcea3d159eca729e9bd227e8660 | bbfd61209fb683d5f75f00bbf81b24933922baac | refs/heads/master | 2021-01-20T12:21:17.215536 | 2010-04-21T14:21:16 | 2010-04-21T14:21:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,543 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'CreditsFooterWidget.h'
**
** Created: Sun Apr 11 11:47:50 2010
** by: The Qt Meta Object Compiler version 62 (Qt 4.6.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "CreditsFooterWidget.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'CreditsFooterWidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.6.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_CreditsFooterWidget[] = {
// content:
4, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
21, 20, 20, 20, 0x08,
0 // eod
};
static const char qt_meta_stringdata_CreditsFooterWidget[] = {
"CreditsFooterWidget\0\0creditsButtonSlot()\0"
};
const QMetaObject CreditsFooterWidget::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_CreditsFooterWidget,
qt_meta_data_CreditsFooterWidget, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &CreditsFooterWidget::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *CreditsFooterWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *CreditsFooterWidget::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_CreditsFooterWidget))
return static_cast<void*>(const_cast< CreditsFooterWidget*>(this));
return QWidget::qt_metacast(_clname);
}
int CreditsFooterWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: creditsButtonSlot(); break;
default: ;
}
_id -= 1;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
]
| [
[
[
1,
79
]
]
]
|
b9bd425b9279b33c50c3fff33718a7fdea4b18ee | b8ac0bb1d1731d074b7a3cbebccc283529b750d4 | /Code/controllers/RecollectionBenchmark/protocol/packets/trashbinpacket.cpp | a50540cff6334a471e4521a4e8cc68b35a5f9a4d | []
| 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 | 795 | cpp | // Class automatically generated by Dev-C++ New Class wizard
#include <protocol/packets/TrashBinPacket.h> // class's header file
namespace protocol {
namespace packets {
// class constructor
TrashBinPacket::TrashBinPacket(char groupid, char boardid) : protocol::packets::BoardPacket(groupid, boardid)
{
}
// class destructor
TrashBinPacket::~TrashBinPacket()
{
// insert your code here
}
void TrashBinPacket::senseTrashBin(){
this->setCommand(CMD_TRASHBIN_VALUE);
}
bool TrashBinPacket::isTrashBinFull(){
return this->getCommand() == CMD_FULL_TRASHBIN_ALARM;
}
void TrashBinPacket::setTrashBinFullThreshold(short value){
this->setCommand(CMD_FULL_TRASHBIN_VALUE);
}
short TrashBinPacket::getTrashBinValue(){
return this->getShortData();
}
}
}
| [
"guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a"
]
| [
[
[
1,
37
]
]
]
|
6ec816348a77f6bc850baf478994b78e5cc2ad35 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ClientShellDLL/ClientShellShared/LightGroupFX.h | 171ff040d4b3015abdb1d586588bcfade96c4fa6 | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,067 | h | //////////////////////////////////////////////////////////////////////////////
// LightGroup FX manager header file
#ifndef __LIGHTGROUPFX_H__
#define __LIGHTGROUPFX_H__
#pragma warning (disable : 4786)
#include <map>
#include <slist>
class CLightGroupFXMgr
{
public:
CLightGroupFXMgr();
~CLightGroupFXMgr();
void HandleSFXMsg(ILTMessage_Read *pMsg);
void Update();
void Clear();
private:
bool ChangeLGColor(uint32 nID, const LTVector &vAdj);
typedef std::map<uint32, LTVector> TLGColorMap;
TLGColorMap m_cColorMap;
struct SWaitingAdj
{
SWaitingAdj() {}
SWaitingAdj(uint32 nID, const LTVector &vAdj) : m_nID(nID), m_vAdj(vAdj) {}
SWaitingAdj(const SWaitingAdj &cOther) : m_nID(cOther.m_nID), m_vAdj(cOther.m_vAdj) {}
SWaitingAdj &operator=(const SWaitingAdj &cOther) {
m_nID = cOther.m_nID;
m_vAdj = cOther.m_vAdj;
return *this;
}
uint32 m_nID;
LTVector m_vAdj;
};
typedef std::slist<SWaitingAdj> TWaitingAdjList;
TWaitingAdjList m_aWaitingAdjList;
};
#endif //__LIGHTGROUPFX_H__ | [
"[email protected]"
]
| [
[
[
1,
44
]
]
]
|
1750a6eeef473792472ac6514913de7d3086d457 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Models/MDLBASE/MakeupBlock.h | d59221b12b0a2f1ed29cdc6916839cca5f0a91f6 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,915 | h | #pragma once
#include "flwnode.h"
#include "blockevalbase.h"
#ifdef __MAKEUPBLOCK_CPP
#define DllImportExport DllExport
#elif !defined(MdlBase)
#define DllImportExport DllImport
#else
#define DllImportExport
#endif
// ==========================================================================
//
//
//
// ==========================================================================
class CMakeupBase;
// ==========================================================================
//
// Makeup Blocks
//
// ==========================================================================
#define DEFINE_MAKEUPBLOCK(SM) DEFINE_TAGOBJ(SM)
#define IMPLEMENT_MAKEUPBLOCK(Obj, ModelId, Version, Cat, SDesc, LDesc) \
IMPLEMENT_TAGOBJ(Obj, CMakeupBlock::GroupName, ModelId, Version, "", "", Cat, SDesc, LDesc)
class DllImportExport CMakeupBlock : public TaggedObject
{
public:
CMakeupBlock(TagObjClass* pClass_, pchar Tag_, TaggedObject* pAttach, TagObjAttachment eAttach);
virtual ~CMakeupBlock();
virtual flag DoesSomething() { return true/*false*/; };
virtual void BuildDataDefn(DataDefnBlk& DDB);
virtual flag DataXchg(DataChangeBlk & DCB) { return 0; };
virtual flag ValidateData(ValidateDataBlk & VDB) { return 1; };
virtual void EvalProducts(SpConduit & QPrd, double Po, double FinalTEst=dNAN);
virtual void EvalProductsInline(SpConduit & QPrd, double Len, double Diam, double Po, double FinalTEst=dNAN);
virtual double Duty() { return 0.0; };
inline CDirectFlwIO & getSrcIO();
public:
static const pchar GroupName;
CMakeupBase * m_pMakeupBase;
_declspec(property(get=getSrcIO)) CDirectFlwIO & SrcIO;
};
DEFINE_MAKEUPBLOCK(CMakeupBlock);
// ===========================================================================
//
// Makeup Base
//
// ===========================================================================
class DllImportExport CMakeupBase : public CBlockEvalBase
{
friend class CMakeupBlock;
friend class CBlockEvaluator;
public:
CMakeupBase(TaggedObject * pAttach, int Index, LPTSTR Tag);
~CMakeupBase();
//virtual Strng Name();
flag Open(TagObjClass * pEvapClass=NULL, flag Fixed=False);
flag Open(byte OnOffSeq, TagObjClass * pEvapClass=NULL, flag Fixed=False) { CBlockEvalBase::Open(OnOffSeq); return Open(pEvapClass, Fixed); }
byte OpenStatus() { return CBlockEvalBase::OpenStatus(Enabled()); }
void Close();
CMakeupBlock * operator->() { return m_pMakeupB; };
flag Enabled() { return m_fEnabled && (m_pMakeupB!=NULL); };
void SetEnable(bool On)
{
//dbgpln("MakeupEnable=%s", On?"On":"Off");
m_pMakeupB->SrcIO.UsrEnable = On;
m_fEnabled=On;
};
void Add_OnOff(DataDefnBlk &DDB, dword Flags=isParmStopped, int UserInfo=0);
void BuildDataDefn(DataDefnBlk &DDB, char* pTag="Adj", char* pTagComment=NULL, DDBPages PageIs=DDB_RqdPage, dword UserInfo=0);
flag DataXchg(DataChangeBlk & DCB);
flag ValidateData(ValidateDataBlk & VDB);
void EvalProducts(SpConduit & QPrd, double Po, double FinalTEst=dNAN)
{
if (Enabled())
m_pMakeupB->EvalProducts(QPrd, Po, FinalTEst);
else
{
m_pMakeupB->SrcIO.Cd.QZero();
m_pMakeupB->SrcIO.Sum.ZeroFlows();
}
};
void EvalProductsInline(SpConduit & QPrd, double Len, double Diam, double Po, double FinalTEst=dNAN)
{
if (Enabled())
m_pMakeupB->EvalProductsInline(QPrd, Len, Diam, Po, FinalTEst);
else
{
m_pMakeupB->SrcIO.Cd.QZero();
m_pMakeupB->SrcIO.Sum.ZeroFlows();
}
};
double Duty()
{
return (Enabled() ? m_pMakeupB->Duty() : 0.0);
};
bool On() { return m_On; };
virtual int ChangeTag(char * pOldTag, char * pNewTag);
virtual int DeleteTag(char * pDelTag);
protected:
flag m_fFixed;
flag m_fEnabled;
CMakeupBlock * m_pMakeupB;
FlwNode * m_pNd;
bool m_ConfigChecked;
bool m_On;
CDirectFlwIO m_SrcIO;
public:
};
// ===========================================================================
//
//
//
// ===========================================================================
CDirectFlwIO & CMakeupBlock::getSrcIO() { return m_pMakeupBase->m_SrcIO; };
// ===========================================================================
//
//
//
// ===========================================================================
#undef DllImportExport
| [
"[email protected]"
]
| [
[
[
1,
157
]
]
]
|
e7c163eae9e6fdb4e0f431ae394599c92aa11f42 | 0bab4267636e3b06cb0e73fe9d31b0edd76260c2 | /freewar-alpha/src/Graphics/create_surface.cpp | f6ef07f652d27ca64b0853454a350550972ae627 | []
| no_license | BackupTheBerlios/freewar-svn | 15fafedeed3ea1d374500d3430ff16b412b2f223 | aa1a28f19610dbce12be463d5ccd98f712631bc3 | refs/heads/master | 2021-01-10T19:54:11.599797 | 2006-12-10T21:45:11 | 2006-12-10T21:45:11 | 40,725,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,300 | cpp | //
// create_surface.cpp for graphics in /u/ept2/huot_j
//
// Made by jonathan huot
// Login <[email protected]>
//
// Started on Fri Jun 4 17:27:53 2004 jonathan huot
// Last update Tue Jun 29 18:43:28 2004 jonathan huot
//
#include "graphics.h"
extern t_gfx *gfx;
int create_surface(int width, int height, int depth, Uint32 color, int arena)
{
int i;
for (i = 0; i < MAXSUBSCREEN && gfx->surface[i].exist == true; i++)
;
if (i == MAXSUBSCREEN)
return (-1);
gfx->surface[i].exist = true;
if (arena)
{
gfx->surface[i].zoom = 100;
gfx->surface[i].off.x = 0;
gfx->surface[i].off.y = 0;
gfx->surface[i].scale.x = 0;
gfx->surface[i].scale.y = 0;
}
else
{
gfx->surface[i].color = color;
gfx->surface[i].s = SDL_CreateRGBSurface(SDL_HWSURFACE |
SDL_SRCCOLORKEY, width, height, gfx->buff->format->BitsPerPixel,
gfx->buff->format->Rmask, gfx->buff->format->Gmask,
gfx->buff->format->Bmask, gfx->buff->format->Amask);
//if (color)
//{
SDL_FillRect(gfx->surface[i].s, NULL, color);
//}
}
gfx->surface[i].w = width;
gfx->surface[i].h = height;
gfx->surface[i].arena = arena;
gfx->surface[i].depth = depth;
gfx->surface[i].show = 0;
return (i);
}
| [
"doomsday@b2c3ed95-53e8-0310-b220-efb193137011"
]
| [
[
[
1,
50
]
]
]
|
fdcaa62d9e91c5405d0a40c7b430adf9935f39d2 | 11da90929ba1488c59d25c57a5fb0899396b3bb2 | /Src/FormGadget.cpp | 5680d77662367cb9989f29004eaade050a293e10 | []
| no_license | danste/ars-framework | 5e7864630fd8dbf7f498f58cf6f9a62f8e1d95c6 | 90f99d43804d3892432acbe622b15ded6066ea5d | refs/heads/master | 2022-11-11T15:31:02.271791 | 2005-10-17T15:37:36 | 2005-10-17T15:37:36 | 263,623,421 | 0 | 0 | null | 2020-05-13T12:28:22 | 2020-05-13T12:28:21 | null | UTF-8 | C++ | false | false | 3,403 | cpp | #include <FormGadget.hpp>
#include <Graphics.hpp>
#include <Application.hpp>
#include <68k/Hs.h>
FormGadget::FormGadget(Form& form, UInt16 id):
FormObjectWrapper(form, id),
visible_(false),
usable_(false),
doubleBuffer_(false)
{}
FormGadget::~FormGadget()
{}
void FormGadget::setupGadget(FormType* form, UInt16 index)
{
assert(valid());
FrmSetGadgetData(form, index, this);
#ifdef __MWERKS__
FormGadgetHandlerType* handler=reinterpret_cast<FormGadgetHandlerType*>(Application::instance().gadgetHandlerThunk_.thunkData);
#else
FormGadgetHandlerType* handler=gadgetHandler;
#endif
FrmSetGadgetHandler(form, index, handler);
}
void FormGadget::attach(UInt16 id)
{
FormObjectWrapper::attach(id);
setupGadget(*form(), index());
}
void FormGadget::attachByIndex(UInt16 index)
{
FormObjectWrapper::attachByIndex(index);
setupGadget(*form(), index);
}
void FormGadget::drawProxy()
{
if (!visible())
return;
if (form()->application().runningOnTreo600() && hasFocus())
drawFocusRing();
Graphics graphics(WinGetDrawWindow()); // form()->windowHandle()
Rect rect;
bounds(rect);
bool db=doubleBuffer_;
if (db)
{
Rect formBounds;
form()->bounds(formBounds);
Err error;
WinHandle wh = WinCreateOffscreenWindow(formBounds.width(), formBounds.height(), nativeFormat, &error);
if (errNone == error)
{
{
Graphics offscreen(wh);
ActivateGraphics active(offscreen);
handleDraw(graphics);
offscreen.copyArea(rect, graphics, rect.topLeft());
}
WinDeleteWindow(wh, false);
}
else
db=false;
}
if (!db)
{
Graphics::ClipRectangleSetter setClip(graphics, rect);
handleDraw(graphics);
}
fireDrawCompleted();
}
void FormGadget::handleDraw(Graphics& graphics)
{}
bool FormGadget::handleEnter(const EventType& event)
{return false;}
bool FormGadget::handleMiscEvent(const EventType& event)
{return false;}
bool FormGadget::handleEvent(EventType& event)
{
bool handled=false;
switch (event.eType)
{
case frmGadgetEnterEvent:
handled=handleEnter(event);
break;
case frmGadgetMiscEvent:
handled=handleMiscEvent(event);
break;
}
return handled;
}
bool FormGadget::handleGadgetCommand(UInt16 command, void* param)
{
bool handled=false;
switch (command)
{
case formGadgetDrawCmd:
drawProxy();
handled=true;
break;
case formGadgetHandleEventCmd:
assert(0!=param);
handled=handleEvent(*static_cast<EventType*>(param));
break;
}
return handled;
}
void FormGadget::handleFocusChange(FocusChange change)
{
if (form()->application().runningOnTreo600() && visible() && form()->visible())
{
if (focusTaking == change)
drawFocusRing();
else
removeFocusRing();
}
}
void FormGadget::notifyHide() {}
void FormGadget::notifyShow() {}
void FormGadget::removeFocusRing()
{
HsNavRemoveFocusRing(*form());
}
| [
"andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9"
]
| [
[
[
1,
140
]
]
]
|
f48bd7452680e98a1e2fad7043cfa9b42a4607c3 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/utilcpp/include/utilcpp/HardConfig.hpp | b489ab0d162cfd2a4e81bf916a1934ba51389a03 | []
| no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | hpp | #ifndef HGUARD_UTILCPP_HARDCONFIG_HPP__
#define HGUARD_UTILCPP_HARDCONFIG_HPP__
#pragma once
#ifndef UTILCPP_DEBUG_LOG_ON
#ifdef _DEBUG
#define UTILCPP_DEBUG_LOG_ON 1
#else
#define UTILCPP_DEBUG_LOG_ON 0
#endif
#endif
#ifndef UTILCPP_ASSERTIONS_ON
#ifdef _DEBUG
#define UTILCPP_ASSERTIONS_ON 1
#else
#define UTILCPP_ASSERTIONS_ON 0
#endif
#endif
#ifndef UTILCPP_ASSERTIONS_LOG_ON
#ifdef _DEBUG
#define UTILCPP_ASSERTIONS_LOG_ON 1
#else
#define UTILCPP_ASSERTIONS_LOG_ON 0
#endif
#endif
#ifndef UTILCPP_ASSERTIONS_DEBUGBREAK_ON
#ifdef _DEBUG
#define UTILCPP_ASSERTIONS_DEBUGBREAK_ON 1
#else
#define UTILCPP_ASSERTIONS_DEBUGBREAK_ON 0
#endif
#endif
#ifndef UTILCPP_ASSERTIONS_CRASH_ON
#ifdef _DEBUG
#define UTILCPP_ASSERTIONS_CRASH_ON 1
#else
#define UTILCPP_ASSERTIONS_CRASH_ON 0
#endif
#endif
#endif | [
"klaim@localhost"
]
| [
[
[
1,
47
]
]
]
|
cc88ef63ce18fcd1cef70a31b3445706961d7ec2 | 74e7667ad65cbdaa869c6e384fdd8dc7e94aca34 | /MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/corlib_native_System_Collections_Stack.cpp | 0f52368410545ec74a2acce15da3b3ff6916385a | [
"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 | 1,051 | cpp | //-----------------------------------------------------------------------------
//
// ** WARNING! **
// This file was generated automatically by a tool.
// Re-running the tool will overwrite this file.
// You should copy this file to a custom location
// before adding any customization in the copy to
// prevent loss of your changes when the tool is
// re-run.
//
//-----------------------------------------------------------------------------
#include "corlib_native.h"
#include "corlib_native_System_Collections_Stack.h"
using namespace System::Collections;
void Stack::Clear( CLR_RT_HeapBlock* pMngObj, HRESULT &hr )
{
}
UNSUPPORTED_TYPE Stack::Peek( CLR_RT_HeapBlock* pMngObj, HRESULT &hr )
{
UNSUPPORTED_TYPE retVal = 0;
return retVal;
}
UNSUPPORTED_TYPE Stack::Pop( CLR_RT_HeapBlock* pMngObj, HRESULT &hr )
{
UNSUPPORTED_TYPE retVal = 0;
return retVal;
}
void Stack::Push( CLR_RT_HeapBlock* pMngObj, UNSUPPORTED_TYPE param0, HRESULT &hr )
{
}
| [
"[email protected]"
]
| [
[
[
1,
38
]
]
]
|
6eec094af8ed4a080dce0d86f42eb2400a6b1fe5 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/tutorials/mtutorial04/mtestapp.cc | da3ce07d2fbc1e4e5aa21a6b47fb097cc8381269 | []
| no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,491 | cc | //------------------------------------------------------------------------------
// mTutorial01/mTestapp.cc
// (C) 2006 [email protected] for nebula2
//------------------------------------------------------------------------------
#include "mtutorial04/mtestapp.h"
#include "scene/nsceneserver.h"
#include "managers/entitymanager.h"
#include "managers/factorymanager.h"
#include "application/gamestatehandler.h"
#include "gui/nguiserver.h"
#include "game/property.h"
#include "game/entity.h"
#include "properties/lightproperty.h"
#include "properties/graphicsproperty.h"
#include "mtutorial04/state/mtestenterstatehandler.h"
#include "mtutorial04/state/mtestgamestatehandler.h"
#include "mtutorial04/state/mtestpausestatehandler.h"
#include "mtutorial04/state/mtestexitstatehandler.h"
#include "mtutorial04/property/polarcameraproperty.h"
namespace mTutorial
{
mTestApp* mTestApp::Singleton = 0;
//------------------------------------------------------------------------------
/**
Constructor
*/
mTestApp::mTestApp()
{
n_assert(0 == Singleton);
Singleton = this;
}
//------------------------------------------------------------------------------
/**
Destructor
*/
mTestApp::~mTestApp()
{
n_assert(0 != Singleton);
Singleton = 0;
}
//------------------------------------------------------------------------------
/**
Override this method in subclasses to return a different application name.
*/
nString mTestApp::GetAppName() const
{
return "Tutorial 04, Working with game state handler";
}
//------------------------------------------------------------------------------
/**
Override this method in subclasses to return a different version string.
*/
nString mTestApp::GetAppVersion() const
{
return "1.0";
}
//------------------------------------------------------------------------------
/**
Get the application vendor. This is usually the publishers company name.
*/
nString mTestApp::GetVendorName() const
{
return "Radon Labs GmbH";
}
//------------------------------------------------------------------------------
/**
Sets up default state which may be modified by command line args and
user profile.
*/
void mTestApp::SetupFromDefaults()
{
App::SetupFromDefaults();
}
//------------------------------------------------------------------------------
/**
setup the app's input mapping (called in SetupSubsystems())
*/
void mTestApp::SetupDefaultInputMapping() {
App::SetupDefaultInputMapping();
}
//------------------------------------------------------------------------------
/**
This initializes some objects owned by DsaApp.
*/
bool mTestApp::Open()
{
if (App::Open())
{
// FIXME: turn off clip plane fencing and occlusion query (FOR NOW)
// because of compatibility problems on Radeon cards
nSceneServer::Instance()->SetClipPlaneFencing(false);
nSceneServer::Instance()->SetOcclusionQuery(false);
// then setup all parts of the application : input, camera, world, etc...
// the purpose of SetupGui was to 1) override default gui path 2) add widgets
// this app use default path and each gamestate now take care about widget
// this->SetupGui();
// add some object to lock at...
this->CreateViewedEntity();
// add at least one light
this->SetupLightsInScene();
// add a came where we can look from
this->SetupCameraAndInput();
return true;
}
return false;
}
//------------------------------------------------------------------------------
/**
Clean up objects created by Open().
*/
void mTestApp::Close()
{
App::Close();
}
//------------------------------------------------------------------------------
/**
This method is called once per-frame by App::Run(). It is used here
to check if reset is requested and that case to evoke it.
*/
void mTestApp::OnFrame()
{
// Move the code where it should belong : IN THE STATE HANDLER OnFrame !!!
}
//------------------------------------------------------------------------------
/**
// setup the state of our application, directly start in "game" state
*/
void mTestApp::SetupStateHandlers()
{
Ptr<Application::GameStateHandler> mtestStateHandler;
// initialize the first state : "game"
mtestStateHandler = n_new(Application::mTestGameStateHandler);
this->AddStateHandler(mtestStateHandler); // add it to the world
// that new ! a second state, "pause"
mtestStateHandler = n_new(Application::mTestPauseStateHandler);
this->AddStateHandler(mtestStateHandler); // add it to the world
// to prevent switching of the wold, level, db.. between state handler, let's create 2 news ones
//, enterstate, exitstate
mtestStateHandler = n_new(Application::mTestEnterStateHandler);
this->AddStateHandler(mtestStateHandler); // add it to the world
mtestStateHandler = n_new(Application::mTestExitStateHandler);
this->AddStateHandler(mtestStateHandler); // add it to the world
// Nota : note now each state constructor take care about SetName, SetExistState, etc...
// (still, it won't be alway true ; there're specific state here...)
// now set the state we want to start with...
// enter will take care about loading the world (actually statically created entities)
this->SetState("EnterState");
}
//------------------------------------------------------------------------------
/**
// statically load some object, here the opelblitz
*/
void mTestApp::CreateViewedEntity()
{
// name of the object, relative to export:gfxlib
nString objectName = "examples/opelblitz";
Ptr<Game::Entity> entity;
Ptr<Game::Property> graphicProperty;
//------------------------------------
// The object, every thing is done though property : here add the graphic property
// to our object in order to get it... on screen !
entity = Managers::FactoryManager::Instance()->CreateEntityByClassName("Entity");
graphicProperty = Managers::FactoryManager::Instance()->CreateProperty("GraphicsProperty");
entity->SetString( Attr::Name, "OpelBlitz" );
// attach properties
entity->AttachProperty( graphicProperty );
entity->SetString( Attr::Graphics, objectName );
// a transformation matrix is mandatory, even if just init
matrix44 entityTransform;
entity->SetMatrix44(Attr::Transform, entityTransform);
// attach to world
Managers::EntityManager::Instance()->AttachEntity(entity);
}
//------------------------------------------------------------------------------
/**
// no light, no display !!
*/
void mTestApp::SetupLightsInScene()
{
Ptr<Game::Entity> entity;
Ptr<Game::Property> lightProperty;
// create an object in the same wat as the opelblitz one, but this time
// attach a light property instead of graphics.
// there must be at least one light
//create new Entity for light in scene, create lightProperty and attach it to the entity
entity = Managers::FactoryManager::Instance()->CreateEntityByClassName("Entity");
lightProperty = Managers::FactoryManager::Instance()->CreateProperty("LightProperty");
entity->AttachProperty(lightProperty);
//set position of lightsource
matrix44 lightTransform;
lightTransform.translate(vector3(0.0, 100.0f, 0.0));
entity->SetMatrix44(Attr::Transform, lightTransform);
//set Attributes of the lightsource
entity->SetString(Attr::LightType, "Point");
entity->SetVector4(Attr::LightColor, vector4(1.0f, 1.0f, 1.0f, 1.0f));
entity->SetFloat(Attr::LightRange, 1000.0f);
entity->SetVector4(Attr::LightAmbient, vector4(1.0f, 0.0f, 0.0f, 0.0f));
entity->SetBool(Attr::LightCastShadows, false);
//attach lightproperty to entity
Managers::EntityManager::Instance()->AttachEntity(entity);
}
//------------------------------------------------------------------------------
/**
*/
void mTestApp::SetupCameraAndInput()
{
Ptr<Game::Entity> entity;
Ptr<Game::Property> cameraProperty;
Ptr<Game::Property> inputProperty;
// create new Entity as a camera,
// attach our more flexible camera with polar coordinate system property
entity = Managers::FactoryManager::Instance()->CreateEntityByClassName("Entity");
cameraProperty = Managers::FactoryManager::Instance()->CreateProperty("PolarCameraProperty");
entity->AttachProperty(cameraProperty);
// It's important to name the entity since we use this name inside the OnFrame loop in order
// to display camera value
entity->SetString( Attr::Name, "MainGameCamera" );
// set some default values from where the camera will look at the "opelblitz"
entity->SetVector3( Attr::PolarCameraLookAt, vector3.zero ); // look at origine
entity->SetFloat( Attr::PolarCameraPhi, -45.0f ); // -45, that's not a mistake... do our math !
entity->SetFloat( Attr::PolarCameraTheta, 45.0f );
entity->SetFloat( Attr::PolarCameraDistance, 10.0f );
// NOTA : no more input management. each state (game, pause) now take care
// of that. (ps : I could have set a specific camera too...)
//attach camera to world (entity pool), and tell mangalore we use it for display !!!
Managers::EntityManager::Instance()->AttachEntity(entity);
Managers::FocusManager::Instance()->SetCameraFocusEntity(entity);
}
}; // namespace | [
"[email protected]@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
]
| [
[
[
1,
270
]
]
]
|
7a8381f0914a0bfb2adc8b096c4c7e9e829f7324 | 9907be749dc7553f97c9e51c5f35e69f55bd02c0 | /april5/modules/Wordplay/project files & code/code/main.cpp | dfd037453ff0f1e8ccfb4b26a7b3726e96742225 | []
| no_license | jdeering/csci476winthrop | bc8907b9cc0406826de76aca05e6758810377813 | 2bc485781f819c8fd82393ac86de33404e7ad6d3 | refs/heads/master | 2021-01-10T19:53:14.853438 | 2009-04-24T14:26:36 | 2009-04-24T14:26:36 | 32,223,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,149 | cpp | #include <vector>
#include <string>
#include <ctime>
#include "../../../../api/GameFramework.h"
#include "../classes/Board.h"
#include "../classes/Dictionary.h"
#include "../classes/Tile.h"
using namespace std;
enum GameStatus {CHOOSE_LEVEL, INSTRUCTIONS_1, INSTRUCTIONS_2, IN_GAME, DIALOGUE_EXIT, DIALOGUE_RESET};
GameStatus currentState = CHOOSE_LEVEL;
GFSprite * background;
Dictionary * userDictionary;
Board * gameBoard;
void masterClickHandler(int, int, int, int);
void introClickHandler(int x, int y);
bool returnRunning();
void showInstructions(int gameLevel, int page);
void instructionsClickHandler(int x, int y, int instructionsPage);
void beginGame();
int main(int argc, char argv[]){
srand(time(0));
//display the beginning screen
GameFramework::createSprite("intro", 0, 0, 600, 600);
currentState = CHOOSE_LEVEL;
//set the correct click handler
GameFramework::mouseFunc(masterClickHandler);
//begin the game loop
GameFramework::gameFunc(returnRunning);
GameFramework::gameLoop();
return 0;
}
void masterClickHandler(int button, int state, int x, int y)
{
//1 is clicked, not worrying about which button for the purposes of this game
if (state == 1){
//dependent on status, choose the correct click handler
if (currentState == CHOOSE_LEVEL)
{
introClickHandler(x,y);
}
else if (currentState == INSTRUCTIONS_1)
{
instructionsClickHandler(x, y, 1);
}
else if (currentState == INSTRUCTIONS_2)
{
instructionsClickHandler (x, y, 2);
}
else if (currentState == IN_GAME)
{
// inGameClickHandler(x,y);
}
else if (currentState == DIALOGUE_EXIT)
{
// dialogueClickHandler(x, y, exitGame, endDialogue);
}
else if (currentState == DIALOGUE_RESET)
{
// dialogueClickHandler(x,y, resetBoard, endDialogue);
}
}
}
void introClickHandler(int x, int y)
{
cout<<"intro"<<endl;
//this will hold the game level the user selects
int gameLevel = -1;
//if it's in the right y-value for a level button
if(y > 400 && y < 575)
{
//decide which level it is, and select that level
if(x > 20 && x < 145)
{
gameLevel = 1;
}
else if (x > 165 && x < 290)
{
gameLevel = 2;
}
else if (x > 310 && x < 435)
{
gameLevel = 3;
}
else if (x > 455 && x < 580)
{
gameLevel = 4;
}
//as long as they clicked on a level button
if (gameLevel != -1){
//go ahead and show instructions for that level
cout<<"here in if"<<endl;
//make the dictionary
userDictionary = new Dictionary();
cout<<"after dictionary"<<endl;
//create background
background = &GameFramework::createSprite("background", 0, 0, 600, 600);
background->setVisible(false);
cout<<"after background"<<endl;
//create gameboard
gameBoard = new Board(gameLevel, userDictionary);
cout<<"after gameboard"<<endl;
//show instructions
showInstructions(gameLevel, 1); //that 1 tells us to show the first page of the instructions
cout<<"after show"<<endl;
}
}
}
bool returnRunning()
{
return true;
//return gameRunning;
}
void showInstructions(int gameLevel, int page)
{
cout<<"here"<<endl;
//clear out the screen
// removeAllButGameboard();
string assetName;
//construct the asset name based on the game level and the page number
switch (gameLevel)
{
case 1:
assetName = "easy_";
break;
case 2:
assetName = "medium_";
break;
case 3:
assetName = "hard_";
break;
case 4:
assetName = "challenge_";
break;
}
switch (page){
case 1:
assetName += "1";
break;
case 2:
assetName += "2";
break;
}
//and display it
GameFramework::createSprite(assetName, 0, 0, 600, 600);
//set the game state to be in the instructions state
switch (page)
{
case 1:
currentState = INSTRUCTIONS_1;
break;
case 2:
currentState = INSTRUCTIONS_2;
break;
}
}
void instructionsClickHandler(int x, int y, int instructionsPage){
//if we're on the second instructions page, there's a begin game and previous page button
if (instructionsPage == 2){
//if it's the begin game button
if(x > 335 && x < 550 && y > 505 && y < 550)
{
beginGame();
}
//if it's the previous button
else if(x > 40 && x < 170 && y > 505 && y < 550)
{
showInstructions(gameBoard->returnLevel(), 1);
}
}
//if we're on the first instructions page, there's a next button
else{
//if it's the 'next' button
if (x > 420 && x < 545 && y > 505 && y < 550)
{
showInstructions(gameBoard->returnLevel(), 2);
}
}
}
void beginGame()
{
//display the background
background->setVisible(true);
//display the gameboard
//gameBoard->displayBoard();
//display the user score and current word text fields
//GFText& createTextFromString(std::string, int, int, int);
//currentWord = &GameFramework::createTextFromString("current",7,535,40);
//gScore = &GameFramework::createTextFromString("0", 1, 490, 315);
//set the state of the game
currentState = IN_GAME;
} | [
"lcairco@2656ef14-ecf4-11dd-8fb1-9960f2a117f8"
]
| [
[
[
1,
223
]
]
]
|
5f37a7b639198b12704d7447dd22a844f7a9b7b7 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/config/test/math_info.cpp | 28b60c31d7f274cdf099c5ac4c47b1d1e84a423c | [
"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 | 12,992 | cpp | // (C) Copyright John Maddock 2005.
// Use, modification and distribution are 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)
// See http://www.boost.org/libs/config/test for most recent version.
//
// This test prints out informative information about <math.h>, <float.h>
// and <limits>. Note that this file does require a correctly configured
// Boost setup, and so can't be folded into config_info which is designed
// to function without Boost.Confg support. Each test is documented in
// more detail below.
//
#include <boost/limits.hpp>
#include <limits.h>
#include <math.h>
#include <cmath>
#include <float.h>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <boost/type_traits/alignment_of.hpp>
#ifdef BOOST_NO_STDC_NAMESPACE
namespace std{ using ::strcmp; using ::pow; using ::fabs; using ::sqrt; using ::sin; using ::atan2; }
#endif
static unsigned int indent = 4;
static unsigned int width = 40;
void print_macro(const char* name, const char* value)
{
// if name == value+1 then then macro is not defined,
// in which case we don't print anything:
if(0 != std::strcmp(name, value+1))
{
for(unsigned i = 0; i < indent; ++i) std::cout.put(' ');
std::cout << std::setw(width);
std::cout.setf(std::istream::left, std::istream::adjustfield);
std::cout << name;
if(value[1])
{
// macro has a value:
std::cout << value << "\n";
}
else
{
// macro is defined but has no value:
std::cout << " [no value]\n";
}
}
}
#define PRINT_MACRO(X) print_macro(#X, BOOST_STRINGIZE(=X))
template <class T>
void print_expression(const char* expression, T val)
{
for(unsigned i = 0; i < indent; ++i) std::cout.put(' ');
std::cout << std::setw(width);
std::cout.setf(std::istream::left, std::istream::adjustfield);
std::cout << std::setprecision(std::numeric_limits<T>::digits10+2);
std::cout << expression << "=" << val << std::endl;
}
#define PRINT_EXPRESSION(E) print_expression(#E, E);
template <class T>
void print_limits(T, const char* name)
{
//
// Output general information on numeric_limits, as well as
// probing known and supected problems.
//
std::cout <<
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
"std::numeric_limits information for type " << name << std::endl;
std::cout <<
" is_specialized = " << std::numeric_limits<T>::is_specialized << std::endl;
std::cout <<
" min" "() = " << std::setprecision(std::numeric_limits<T>::digits10 + 2) << (std::numeric_limits<T>::min)() << std::endl;
std::cout <<
" max" "() = " << std::setprecision(std::numeric_limits<T>::digits10 + 2) << (std::numeric_limits<T>::max)() << std::endl;
std::cout <<
" digits = " << std::numeric_limits<T>::digits << std::endl;
std::cout <<
" digits10 = " << std::numeric_limits<T>::digits10 << std::endl;
std::cout <<
" is_signed = " << std::numeric_limits<T>::is_signed << std::endl;
std::cout <<
" is_integer = " << std::numeric_limits<T>::is_integer << std::endl;
std::cout <<
" is_exact = " << std::numeric_limits<T>::is_exact << std::endl;
std::cout <<
" radix = " << std::numeric_limits<T>::radix << std::endl;
std::cout <<
" epsilon() = " << std::setprecision(std::numeric_limits<T>::digits10 + 2) << (std::numeric_limits<T>::epsilon)() << std::endl;
std::cout <<
" round_error() = " << std::setprecision(std::numeric_limits<T>::digits10 + 2) << (std::numeric_limits<T>::round_error)() << std::endl;
std::cout <<
" min_exponent = " << std::numeric_limits<T>::min_exponent << std::endl;
std::cout <<
" min_exponent10 = " << std::numeric_limits<T>::min_exponent10 << std::endl;
std::cout <<
" max_exponent = " << std::numeric_limits<T>::max_exponent << std::endl;
std::cout <<
" max_exponent10 = " << std::numeric_limits<T>::max_exponent10 << std::endl;
std::cout <<
" has_infinity = " << std::numeric_limits<T>::has_infinity << std::endl;
std::cout <<
" has_quiet_NaN = " << std::numeric_limits<T>::has_quiet_NaN << std::endl;
std::cout <<
" has_signaling_NaN = " << std::numeric_limits<T>::has_signaling_NaN << std::endl;
std::cout <<
" has_denorm = " << std::numeric_limits<T>::has_denorm << std::endl;
std::cout <<
" has_denorm_loss = " << std::numeric_limits<T>::has_denorm_loss << std::endl;
std::cout <<
" infinity() = " << std::setprecision(std::numeric_limits<T>::digits10 + 2) << (std::numeric_limits<T>::infinity)() << std::endl;
std::cout <<
" quiet_NaN() = " << std::setprecision(std::numeric_limits<T>::digits10 + 2) << (std::numeric_limits<T>::quiet_NaN)() << std::endl;
std::cout <<
" signaling_NaN() = " << std::setprecision(std::numeric_limits<T>::digits10 + 2) << (std::numeric_limits<T>::signaling_NaN)() << std::endl;
std::cout <<
" denorm_min() = " << std::setprecision(std::numeric_limits<T>::digits10 + 2) << (std::numeric_limits<T>::denorm_min)() << std::endl;
std::cout <<
" is_iec559 = " << std::numeric_limits<T>::is_iec559 << std::endl;
std::cout <<
" is_bounded = " << std::numeric_limits<T>::is_bounded << std::endl;
std::cout <<
" is_modulo = " << std::numeric_limits<T>::is_modulo << std::endl;
std::cout <<
" traps = " << std::numeric_limits<T>::traps << std::endl;
std::cout <<
" tinyness_before = " << std::numeric_limits<T>::tinyness_before << std::endl;
std::cout <<
" round_style = " << std::numeric_limits<T>::round_style << std::endl << std::endl;
if(std::numeric_limits<T>::is_exact == 0)
{
bool r = std::numeric_limits<T>::epsilon() == std::pow(static_cast<T>(std::numeric_limits<T>::radix), 1-std::numeric_limits<T>::digits);
if(r)
std::cout << "Epsilon has sane value of std::pow(std::numeric_limits<T>::radix, 1-std::numeric_limits<T>::digits)." << std::endl;
else
std::cout << "CAUTION: epsilon does not have a sane value." << std::endl;
std::cout << std::endl;
}
std::cout <<
" sizeof(" << name << ") = " << sizeof(T) << std::endl;
std::cout <<
" alignment_of<" << name << "> = " << boost::alignment_of<T>::value << std::endl << std::endl;
}
/*
template <class T>
bool is_same_type(T, T)
{
return true;
}*/
bool is_same_type(float, float)
{ return true; }
bool is_same_type(double, double)
{ return true; }
bool is_same_type(long double, long double)
{ return true; }
template <class T, class U>
bool is_same_type(T, U)
{
return false;
}
//
// We need this to test whether abs has been overloaded for
// the floating point types or not:
//
namespace std{
#if !BOOST_WORKAROUND(BOOST_MSVC, == 1300)
template <class T>
char abs(T)
{
return ' ';
}
#endif
}
template <class T>
void test_overloads(T, const char* name)
{
//
// Probe known and suspected problems with the std lib Math functions.
//
std::cout <<
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
"Math function overload information for type " << name << std::endl;
//
// Are the math functions overloaded for type T,
// or do we just get double versions?
//
bool r = is_same_type(std::fabs(T(0)), T(0));
r &= is_same_type(std::sqrt(T(0)), T(0));
r &= is_same_type(std::sin(T(0)), T(0));
if(r)
std::cout << "The Math functions are overloaded for type " << name << std::endl;
else
std::cout << "CAUTION: The Math functions are NOT overloaded for type " << name << std::endl;
//
// Check that a few of the functions work OK, we do this because if these
// are implemented as double precision internally then we can get
// overflow or underflow when passing arguments of other types.
//
r = (std::fabs((std::numeric_limits<T>::max)()) == (std::numeric_limits<T>::max)());
r &= (std::fabs(-(std::numeric_limits<T>::max)()) == (std::numeric_limits<T>::max)());
r &= (std::fabs((std::numeric_limits<T>::min)()) == (std::numeric_limits<T>::min)());
r &= (std::fabs(-(std::numeric_limits<T>::min)()) == (std::numeric_limits<T>::min)());
if(r)
std::cout << "std::fabs looks OK for type " << name << std::endl;
else
std::cout << "CAUTION: std::fabs is broken for type " << name << std::endl;
//
// abs not overloaded for real arguments with VC6 (and others?)
//
r = (std::abs((std::numeric_limits<T>::max)()) == (std::numeric_limits<T>::max)());
r &= (std::abs(-(std::numeric_limits<T>::max)()) == (std::numeric_limits<T>::max)());
r &= (std::abs((std::numeric_limits<T>::min)()) == (std::numeric_limits<T>::min)());
r &= (std::abs(-(std::numeric_limits<T>::min)()) == (std::numeric_limits<T>::min)());
if(r)
std::cout << "std::abs looks OK for type " << name << std::endl;
else
std::cout << "CAUTION: std::abs is broken for type " << name << std::endl;
//
// std::sqrt on FreeBSD converts long double arguments to double leading to
// overflow/underflow:
//
r = (std::sqrt((std::numeric_limits<T>::max)()) < (std::numeric_limits<T>::max)());
if(r)
std::cout << "std::sqrt looks OK for type " << name << std::endl;
else
std::cout << "CAUTION: std::sqrt is broken for type " << name << std::endl;
//
// Sanity check for atan2: verify that it returns arguments in the correct
// range and not just atan(x/y).
//
static const T half_pi = static_cast<T>(1.57079632679489661923132169163975144L);
T val = std::atan2(T(-1), T(-1));
r = -half_pi > val;
val = std::atan2(T(1), T(-1));
r &= half_pi < val;
val = std::atan2(T(1), T(1));
r &= (val > 0) && (val < half_pi);
val = std::atan2(T(-1), T(1));
r &= (val < 0) && (val > -half_pi);
if(r)
std::cout << "std::atan2 looks OK for type " << name << std::endl;
else
std::cout << "CAUTION: std::atan2 is broken for type " << name << std::endl;
}
int main()
{
//
// Start by printing the values of the macros from float.h
//
std::cout <<
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
"Macros from <math.h>" << std::endl;
PRINT_EXPRESSION(HUGE_VAL);
#ifdef HUGE_VALF
PRINT_EXPRESSION(HUGE_VALF);
#endif
#ifdef HUGE_VALL
PRINT_EXPRESSION(HUGE_VALL);
#endif
#ifdef INFINITY
PRINT_EXPRESSION(INFINITY);
#endif
PRINT_MACRO(NAN);
PRINT_MACRO(FP_INFINITE);
PRINT_MACRO(FP_NAN);
PRINT_MACRO(FP_NORMAL);
PRINT_MACRO(FP_SUBNORMAL);
PRINT_MACRO(FP_ZERO);
PRINT_MACRO(FP_FAST_FMA);
PRINT_MACRO(FP_FAST_FMAF);
PRINT_MACRO(FP_FAST_FMAL);
PRINT_MACRO(FP_ILOGB0);
PRINT_MACRO(FP_ILOGBNAN);
PRINT_MACRO(MATH_ERRNO);
PRINT_MACRO(MATH_ERREXCEPT);
PRINT_EXPRESSION(FLT_MIN_10_EXP);
PRINT_EXPRESSION(FLT_DIG);
PRINT_EXPRESSION(FLT_MIN_EXP);
PRINT_EXPRESSION(FLT_EPSILON);
PRINT_EXPRESSION(FLT_RADIX);
PRINT_EXPRESSION(FLT_MANT_DIG);
PRINT_EXPRESSION(FLT_ROUNDS);
PRINT_EXPRESSION(FLT_MAX);
PRINT_EXPRESSION(FLT_MAX_10_EXP);
PRINT_EXPRESSION(FLT_MAX_EXP);
PRINT_EXPRESSION(FLT_MIN);
PRINT_EXPRESSION(DBL_DIG);
PRINT_EXPRESSION(DBL_MIN_EXP);
PRINT_EXPRESSION(DBL_EPSILON);
PRINT_EXPRESSION(DBL_MANT_DIG);
PRINT_EXPRESSION(DBL_MAX);
PRINT_EXPRESSION(DBL_MIN);
PRINT_EXPRESSION(DBL_MAX_10_EXP);
PRINT_EXPRESSION(DBL_MAX_EXP);
PRINT_EXPRESSION(DBL_MIN_10_EXP);
PRINT_EXPRESSION(LDBL_MAX_10_EXP);
PRINT_EXPRESSION(LDBL_MAX_EXP);
PRINT_EXPRESSION(LDBL_MIN);
PRINT_EXPRESSION(LDBL_MIN_10_EXP);
PRINT_EXPRESSION(LDBL_DIG);
PRINT_EXPRESSION(LDBL_MIN_EXP);
PRINT_EXPRESSION(LDBL_EPSILON);
PRINT_EXPRESSION(LDBL_MANT_DIG);
PRINT_EXPRESSION(LDBL_MAX);
std::cout << std::endl;
//
// print out numeric_limits info:
//
print_limits(float(0), "float");
print_limits(double(0), "double");
print_limits((long double)(0), "long double");
//
// print out function overload information:
//
test_overloads(float(0), "float");
test_overloads(double(0), "double");
test_overloads((long double)(0), "long double");
return 0;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
358
]
]
]
|
7a9e723d413b902e274188ea5e4a5d58d188c910 | 6ee200c9dba87a5d622c2bd525b50680e92b8dab | /Walkyrie Dx9/DoomeRX/Scenes/SceneTemplate.h | 32223f78ba73be1edc676829e12524d07fc66a04 | []
| no_license | Ishoa/bizon | 4dbcbbe94d1b380f213115251e1caac5e3139f4d | d7820563ab6831d19e973a9ded259d9649e20e27 | refs/heads/master | 2016-09-05T11:44:00.831438 | 2010-03-10T23:14:22 | 2010-03-10T23:14:22 | 32,632,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 732 | h | #pragma once
#include "..\..\Valkyrie\Moteur\Scene.h"
#include "..\..\Valkyrie\Moteur\Interface.h"
class CSceneTemplate : public CScene
{
public:
D3DXMATRIXA16 m_MatriceGeneral; // Matrice de transformation
int m_QualiterFiltrage; // type de filtrage des textures
CInterface* m_pInterface;
CSceneTemplate(CMoteur* pMoteur);
~CSceneTemplate();
bool ConfirmeFonction3D(D3DCAPS9* pCaps);
bool Initialisation();
bool CreationObjet();
void DestructionObjet();
void Rendu3D();
void Aquisition(BYTE EtatClavier[], DIMOUSESTATE* pEtatSouris,DIJOYSTATE2* pEtatJoystick);
void Animation(double TempsEcouler, double DeltaTemps);
void Destruction();
void SetFiltreTexture(int Type);
};
| [
"Colas.Vincent@ab19582e-f48f-11de-8f43-4547254af6c6"
]
| [
[
[
1,
28
]
]
]
|
3d4c98b7cea1c0c36c773f6007083817ea3b4ab9 | 718dc2ad71e8b39471b5bf0c6d60cbe5f5c183e1 | /soft micros/Codigo/HC12_CPP/pruebas/aparatos/Adquisidor/Sources/main.cpp | 6ca70503836df7fcb63efd968a43981709e032ad | []
| no_license | jonyMarino/microsdhacel | affb7a6b0ea1f4fd96d79a04d1a3ec3eaa917bca | 66d03c6a9d3a2d22b4d7104e2a38a2c9bb4061d3 | refs/heads/master | 2020-05-18T19:53:51.301695 | 2011-05-30T20:40:24 | 2011-05-30T20:40:24 | 34,532,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,621 | cpp | #include <hidef.h> /* common defines and macros */
#include <stdio.h>
#include <stdlib.h>
#include "derivative.h" /* derivative-specific definitions */
#include "timer_interrupt.h"
#include "Adc.hpp"
#include "IAdc.hpp"
#include "Termometro.hpp"
#include "OutputStream.hpp"
#include "Cpu.h"
#include "WDog1.h"
//#include "object_r.h"
//#include "Object.h"
#include "FrenteDH.hpp"
#include "Timer/Timer.hpp"
#include "Timer/interrup_1ms_40ms/BaseTimers_1ms_40ms.hpp"
#include "Memoria/Prom/Flash/FlashBkpMitad/FlashBkpMitad.hpp"
#include "PropiedadGetter.hpp"
#include "ConstructorPropiedadGetter.hpp"
#include "vistasensortermopt100.hpp"
#include "BoxPrincipal.hpp"
#include "FstBoxPointer.hpp"
#include "BoxList.hpp"
#include "Access.hpp"
#include "DiagramaNavegacion.hpp"
#include "VistaSetContrasenia.hpp"
#include "VistaControl.hpp"
#include "Salida.hpp"
#include "IPWM.hpp"
#include "PWM.hpp"
#include "PWMHard.hpp"
#include "PWMHard23.hpp"
#include "PWMManager01_45.hpp"
#include "PWMTimer.hpp"
#include "configuracionControlPID.hpp"
#include "SensorTermoPT100.hpp"
#include "VistaPWM.hpp"
#include "BoxPrincipalControl.hpp"
#include "MessagesOut.hpp"
#include "LedSalida.hpp"
#include "configuracionAlarmas.hpp"
#include "configuracionLazoAlarmas.hpp"
#include "ConfiguracionRetransmision.hpp"
#include "ConfiguracionAdapSalida.hpp"
#include "configuracionValorControl.hpp"
#include "VistaAlarmas.hpp"
#include "AlarmaControl.hpp"
#include "CoordinadorControladorSintonizador.hpp"
#include "AutoSintonia.hpp"
#include "RegistradorSD.hpp"
#include "Math.hpp"
#include "SPI.hpp"
void conectarSalidas(void * a);
void OnTipoSalChange(void * b);
const LedsSalida::LedConfig configuracionLedsSalida[]= {
&PTIP,1<<3,0,
&PTIP,1<<1,1,
&PTIP,1<<5,2,
&PTIP,1<<7,3
};
const LedsSalida::LedConfig* pConfiguracionLedsSalida[]={
&configuracionLedsSalida[0],
&configuracionLedsSalida[1],
&configuracionLedsSalida[2],
&configuracionLedsSalida[3]
};
#pragma CONST_SEG PARAMETERS_PAGE
/* Tiempo inicial en el que el control permanece desconectado */
#ifdef _COLADA_CALIENTE
#define SALIDA_TIEMPO_DESCONECTADA 20000
#else
#define SALIDA_TIEMPO_DESCONECTADA 3000 //tiene que alcanzar para hacer 2 mediciones
#endif
volatile const ConfiguracionControlPID::ControlConf control_config[CANTIDAD_CANALES]={
ControlDefaultConf,
#if CANTIDAD_CANALES>1
ControlDefaultConf
#endif
};
/*
volatile const ConfiguracionAlarmas::AlarmConf alar_conf[CANTIDAD_SAL_ALARMA]={
4,1,
#if CANTIDAD_SAL_ALARMA>1
4,1,
#if CANTIDAD_SAL_ALARMA>2
4,1,
#if CANTIDAD_SAL_ALARMA>3
4,1,
#endif
#endif
#endif
};
volatile const ConfiguracionLazoAlarmas::LazoAlarmConf lazo_alar_conf[CANTIDAD_SAL_ALARMA]={
0,
#if CANTIDAD_SAL_ALARMA>1
0,
#if CANTIDAD_SAL_ALARMA>2
0,
#if CANTIDAD_SAL_ALARMA>3
0,
#endif
#endif
#endif
};
volatile const ConfiguracionRetransm::RetConf ret_conf[CANTIDAD_SAL_ALARMA]={
0,100,
#if CANTIDAD_SAL_ALARMA>1
0,100,
#if CANTIDAD_SAL_ALARMA>2
0,100,
#if CANTIDAD_SAL_ALARMA>3
0,100,
#endif
#endif
#endif
};
volatile const ConfiguracionAdapSalida::AdapSalConf adapSal_conf[CANTIDAD_SAL_ALARMA]={
-2,0,
#if CANTIDAD_SAL_ALARMA>1
-2,0,
#if CANTIDAD_SAL_ALARMA>2
-2,0,
#if CANTIDAD_SAL_ALARMA>3
-2,0,
#endif
#endif
#endif
};
volatile const ConfiguracionValorControlado::ValorControlConf alarmaSP_conf[CANTIDAD_SAL_ALARMA]={
10,
#if CANTIDAD_SAL_ALARMA>1
10,
#if CANTIDAD_SAL_ALARMA>2
10,
#endif
#endif
};
*/
volatile const SensorTermoPT100::TConfSensor sensor_config[CANTIDAD_CANALES]= {
STPT_DEF_CONF,
#if CANTIDAD_CANALES>1
STPT_DEF_CONF,
#if CANTIDAD_CANALES>2
STPT_DEF_CONF,
#if CANTIDAD_CANALES>3
STPT_DEF_CONF,
#endif
#endif
#endif
};
volatile const TConfPWM confPWM[CANTIDAD_CANALES+CANTIDAD_SAL_ALARMA]={
0,
0,
#if CANTIDAD_CANALES>1 || CANTIDAD_SAL_ALARMA>1
0,
#if CANTIDAD_CANALES>1 || CANTIDAD_SAL_ALARMA>2
0,
#endif
#endif
};
volatile const int ta=0;
#ifdef NDEBUG
volatile const int codigo = 1234;
#else
volatile const int codigo = 0;
#endif
#pragma CONST_SEG DEFAULT
FlashBkpMitad flash((void*)0x4200);
class Init{
public:
Init(){
Timer::setBaseTimerDefault(*BaseTimers_1ms_40ms::getInstance());
SensorTermoPT100::setConfiguracionTemperaturaAmbiente((int*)&ta);
}
}ini;
Termometro termometro(flash);
#if CANTIDAD_CANALES == 1
Adc ad0(0);
SensorTermoPT100 sensor0(ad0,sensor_config[0],flash);
#else
Adc ad0(0);
Adc ad1(1);
SensorTermoPT100 sensor0(ad0,sensor_config[0],flash);
SensorTermoPT100 sensor1(ad1,sensor_config[1],flash);
#endif
PWMHard23 pwm23(flash,confPWM[0]); // pwm control 0
PWMTimer pwm2(flash,confPWM[1],1); // pwm alarma 1 o si es de 2 canales pwm control 1
PWMTimer pwm3(flash,confPWM[2],4); // pwm alarma 2 o si es de 2 canales pwm alarma 1(canal 1)
PWMTimer pwm4(flash,confPWM[3],7); // pwm alarma 3 o si es de 2 canales alarma 1(canal 2)
const ConfiguracionControlPID configuraControl0(*(ConfiguracionControlPID::ControlConf*)&control_config[0],flash);
//ControlPID control0(sensor0,pwm23,configuraControl0);
CoordinadorControladorSintonizador control0(sensor0,pwm23,configuraControl0);
#if CANTIDAD_CANALES>1
const ConfiguracionControlPID configuraControl1(*(ConfiguracionControlPID::ControlConf*)&control_config[1],flash);
ControlPID control1(sensor1,pwm2,configuraControl1);
#endif
MessagesOut mjsCambioTipoSalida;
/*
ConfiguracionLazoAlarmas configuracionLazoAlarmas0(*(ConfiguracionLazoAlarmas::LazoAlarmConf*)&lazo_alar_conf[0],flash);
ConfiguracionAlarmas configuracionAlarma0(*(ConfiguracionAlarmas::AlarmConf*)&alar_conf[0],flash);
ConfiguracionRetransm configuracionRetrans0(*(ConfiguracionRetransm::RetConf*)&ret_conf[0],flash);
ConfiguracionAdapSalida configuracionAdapSalida0(*(ConfiguracionAdapSalida::AdapSalConf*)&adapSal_conf[0],flash);
ConfiguracionValorControlado configuracionValorAlarma0(*(ConfiguracionValorControlado::ValorControlConf*)&alarmaSP_conf[0],flash);
CoordinadorLazosAlCntrRet alarma0(configuracionLazoAlarmas0,configuracionAlarma0,configuracionValorAlarma0,configuracionAdapSalida0,configuracionRetrans0,(*(ControlPID*)(control0.getControl())),pwm3);
*/
#if CANTIDAD_SAL_ALARMA>1 && CANTIDAD_CANALES==1
ConfiguracionLazoAlarmas configuracionLazoAlarmas1(*(ConfiguracionLazoAlarmas::LazoAlarmConf*)&lazo_alar_conf[1],flash);
ConfiguracionAlarmas configuracionAlarma1(*(ConfiguracionAlarmas::AlarmConf*)&alar_conf[1],flash);
ConfiguracionRetransm configuracionRetrans1(*(ConfiguracionRetransm::RetConf*)&ret_conf[1],flash);
ConfiguracionAdapSalida configuracionAdapSalida1(*(ConfiguracionAdapSalida::AdapSalConf*)&adapSal_conf[1],flash);
ConfiguracionValorControlado configuracionValorAlarma1(*(ConfiguracionValorControlado::ValorControlConf*)&alarmaSP_conf[1],flash);
CoordinadorLazosAlCntrRet alarma1(configuracionLazoAlarmas1,configuracionAlarma1,configuracionValorAlarma1,configuracionAdapSalida1,configuracionRetrans1,control0,pwm2);
#elif CANTIDAD_CANALES>1
ConfiguracionLazoAlarmas configuracionLazoAlarmas1(*(ConfiguracionLazoAlarmas::LazoAlarmConf*)&lazo_alar_conf[1],flash);
ConfiguracionAlarmas configuracionAlarma1(*(ConfiguracionAlarmas::AlarmConf*)&alar_conf[1],flash);
ConfiguracionRetransm configuracionRetrans1(*(ConfiguracionRetransm::RetConf*)&ret_conf[1],flash);
ConfiguracionAdapSalida configuracionAdapSalida1(*(ConfiguracionAdapSalida::AdapSalConf*)&adapSal_conf[1],flash);
ConfiguracionValorControlado configuracionValorAlarma1(*(ConfiguracionValorControlado::ValorControlConf*)&alarmaSP_conf[1],flash);
CoordinadorLazosAlCntrRet alarma1(configuracionLazoAlarmas1,configuracionAlarma1,configuracionValorAlarma1,configuracionAdapSalida1,configuracionRetrans1,control1,pwm4);
#endif
#if CANTIDAD_SAL_ALARMA>2
ConfiguracionLazoAlarmas configuracionLazoAlarmas2(*(ConfiguracionLazoAlarmas::LazoAlarmConf*)&lazo_alar_conf[2],flash);
ConfiguracionAlarmas configuracionAlarma2(*(ConfiguracionAlarmas::AlarmConf*)&alar_conf[2],flash);
ConfiguracionRetransm configuracionRetrans2(*(ConfiguracionRetransm::RetConf*)&ret_conf[2],flash);
ConfiguracionAdapSalida configuracionAdapSalida2(*(ConfiguracionAdapSalida::AdapSalConf*)&adapSal_conf[2],flash);
ConfiguracionValorControlado configuracionValorAlarma2(*(ConfiguracionValorControlado::ValorControlConf*)&alarmaSP_conf[2],flash);
CoordinadorLazosAlCntrRet alarma2(configuracionLazoAlarmas2,configuracionAlarma2,configuracionValorAlarma2,configuracionAdapSalida2,configuracionRetrans2,control0,pwm4);
#endif
#if CANTIDAD_CANALES==1
//potencia
const struct FstBoxPointer potInst0={
(const struct ConstructorBox*)&cBoxPotInst,&control0.poolModo,0
};
const struct FstBoxPointer potMan0={
(const struct ConstructorBox*)&cBoxPotMan,&control0.poolModo,0
};
#else
const struct FstBoxPointer potInst0={
(const struct ConstructorBox*)&cBoxPotInst,&control0,1
};
const struct FstBoxPointer potMan0={
(const struct ConstructorBox*)&cBoxPotMan,&control0,1
};
const struct FstBoxPointer potInst1={
(const struct ConstructorBox*)&cBoxPotInst,&control1,2
};
const struct FstBoxPointer potMan1={
(const struct ConstructorBox*)&cBoxPotMan,&control1,2
};
#endif
#if CANTIDAD_CANALES==1
#if CANTIDAD_SAL_ALARMA>1
//SP_alarma
const struct FstBoxPointer SPal0={
(const struct ConstructorBox*)&cBoxesSetPointAlarma,&alarma0,1
};
const struct FstBoxPointer SPal1={
(const struct ConstructorBox*)&cBoxesSetPointAlarma,&alarma1,2
};
#else
/*
const struct FstBoxPointer SPal0={
(const struct ConstructorBox*)&cBoxesSetPointAlarma,&alarma0,0
};
*/
#endif
#if CANTIDAD_SAL_ALARMA>2
const struct FstBoxPointer SPal2={
(const struct ConstructorBox*)&cBoxesSetPointAlarma,&alarma2,3
};
#endif
#else
const struct FstBoxPointer SPal0={
(const struct ConstructorBox*)&cBoxesSetPointAlarma,&alarma0,1
};
const struct FstBoxPointer SPal1={
(const struct ConstructorBox*)&cBoxesSetPointAlarma,&alarma1,2
};
#endif
struct ConstructorBoxPrincipalControl cBoxPri={
&boxPrincipalControlFactory, /* funcion que procesa al box*/
&sensor0,
&mjsCambioTipoSalida,
&mjsCambioTipoSalida,
//&flash
};
const struct FstBoxPointer principal={
(const ConstructorBox*)&cBoxPri,NULL,0
};
const struct FstBoxPointer *const opArray[]={
&principal,
&potInst0,
&potMan0,
#if CANTIDAD_CANALES>1
&potInst1,
&potMan1,
#endif
};
/*const struct BoxList opList ={
&opArray,
1,
FALSE,
""
};*/
const NEW_BOX_LIST(opList,opArray,"");
//TUN
const struct FstBoxPointer autoSintonia0={
(const struct ConstructorBox*)&cBoxModos,&control0,0
};
#if CANTIDAD_CANALES==1
const struct FstBoxPointer reset0={
(const struct ConstructorBox*)&cBoxesReset,&control0.poolModo,0
};
const struct FstBoxPointer aparatoConf0={
(const struct ConstructorBox*)&cBoxesSintonia,&control0.poolModo,0
};
const struct FstBoxPointer periodo0={
(const struct ConstructorBox*)&cBoxPeriodo,&pwm23,0
};
#else
const struct FstBoxPointer reset0={
(const struct ConstructorBox*)&cBoxesReset,&control0,1
};
const struct FstBoxPointer aparatoConf0={
(const struct ConstructorBox*)&cBoxesSintonia,&control0,1
};
const struct FstBoxPointer reset1={
(const struct ConstructorBox*)&cBoxesReset,&control1,2
};
const struct FstBoxPointer aparatoConf1={
(const struct ConstructorBox*)&cBoxesSintonia,&control1,2
};
const struct FstBoxPointer periodo0={
(const struct ConstructorBox*)&cBoxPeriodo,&pwm23,1
};
const struct FstBoxPointer periodo1={
(const struct ConstructorBox*)&cBoxPeriodo,&pwm2,2
};
#endif
static const struct FstBoxPointer *const tunArray[]={
&autoSintonia0,
&reset0,
&periodo0,
// &aparatoConf0,
};
static const NEW_BOX_LIST(tun,tunArray,"SintoniA");
//CAL
#if CANTIDAD_CANALES==1
const struct FstBoxPointer sensor1List0={
(const struct ConstructorBox*)&cBoxesSensor,&sensor0,0
};
#else
const struct FstBoxPointer sensor1List0={
(const struct ConstructorBox*)&cBoxesSensor,&sensor0,1
};
const struct FstBoxPointer sensor1List1={
(const struct ConstructorBox*)&cBoxesSensor,&sensor1,2
};
#endif
#if CANTIDAD_SAL_ALARMA>1 || CANTIDAD_CANALES>1
const struct FstBoxPointer retAlmLimInf1={
(const struct ConstructorBox*)&cBoxesRetLimInf,&alarma1,2
};
const struct FstBoxPointer retAlmLimSup1={
(const struct ConstructorBox*)&cBoxesRetLimSup,&alarma1,2
};
#if CANTIDAD_SAL_ALARMA>2
const struct FstBoxPointer retAlmLimInf2={
(const struct ConstructorBox*)&cBoxesRetLimInf,&alarma2,3
};
const struct FstBoxPointer retAlmLimSup2={
(const struct ConstructorBox*)&cBoxesRetLimSup,&alarma2,3
};
#endif
#endif
static const struct FstBoxPointer *const calArray[]={
&sensor1List0,
#if CANTIDAD_CANALES>1
&sensor1List1,
#endif
};
static const NEW_BOX_LIST(cal,calArray,"CALibrAcion");
//SET
const VistaSetContrasenia vistaSetContrasenia={
(const int *)&codigo,
&flash
};
const struct FstBoxPointer setCList={
(const struct ConstructorBox*)&(VistaSetContrasenia::cBoxSetContrasenia),(void *)&vistaSetContrasenia,0
};
#if CANTIDAD_CANALES==1
const struct FstBoxPointer modosSalida0={
(const struct ConstructorBox*)&cBoxModoSalida,&control0.poolModo,0
};
#else
const struct FstBoxPointer modosSalida0={
(const struct ConstructorBox*)&cBoxModoSalida,&control0.poolModo,1
};
const struct FstBoxPointer modosSalida1={
(const struct ConstructorBox*)&cBoxModoSalida,&control1,2
};
#endif
#if CANTIDAD_SAL_ALARMA>1 || CANTIDAD_CANALES>1
const struct FstBoxPointer tipoLazoAlarma1={
(const struct ConstructorBox*)&cBoxesTipoLazo,&alarma1,2
};
const struct FstBoxPointer modosAlarma1={
(const struct ConstructorBox*)&cBoxesAlarma,&alarma1,2
};
const struct FstBoxPointer ctrlAlarma1={
(const struct ConstructorBox*)&cBoxesAlarmaCtrl,&alarma1,2
};
#if CANTIDAD_SAL_ALARMA>2
const struct FstBoxPointer tipoLazoAlarma2={
(const struct ConstructorBox*)&cBoxesTipoLazo,&alarma2,3
};
const struct FstBoxPointer modosAlarma2={
(const struct ConstructorBox*)&cBoxesAlarma,&alarma2,3
};
const struct FstBoxPointer ctrlAlarma2={
(const struct ConstructorBox*)&cBoxesAlarmaCtrl,&alarma2,3
};
#endif
#endif
static const struct FstBoxPointer *const setArray[]={
&modosSalida0,
&setCList
};
static const NEW_BOX_LIST(set,setArray,"ConFigurAcion");
//LIMITES
#if CANTIDAD_CANALES==1
const struct FstBoxPointer limites0={
(const struct ConstructorBox*)&cBoxesLimites,&control0,0
};
#else
const struct FstBoxPointer limites0={
(const struct ConstructorBox*)&cBoxesLimites,&control0,1
};
const struct FstBoxPointer limites1={
(const struct ConstructorBox*)&cBoxesLimites,&control1,2
};
#endif
static const struct FstBoxPointer *const limArray[]={
&limites0,
#if CANTIDAD_CANALES>1
&limites1,
#endif
};
static const NEW_BOX_LIST(lim,limArray,"LimitES");
// Acceso comun
const struct BoxList *const boxListArray[]={
&tun,
&cal,
&set,
&lim
};
const NEW_ACCESS(accesoComun,boxListArray,"Cod",(const int*)&codigo);
const struct Access *const accessArray[]={
&accesoComun
};
const NEW_ARRAY(accessList,accessArray);
NEW_ARRAY(arrayLedConfig,pConfiguracionLedsSalida);
const LedsSalida leds (arrayLedConfig,*(FrenteDH::getInstancia()));
void * timer=NULL;
struct Method timerSalida={
&conectarSalidas,NULL
};
struct Method cambioTipoSalida={
&OnTipoSalChange,NULL
};
/***REGISTRADOR SD**********/
class ConfiguracionRegistradorSD:public ConfiguracionRegistrador{
public:
virtual byte getAdquirir(){
return adquirir;
}
virtual void setAdquirir(byte a){
adquirir = a;
}
virtual int getIntervalo(){
return intervalo;
}
virtual void setIntervalo(int i){
if(i>0 && i<10000)
intervalo = i;
}
private:
int adquirir,intervalo;
}confRegistrador;
class SerializadorSensor:public ElementoRegistrable{
public:
virtual const char * serializar(int& tamanio){
sensor0.print(o);
return o.str;
}
virtual const char * getDescripcion(){
return "SENSOR";
}
virtual Tipo getTipo(){
return ElementoRegistrable::TXT;
}
private:
class O: public OutputStream{ //mejorar codigo para aparato C++, copia de codigo con Display
public:
virtual void write(const char * b){
memcpy(str,b,7);
}
virtual void write(int i){
sprintf(str,"%i",i);
}
virtual void writeAsFloat(int i,uchar decimales){
if(!decimales){
write(i);
return;
}
int a;
a=sprintf(str,"%*i.",4-decimales,1);//i/ Math::pow10(decimales));
sprintf(str+a,"%0*i",decimales,abs(i)% Math::pow10(decimales));
write(str);
}
char str[7];
}o;
}serializadorSensor;
ElementoRegistrable * arraySerializables[]={
&serializadorSensor
};
NEW_ARRAY( serializables,arraySerializables);
/*Reemplazar por verdaderos:*/
SPI spi;
class SDPresent: public BitIn{
public:
SDPresent(){
DDRB_BIT3 = 1; //PTB bit3 es entrada
}
bool getBit(){
return PORTB_BIT3;
}
}sdPresent;
/*****************************/
SDFat sd(spi,sdPresent);
RegistradorSD registrador(serializables,confRegistrador,sd);
void main(void) {
static MessagesOut::Message msj_AutoSintonia;
#if CANTIDAD_CANALES>1
BoxPrincipalControl::MostrarGetter((ConstructorPropGetterVisual *)&cPropiedadGetSensor1,&control1);
#else
BoxPrincipalControl::MostrarProp((ConstructorPropGetterVisual *)&cPropiedadSetPoint,&control0);
#endif
RlxMTimer timerConexionSalidas(SALIDA_TIEMPO_DESCONECTADA,timerSalida);
timer=&timerConexionSalidas;
DiagramaNavegacion d(&opList,&accessList,FrenteDH::getInstancia());
PE_low_level_init();
#if CANTIDAD_CANALES==1
//control0.addOnTipoSalidaListener(cambioTipoSalida);
((ControlPID*)(control0.getControl()))->addOnTipoSalidaListener(cambioTipoSalida);
#elif CANTIDAD_CANALES==2
control1.addOnTipoSalidaListener(cambioTipoSalida);
#endif
for(;;){
byte tecla = FrenteDH::getInstancia()->getTecla();
termometro.mainLoop();
d.procesar(tecla);
#if CANTIDAD_CANALES == 1
sensor0.checkADC();
if(control0.getEstadoAutosintonia() == TRUE){ //AutoSintonia detenida?
if(msj_AutoSintonia)
mjsCambioTipoSalida.deleteMessage(msj_AutoSintonia);
control0.setModo(CONTROL);
}else if(control0.getEstadoAutosintonia() == FALSE){
//estoy en autoSintonia presento los carteles
char mensaje[5];
mensaje[0]='S';
mensaje[1]='t';
mensaje[2]=' ';
mensaje[3]=((char)(control0.getPasoAutosintonia())+0x30);
mensaje[4]='\0';
if(!msj_AutoSintonia)
msj_AutoSintonia = mjsCambioTipoSalida.addMessage(mensaje);
}
#else
sensor0.checkADC();
sensor1.checkADC();
#endif
}
/* please make sure that you never leave main */
}
void conectarSalidas(void * a){
((RlxMTimer *)timer)->stop();
pwm23.setConectada(TRUE);
pwm23.setPeriodo(pwm23.getPeriodo()); // seteo el periodo inicial
pwm2.setConectada(TRUE);
pwm2.setTipoSalida(SALIDA_ONOFF);
#if CANTIDAD_SAL_ALARMA>1 || CANTIDAD_CANALES>1
pwm3.setConectada(TRUE);
pwm3.setTipoSalida(SALIDA_ONOFF);
#endif
#if CANTIDAD_SAL_ALARMA>2 || CANTIDAD_CANALES>1
pwm4.setConectada(TRUE);
pwm4.setTipoSalida(SALIDA_ONOFF);
#endif
}
void OnTipoSalChange(void * b){
#if CANTIDAD_CANALES == 1
static MessagesOut::Message msj_on_sal_change;
if(((ControlPID*)(control0.getControl()))->getModoSalida()==ControlPID::_MAN/*control0.getModoSalida()==ControlPID::_MAN*/){
if(!msj_on_sal_change)
msj_on_sal_change = mjsCambioTipoSalida.addMessage("Pot ");
BoxPrincipalControl::MostrarProp((ConstructorPropGetterVisual *)&cPropiedadPotManual,&control0);
}else{
if(msj_on_sal_change){
mjsCambioTipoSalida.deleteMessage(msj_on_sal_change);
BoxPrincipalControl::MostrarProp((ConstructorPropGetterVisual *)&cPropiedadSetPoint,&control0);
msj_on_sal_change=NULL;
}
}
#elif CANTIDAD_CANALES == 2
if(control1.getModoSalida()==ControlPID::_MAN){
pwm2.setTipoSalida(SALIDA_PROPORCIONAL);
}else{
pwm2.setTipoSalida(SALIDA_ONOFF);
}
#endif
}
| [
"jonymarino@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549"
]
| [
[
[
1,
754
]
]
]
|
46426b001ff0756f127667a2748d3f7952ce76d1 | f8b49ab7b1fd8252576a07d604338ae615a76cc4 | /QSimSourceCode/QSimStartSimulationNoGui.cpp | d0b5925a7a7bd373419abe326901df5f4d01a52d | []
| no_license | ruisebastiao/qsim | 8eb47c7c40a217f902d886526ceede651e80a14e | 7933f8a44e145f18971062bdd8b3421e75f46657 | refs/heads/master | 2016-09-06T04:32:07.445284 | 2011-10-19T18:55:11 | 2011-10-19T18:55:11 | 35,518,359 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,563 | cpp | //-----------------------------------------------------------------------------
// File: QSimStartSimulationNoGui.cpp
// Class: QSimStartSimulation
// Purpose: There are TWO .cpp files for this class.
// QSimStartSimulationNoGui.cpp contains standard C++ (non-Qt) methods to run simulation.
// QSimStartSimulationGui.cpp contains Qt methods to display/interact with simulation.
/* ---------------------------------------------------------------------------- *
* QSim was developed with support from Simbios (NIH Center for Physics-Based *
* Simulation of Biological Structures at Stanford) under NIH Roadmap for *
* Medical Research grant U54 GM072970 and NCSRR (National Center for Simulation *
* in Rehabilitation Research) NIH research infrastructure grant R24 HD065690. *
* *
* To the extent possible under law, the author(s) and contributor(s) have *
* dedicated all copyright and related and neighboring rights to this software *
* to the public domain worldwide. This software is distributed without warranty.*
* *
* Authors: Paul Mitiguy (2011) *
* Contributors: Ayman Habib, Michael Sherman *
* *
* Permission is 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.*
* *
* Include this sentence, the above public domain and permission notices, and the*
* following disclaimer in all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR CONTRIBUTORS 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. *
* ----------------------------------------------------------------------------- */
// DO NOT #include "QSimStartSimulation.h" or unable to split from Qt
#include "CppStandardHeaders.h"
#if 1 // Change 1 to 0 if want to use Simbody only.
#include <SimTKsimbody.h> // Includes all Simbody header files.
using namespace SimTK;
// #else
#include <OpenSim.h> // Includes all OSimAPI header files.
namespace OSimAPI = OpenSim; // Avoid confusion between QSim and OpenSim namespaces
using namespace OSimAPI;
using namespace SimTK;
#endif
//------------------------------------------------------------------------------
namespace QSim {
//-----------------------------------------------------------------------------
// Prototypes for local functions (functions not called by code in other files)
//-----------------------------------------------------------------------------
bool WriteExceptionToFile( const char* outputString, const char* exceptionStringOrNull )
{
bool retValue = false;
#if QSIM_DEBUG__
FILE *outputFile = fopen( "ExceptionsThrownByQSim.txt", "a+" );
if( outputFile && outputString )
{
retValue = fputs( outputString, outputFile ) != EOF;
if( exceptionStringOrNull ) retValue = retValue && fputs( exceptionStringOrNull, outputFile ) != EOF;
fflush( outputFile );
fclose( outputFile );
}
#endif
return retValue;
}
//-----------------------------------------------------------------------------
bool StartAndRunSimulationMathematicsEngineNoGuiInsideExceptionHandling( )
{
// Create the system, with subsystems for the bodies and some forces.
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
GeneralForceSubsystem forces(system);
// Add gravity as a force element.
SimTK::Force::UniformGravity gravity(forces, matter, Vec3(0, -9.8, 0));
// Create the body and some artwork for it.
SimTK::Body::Rigid pendulumBody(MassProperties(1.0, Vec3(0), Inertia(1)));
// pendulumBody.addDecoration(Transform(), DecorativeSphere(0.1).setColor(Red));
// Add an instance of the body to the multibody system by connecting it to Ground via a pin mobilizer.
MobilizedBody::Pin pendulum(matter.updGround(), Transform(Vec3(0)), pendulumBody, Transform(Vec3(0, 1, 0)));
// Visualize with default options; ask for a report every 1/30 of a second
// to match the Visualizer's default 30 frames per second rate.
// The Simbody visualizer must be able to execute the program VisualizerGUI.exe
// One way for Simbody to find this program is to set the environment variable
// SimTK_INSTALL_DIR with a value FullPathTo/Simbody/bin folder.
Visualizer viz(system);
system.addEventReporter(new Visualizer::Reporter(viz, 1./30));
// Initialize the system and state.
system.realizeTopology();
State state = system.getDefaultState();
pendulum.setOneU(state, 0, 1.0); // initial velocity 1 rad/sec
// Simulate it.
RungeKuttaMersonIntegrator integ(system);
TimeStepper ts(system, integ);
ts.initialize(state);
ts.stepTo(10.0);
// Simulation completed properly
return true;
}
//-----------------------------------------------------------------------------
bool StartAndRunOpenSimApiEngineNoGuiInsideExceptionHandling()
{
// Create an OpenSim model and set its name
Model osimModel;
osimModel.setName( "tugOfWar" );
// GROUND BODY
// Get a reference to the model's ground body
OpenSim::Body& ground = osimModel.getGroundBody();
// Add display geometry to the ground to visualize in the GUI
// FILE *Fptr = fopen( "\\OpenSim2.2.1\\sdk\\APIExamples\\ExampleMain\\ground.vtp", "r" );
ground.addDisplayGeometry( "\\OpenSim2.2.1\\sdk\\APIExamples\\ExampleMain\\ground.vtp" );
ground.addDisplayGeometry( "\\OpenSim2.2.1\\sdk\\APIExamples\\ExampleMain\\anchor1.vtp" );
ground.addDisplayGeometry( "\\OpenSim2.2.1\\sdk\\APIExamples\\ExampleMain\\anchor2.vtp" );
// BLOCK BODY
// Specify properties of a 20 kg, 0.1 m^3 block body
double blockMass = 20.0, blockSideLength = 0.1;
Vec3 blockMassCenter(0);
Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
// Create a new block body with the specified properties
OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
// Add display geometry to the block to visualize in the GUI
block->addDisplayGeometry("\\OpenSim2.2.1\\sdk\\APIExamples\\ExampleMain\\block.vtp");
// FREE JOINT
// Create a new free joint with 6 degrees-of-freedom (coordinates) between the block and ground bodies
Vec3 locationInParent(0, blockSideLength/2, 0), orientationInParent(0), locationInBody(0), orientationInBody(0);
FreeJoint *blockToGround = new FreeJoint("blockToGround", ground, locationInParent, orientationInParent, *block, locationInBody, orientationInBody);
// Get a reference to the coordinate set (6 degrees-of-freedom) between the block and ground bodies
CoordinateSet& jointCoordinateSet = blockToGround->getCoordinateSet();
// Set the angle and position ranges for the coordinate set
double angleRange[2] = {-SimTK::Pi/2, SimTK::Pi/2};
double positionRange[2] = {-1, 1};
jointCoordinateSet[0].setRange(angleRange);
jointCoordinateSet[1].setRange(angleRange);
jointCoordinateSet[2].setRange(angleRange);
jointCoordinateSet[3].setRange(positionRange);
jointCoordinateSet[4].setRange(positionRange);
jointCoordinateSet[5].setRange(positionRange);
// Add the block body to the model
osimModel.addBody(block);
///////////////////////////////////////////////
// DEFINE THE SIMULATION START AND END TIMES //
///////////////////////////////////////////////
// Define the initial and final simulation times
const double initialTime = 0.0;
const double finalTime = 8.4;
/////////////////////////////////////////////
// DEFINE CONSTRAINTS IMPOSED ON THE MODEL //
/////////////////////////////////////////////
// Specify properties of a point on a line constraint to limit the block's motion
Vec3 lineDirection(1,0,-1);
Vec3 pointOnLine(1,0,-1);
Vec3 pointOnFollowerBody(0,-0.05,0);
// Create a new point on line constraint and add it to the model.
// PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnFollowerBody);
// osimModel.addConstraint(lineConstraint);
///////////////////////////////////////
// DEFINE FORCES ACTING ON THE MODEL //
///////////////////////////////////////
// GRAVITY
// Define the acceleration due to gravity
osimModel.setGravity(Vec3(0,-9.80665,0));
// MUSCLE FORCES
// Create two new muscles
double maxIsometricForce = 1000.0, optimalFiberLength = 0.1, tendonSlackLength = 0.2, pennationAngle = 0.0, activation = 0.0001, deactivation = 1.0;
// Create new muscle 1 using the Shutte 1993 muscle model
// Note: activation/deactivation parameters are set differently between the models.
Thelen2003Muscle *muscle1 = new Thelen2003Muscle("muscle1",maxIsometricForce,optimalFiberLength,tendonSlackLength,pennationAngle);
muscle1->setActivationTimeConstant(activation);
muscle1->setDeactivationTimeConstant(deactivation);
// Create new muscle 2 using the Thelen 2003 muscle model
Thelen2003Muscle *muscle2 = new Thelen2003Muscle("muscle2",maxIsometricForce,optimalFiberLength,tendonSlackLength,pennationAngle);
muscle2->setActivationTimeConstant(activation);
muscle2->setDeactivationTimeConstant(deactivation);
// Specify the paths for the two muscles
// Path for muscle 1
muscle1->addNewPathPoint("muscle1-point1", ground, Vec3(0.0,0.05,-0.35));
muscle1->addNewPathPoint("muscle1-point2", *block, Vec3(0.0,0.0,-0.05));
// Path for muscle 2
muscle2->addNewPathPoint("muscle2-point1", ground, Vec3(0.0,0.05,0.35));
muscle2->addNewPathPoint("muscle2-point2", *block, Vec3(0.0,0.0,0.05));
// Add the two muscles (as forces) to the model
osimModel.addForce(muscle1);
osimModel.addForce(muscle2);
// CONTACT FORCE
// Define contact geometry
// Create new floor contact halfspace
ContactHalfSpace *floor = new ContactHalfSpace(SimTK::Vec3(0), SimTK::Vec3(0, 0, -0.5*SimTK_PI), ground, "floor");
// Create new cube contact mesh
OpenSim::ContactMesh *cube = new OpenSim::ContactMesh("\\OpenSim2.2.1\\sdk\\APIExamples\\ExampleMain\\blockRemesh192.obj", SimTK::Vec3(0), SimTK::Vec3(0), *block, "cube");
// Add contact geometry to the model
osimModel.addContactGeometry(floor);
osimModel.addContactGeometry(cube);
// Contact parameters
double stiffness = 1.0e8, dissipation = 0.01, friction = 0.25;
// Define contact parameters for elastic foundation force
OpenSim::ElasticFoundationForce::ContactParameters *contactParams = new OpenSim::ElasticFoundationForce::ContactParameters(stiffness, dissipation, friction, 0, 0);
contactParams->addGeometry("cube");
contactParams->addGeometry("floor");
// Create a new elastic foundation (contact) force between the floor and cube.
OpenSim::ElasticFoundationForce *contactForce = new OpenSim::ElasticFoundationForce(contactParams);
contactForce->setName("contactForce");
// Add the new elastic foundation force to the model
osimModel.addForce(contactForce);
// PRESCRIBED FORCE
// Specify properties of a force function to be applied to the block
double time[2] = {0, finalTime}; // time nodes for linear function
double fXofT[2] = {0, -blockMass*9.80665*3.0}; // force values at t1 and t2
double pXofT[2] = {0, 0.1}; // point in x values at t1 and t2
// Create a new linear functions for the force and point components
PiecewiseLinearFunction *forceX = new PiecewiseLinearFunction(2, time, fXofT);
PiecewiseLinearFunction *pointX = new PiecewiseLinearFunction(2, time, pXofT);
// Create a new prescribed force applied to the block
PrescribedForce *prescribedForce = new PrescribedForce(block);
prescribedForce->setName("prescribedForce");
// Set the force and point functions for the new prescribed force
prescribedForce->setForceFunctions(forceX, new Constant(0.0), new Constant(0.0));
prescribedForce->setPointFunctions(pointX, new Constant(0.0), new Constant(0.0));
// Add the new prescribed force to the model
osimModel.addForce(prescribedForce);
///////////////////////////////////
// DEFINE CONTROLS FOR THE MODEL //
///////////////////////////////////
// Create a prescribed controller that simply applies controls as function of time
PrescribedController *muscleController = new PrescribedController();
muscleController->setActuators(osimModel.updActuators());
// Define linear functions for the control values for the two muscles
Array<double> slopeAndIntercept1(0.0, 2); // array of 2 doubles
Array<double> slopeAndIntercept2(0.0, 2);
// muscle1 control has slope of -1 starting 1 at t = 0
slopeAndIntercept1[0] = -1.0/(finalTime-initialTime); slopeAndIntercept1[1] = 1.0;
// muscle2 control has slope of 1 starting 0.05 at t = 0
slopeAndIntercept2[0] = 1.0/(finalTime-initialTime); slopeAndIntercept2[1] = 0.05;
// Set the indiviudal muscle control functions for the prescribed muscle controller
muscleController->prescribeControlForActuator("muscle1", new LinearFunction(slopeAndIntercept1));
muscleController->prescribeControlForActuator("muscle2", new LinearFunction(slopeAndIntercept2));
// Define the default states for the two muscles
// Activation
muscle1->setDefaultActivation(slopeAndIntercept1[1]);
muscle2->setDefaultActivation(slopeAndIntercept2[1]);
// Fiber length
muscle2->setDefaultFiberLength(0.1);
muscle1->setDefaultFiberLength(0.1);
//////////////////////////
// PERFORM A SIMULATION //
//////////////////////////
// Initialize the system and get the default state
SimTK::State &si = osimModel.initSystem();
// Define non-zero (defaults are 0) states for the free joint
CoordinateSet& modelCoordinateSet = osimModel.updCoordinateSet();
modelCoordinateSet[3].setValue(si, blockSideLength); // set x-translation value
modelCoordinateSet[3].setSpeedValue(si, 0.1); // set x-speed value
modelCoordinateSet[4].setValue(si, blockSideLength/2+0.01); // set y-translation value
// Compute initial conditions for muscles
osimModel.computeEquilibriumForAuxiliaryStates(si);
// Visualize with default options; ask for a report every 1/30 of a second
// to match the Visualizer's default 30 frames per second rate.
// The Simbody visualizer must be able to execute the program VisualizerGUI.exe
// One way for Simbody to find this program is to set the environment variable
// SimTK_INSTALL_DIR with a value FullPathTo/Simbody/bin folder.
const MultibodySystem& simbodyMultibodySystem = osimModel.getMultibodySystem();
SimTK::Visualizer viz( simbodyMultibodySystem );
simbodyMultibodySystem.addEventReporter( new Visualizer::Reporter(viz, 1./30) );
// viz.addDecoration( MobilizedBodyIndex(0), Transform(), DecorativeSphere(0.25).setColor(Blue) );
// viz.addDecoration( MobilizedBodyIndex(1), Transform(), DecorativeBrick( Vec3(1.0,0.2,1.0) ).setColor(Red).setOpacity(0.2) );
PolygonalMesh blockMesh, groundMesh1, groundMesh2, groundMesh3;
blockMesh.loadVtpFile( "\\OpenSim2.2.1\\sdk\\APIExamples\\ExampleMain\\block.vtp" );
viz.addDecoration( MobilizedBodyIndex(1), Transform(), DecorativeMesh(blockMesh).setColor(Blue).setOpacity(0.7) );
groundMesh1.loadVtpFile( "\\OpenSim2.2.1\\sdk\\APIExamples\\ExampleMain\\ground.vtp" );
groundMesh2.loadVtpFile( "\\OpenSim2.2.1\\sdk\\APIExamples\\ExampleMain\\anchor1.vtp" );
groundMesh3.loadVtpFile( "\\OpenSim2.2.1\\sdk\\APIExamples\\ExampleMain\\anchor2.vtp" );
viz.addDecoration( MobilizedBodyIndex(0), Transform(), DecorativeMesh(groundMesh1).setColor(Blue).setOpacity(0.5) );
viz.addDecoration( MobilizedBodyIndex(0), Transform(), DecorativeMesh(groundMesh2).setColor(Green).setOpacity(0.3) );
viz.addDecoration( MobilizedBodyIndex(0), Transform(), DecorativeMesh(groundMesh3).setColor(Green).setOpacity(0.3) );
viz.setBackgroundType( Visualizer::SolidColor );
// Create the integrator, force reporter, and manager for the simulation.
// Create the integrator
SimTK::RungeKuttaMersonIntegrator integrator( osimModel.getMultibodySystem() );
integrator.setAccuracy(1.0e-4);
// Create the force reporter
ForceReporter* reporter = new ForceReporter(&osimModel);
osimModel.addAnalysis(reporter);
// Create the manager
Manager manager(osimModel, integrator);
// Print out details of the model
osimModel.printDetailedInfo(si, std::cout);
// Print out the initial position and velocity states
si.getQ().dump("Initial q's"); // block positions
si.getU().dump("Initial u's"); // block velocities
std::cout << "Initial time: " << si.getTime() << std::endl;
// Integrate from initial time to final time
manager.setInitialTime(initialTime);
manager.setFinalTime(finalTime);
std::cout << "\n\nIntegrating from " << initialTime << " to " << finalTime << std::endl;
manager.integrate(si);
//////////////////////////////
// SAVE THE RESULTS TO FILE //
//////////////////////////////
// Save the simulation results
// Save the states
Storage statesDegrees(manager.getStateStorage());
statesDegrees.print("tugOfWar_states.sto");
osimModel.updSimbodyEngine().convertRadiansToDegrees(statesDegrees);
statesDegrees.setWriteSIMMHeader(true);
statesDegrees.print("tugOfWar_states_degrees.mot");
// Save the forces
reporter->getForceStorage().print("tugOfWar_forces.mot");
// Save the model to a file
osimModel.print("tugOfWar_model.osim");
// Simulation completed properly
return true;
}
//-----------------------------------------------------------------------------
bool StartAndRunSimulationMathematicsEngineNoGui( const bool trueForSimbodyFalseForOpenSimApi )
{
// The try-catch code in this main routine catches exceptions thrown by functions in the
// try block, e.g., catching an exception that occurs when a NULL pointer is de-referenced.
try
{
if( trueForSimbodyFalseForOpenSimApi ) return StartAndRunSimulationMathematicsEngineNoGuiInsideExceptionHandling();
else return StartAndRunOpenSimApiEngineNoGuiInsideExceptionHandling();
}
// This catch statement handles certain types of exceptions
catch( const std::exception &e )
{
WriteExceptionToFile( "\n\n Error: Programming error exception thrown:\n ", e.what() );
return false;
}
// The exception-declaration statement (...) handles any type of exception,
// including C exceptions and system/application generated exceptions.
// This includes exceptions such as memory protection and floating-point violations.
// An ellipsis catch handler must be the last handler for its try block.
catch( ... )
{
WriteExceptionToFile( "\n\n Error: Programming error. Unhandled exception.", NULL );
return false;
}
// Simulation completed properly
return true;
}
//------------------------------------------------------------------------------
} // End of namespace QSim
| [
"mitiguy@c7bcc468-049e-0410-a823-898a083b103d"
]
| [
[
[
1,
425
]
]
]
|
cfb25df66f18085ed7d82c6f56393a277f8f7c66 | 23df069203762da415d03da6f61cdf340e84307b | /2009-2010/winter10/csci245/archive/eval/cons.h | 091f99612265000c0cea4524b63a18143bb20730 | []
| no_license | grablisting/ray | 9356e80e638f3a20c5280b8dba4b6577044d4c6e | 967f8aebe2107c8052c18200872f9389e87d19c1 | refs/heads/master | 2016-09-10T19:51:35.133301 | 2010-09-29T13:37:26 | 2010-09-29T13:37:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,735 | h | #ifndef CONS_H
#define CONS_H
#include "sexpr.h"
#include "functions.h"
#include "number.h"
#include "symbol.h"
#include <iostream>
class Cons : public Sexpr
{
public:
Cons();
/**
Creates a new Cons molecule.
@param newfirst is the car pointer.
@param newrest is the cdr pointer.
*/
Cons(Sexpr* newfirst, Sexpr* newrest);
/**
Evalutes a Cons molecule.
@param return is a pointer to the start of a linked list.
*/
Sexpr* eval();
/**
Creates a new linked list by evaluating an old a linked list.
@param return points to the start of the new list.
*/
Sexpr* eval_map();
/**
Adds all numbers in a list together.
@param return points to the sum of all the arguments.
*/
Sexpr* add_list();
/**
Subtracts two numbers in a list. Ignores extra arguments.
@param return points to the difference of the first two numbers.
*/
Sexpr* subtract_list();
/**
Multiplies all numbers in a list together.
@param return points to the product of all the arguments.
*/
Sexpr* multiply_list();
/**
Provide the car.
@param return is the pointer.
*/
Sexpr* get_first();
/**
Provide the cdr.
@param return is the pointer.
*/
Sexpr* get_rest();
/**
Reads Cons.
@param in is the source.
*/
void read(istream& in);
/**
Creates a new Cons tier.
@param out is the destination.
*/
void print(ostream& out)
{
print_cons(out, true);
};
/**
Prints the atoms of Cons molecules.
@param out is the destination.
@param starting is Boolean sentinel for punctuation.
*/
void print_cons(ostream& out, bool starting);
private:
Sexpr* first;
Sexpr* rest;
};
#endif
| [
"Bobbbbommmbb@Bobbbbommmbb-PC.(none)"
]
| [
[
[
1,
90
]
]
]
|
a7d1eb3a1b83567899682cacc9133315b46cd582 | a296df442777ae1e63188cbdf5bcd2ca0adedf3f | /cppProject/FirstTry/FirstTry/Player.cpp | 8955361b87342143d2ddbae2a32d2c4074a9e578 | []
| no_license | piyushv94/jpcap-scanner | 39b4d710166c12a2fe695d9ec222da7b36787443 | 8fbf4214586e4f07f1b3ec4819f9a3c7451bd679 | refs/heads/master | 2021-01-10T06:15:32.064675 | 2011-11-26T20:23:55 | 2011-11-26T20:23:55 | 44,114,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,967 | cpp | /*[4 points] Design a class Player with the following methods:
string getName() const: returns the name of the player.
char getInitial( char x ) const: returns the first letter of the name of the player which is not x. It will throw an exception illegalName if no such letter in the player's name exists.
Hand<Card>& getHand(): return the hand of the player.
Piece& removePiece(): Removes a piece from this player's home. It will throw an exception noPiece if the no piece is left.
void addPiece(Piece& piece): Increases the count of pieces in this player's home by one.
int increaseBlocks( int i ): Increases the count of blocks for this player returns the number of blocks after the operation.
bool decreaseBlocks( int i ): Decreases the count of blocks for this player returns true if the player had enough blocks for the operation.
int increaseBlocks( int i ): Increases the count of blocks for this player returns the number of blocks after the operation.
int increasePoints( int i ): Increases the points for this player and returns the players points.
A player must also be printable with the insertion operator cout << hand; (see above for an example printout).*/
#include"Player.h"
#include"myException.h"
#include<string>
using std::string;
string Player::getName() const{
return Name;
}
char Player::getInitial(char x) const{
int index=Name.find_first_not_of(x);
if (index==string::npos)
{
throw myException("illegalName");
}
return Name[index];
}
Hand<Card>& Player::getHand(){
return myHand;
}
Piece& Player::removePiece(){
if(countPiece==0)
throw myException("no piece");
countPiece--;
return *myPiece;
}
void Player::addPiece(){
countPiece++;
}
int Player::increaseBlocks( int i ){
Blocks+=i;
return Blocks;
}
bool Player::decreaseBlocks( int i ){
bool res=true;
if(Blocks-i<0)
res=false;
else
Blocks-=i;
return res;
}
int Player::increasePoints( int i ){
return point+=i;
} | [
"[email protected]"
]
| [
[
[
1,
53
]
]
]
|
aa32860b7d034b79a665eee87923e9fe477bc597 | ce28ec891a0d502e7461fd121b4d96a308c9dab7 | /dbmerge/MergeItem.cc | ca9744cdacfd843e80f74c4866bd457117cfa569 | []
| no_license | aktau/Tangerine | fe84f6578ce918d1fa151138c0cc5780161b3b8f | 179ac9901513f90b17c5cd4add35608a7101055b | refs/heads/master | 2020-06-08T17:07:53.860642 | 2011-08-14T09:41:41 | 2011-08-14T09:41:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | cc | #include "MergeItem.h"
#include "MergeAction.h"
MergeItem::MergeItem() : mDone(false), mAction(new NoAction) { }
MergeItem::~MergeItem() { delete mAction; }
bool MergeItem::acceptsAction(const MergeAction *action) const {
return (action) ? acceptedActions().contains(action->type()) : false;
}
bool MergeItem::isResolved() const { return mAction->type() != Merge::NONE; }
bool MergeItem::isDone() const { return mDone; }
Merge::Action MergeItem::currentActionType() const { return mAction ? mAction->type() : Merge::NONE; }
const MergeAction *MergeItem::currentAction() const { return mAction; }
void MergeItem::store(const MergeAction *action) {
delete mAction;
mAction = action->clone();
}
void MergeItem::setDone(bool done) {
mDone = done;
}
| [
"[email protected]"
]
| [
[
[
1,
24
]
]
]
|
bdae269e9fb0e79046f023b89b4750beaa6bf48d | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Collide/Query/Multithreaded/RayCastQuery/hkpRayCastQueryJobUtils.h | 984d340b0b3d768b9692b9f68b932ae6758cbbf1 | []
| 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 | 4,620 | 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_KD_TREE_JOB_UTILS
#define HK_KD_TREE_JOB_UTILS
#include <Common/Internal/KdTree/hkKdTree.h>
#include <Common/Internal/KdTree/QueryUtils/hkKdTreeUtils.h>
#include <Physics/Collide/Query/CastUtil/hkpWorldRayCastOutput.h>
#include <Common/Internal/Collide/Tree/AabbTree/hkAabbTree.h>
#define hkpWorldRayCastOutputPpu hkpWorldRayCastOutput
struct hkpKdTreeBuildSetupJob;
class hkKdTreeRayCastJobUtil
{
public:
// Returns a pointer to the next 'free' hkpWorldRayCastOutput.
// This can either be:
// - the next truly free entry (if there's room left in the array)
// - the furthest hit in the array (if the array is already full and we need to drop entries)
// - HK_NULL if the array is full and the current hit is further away than the furthest hit in the entry
static void HK_CALL initializeBuildSetupJobs(const hkpCollidable** collidablesPtr, int numCollidables, hkKdTreeProjectedEntry* entries, hkSemaphoreBusyWait* semaphore, int numJobs, hkpKdTreeBuildSetupJob* jobsOut);
static void HK_CALL makeBundleFromInputs(hkpWorldRayCastInput* inputs, hkKdTreeUtils::RayBundle& fromBundle, hkKdTreeUtils::RayBundle& toBundle);
};
struct hkpWorldRayCastCommand;
class hkpCollisionFilter;
class hkKdTree;
struct hkpWorldRayCastBundleCommand;
class hkSpu4WayCache;
class hkpFixedBufferRayHitCollector;
class hkTreeRayCastJobUtil
{
public:
static void HK_CALL castRayKdTree(const hkKdTree* kdTree, hkpWorldRayCastCommand* command, const hkpCollisionFilter* filter, hkpFixedBufferRayHitCollector* fixedBufferHitCollector,
hkSpu4WayCache* collidableCache=HK_NULL, hkSpu4WayCache* shapeCache=HK_NULL, hkSpu4WayCache* transformCache=HK_NULL,
hkpWorldRayCastOutputPpu* resultLocalArray = HK_NULL);
template<typename BOUNDING_VOLUME>
static void HK_CALL castRayBundleAabbTree(const hkAabbTree<BOUNDING_VOLUME>* aabbTree, hkpWorldRayCastBundleCommand* command, const hkpCollisionFilter* filter,
hkVector4& earlyHitFractionInOut,
hkSpu4WayCache* collidableCache=HK_NULL, hkSpu4WayCache* shapeCache=HK_NULL, hkSpu4WayCache* transformCache=HK_NULL,
hkpWorldRayCastOutputPpu* resultLocalArray = HK_NULL, int* numResultsOut = HK_NULL);
static void HK_CALL castRayBundleKdTree(const hkKdTree* kdTrees, hkpWorldRayCastBundleCommand* command, const hkpCollisionFilter* filter,
hkVector4& earlyHitFractionInOut,
hkSpu4WayCache* collidableCache=HK_NULL, hkSpu4WayCache* shapeCache=HK_NULL, hkSpu4WayCache* transformCache=HK_NULL,
hkpWorldRayCastOutputPpu* resultLocalArray = HK_NULL, int* numResultsInOut = HK_NULL);
static void HK_CALL castRayByCommands(hkAabbTree<hkAabbTreeData::hkAabbTreeAabb16,hkUint16>* aabbTreeNewInt,
hkKdTree* kdTree, hkpWorldRayCastCommand* commandArrayOnPpu, int numCommands, hkpCollisionFilter* filter,
hkSpu4WayCache* collidableCache=HK_NULL, hkSpu4WayCache* shapeCache=HK_NULL, hkSpu4WayCache* transformCache=HK_NULL);
enum
{
RAY_FILTERING_STREAM_SIZE = 128,
};
static void HK_CALL castRayBundleByCommands(hkAabbTree<hkAabbTreeData::hkAabbTreeAabb16,hkUint16>* aabbTreeNewInt,
hkKdTree* kdTree, hkpWorldRayCastBundleCommand* commandArrayOnPpu, int numCommands, hkpCollisionFilter* filter,
hkSpu4WayCache* collidableCache=HK_NULL, hkSpu4WayCache* shapeCache=HK_NULL, hkSpu4WayCache* transformCache=HK_NULL);
};
#undef hkpWorldRayCastOutputPpu
#endif // HK_COLLISION_JOB_UTILS
/*
* 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,
94
]
]
]
|
7c7f309c81ccd3c1351f88a59fb6e689f451900c | 02cd7f7be30f7660f6928a1b8262dc935673b2d7 | / invols --username [email protected]/PerfPanel.h | 61943746b89a93d6ebfa912c52b75795714bcc3e | []
| 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 | UTF-8 | C++ | false | false | 1,054 | h | #ifndef PERF_PANEL_INC
#define PERF_PANEL_INC
#include "AllDef.h"
#include "MyApp.h"
#include "TF_window.h"
#include "AllInc.h"
#include "wxIncludes.h"
class PerfPanel: public wxPanel
{
public:
PerfPanel(wxWindow *frame);
~PerfPanel()
{
}
void OnBtnUpdate(wxCommandEvent& event);
void OnSliderZ(wxCommandEvent& WXUNUSED(event));
void OnSliderFastView(wxCommandEvent& WXUNUSED(event));
void OnSliderIQ(wxCommandEvent& WXUNUSED(event));//interaction quality
void OnCheckBB(wxCommandEvent& event);
void Update_(bool self);
void OnListRenderingType(wxCommandEvent& WXUNUSED(event));
void OnListRenderingMode(wxCommandEvent& WXUNUSED(event));
void OnListShadingMode(wxCommandEvent& WXUNUSED(event));
void OnListTF(wxCommandEvent& WXUNUSED(event));
private:
wxChoice *m_box_rmode,*m_box_rtype,*m_box_shading_type,*m_box_tf;
wxSlider *m_slider_z[3];
wxCheckBox *m_check_box_autofps,*m_check_use_accel_struct,*m_check_use_cubic_filt,*m_check_bicubic_filtering;
DECLARE_EVENT_TABLE()
};
#endif | [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
b251711a3b0b865f9d061c058b40ee1dcda52995 | ff5c060273aeafed9f0e5aa7018f371b8b11cdfd | /Codigo/C/Tipos_Estructura.h | e682d571d0f181e6ea6ebbadf9e16007268232f9 | []
| 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 | WINDOWS-1250 | C++ | false | false | 4,271 | h | //---------------------------------------------------------------------------
#ifndef Tipos_EstructuraH
#define Tipos_EstructuraH
#include <stdlib.h>
#include <vector.h>
//---------------------------------------------------------------------------
enum Tipo_Pista {ACOMP=0,MELOD=1};
//---------------------------------------------------------------------------
int Es_Progresion_Valida(String fichero_Progresion);
TStringList* Come_Progresion(String fichero_Progresion);
String Come_Azucar(String Fichero);
int Procesar(String &Total,String A_Eliminar);
String Procesar2(String &Total,int A_Eliminar);
int Procesar_Grado(String &Progresion,String &Salida);
int Procesar_Matricula(String &Progresion);
int Procesa_Num_Natural(String &Progresion);
String Dame_Token(String &Total);
const Tam_Inter_Simples=23;
String Inter_Simples[Tam_Inter_Simples]={"i", "bii", "ii", "biii", "iii", "iv", "bv", "v", "auv", "vi", "bvii", "vii", "bbii", "bbiii", "auii", "biv", "auiii", "auiv", "bbvi", "bvi", "auvi", "bviii", "auviii"};
const Tam_Matriculas=13;
String Matriculas[Tam_Matriculas]={"mayor","m","au","dis","6","m6","m7b5", "maj7","7","m7","mMaj7","au7","dis7"};
//---------------------------------------------------------------------------
struct Bloque
{
public:
int Num_Compases;
bool Vacio;
String Patron_Ritmico;
bool Es_Sistema_Paralelo;
int Notas_Totales;
String Inversion;
String Disposicion;
String Curva_Melodica;
String Tipo_Music;
int Octava_Inicial;
int N_Pista_Acomp;
bool Triadas;
int Tipo_Melodia; //0=delegar en haskell, 1= curva melódica ... 2=editor midi
int Aplicacion_Horizontal;//0=ciclico, 1= no ciclico
int Aplicacion_Vertical_Mayor;//0=truncar, 1=saturar
int Aplicacion_Vertical_Menor;//0=truncar, 1=saturar,2=ciclico, 3=modulo
//String Curva_Melodica;
//String Octava_Inicial
//?? tipo enlace voces
String Progresion;
int N_Divisiones;
int Fase2;
int Fase3;
int Fase4;
int Bajo_Duracion_Numerador;
int Bajo_Duracion_Denominador;
int Bajo_Tipo;
int Bajo_Parametro1;
int Bajo_Parametro2;
int Bajo_Parametro3;
int Bajo_Parametro4;
int Bajo_Parametro5;
void Inicializa();
void Copia(Bloque Original,int bloque);
};
//---------------------------------------------------------------------------
typedef vector<Bloque> Bloques_Pista;
//---------------------------------------------------------------------------
class Pista
{
private:
Tipo_Pista Tipo;
bool Mute;
unsigned char Instrumento;
Bloques_Pista Bloques;
public:
Pista(Tipo_Pista tipopista=ACOMP);
Tipo_Pista Dame_Tipo(){return Tipo;};
Bloque Dame_Bloque(int numbloque){return Bloques[numbloque];};
void Cambia_Bloque(Bloque N_Bloque,int numbloque){Bloques[numbloque]=N_Bloque;};
bool Dame_Mute(){return Mute;};
int Dame_Instrumento(){return Instrumento;};
void Cambia_Mute(bool n_mute){Mute=n_mute;};
void Cambia_Instrumento(int instr){Instrumento=instr;};
//void cambia_tipo???
void Inserta_Bloque(Bloque Nuevo_Bloque){Bloques.push_back(Nuevo_Bloque);}
int Dame_Numero_Bloques(){return Bloques.size();};
};
//---------------------------------------------------------------------------
typedef vector<Pista*> Pistas_Cancion;
//---------------------------------------------------------------------------
class Cancion
{
private:
Pistas_Cancion Pistas;
public:
~Cancion();
Cancion(){Pistas.clear();};
void Nueva_Pista(Tipo_Pista tipopista=ACOMP);//Hay que poner tantos bloques como haya en las demás pistas
//inserta mete un bloque y pone a vacio los demás, y cambia cambia el bloque actual.
void Inserta_Bloque(Bloque Nuevo_Bloque, int Num_Pista);
void Nuevo_Bloque(int Num_Compases,String P_Ritmico,String Disposicion, String Inversion);
int Dame_Tipo_Pista(int N_Pista){return Pistas[N_Pista]->Dame_Tipo();};
int Dame_Numero_Pistas(){return Pistas.size();};
Pista* Dame_Pista(int N_Pista){return Pistas[N_Pista];};
void Guarda_Archivo(String nombre_archivo);
void Guarda_Archivo_Haskell(String Fichero_Gen,int tempo,String tonalidad);
void Limpia();
int Cargar(String fichero);
};
#endif
| [
"gatchan"
]
| [
[
[
1,
108
]
]
]
|
678dc7d96e3dbd2f3557cb0d7c07b4eef9f49a51 | 14e30c5f520f0ed28117914101d9bdf2f3d5dac7 | /project/source/util/rand.cpp | ec30bdb7b1f3bbe811f854e1ba1f440c600fdd9e | []
| no_license | danielePiracci/arlight | f356eb5a162d0cd62a759720cbc6da41a820642f | 15a68c4c80c97f2fe7458e7ddf03f3e1063e25a4 | refs/heads/master | 2016-08-11T13:45:35.252916 | 2011-01-24T20:22:50 | 2011-01-24T20:22:50 | 44,962,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | cpp | /// \file util/rand.cpp
/// \author Juan Carlos De Abreu ([email protected])
/// \date 2009/11/07
/// \version 1.0
#include "util/rand.h"
#include "stdlib.h"
BEGIN_PROJECT_NAMESPACE();
float Rand(float min_range, float max_range) {
return min_range + rand() * (max_range - min_range) / RAND_MAX;
}
END_PROJECT_NAMESPACE();
| [
"jcabreur@db05138c-34b8-7cfb-67b9-2db12d2e1ab0"
]
| [
[
[
1,
15
]
]
]
|
ced466920c107f2fa2c9295f53ade3f0432ad54a | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /APSVis/source/TProb_prop_form.h | 80c54e6e533cbe5448d180501239ddd8914c5fe7 | []
| 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 | 1,213 | h | //---------------------------------------------------------------------------
#ifndef TProb_prop_formH
#define TProb_prop_formH
//---------------------------------------------------------------------------
#include <vcl\Classes.hpp>
#include <vcl\Controls.hpp>
#include <vcl\StdCtrls.hpp>
#include <vcl\Forms.hpp>
#include <vcl\Buttons.hpp>
#include "AdvCombo.hpp"
#include "ImagePicker.hpp"
#include <ImgList.hpp>
//---------------------------------------------------------------------------
class TProb_prop_form : public TForm
{
__published: // IDE-managed Components
TLabel *Label2;
TBitBtn *BitBtn1;
TBitBtn *BitBtn2;
TListBox *X_variables;
TGroupBox *GroupBox1;
TRadioButton *Prob_exceed;
TRadioButton *Cum_prob;
TLabel *Label4;
TImageList *ImageList1;
TImagePicker *Chart_type_combo;
private: // User declarations
public: // User declarations
__fastcall TProb_prop_form(TComponent* Owner);
void Setup (TStringList* Field_list);
};
//---------------------------------------------------------------------------
extern TProb_prop_form *Prob_prop_form;
//---------------------------------------------------------------------------
#endif
| [
"devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8"
]
| [
[
[
1,
35
]
]
]
|
a931d6e0260004f79601c11264b79d20a11951a1 | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/06112002/src/VirtualFS/VirtualFS_static.cpp | a4be45ec2013d66d4c7d14290b802fb24d47f98c | []
| 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 | 426 | cpp | #include <VirtualFS/VirtualFS.h>
#include <fusion.h>
/*
DOCUMENT PROPERLY YOU ASSHOLE
FOR THE BENEFIT OF STATIC LINKING,
THESE FUNCTIONS ARE PROVIDED TO
ALLOW AN APPLICATION TO CREATE
THE OBJECT AND DESTROY IT
*/
void CreateVFS(Fusion &f)
{
f.vfs = new VirtualFS();
if(f.vfs->Initialise() == false) DestroyVFS();
}
void DestroyVFS(void)
{
delete fusion->vfs;
fusion->vfs = NULL;
} | [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
]
| [
[
[
1,
24
]
]
]
|
809747a7c24897b5031c58f7a1c0d84ce05c612f | 485c5413e1a4769516c549ed7f5cd4e835751187 | /Source/ImacDemo/scenes/ShadowScene.cpp | d4f763869ea297685d2dafd19fa1c14b23c9bb8c | []
| no_license | FranckLetellier/rvstereogram | 44d0a78c47288ec0d9fc88efac5c34088af88d41 | c494b87ee8ebb00cf806214bc547ecbec9ad0ca0 | refs/heads/master | 2021-05-29T12:00:15.042441 | 2010-03-25T13:06:10 | 2010-03-25T13:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,121 | cpp | #include "ShadowScene.h"
#include "plan.h"
#include "heightMap.h"
#include "cubeMapObject.h"
#include "abstractCamera.h"
#include "FBO.h"
#include "glh/glh_linear.h"
//Managers
#include "shaderManager.h"
#include "shader.h"
#include "textureManager.h"
#include "texture2D.h"
#include "meshManager.h"
#include "objMesh.h"
#include "Spline.hpp"
ShadowScene::ShadowScene(const std::string& sName, AbstractCamera* pCam):AbstractScene(sName,pCam)
{
m_pShadowMapFBO = NULL;
}
ShadowScene::~ShadowScene()
{
delete [] m_fLightPosition;
delete [] m_fLightDirection;
delete [] m_fLightDistance;
delete [] m_fLightZeros;
delete m_pShadowMapFBO;
}
bool ShadowScene::init()
{
ShaderManager & shaderManager = ShaderManager::getInstance();
MeshManager & meshManager = MeshManager::getInstance();
TextureManager & textureManager = TextureManager::getInstance();
m_sNextSceneName = "outdoor";
meshManager.loadMesh("cone.obj");
meshManager.loadMesh("sceneShadow.obj");
meshManager.loadMesh("teapot.obj");
//Spline
cameraSpline = new Spline("../../data/Spline/shadow_pos.xml");
cameraAimSpline = new Spline("../../data/Spline/shadow_aim.xml");
srand ( time(NULL) );
iShadowMapWidth = 2*iWindowWidth;
iShadowMapHeight = 2*iWindowHeight;
m_pShadowMapFBO = new FBO(iShadowMapWidth,iShadowMapHeight,E_FBO_2D);
m_pShadowMapFBO->generateDepthOnly();
//Set the value of the light
m_fLightPosition = new GLfloat[4];
m_fLightDirection = new GLfloat[4];
m_fLightDistance = new GLfloat[3];
m_fLightZeros = new GLfloat[4];
spotCutOff0 = 25.0f;
fallOff0 = 10.0f;
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, spotCutOff0);
cosfallOff0 = cos((spotCutOff0+fallOff0)*M_PI/180.0);
shaderManager.getShader("light")->Activate();
shaderManager.getShader("light")->setUniformf("cosOut",cosfallOff0);
shaderManager.getShader("light")->Desactivate();
depLightPSignX = 1;
depLightPSignY = -1;
depLightPAttX = 1;
depLightPAttY = 1;
depLightPSpeedX = 0.01 + (rand()%10)/1000.0;
depLightPSpeedY = 0.01 + (rand()%10)/1000.0;
//Initialize textures
textureManager.getTexture2D("../../data/stonewall_diffuse.jpg");
textureManager.getTexture2D("../../data/stonewall_normals.jpg");
textureManager.getTexture2D("../../data/rocks_diffuse.jpg");
textureManager.getTexture2D("../../data/rocks_NM_height.tga");
textureManager.getTexture2D("../../data/face_diffuse.jpg");
textureManager.getTexture2D("../../data/face_NM_height.png");
textureManager.getTexture2D("../../data/stonefloor_diffuse.jpg");
textureManager.getTexture2D("../../data/stonefloor_normal.jpg");
textureManager.getTexture2D("../../data/wood.jpg.");
textureManager.getTexture2D("../../data/wand_boden_diffuse.jpg.");
textureManager.getTexture2D("../../data/web.png",false);
return true;
}
void ShadowScene::preRender(){
//Render the depth on a texture, form light point of view
glViewport(0, 0, (GLint)iShadowMapWidth, (GLint)iShadowMapHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(spotCutOff0*2.0+fallOff0*2.0, float(iShadowMapWidth)/float(iShadowMapHeight), 0.4, 1000.0);
glGetFloatv(GL_PROJECTION_MATRIX,projectionMatrix);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
m_pShadowMapFBO->activate();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glPushMatrix();
glLoadIdentity();
//light point of view
glTranslatef(-m_fLightDistance[0],-m_fLightDistance[1],-m_fLightDistance[2]);
glRotatef(-fAngle,0.0,1.0,0.0);
glTranslatef(-m_fLightPosition[0],-m_fLightPosition[1],-m_fLightPosition[2]);
glGetFloatv(GL_MODELVIEW_MATRIX,modelviewMatrix);
glPushMatrix();
glLoadIdentity();
glMultMatrixf (projectionMatrix);
glMultMatrixf (modelviewMatrix);
glGetFloatv(GL_MODELVIEW_MATRIX, shadowmatrix);
glPopMatrix();
glCullFace(GL_FRONT);
renderEnvironment(true);
glCullFace(GL_BACK);
glPopMatrix();
m_pShadowMapFBO->desactivate();
}
void ShadowScene::render(){
ShaderManager & shaderManager = ShaderManager::getInstance();
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, iWindowWidth, iWindowHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, float(iWindowWidth)/float(iWindowHeight), 0.4, 1000.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix();
m_pCam->lookAt();
shaderManager.getShader("light")->Activate();
shaderManager.getShader("light")->setUniformMatrix4fv("eyematrix",shadowmatrix);
shaderManager.getShader("light")->Desactivate();
renderEnvironment(false);
glPopMatrix();
}
void ShadowScene::renderEnvironment(bool m_bShadow){
MeshManager & meshManager = MeshManager::getInstance();
ShaderManager & shaderManager = ShaderManager::getInstance();
TextureManager & textureManager = TextureManager::getInstance();
glMaterialfv(GL_FRONT, GL_AMBIENT,m_fDarkGreyColor);
glMaterialfv(GL_FRONT, GL_DIFFUSE,m_fWhiteColor);
glMaterialfv(GL_FRONT, GL_SPECULAR,m_fWhiteColor);
glMaterialf( GL_FRONT, GL_SHININESS, 100.0f);
glDisable(GL_BLEND);
glPushMatrix();
glTranslatef(m_fLightPosition[0],m_fLightPosition[1],m_fLightPosition[2]);
glRotatef(fAngle,0.0,1.0,0.0);
glTranslatef(m_fLightDistance[0],m_fLightDistance[1],m_fLightDistance[2]);
glLightfv(GL_LIGHT0, GL_POSITION,m_fLightZeros);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION,m_fLightDirection);
glPopMatrix();
if(!m_bShadow){
//display the light
glPushMatrix();
glTranslatef(m_fLightPosition[0],m_fLightPosition[1],m_fLightPosition[2]);
glRotatef(fAngle,0.0,1.0,0.0);
glTranslatef(m_fLightDistance[0],m_fLightDistance[1],m_fLightDistance[2]);
glScalef(0.02,0.02,0.02);
glColor3f(0.0,0.0,0.0);
meshManager.getMesh("cone.obj")->Draw(0);
glColor3f(1.0,1.0,1.0);
meshManager.getMesh("cone.obj")->Draw(1);
glPopMatrix();
//enable the light shader
shaderManager.getShader("light")->Activate();
shaderManager.getShader("light")->setUniformi("useShadowMap",1);
shaderManager.getShader("light")->setUniformi("useTexture",1);
//activate the shadowmap
glActiveTextureARB(GL_TEXTURE7);
m_pShadowMapFBO->activateDepthTexture();
glActiveTextureARB(GL_TEXTURE0);
}
////// Temple //////
//transformation matrix for the shadow mapping
if(!m_bShadow){
glPushMatrix();
glLoadIdentity();
glScalef(0.2,0.2,0.2);
glGetFloatv(GL_MODELVIEW_MATRIX, transformationmatrix);
shaderManager.getShader("light")->setUniformMatrix4fv("transmatrix",transformationmatrix);
glPopMatrix();
glPushMatrix();
glScalef(0.2,0.2,0.2);
shaderManager.getShader("light")->setUniformi("useBump",1);
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/stonefloor_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/stonefloor_NM_height.tga")->activate();
meshManager.getMesh("sceneShadow.obj")->Draw(0);//floor
meshManager.getMesh("sceneShadow.obj")->Draw(2);//columns
meshManager.getMesh("sceneShadow.obj")->Draw(3);//pedestal
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/stonewall_diffuse.jpg.")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/stonewall_normals.jpg")->activate();
glMaterialf( GL_FRONT, GL_SHININESS, 20.0f);
meshManager.getMesh("sceneShadow.obj")->Draw(4);//walls
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/rocks_diffuse.jpg.")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/rocks_NM_height.tga")->activate();
shaderManager.getShader("light")->setUniformi("useBump",0);
shaderManager.getShader("light")->setUniformi("usePOM",1);
shaderManager.getShader("light")->setUniformf("heightFactor",0.03f);
meshManager.getMesh("sceneShadow.obj")->Draw(1);//ceiling
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/face_diffuse.jpg.")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/face_NM_height.png")->activate();
shaderManager.getShader("light")->setUniformf("heightFactor",0.1f);
meshManager.getMesh("sceneShadow.obj")->Draw(6);//cube
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/stonefloor_diffuse.jpg")->desactivate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/stonefloor_normal.jpg")->desactivate();
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/wood.jpg.")->activate();
shaderManager.getShader("light")->setUniformi("usePOM",0);
meshManager.getMesh("sceneShadow.obj")->Draw(5);//ladder
glPopMatrix();
}
else{
glPushMatrix();
glScalef(0.2,0.2,0.2);
meshManager.getMesh("sceneShadow.obj")->Draw();
glPopMatrix();
}
////// END TEMPLE //////
////// TEAPOT //////
if(!m_bShadow){
glPushMatrix();
glLoadIdentity();
glTranslatef(0.0,0.68,-10.0);
glScalef(0.08,0.08,0.08);
glGetFloatv(GL_MODELVIEW_MATRIX, transformationmatrix);
shaderManager.getShader("light")->setUniformMatrix4fv("transmatrix",transformationmatrix);
glPopMatrix();
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/wand_boden_diffuse.jpg.")->activate();
}
glPushMatrix();
glTranslatef(0.0,0.68,-10.0);
glScalef(0.08,0.08,0.08);
meshManager.getMesh("teapot.obj")->Draw();//floor
if(!m_bShadow){
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/wand_boden_diffuse.jpg")->desactivate();
}
glPopMatrix();
////// END TEAPOT //////
////// SPIDER WEB //////
glMaterialfv(GL_FRONT, GL_SPECULAR,m_fBlackColor);
glDisable(GL_CULL_FACE);
if(!m_bShadow){
glPushMatrix();
glLoadIdentity();
glTranslatef(-2.0,2.0,-8.0);
glRotatef(90,0.0,1.0,0.0);
glScalef(0.7,0.7,0.7);
glGetFloatv(GL_MODELVIEW_MATRIX, transformationmatrix);
shaderManager.getShader("light")->setUniformMatrix4fv("transmatrix",transformationmatrix);
glPopMatrix();
glEnable(GL_BLEND);
}
else{
shaderManager.getShader("simpleDiscard")->Activate();
}
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/web.png",false)->activate();
glPushMatrix();
glTranslatef(-2.0,2.0,-8.0);
glRotatef(90,0.0,1.0,0.0);
glScalef(0.7,0.7,0.7);
meshManager.getMesh("plane.obj")->Draw();//web
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/web.png")->desactivate();
if(!m_bShadow){
glDisable(GL_BLEND);
shaderManager.getShader("light")->Activate();
}
else{
shaderManager.getShader("simpleDiscard")->Desactivate();
}
glPopMatrix();
glEnable(GL_CULL_FACE);
////// END SPIDER WEB //////
shaderManager.getShader("light")->Desactivate();
if (m_bDisplaySpline)
displaySpline();
}
void ShadowScene::update()
{
AbstractScene::update();
fAngle +=0.2;
m_fLightPosition[0] += depLightPAttX * 0.007;
depLightPAttX -= depLightPSignX * depLightPSpeedX;
if(depLightPAttX < -1.0 || depLightPAttX > 1.0){
depLightPSignX *= -1;
}
m_fLightPosition[1] += depLightPAttY * 0.007;
depLightPAttY -= depLightPSignY * depLightPSpeedY;
if(depLightPAttY < -1.0 || depLightPAttY > 1.0){
depLightPSignY *= -1;
}
}
bool ShadowScene::isFinished()
{
if (m_pCam->getCurrentControlPoint() == 5)
{
///going back to outdoor
return true;
}
return false;
}
void ShadowScene::handleKeyUp(unsigned char c, int x, int y)
{
AbstractScene::handleKeyUp(c,x,y);
}
void ShadowScene::handleKeyDown(unsigned char c, int x, int y){
switch(c){
case 'x' :
fAngle +=2.2;
}
}
void ShadowScene::reset(){
AbstractScene::reset();
glLightfv(GL_LIGHT0, GL_SPECULAR, m_fWhiteColor);
glLightfv(GL_LIGHT0, GL_DIFFUSE, m_fWhiteColor);
glLightfv(GL_LIGHT0, GL_AMBIENT, m_fWhiteColor);
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.0f);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.025f);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.0f);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, spotCutOff0);
m_fLightPosition[0] = 0.0;
m_fLightPosition[1] = 0.0;
m_fLightPosition[2] = -10.0;
m_fLightPosition[3] = 1.0;
m_fLightDistance[0] = 0.0;
m_fLightDistance[1] = 2.0;
m_fLightDistance[2] = 10.0;
m_fLightDirection[0] = 0.0;
m_fLightDirection[1] = 0.0;
m_fLightDirection[2] = -1.0;
m_fLightDirection[3] = 1.0;
m_fLightZeros[0] = 0.0;
m_fLightZeros[1] = 0.0;
m_fLightZeros[2] = 0.0;
m_fLightZeros[3] = 1.0;
fAngle = 0.0;
m_pCam->setSpeed(0.05);
} | [
"[email protected]"
]
| [
[
[
1,
494
]
]
]
|
b502b403fb943a6410e0b2c0032cb3eca364180f | 5914cd9c29d20cd1dae6e76df4aa8ed50688ebee | /Networks/genacje_salzmamy_connector.h | 1039d43347c978e55186f597acfdd2aef9c5a51a | []
| no_license | nagyistoce/cs462genacje-salzmamy-networks | 86f03cf5ba1f26d3a7dd9da9a9a6a2670040bf56 | da50f8ba7b727fcde9dd9cf4d88ca0e6b76c41b8 | refs/heads/master | 2016-09-05T15:25:54.497672 | 2011-12-13T01:16:54 | 2011-12-13T01:16:54 | 32,271,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,697 | h | /*
* connector.h
*
* Created on: Mar 10, 2011
* Author: salzmamy
*/
#ifndef CONNECTOR_H_
#define CONNECTOR_H_
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <iostream>
#include "genacje_salzmamy_blowfish.h"
#include "genacje_salzmamy_crc.h"
// 63 kb packet + 8 byte long checksum
// this is the size of the buf array; the packet will be taken from
// and inserted into this array up to the pkt_size index.
#define TAILSIZE 16
#define MAXPKTSIZE ((63*1024)+TAILSIZE)
#define DEFAULTPKTSIZE 1024
using namespace std;
class Connector {
public:
Connector ();
Connector (int); // constructor that sets up a listening port right away
Connector (char *, int); // allows sending of messages right away (and listening)
~Connector ();
void send (char *);
void send_unencrypted(char*);
bool listen (); // returns false if a damaged packet is detected.
char * get_msg ();
void set_print_encrypted(bool print);
void set_key (char *);
void set_msg_size (int);
int get_msg_size ();
private:
Blowfish * key;
CCRC32* crc;
struct sockaddr_in their_addr; // connectors address information
struct sockaddr_in my_addr; // my address information
bool print_encrypted;
int sockfd;
int numbytes;
int port;
int addr_len;
int msg_size; // Important: this is larger than the user's msg size to
// fit the CRC at the end!
struct hostent * he;
char buf[MAXPKTSIZE];
};
#endif /* CONNECTOR_H_ */
| [
"[email protected]@79cf5116-dcd4-c039-58dd-6f4206d1403f"
]
| [
[
[
1,
71
]
]
]
|
2d5a9793a4f3531a14fe0568879be7e6cdc00b98 | a84b013cd995870071589cefe0ab060ff3105f35 | /webdriver/trunk/jobbie/src/cpp/InternetExplorerDriver/IeSink.cpp | 451ff465b7ac2fbcca7b9d5d3de54de4ccb4a2cc | [
"Apache-2.0"
]
| permissive | vdt/selenium | 137bcad58b7184690b8785859d77da0cd9f745a0 | 30e5e122b068aadf31bcd010d00a58afd8075217 | refs/heads/master | 2020-12-27T21:35:06.461381 | 2009-08-18T15:56:32 | 2009-08-18T15:56:32 | 13,650,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,833 | cpp | /*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// IeSink.cpp : implementation file
//
#include "stdafx.h"
#include "IeSink.h"
#include "utils.h"
#include "InternetExplorerDriver.h"
#include "InternalCustomMessage.h"
using namespace std;
// IeSink
IeSink::IeSink() : p_Thread(NULL)
{
}
IeSink::~IeSink()
{
}
// IeSink message handlers
void __stdcall IeSink::BeforeNavigate2(IDispatch * pObject, VARIANT * pvarUrl, VARIANT * pvarFlags, VARIANT * pvarTargetFrame,
VARIANT * pvarData, VARIANT * pvarHeaders, VARIANT_BOOL * pbCancel)
{
safeIO::CoutA("In IeSink::BeforeNavigate2", true);
};
void __stdcall IeSink::OnQuit()
{
SCOPETRACER
DataMarshaller& dataMarshaller = p_Thread->getCmdData();
dataMarshaller.resetOutputs();
CScopeCaller SC(dataMarshaller);
ConnectionUnAdvise();
}
void __stdcall IeSink::DocumentComplete(IDispatch *pDisp,VARIANT *URL)
{
SCOPETRACER
if(p_Thread->m_EventToNotifyWhenNavigationCompleted)
{
safeIO::CoutA("sending _WD_WAITFORNAVIGATIONTOFINISH", true);
p_Thread->PostThreadMessageW(_WD_WAITFORNAVIGATIONTOFINISH , 0, 0);
}
}
void __stdcall IeSink::DownloadBegin()
{
safeIO::CoutA("in DownloadBegin", true);
}
void __stdcall IeSink::DownloadComplete()
{
SCOPETRACER
if(p_Thread->m_EventToNotifyWhenNavigationCompleted)
{
safeIO::CoutA("sending _WD_WAITFORNAVIGATIONTOFINISH", true);
p_Thread->PostThreadMessageW(_WD_WAITFORNAVIGATIONTOFINISH , 0, 0);
}
}
void IeSink::ConnectionAdvise()
{
SCOPETRACER
LOG(DEBUG) << "Advising connection: " << p_Thread << " " << p_Thread->pBody->ieThreaded << endl;
CComQIPtr<IDispatch> dispatcher(p_Thread->pBody->ieThreaded);
CComPtr<IUnknown> univ(dispatcher);
this->DispEventAdvise(univ);
}
void IeSink::ConnectionUnAdvise()
{
SCOPETRACER
if (!p_Thread && p_Thread->pBody) {
LOG(DEBUG) << "Unable to disconnect from IE instance";
return;
}
CComQIPtr<IDispatch> dispatcher(p_Thread->pBody->ieThreaded);
if (!dispatcher) {
LOG(DEBUG) << "No dispatcher located for IE instance";
return;
}
CComPtr<IUnknown> univ(dispatcher);
if (!univ) {
LOG(DEBUG) << "Unable to unadvise the IE instance";
return;
}
this->DispEventUnadvise(univ);
}
| [
"simon.m.stewart@07704840-8298-11de-bf8c-fd130f914ac9",
"alexis.j.vuillemin@07704840-8298-11de-bf8c-fd130f914ac9"
]
| [
[
[
1,
17
],
[
23,
23
],
[
47,
47
],
[
68,
68
],
[
73,
73
],
[
86,
88
],
[
97,
101
],
[
103,
106
],
[
108,
111
]
],
[
[
18,
22
],
[
24,
46
],
[
48,
67
],
[
69,
72
],
[
74,
85
],
[
89,
96
],
[
102,
102
],
[
107,
107
],
[
112,
113
]
]
]
|
a295fb91d39eaa09eb75c9c7dd89191ea9c519df | d4ca98982dbe82e342eddb69662c6aa2e03cab04 | /AugmentedBizzClient/jni/MathOps.h | bca49f5fbffe7c31e31ec10ee98c92d4cdbf2a6e | []
| no_license | Vladee/com.client.AugmentedBizz | 88469f0bcf76d61a7466938d99d7859f25ab39bf | 798233a86d6acc6b7977b2b66efbe3d996cb2016 | refs/heads/master | 2021-01-10T19:05:17.017499 | 2011-11-30T16:41:20 | 2011-11-30T16:41:20 | 2,528,785 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,720 | h | /*==============================================================================
Copyright (c) 2010-2011 QUALCOMM Incorporated.
All Rights Reserved.
Qualcomm Confidential and Proprietary
@file
SampleMath.h
@brief
A utility class.
==============================================================================*/
#ifndef _MATHOPS_H_
#define _MATHOPS_H_
// Includes:
#include <QCAR/Tool.h>
/// A utility class used by the QCAR SDK samples.
class SampleMath
{
public:
static QCAR::Vec2F Vec2FSub(QCAR::Vec2F v1, QCAR::Vec2F v2);
static float Vec2FDist(QCAR::Vec2F v1, QCAR::Vec2F v2);
static QCAR::Vec3F Vec3FAdd(QCAR::Vec3F v1, QCAR::Vec3F v2);
static QCAR::Vec3F Vec3FSub(QCAR::Vec3F v1, QCAR::Vec3F v2);
static QCAR::Vec3F Vec3FScale(QCAR::Vec3F v, float s);
static QCAR::Vec4F Vec3FDiv(QCAR::Vec4F v1, float s);
static float Vec3FDot(QCAR::Vec3F v1, QCAR::Vec3F v2);
static QCAR::Vec3F Vec3FCross(QCAR::Vec3F v1, QCAR::Vec3F v2);
static QCAR::Vec3F Vec3FNormalize(QCAR::Vec3F v);
static QCAR::Vec3F Vec3FTransform(QCAR::Vec3F& v, QCAR::Matrix44F& m);
static QCAR::Vec3F Vec3FTransformNormal(QCAR::Vec3F& v, QCAR::Matrix44F& m);
static QCAR::Vec4F Vec4FTransform(QCAR::Vec4F& v, QCAR::Matrix44F& m);
static QCAR::Matrix44F Matrix44FIdentity();
static QCAR::Matrix44F Matrix44FTranspose(QCAR::Matrix44F m);
static float Matrix44FDeterminate(QCAR::Matrix44F& m);
static QCAR::Matrix44F Matrix44FInverse(QCAR::Matrix44F& m);
};
#endif // _MATHOPS_H_
| [
"[email protected]"
]
| [
[
[
1,
60
]
]
]
|
7637c076f4e5fc2f5ff1c10d4696ba5bcf31e47b | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/src/microtcl/tclLiteral.cc | 1cdad5cc6642ca190c5787ebdc9a6bf444e324bc | []
| 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 | 32,672 | cc | /*
* tclLiteral.c --
*
* Implementation of the global and ByteCode-local literal tables
* used to manage the Tcl objects created for literal values during
* compilation of Tcl scripts. This implementation borrows heavily
* from the more general hashtable implementation of Tcl hash tables
* that appears in tclHash.c.
*
* Copyright (c) 1997-1998 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
* RCS: @(#) $Id: tclLiteral.cc,v 1.2 2003/03/23 17:12:30 brucem Exp $
*/
#include "microtcl/tclInt.h"
#include "microtcl/tclCompile.h"
#include "microtcl/tclPort.h"
/*
* When there are this many entries per bucket, on average, rebuild
* a literal's hash table to make it larger.
*/
#define REBUILD_MULTIPLIER 3
/*
* Procedure prototypes for static procedures in this file:
*/
static int AddLocalLiteralEntry _ANSI_ARGS_((
CompileEnv *envPtr, LiteralEntry *globalPtr,
int localHash));
static void ExpandLocalLiteralArray _ANSI_ARGS_((
CompileEnv *envPtr));
static unsigned int HashString _ANSI_ARGS_((CONST char *bytes,
int length));
static void RebuildLiteralTable _ANSI_ARGS_((
LiteralTable *tablePtr));
/*
*----------------------------------------------------------------------
*
* TclInitLiteralTable --
*
* This procedure is called to initialize the fields of a literal table
* structure for either an interpreter or a compilation's CompileEnv
* structure.
*
* Results:
* None.
*
* Side effects:
* The literal table is made ready for use.
*
*----------------------------------------------------------------------
*/
void
TclInitLiteralTable(tablePtr)
register LiteralTable *tablePtr; /* Pointer to table structure, which
* is supplied by the caller. */
{
#if (TCL_SMALL_HASH_TABLE != 4)
panic("TclInitLiteralTable: TCL_SMALL_HASH_TABLE is %d, not 4\n",
TCL_SMALL_HASH_TABLE);
#endif
tablePtr->buckets = tablePtr->staticBuckets;
tablePtr->staticBuckets[0] = tablePtr->staticBuckets[1] = 0;
tablePtr->staticBuckets[2] = tablePtr->staticBuckets[3] = 0;
tablePtr->numBuckets = TCL_SMALL_HASH_TABLE;
tablePtr->numEntries = 0;
tablePtr->rebuildSize = TCL_SMALL_HASH_TABLE*REBUILD_MULTIPLIER;
tablePtr->mask = 3;
}
/*
*----------------------------------------------------------------------
*
* TclDeleteLiteralTable --
*
* This procedure frees up everything associated with a literal table
* except for the table's structure itself.
*
* Results:
* None.
*
* Side effects:
* Each literal in the table is released: i.e., its reference count
* in the global literal table is decremented and, if it becomes zero,
* the literal is freed. In addition, the table's bucket array is
* freed.
*
*----------------------------------------------------------------------
*/
void
TclDeleteLiteralTable(interp, tablePtr)
Tcl_Interp *interp; /* Interpreter containing shared literals
* referenced by the table to delete. */
LiteralTable *tablePtr; /* Points to the literal table to delete. */
{
LiteralEntry *entryPtr;
int i, start;
/*
* Release remaining literals in the table. Note that releasing a
* literal might release other literals, modifying the table, so we
* restart the search from the bucket chain we last found an entry.
*/
#ifdef TCL_COMPILE_DEBUG
TclVerifyGlobalLiteralTable((Interp *) interp);
#endif /*TCL_COMPILE_DEBUG*/
start = 0;
while (tablePtr->numEntries > 0) {
for (i = start; i < tablePtr->numBuckets; i++) {
entryPtr = tablePtr->buckets[i];
if (entryPtr != NULL) {
TclReleaseLiteral(interp, entryPtr->objPtr);
start = i;
break;
}
}
}
/*
* Free up the table's bucket array if it was dynamically allocated.
*/
if (tablePtr->buckets != tablePtr->staticBuckets) {
ckfree((char *) tablePtr->buckets);
}
}
/*
*----------------------------------------------------------------------
*
* TclRegisterLiteral --
*
* Find, or if necessary create, an object in a CompileEnv literal
* array that has a string representation matching the argument string.
*
* Results:
* The index in the CompileEnv's literal array that references a
* shared literal matching the string. The object is created if
* necessary.
*
* Side effects:
* To maximize sharing, we look up the string in the interpreter's
* global literal table. If not found, we create a new shared literal
* in the global table. We then add a reference to the shared
* literal in the CompileEnv's literal array.
*
* If onHeap is 1, this procedure is given ownership of the string: if
* an object is created then its string representation is set directly
* from string, otherwise the string is freed. Typically, a caller sets
* onHeap 1 if "string" is an already heap-allocated buffer holding the
* result of backslash substitutions.
*
*----------------------------------------------------------------------
*/
int
TclRegisterLiteral(envPtr, bytes, length, onHeap)
CompileEnv *envPtr; /* Points to the CompileEnv in whose object
* array an object is found or created. */
register char *bytes; /* Points to string for which to find or
* create an object in CompileEnv's object
* array. */
int length; /* Number of bytes in the string. If < 0,
* the string consists of all bytes up to
* the first null character. */
int onHeap; /* If 1 then the caller already malloc'd
* bytes and ownership is passed to this
* procedure. */
{
Interp *iPtr = envPtr->iPtr;
LiteralTable *globalTablePtr = &(iPtr->literalTable);
LiteralTable *localTablePtr = &(envPtr->localLitTable);
register LiteralEntry *globalPtr, *localPtr;
register Tcl_Obj *objPtr;
unsigned int hash;
int localHash, globalHash, objIndex;
long n;
char buf[TCL_INTEGER_SPACE];
if (length < 0) {
length = (bytes? strlen(bytes) : 0);
}
hash = HashString(bytes, length);
/*
* Is the literal already in the CompileEnv's local literal array?
* If so, just return its index.
*/
localHash = (hash & localTablePtr->mask);
for (localPtr = localTablePtr->buckets[localHash];
localPtr != NULL; localPtr = localPtr->nextPtr) {
objPtr = localPtr->objPtr;
if ((objPtr->length == length) && ((length == 0)
|| ((objPtr->bytes[0] == bytes[0])
&& (memcmp(objPtr->bytes, bytes, (unsigned) length)
== 0)))) {
if (onHeap) {
ckfree(bytes);
}
objIndex = (localPtr - envPtr->literalArrayPtr);
#ifdef TCL_COMPILE_DEBUG
TclVerifyLocalLiteralTable(envPtr);
#endif /*TCL_COMPILE_DEBUG*/
return objIndex;
}
}
/*
* The literal is new to this CompileEnv. Is it in the interpreter's
* global literal table?
*/
globalHash = (hash & globalTablePtr->mask);
for (globalPtr = globalTablePtr->buckets[globalHash];
globalPtr != NULL; globalPtr = globalPtr->nextPtr) {
objPtr = globalPtr->objPtr;
if ((objPtr->length == length) && ((length == 0)
|| ((objPtr->bytes[0] == bytes[0])
&& (memcmp(objPtr->bytes, bytes, (unsigned) length)
== 0)))) {
/*
* A global literal was found. Add an entry to the CompileEnv's
* local literal array.
*/
if (onHeap) {
ckfree(bytes);
}
objIndex = AddLocalLiteralEntry(envPtr, globalPtr, localHash);
#ifdef TCL_COMPILE_DEBUG
if (globalPtr->refCount < 1) {
panic("TclRegisterLiteral: global literal \"%.*s\" had bad refCount %d",
(length>60? 60 : length), bytes,
globalPtr->refCount);
}
TclVerifyLocalLiteralTable(envPtr);
#endif /*TCL_COMPILE_DEBUG*/
return objIndex;
}
}
/*
* The literal is new to the interpreter. Add it to the global literal
* table then add an entry to the CompileEnv's local literal array.
* Convert the object to an integer object if possible.
*/
TclNewObj(objPtr);
Tcl_IncrRefCount(objPtr);
if (onHeap) {
objPtr->bytes = bytes;
objPtr->length = length;
} else {
TclInitStringRep(objPtr, bytes, length);
}
if (TclLooksLikeInt(bytes, length)) {
/*
* From here we use the objPtr, because it is NULL terminated
*/
if (TclGetLong((Tcl_Interp *) NULL, objPtr->bytes, &n) == TCL_OK) {
TclFormatInt(buf, n);
if (strcmp(objPtr->bytes, buf) == 0) {
objPtr->internalRep.longValue = n;
objPtr->typePtr = &tclIntType;
}
}
}
#ifdef TCL_COMPILE_DEBUG
if (TclLookupLiteralEntry((Tcl_Interp *) iPtr, objPtr) != NULL) {
panic("TclRegisterLiteral: literal \"%.*s\" found globally but shouldn't be",
(length>60? 60 : length), bytes);
}
#endif
globalPtr = (LiteralEntry *) ckalloc((unsigned) sizeof(LiteralEntry));
globalPtr->objPtr = objPtr;
globalPtr->refCount = 0;
globalPtr->nextPtr = globalTablePtr->buckets[globalHash];
globalTablePtr->buckets[globalHash] = globalPtr;
globalTablePtr->numEntries++;
/*
* If the global literal table has exceeded a decent size, rebuild it
* with more buckets.
*/
if (globalTablePtr->numEntries >= globalTablePtr->rebuildSize) {
RebuildLiteralTable(globalTablePtr);
}
objIndex = AddLocalLiteralEntry(envPtr, globalPtr, localHash);
#ifdef TCL_COMPILE_DEBUG
TclVerifyGlobalLiteralTable(iPtr);
TclVerifyLocalLiteralTable(envPtr);
{
LiteralEntry *entryPtr;
int found, i;
found = 0;
for (i = 0; i < globalTablePtr->numBuckets; i++) {
for (entryPtr = globalTablePtr->buckets[i];
entryPtr != NULL; entryPtr = entryPtr->nextPtr) {
if ((entryPtr == globalPtr)
&& (entryPtr->objPtr == objPtr)) {
found = 1;
}
}
}
if (!found) {
panic("TclRegisterLiteral: literal \"%.*s\" wasn't global",
(length>60? 60 : length), bytes);
}
}
#endif /*TCL_COMPILE_DEBUG*/
#ifdef TCL_COMPILE_STATS
iPtr->stats.numLiteralsCreated++;
iPtr->stats.totalLitStringBytes += (double) (length + 1);
iPtr->stats.currentLitStringBytes += (double) (length + 1);
iPtr->stats.literalCount[TclLog2(length)]++;
#endif /*TCL_COMPILE_STATS*/
return objIndex;
}
/*
*----------------------------------------------------------------------
*
* TclLookupLiteralEntry --
*
* Finds the LiteralEntry that corresponds to a literal Tcl object
* holding a literal.
*
* Results:
* Returns the matching LiteralEntry if found, otherwise NULL.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
LiteralEntry *
TclLookupLiteralEntry(interp, objPtr)
Tcl_Interp *interp; /* Interpreter for which objPtr was created
* to hold a literal. */
register Tcl_Obj *objPtr; /* Points to a Tcl object holding a
* literal that was previously created by a
* call to TclRegisterLiteral. */
{
Interp *iPtr = (Interp *) interp;
LiteralTable *globalTablePtr = &(iPtr->literalTable);
register LiteralEntry *entryPtr;
char *bytes;
int length, globalHash;
bytes = Tcl_GetStringFromObj(objPtr, &length);
globalHash = (HashString(bytes, length) & globalTablePtr->mask);
for (entryPtr = globalTablePtr->buckets[globalHash];
entryPtr != NULL; entryPtr = entryPtr->nextPtr) {
if (entryPtr->objPtr == objPtr) {
return entryPtr;
}
}
return NULL;
}
/*
*----------------------------------------------------------------------
*
* TclHideLiteral --
*
* Remove a literal entry from the literal hash tables, leaving it in
* the literal array so existing references continue to function.
* This makes it possible to turn a shared literal into a private
* literal that cannot be shared.
*
* Results:
* None.
*
* Side effects:
* Removes the literal from the local hash table and decrements the
* global hash entry's reference count.
*
*----------------------------------------------------------------------
*/
void
TclHideLiteral(interp, envPtr, index)
Tcl_Interp *interp; /* Interpreter for which objPtr was created
* to hold a literal. */
register CompileEnv *envPtr; /* Points to CompileEnv whose literal array
* contains the entry being hidden. */
int index; /* The index of the entry in the literal
* array. */
{
LiteralEntry **nextPtrPtr, *entryPtr, *lPtr;
LiteralTable *localTablePtr = &(envPtr->localLitTable);
int localHash, length;
char *bytes;
Tcl_Obj *newObjPtr;
lPtr = &(envPtr->literalArrayPtr[index]);
/*
* To avoid unwanted sharing we need to copy the object and remove it from
* the local and global literal tables. It still has a slot in the literal
* array so it can be referred to by byte codes, but it will not be matched
* by literal searches.
*/
newObjPtr = Tcl_DuplicateObj(lPtr->objPtr);
Tcl_IncrRefCount(newObjPtr);
TclReleaseLiteral(interp, lPtr->objPtr);
lPtr->objPtr = newObjPtr;
bytes = Tcl_GetStringFromObj(newObjPtr, &length);
localHash = (HashString(bytes, length) & localTablePtr->mask);
nextPtrPtr = &localTablePtr->buckets[localHash];
for (entryPtr = *nextPtrPtr; entryPtr != NULL; entryPtr = *nextPtrPtr) {
if (entryPtr == lPtr) {
*nextPtrPtr = lPtr->nextPtr;
lPtr->nextPtr = NULL;
localTablePtr->numEntries--;
break;
}
nextPtrPtr = &entryPtr->nextPtr;
}
}
/*
*----------------------------------------------------------------------
*
* TclAddLiteralObj --
*
* Add a single literal object to the literal array. This
* function does not add the literal to the local or global
* literal tables. The caller is expected to add the entry
* to whatever tables are appropriate.
*
* Results:
* The index in the CompileEnv's literal array that references the
* literal. Stores the pointer to the new literal entry in the
* location referenced by the localPtrPtr argument.
*
* Side effects:
* Expands the literal array if necessary. Increments the refcount
* on the literal object.
*
*----------------------------------------------------------------------
*/
int
TclAddLiteralObj(envPtr, objPtr, litPtrPtr)
register CompileEnv *envPtr; /* Points to CompileEnv in whose literal
* array the object is to be inserted. */
Tcl_Obj *objPtr; /* The object to insert into the array. */
LiteralEntry **litPtrPtr; /* The location where the pointer to the
* new literal entry should be stored.
* May be NULL. */
{
register LiteralEntry *lPtr;
int objIndex;
if (envPtr->literalArrayNext >= envPtr->literalArrayEnd) {
ExpandLocalLiteralArray(envPtr);
}
objIndex = envPtr->literalArrayNext;
envPtr->literalArrayNext++;
lPtr = &(envPtr->literalArrayPtr[objIndex]);
lPtr->objPtr = objPtr;
Tcl_IncrRefCount(objPtr);
lPtr->refCount = -1; /* i.e., unused */
lPtr->nextPtr = NULL;
if (litPtrPtr) {
*litPtrPtr = lPtr;
}
return objIndex;
}
/*
*----------------------------------------------------------------------
*
* AddLocalLiteralEntry --
*
* Insert a new literal into a CompileEnv's local literal array.
*
* Results:
* The index in the CompileEnv's literal array that references the
* literal.
*
* Side effects:
* Increments the ref count of the global LiteralEntry since the
* CompileEnv now refers to the literal. Expands the literal array
* if necessary. May rebuild the hash bucket array of the CompileEnv's
* literal array if it becomes too large.
*
*----------------------------------------------------------------------
*/
static int
AddLocalLiteralEntry(envPtr, globalPtr, localHash)
register CompileEnv *envPtr; /* Points to CompileEnv in whose literal
* array the object is to be inserted. */
LiteralEntry *globalPtr; /* Points to the global LiteralEntry for
* the literal to add to the CompileEnv. */
int localHash; /* Hash value for the literal's string. */
{
register LiteralTable *localTablePtr = &(envPtr->localLitTable);
LiteralEntry *localPtr;
int objIndex;
objIndex = TclAddLiteralObj(envPtr, globalPtr->objPtr, &localPtr);
/*
* Add the literal to the local table.
*/
localPtr->nextPtr = localTablePtr->buckets[localHash];
localTablePtr->buckets[localHash] = localPtr;
localTablePtr->numEntries++;
globalPtr->refCount++;
/*
* If the CompileEnv's local literal table has exceeded a decent size,
* rebuild it with more buckets.
*/
if (localTablePtr->numEntries >= localTablePtr->rebuildSize) {
RebuildLiteralTable(localTablePtr);
}
#ifdef TCL_COMPILE_DEBUG
TclVerifyLocalLiteralTable(envPtr);
{
char *bytes;
int length, found, i;
found = 0;
for (i = 0; i < localTablePtr->numBuckets; i++) {
for (localPtr = localTablePtr->buckets[i];
localPtr != NULL; localPtr = localPtr->nextPtr) {
if (localPtr->objPtr == globalPtr->objPtr) {
found = 1;
}
}
}
if (!found) {
bytes = Tcl_GetStringFromObj(globalPtr->objPtr, &length);
panic("AddLocalLiteralEntry: literal \"%.*s\" wasn't found locally",
(length>60? 60 : length), bytes);
}
}
#endif /*TCL_COMPILE_DEBUG*/
return objIndex;
}
/*
*----------------------------------------------------------------------
*
* ExpandLocalLiteralArray --
*
* Procedure that uses malloc to allocate more storage for a
* CompileEnv's local literal array.
*
* Results:
* None.
*
* Side effects:
* The literal array in *envPtr is reallocated to a new array of
* double the size, and if envPtr->mallocedLiteralArray is non-zero
* the old array is freed. Entries are copied from the old array
* to the new one. The local literal table is updated to refer to
* the new entries.
*
*----------------------------------------------------------------------
*/
static void
ExpandLocalLiteralArray(envPtr)
register CompileEnv *envPtr; /* Points to the CompileEnv whose object
* array must be enlarged. */
{
/*
* The current allocated local literal entries are stored between
* elements 0 and (envPtr->literalArrayNext - 1) [inclusive].
*/
LiteralTable *localTablePtr = &(envPtr->localLitTable);
int currElems = envPtr->literalArrayNext;
size_t currBytes = (currElems * sizeof(LiteralEntry));
register LiteralEntry *currArrayPtr = envPtr->literalArrayPtr;
register LiteralEntry *newArrayPtr =
(LiteralEntry *) ckalloc((unsigned) (2 * currBytes));
int i;
/*
* Copy from the old literal array to the new, then update the local
* literal table's bucket array.
*/
memcpy((VOID *) newArrayPtr, (VOID *) currArrayPtr, currBytes);
for (i = 0; i < currElems; i++) {
if (currArrayPtr[i].nextPtr == NULL) {
newArrayPtr[i].nextPtr = NULL;
} else {
newArrayPtr[i].nextPtr = newArrayPtr
+ (currArrayPtr[i].nextPtr - currArrayPtr);
}
}
for (i = 0; i < localTablePtr->numBuckets; i++) {
if (localTablePtr->buckets[i] != NULL) {
localTablePtr->buckets[i] = newArrayPtr
+ (localTablePtr->buckets[i] - currArrayPtr);
}
}
/*
* Free the old literal array if needed, and mark the new literal
* array as malloced.
*/
if (envPtr->mallocedLiteralArray) {
ckfree((char *) currArrayPtr);
}
envPtr->literalArrayPtr = newArrayPtr;
envPtr->literalArrayEnd = (2 * currElems);
envPtr->mallocedLiteralArray = 1;
}
/*
*----------------------------------------------------------------------
*
* TclReleaseLiteral --
*
* This procedure releases a reference to one of the shared Tcl objects
* that hold literals. It is called to release the literals referenced
* by a ByteCode that is being destroyed, and it is also called by
* TclDeleteLiteralTable.
*
* Results:
* None.
*
* Side effects:
* The reference count for the global LiteralTable entry that
* corresponds to the literal is decremented. If no other reference
* to a global literal object remains, it is freed.
*
*----------------------------------------------------------------------
*/
void
TclReleaseLiteral(interp, objPtr)
Tcl_Interp *interp; /* Interpreter for which objPtr was created
* to hold a literal. */
register Tcl_Obj *objPtr; /* Points to a literal object that was
* previously created by a call to
* TclRegisterLiteral. */
{
Interp *iPtr = (Interp *) interp;
LiteralTable *globalTablePtr = &(iPtr->literalTable);
register LiteralEntry *entryPtr, *prevPtr;
ByteCode* codePtr;
char *bytes;
int length, index;
bytes = Tcl_GetStringFromObj(objPtr, &length);
index = (HashString(bytes, length) & globalTablePtr->mask);
/*
* Check to see if the object is in the global literal table and
* remove this reference. The object may not be in the table if
* it is a hidden local literal.
*/
for (prevPtr = NULL, entryPtr = globalTablePtr->buckets[index];
entryPtr != NULL;
prevPtr = entryPtr, entryPtr = entryPtr->nextPtr) {
if (entryPtr->objPtr == objPtr) {
entryPtr->refCount--;
/*
* We found the matching LiteralEntry. Check if it's only being
* kept alive only by a circular reference from a ByteCode
* stored as its internal rep.
*/
if ((entryPtr->refCount == 1)
&& (objPtr->typePtr == &tclByteCodeType)) {
codePtr = (ByteCode *) objPtr->internalRep.otherValuePtr;
if ((codePtr->numLitObjects == 1)
&& (codePtr->objArrayPtr[0] == objPtr)) {
entryPtr->refCount = 0;
/*
* Set the ByteCode object array entry NULL to signal
* to TclCleanupByteCode to not try to release this
* about to be freed literal again.
*/
codePtr->objArrayPtr[0] = NULL;
}
}
/*
* If the literal is no longer being used by any ByteCode,
* delete the entry then decrement the ref count of its object.
*/
if (entryPtr->refCount == 0) {
if (prevPtr == NULL) {
globalTablePtr->buckets[index] = entryPtr->nextPtr;
} else {
prevPtr->nextPtr = entryPtr->nextPtr;
}
#ifdef TCL_COMPILE_STATS
iPtr->stats.currentLitStringBytes -= (double) (length + 1);
#endif /*TCL_COMPILE_STATS*/
ckfree((char *) entryPtr);
globalTablePtr->numEntries--;
/*
* Remove the reference corresponding to the global
* literal table entry.
*/
TclDecrRefCount(objPtr);
}
break;
}
}
/*
* Remove the reference corresponding to the local literal table
* entry.
*/
Tcl_DecrRefCount(objPtr);
}
/*
*----------------------------------------------------------------------
*
* HashString --
*
* Compute a one-word summary of a text string, which can be
* used to generate a hash index.
*
* Results:
* The return value is a one-word summary of the information in
* string.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static unsigned int
HashString(bytes, length)
register CONST char *bytes; /* String for which to compute hash
* value. */
int length; /* Number of bytes in the string. */
{
register unsigned int result;
register int i;
/*
* I tried a zillion different hash functions and asked many other
* people for advice. Many people had their own favorite functions,
* all different, but no-one had much idea why they were good ones.
* I chose the one below (multiply by 9 and add new character)
* because of the following reasons:
*
* 1. Multiplying by 10 is perfect for keys that are decimal strings,
* and multiplying by 9 is just about as good.
* 2. Times-9 is (shift-left-3) plus (old). This means that each
* character's bits hang around in the low-order bits of the
* hash value for ever, plus they spread fairly rapidly up to
* the high-order bits to fill out the hash value. This seems
* works well both for decimal and non-decimal strings.
*/
result = 0;
for (i = 0; i < length; i++) {
result += (result<<3) + *bytes++;
}
return result;
}
/*
*----------------------------------------------------------------------
*
* RebuildLiteralTable --
*
* This procedure is invoked when the ratio of entries to hash buckets
* becomes too large in a local or global literal table. It allocates
* a larger bucket array and moves the entries into the new buckets.
*
* Results:
* None.
*
* Side effects:
* Memory gets reallocated and entries get rehashed into new buckets.
*
*----------------------------------------------------------------------
*/
static void
RebuildLiteralTable(tablePtr)
register LiteralTable *tablePtr; /* Local or global table to enlarge. */
{
LiteralEntry **oldBuckets;
register LiteralEntry **oldChainPtr, **newChainPtr;
register LiteralEntry *entryPtr;
LiteralEntry **bucketPtr;
char *bytes;
int oldSize, count, index, length;
oldSize = tablePtr->numBuckets;
oldBuckets = tablePtr->buckets;
/*
* Allocate and initialize the new bucket array, and set up
* hashing constants for new array size.
*/
tablePtr->numBuckets *= 4;
tablePtr->buckets = (LiteralEntry **) ckalloc((unsigned)
(tablePtr->numBuckets * sizeof(LiteralEntry *)));
for (count = tablePtr->numBuckets, newChainPtr = tablePtr->buckets;
count > 0;
count--, newChainPtr++) {
*newChainPtr = NULL;
}
tablePtr->rebuildSize *= 4;
tablePtr->mask = (tablePtr->mask << 2) + 3;
/*
* Rehash all of the existing entries into the new bucket array.
*/
for (oldChainPtr = oldBuckets;
oldSize > 0;
oldSize--, oldChainPtr++) {
for (entryPtr = *oldChainPtr; entryPtr != NULL;
entryPtr = *oldChainPtr) {
bytes = Tcl_GetStringFromObj(entryPtr->objPtr, &length);
index = (HashString(bytes, length) & tablePtr->mask);
*oldChainPtr = entryPtr->nextPtr;
bucketPtr = &(tablePtr->buckets[index]);
entryPtr->nextPtr = *bucketPtr;
*bucketPtr = entryPtr;
}
}
/*
* Free up the old bucket array, if it was dynamically allocated.
*/
if (oldBuckets != tablePtr->staticBuckets) {
ckfree((char *) oldBuckets);
}
}
#ifdef TCL_COMPILE_STATS
/*
*----------------------------------------------------------------------
*
* TclLiteralStats --
*
* Return statistics describing the layout of the hash table
* in its hash buckets.
*
* Results:
* The return value is a malloc-ed string containing information
* about tablePtr. It is the caller's responsibility to free
* this string.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
char *
TclLiteralStats(tablePtr)
LiteralTable *tablePtr; /* Table for which to produce stats. */
{
#define NUM_COUNTERS 10
int count[NUM_COUNTERS], overflow, i, j;
double average, tmp;
register LiteralEntry *entryPtr;
char *result, *p;
/*
* Compute a histogram of bucket usage. For each bucket chain i,
* j is the number of entries in the chain.
*/
for (i = 0; i < NUM_COUNTERS; i++) {
count[i] = 0;
}
overflow = 0;
average = 0.0;
for (i = 0; i < tablePtr->numBuckets; i++) {
j = 0;
for (entryPtr = tablePtr->buckets[i]; entryPtr != NULL;
entryPtr = entryPtr->nextPtr) {
j++;
}
if (j < NUM_COUNTERS) {
count[j]++;
} else {
overflow++;
}
tmp = j;
average += (tmp+1.0)*(tmp/tablePtr->numEntries)/2.0;
}
/*
* Print out the histogram and a few other pieces of information.
*/
result = (char *) ckalloc((unsigned) ((NUM_COUNTERS*60) + 300));
sprintf(result, "%d entries in table, %d buckets\n",
tablePtr->numEntries, tablePtr->numBuckets);
p = result + strlen(result);
for (i = 0; i < NUM_COUNTERS; i++) {
sprintf(p, "number of buckets with %d entries: %d\n",
i, count[i]);
p += strlen(p);
}
sprintf(p, "number of buckets with %d or more entries: %d\n",
NUM_COUNTERS, overflow);
p += strlen(p);
sprintf(p, "average search distance for entry: %.1f", average);
return result;
}
#endif /*TCL_COMPILE_STATS*/
#ifdef TCL_COMPILE_DEBUG
/*
*----------------------------------------------------------------------
*
* TclVerifyLocalLiteralTable --
*
* Check a CompileEnv's local literal table for consistency.
*
* Results:
* None.
*
* Side effects:
* Panics if problems are found.
*
*----------------------------------------------------------------------
*/
void
TclVerifyLocalLiteralTable(envPtr)
CompileEnv *envPtr; /* Points to CompileEnv whose literal
* table is to be validated. */
{
register LiteralTable *localTablePtr = &(envPtr->localLitTable);
register LiteralEntry *localPtr;
char *bytes;
register int i;
int length, count;
count = 0;
for (i = 0; i < localTablePtr->numBuckets; i++) {
for (localPtr = localTablePtr->buckets[i];
localPtr != NULL; localPtr = localPtr->nextPtr) {
count++;
if (localPtr->refCount != -1) {
bytes = Tcl_GetStringFromObj(localPtr->objPtr, &length);
panic("TclVerifyLocalLiteralTable: local literal \"%.*s\" had bad refCount %d",
(length>60? 60 : length), bytes,
localPtr->refCount);
}
if (TclLookupLiteralEntry((Tcl_Interp *) envPtr->iPtr,
localPtr->objPtr) == NULL) {
bytes = Tcl_GetStringFromObj(localPtr->objPtr, &length);
panic("TclVerifyLocalLiteralTable: local literal \"%.*s\" is not global",
(length>60? 60 : length), bytes);
}
if (localPtr->objPtr->bytes == NULL) {
panic("TclVerifyLocalLiteralTable: literal has NULL string rep");
}
}
}
if (count != localTablePtr->numEntries) {
panic("TclVerifyLocalLiteralTable: local literal table had %d entries, should be %d",
count, localTablePtr->numEntries);
}
}
/*
*----------------------------------------------------------------------
*
* TclVerifyGlobalLiteralTable --
*
* Check an interpreter's global literal table literal for consistency.
*
* Results:
* None.
*
* Side effects:
* Panics if problems are found.
*
*----------------------------------------------------------------------
*/
void
TclVerifyGlobalLiteralTable(iPtr)
Interp *iPtr; /* Points to interpreter whose global
* literal table is to be validated. */
{
register LiteralTable *globalTablePtr = &(iPtr->literalTable);
register LiteralEntry *globalPtr;
char *bytes;
register int i;
int length, count;
count = 0;
for (i = 0; i < globalTablePtr->numBuckets; i++) {
for (globalPtr = globalTablePtr->buckets[i];
globalPtr != NULL; globalPtr = globalPtr->nextPtr) {
count++;
if (globalPtr->refCount < 1) {
bytes = Tcl_GetStringFromObj(globalPtr->objPtr, &length);
panic("TclVerifyGlobalLiteralTable: global literal \"%.*s\" had bad refCount %d",
(length>60? 60 : length), bytes,
globalPtr->refCount);
}
if (globalPtr->objPtr->bytes == NULL) {
panic("TclVerifyGlobalLiteralTable: literal has NULL string rep");
}
}
}
if (count != globalTablePtr->numEntries) {
panic("TclVerifyGlobalLiteralTable: global literal table had %d entries, should be %d",
count, globalTablePtr->numEntries);
}
}
#endif /*TCL_COMPILE_DEBUG*/
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
1062
]
]
]
|
0ea80f0aad537b2ec0d52c17105282bab42b20e8 | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Networking/SecureSockets/SecureSockets.h | 3354a194873c01f3522c935d4403859bdcdea482 | []
| no_license | huellif/symbian-example | 72097c9aec6d45d555a79a30d576dddc04a65a16 | 56f6c5e67a3d37961408fc51188d46d49bddcfdc | refs/heads/master | 2016-09-06T12:49:32.021854 | 2010-10-14T06:31:20 | 2010-10-14T06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,681 | h | // SecureSockets.h
//
// Copyright (c) 2001 Symbian Ltd. All rights reserved.
//
#include <basched.h>
#include <eikenv.h>
#include <coecntrl.h>
#include <eikappui.h>
#include <e32keys.h>
#include <eikconso.h>
#include <eikapp.h>
#include <eikdoc.h>
#include <eikon.rsg>
#include <eikinfo.h>
#include <eikon.hrh>
#include <SecureSockets.rsg>
#include "secengine.h"
#ifndef _SECAPP_H_
#define _SECAPP_H_
/** Application UID */
const TUid KUidSecApp = {0xE8000068};
/**
Console-type control
*/
class CConsoleControl : public CCoeControl
{
public:
static CConsoleControl* NewL(const TRect& aClientRect);
~CConsoleControl();
void ConstructL(const TRect& aClientRect);
CConsoleBase& Console();
// Override CCoeControl
void ActivateL();
protected:
CConsoleControl() {}
private:
CEikConsoleScreen* iConsole; // Standard console control
};
/**
Dialog that allows user to specify web page to securely connect to
*/
class CSettingsDialog: public CEikDialog
{
public:
/**
Creates and runs the settings dialog.
@return True if settings confirmed
@param aConnectSettings The settings, on return the dialog values
*/
static TBool RunDlgLD(TConnectSettings& aConnectSettings);
private:
/**
Constructor.
@param aConnectSettings The settings
*/
CSettingsDialog(TConnectSettings& aConnectSettings);
// From CEikDialog
/** Populate dialog with initial settings */
void PreLayoutDynInitL();
/** Store dialog input */
TBool OkToExitL(TInt aButtonId);
private:
/** The settings */
TConnectSettings& iConnectSettings;
};
/**
User interface command handling
*/
class CSecAppUi : public CEikAppUi
{
public:
CSecAppUi(CSecEngine* aSecEngine);
void ConstructL();
~CSecAppUi();
private:
// Override CEikAppUi
void HandleCommandL(TInt aCommand);
void DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane);
private:
CConsoleControl* iConsoleControl;
CSecEngine* iSecEngine;
TConnectSettings iConnectSettings;
RFile iOutputFile;
TFileName iOutputFileName;
};
/**
Document class, which owns the engine
*/
class CSecDocument : public CEikDocument
{
public:
CSecDocument(CEikApplication& aApp);
static CSecDocument* NewL(CEikApplication& aApp);
~CSecDocument();
void ConstructL();
private:
// Override CApaDocument
CEikAppUi* CreateAppUiL();
private:
CSecEngine* iSecEngine; // Document owns the engine
};
/**
Application class
*/
class CSecApplication : public CEikApplication
{
private: // from CApaApplication
CApaDocument* CreateDocumentL();
TUid AppDllUid() const;
};
#endif
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
]
| [
[
[
1,
133
]
]
]
|
ad5de11629a7e7df161d567ae5e3cdf80fb5b08c | 8c4d8b2646a9c96ec7f1178a7f2716823fb99984 | /testes_zuka/glm.cpp | 790316f888d05c231d84001279618af413c20fb4 | []
| no_license | MiguelCosta/cg-trabalho | c93987ff8c2ec8ac022b936e620594a4f420789d | b293ca8d55d9c4938b66a0561695be0079bd50ac | refs/heads/master | 2020-07-08T13:02:35.644637 | 2011-05-23T13:57:47 | 2011-05-23T13:57:47 | 32,185,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,328 | cpp | /*
glm.c
Nate Robins, 1997
[email protected], http://www.pobox.com/~ndr/
Wavefront OBJ model file format reader/writer/manipulator.
Includes routines for generating smooth normals with
preservation of edges, welding redundant vertices & texture
coordinate generation (spheremap and planar projections) + more.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "glm.h"
#define T(x) (model->triangles[(x)])
/* _GLMnode: general purpose node extern
*/
typedef struct _GLMnode {
GLuint index;
GLboolean averaged;
struct _GLMnode* next;
} GLMnode;
/* glmMax: returns the maximum of two floats */
static GLfloat
glmMax(GLfloat a, GLfloat b)
{
if (b > a)
return b;
return a;
}
/* glmAbs: returns the absolute value of a float */
static GLfloat
glmAbs(GLfloat f)
{
if (f < 0)
return -f;
return f;
}
/* glmDot: compute the dot product of two vectors
*
* u - array of 3 GLfloats (GLfloat u[3])
* v - array of 3 GLfloats (GLfloat v[3])
*/
static GLfloat
glmDot(GLfloat* u, GLfloat* v)
{
assert(u); assert(v);
return u[0]*v[0] + u[1]*v[1] + u[2]*v[2];
}
/* glmCross: compute the cross product of two vectors
*
* u - array of 3 GLfloats (GLfloat u[3])
* v - array of 3 GLfloats (GLfloat v[3])
* n - array of 3 GLfloats (GLfloat n[3]) to return the cross product in
*/
static GLvoid
glmCross(GLfloat* u, GLfloat* v, GLfloat* n)
{
assert(u); assert(v); assert(n);
n[0] = u[1]*v[2] - u[2]*v[1];
n[1] = u[2]*v[0] - u[0]*v[2];
n[2] = u[0]*v[1] - u[1]*v[0];
}
/* glmNormalize: normalize a vector
*
* v - array of 3 GLfloats (GLfloat v[3]) to be normalized
*/
static GLvoid
glmNormalize(GLfloat* v)
{
GLfloat l;
assert(v);
l = (GLfloat)sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= l;
v[1] /= l;
v[2] /= l;
}
/* glmEqual: compares two vectors and returns GL_TRUE if they are
* equal (within a certain threshold) or GL_FALSE if not. An epsilon
* that works fairly well is 0.000001.
*
* u - array of 3 GLfloats (GLfloat u[3])
* v - array of 3 GLfloats (GLfloat v[3])
*/
static GLboolean
glmEqual(GLfloat* u, GLfloat* v, GLfloat epsilon)
{
if (glmAbs(u[0] - v[0]) < epsilon &&
glmAbs(u[1] - v[1]) < epsilon &&
glmAbs(u[2] - v[2]) < epsilon)
{
return GL_TRUE;
}
return GL_FALSE;
}
/* glmWeldVectors: eliminate (weld) vectors that are within an
* epsilon of each other.
*
* vectors - array of GLfloat[3]'s to be welded
* numvectors - number of GLfloat[3]'s in vectors
* epsilon - maximum difference between vectors
*
*/
GLfloat*
glmWeldVectors(GLfloat* vectors, GLuint* numvectors, GLfloat epsilon)
{
GLfloat* copies;
GLuint copied;
GLuint i, j;
copies = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (*numvectors + 1));
memcpy(copies, vectors, (sizeof(GLfloat) * 3 * (*numvectors + 1)));
copied = 1;
for (i = 1; i <= *numvectors; i++) {
for (j = 1; j <= copied; j++) {
if (glmEqual(&vectors[3 * i], &copies[3 * j], epsilon)) {
goto duplicate;
}
}
/* must not be any duplicates -- add to the copies array */
copies[3 * copied + 0] = vectors[3 * i + 0];
copies[3 * copied + 1] = vectors[3 * i + 1];
copies[3 * copied + 2] = vectors[3 * i + 2];
j = copied; /* pass this along for below */
copied++;
duplicate:
/* set the first component of this vector to point at the correct
index into the new copies array */
vectors[3 * i + 0] = (GLfloat)j;
}
*numvectors = copied-1;
return copies;
}
/* glmFindGroup: Find a group in the model
*/
GLMgroup*
glmFindGroup(GLMmodel* model, char* name)
{
GLMgroup* group;
assert(model);
group = model->groups;
while(group) {
if (!strcmp(name, group->name))
break;
group = group->next;
}
return group;
}
/* glmAddGroup: Add a group to the model
*/
GLMgroup*
glmAddGroup(GLMmodel* model, char* name)
{
GLMgroup* group;
group = glmFindGroup(model, name);
if (!group) {
group = (GLMgroup*)malloc(sizeof(GLMgroup));
group->name = strdup(name);
group->material = 0;
group->numtriangles = 0;
group->triangles = NULL;
group->next = model->groups;
model->groups = group;
model->numgroups++;
}
return group;
}
/* glmFindGroup: Find a material in the model
*/
GLuint
glmFindMaterial(GLMmodel* model, char* name)
{
GLuint i;
/* XXX doing a linear search on a string key'd list is pretty lame,
but it works and is fast enough for now. */
for (i = 0; i < model->nummaterials; i++) {
if (!strcmp(model->materials[i].name, name))
goto found;
}
/* didn't find the name, so print a warning and return the default
material (0). */
printf("glmFindMaterial(): can't find material \"%s\".\n", name);
i = 0;
found:
return i;
}
/* glmDirName: return the directory given a path
*
* path - filesystem path
*
* NOTE: the return value should be free'd.
*/
static char*
glmDirName(char* path)
{
char* dir;
char* s;
dir = strdup(path);
s = strrchr(dir, '/');
if (s)
s[1] = '\0';
else
dir[0] = '\0';
return dir;
}
/* glmReadMTL: read a wavefront material library file
*
* model - properly initialized GLMmodel structure
* name - name of the material library
*/
static GLvoid
glmReadMTL(GLMmodel* model, char* name)
{
FILE* file;
char* dir;
char* filename;
char buf[128];
GLuint nummaterials, i;
dir = glmDirName(model->pathname);
filename = (char*)malloc(sizeof(char) * (strlen(dir) + strlen(name) + 1));
strcpy(filename, dir);
strcat(filename, name);
free(dir);
file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "glmReadMTL() failed: can't open material file \"%s\".\n",
filename);
exit(1);
}
free(filename);
/* count the number of materials in the file */
nummaterials = 1;
while(fscanf(file, "%s", buf) != EOF) {
switch(buf[0]) {
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'n': /* newmtl */
fgets(buf, sizeof(buf), file);
nummaterials++;
sscanf(buf, "%s %s", buf, buf);
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
}
rewind(file);
model->materials = (GLMmaterial*)malloc(sizeof(GLMmaterial) * nummaterials);
model->nummaterials = nummaterials;
/* set the default material */
for (i = 0; i < nummaterials; i++) {
model->materials[i].name = NULL;
model->materials[i].shininess = 65.0;
model->materials[i].diffuse[0] = 0.8;
model->materials[i].diffuse[1] = 0.8;
model->materials[i].diffuse[2] = 0.8;
model->materials[i].diffuse[3] = 1.0;
model->materials[i].ambient[0] = 0.2;
model->materials[i].ambient[1] = 0.2;
model->materials[i].ambient[2] = 0.2;
model->materials[i].ambient[3] = 1.0;
model->materials[i].specular[0] = 0.0;
model->materials[i].specular[1] = 0.0;
model->materials[i].specular[2] = 0.0;
model->materials[i].specular[3] = 1.0;
}
model->materials[0].name = strdup("default");
/* now, read in the data */
nummaterials = 0;
while(fscanf(file, "%s", buf) != EOF) {
switch(buf[0]) {
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'n': /* newmtl */
fgets(buf, sizeof(buf), file);
sscanf(buf, "%s %s", buf, buf);
nummaterials++;
model->materials[nummaterials].name = strdup(buf);
break;
case 'N':
fscanf(file, "%f", &model->materials[nummaterials].shininess);
/* wavefront shininess is from [0, 1000], so scale for OpenGL */
model->materials[nummaterials].shininess /= 1000.0;
model->materials[nummaterials].shininess *= 128.0;
break;
case 'K':
switch(buf[1]) {
case 'd':
fscanf(file, "%f %f %f",
&model->materials[nummaterials].diffuse[0],
&model->materials[nummaterials].diffuse[1],
&model->materials[nummaterials].diffuse[2]);
break;
case 's':
fscanf(file, "%f %f %f",
&model->materials[nummaterials].specular[0],
&model->materials[nummaterials].specular[1],
&model->materials[nummaterials].specular[2]);
break;
case 'a':
fscanf(file, "%f %f %f",
&model->materials[nummaterials].ambient[0],
&model->materials[nummaterials].ambient[1],
&model->materials[nummaterials].ambient[2]);
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
}
}
/* glmWriteMTL: write a wavefront material library file
*
* model - properly initialized GLMmodel structure
* modelpath - pathname of the model being written
* mtllibname - name of the material library to be written
*/
static GLvoid
glmWriteMTL(GLMmodel* model, char* modelpath, char* mtllibname)
{
FILE* file;
char* dir;
char* filename;
GLMmaterial* material;
GLuint i;
dir = glmDirName(modelpath);
filename = (char*)malloc(sizeof(char) * (strlen(dir)+strlen(mtllibname)));
strcpy(filename, dir);
strcat(filename, mtllibname);
free(dir);
/* open the file */
file = fopen(filename, "w");
if (!file) {
fprintf(stderr, "glmWriteMTL() failed: can't open file \"%s\".\n",
filename);
exit(1);
}
free(filename);
/* spit out a header */
fprintf(file, "# \n");
fprintf(file, "# Wavefront MTL generated by GLM library\n");
fprintf(file, "# \n");
fprintf(file, "# GLM library\n");
fprintf(file, "# Nate Robins\n");
fprintf(file, "# [email protected]\n");
fprintf(file, "# http://www.pobox.com/~ndr\n");
fprintf(file, "# \n\n");
for (i = 0; i < model->nummaterials; i++) {
material = &model->materials[i];
fprintf(file, "newmtl %s\n", material->name);
fprintf(file, "Ka %f %f %f\n",
material->ambient[0], material->ambient[1], material->ambient[2]);
fprintf(file, "Kd %f %f %f\n",
material->diffuse[0], material->diffuse[1], material->diffuse[2]);
fprintf(file, "Ks %f %f %f\n",
material->specular[0],material->specular[1],material->specular[2]);
fprintf(file, "Ns %f\n", material->shininess / 128.0 * 1000.0);
fprintf(file, "\n");
}
}
/* glmFirstPass: first pass at a Wavefront OBJ file that gets all the
* statistics of the model (such as #vertices, #normals, etc)
*
* model - properly initialized GLMmodel structure
* file - (fopen'd) file descriptor
*/
static GLvoid
glmFirstPass(GLMmodel* model, FILE* file)
{
GLuint numvertices; /* number of vertices in model */
GLuint numnormals; /* number of normals in model */
GLuint numtexcoords; /* number of texcoords in model */
GLuint numtriangles; /* number of triangles in model */
GLMgroup* group; /* current group */
unsigned v, n, t;
char buf[128];
/* make a default group */
group = glmAddGroup(model, "default");
numvertices = numnormals = numtexcoords = numtriangles = 0;
while(fscanf(file, "%s", buf) != EOF) {
switch(buf[0]) {
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'v': /* v, vn, vt */
switch(buf[1]) {
case '\0': /* vertex */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numvertices++;
break;
case 'n': /* normal */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numnormals++;
break;
case 't': /* texcoord */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numtexcoords++;
break;
default:
printf("glmFirstPass(): Unknown token \"%s\".\n", buf);
exit(1);
break;
}
break;
case 'm':
fgets(buf, sizeof(buf), file);
sscanf(buf, "%s %s", buf, buf);
model->mtllibname = strdup(buf);
glmReadMTL(model, buf);
break;
case 'u':
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'g': /* group */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
#if SINGLE_STRING_GROUP_NAMES
sscanf(buf, "%s", buf);
#else
buf[strlen(buf)-1] = '\0'; /* nuke '\n' */
#endif
group = glmAddGroup(model, buf);
break;
case 'f': /* face */
v = n = t = 0;
fscanf(file, "%s", buf);
/* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
if (strstr(buf, "//")) {
/* v//n */
sscanf(buf, "%d//%d", &v, &n);
fscanf(file, "%d//%d", &v, &n);
fscanf(file, "%d//%d", &v, &n);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d//%d", &v, &n) > 0) {
numtriangles++;
group->numtriangles++;
}
} else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) {
/* v/t/n */
fscanf(file, "%d/%d/%d", &v, &t, &n);
fscanf(file, "%d/%d/%d", &v, &t, &n);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
numtriangles++;
group->numtriangles++;
}
} else if (sscanf(buf, "%d/%d", &v, &t) == 2) {
/* v/t */
fscanf(file, "%d/%d", &v, &t);
fscanf(file, "%d/%d", &v, &t);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d/%d", &v, &t) > 0) {
numtriangles++;
group->numtriangles++;
}
} else {
/* v */
fscanf(file, "%d", &v);
fscanf(file, "%d", &v);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d", &v) > 0) {
numtriangles++;
group->numtriangles++;
}
}
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
}
/* set the stats in the model structure */
model->numvertices = numvertices;
model->numnormals = numnormals;
model->numtexcoords = numtexcoords;
model->numtriangles = numtriangles;
/* allocate memory for the triangles in each group */
group = model->groups;
while(group) {
group->triangles = (GLuint*)malloc(sizeof(GLuint) * group->numtriangles);
group->numtriangles = 0;
group = group->next;
}
}
/* glmSecondPass: second pass at a Wavefront OBJ file that gets all
* the data.
*
* model - properly initialized GLMmodel structure
* file - (fopen'd) file descriptor
*/
static GLvoid
glmSecondPass(GLMmodel* model, FILE* file)
{
GLuint numvertices; /* number of vertices in model */
GLuint numnormals; /* number of normals in model */
GLuint numtexcoords; /* number of texcoords in model */
GLuint numtriangles; /* number of triangles in model */
GLfloat* vertices; /* array of vertices */
GLfloat* normals; /* array of normals */
GLfloat* texcoords; /* array of texture coordinates */
GLMgroup* group; /* current group pointer */
GLuint material; /* current material */
GLuint v, n, t;
char buf[128];
/* set the pointer shortcuts */
vertices = model->vertices;
normals = model->normals;
texcoords = model->texcoords;
group = model->groups;
/* on the second pass through the file, read all the data into the
allocated arrays */
numvertices = numnormals = numtexcoords = 1;
numtriangles = 0;
material = 0;
while(fscanf(file, "%s", buf) != EOF) {
switch(buf[0]) {
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'v': /* v, vn, vt */
switch(buf[1]) {
case '\0': /* vertex */
fscanf(file, "%f %f %f",
&vertices[3 * numvertices + 0],
&vertices[3 * numvertices + 1],
&vertices[3 * numvertices + 2]);
numvertices++;
break;
case 'n': /* normal */
fscanf(file, "%f %f %f",
&normals[3 * numnormals + 0],
&normals[3 * numnormals + 1],
&normals[3 * numnormals + 2]);
numnormals++;
break;
case 't': /* texcoord */
fscanf(file, "%f %f",
&texcoords[2 * numtexcoords + 0],
&texcoords[2 * numtexcoords + 1]);
numtexcoords++;
break;
}
break;
case 'u':
fgets(buf, sizeof(buf), file);
sscanf(buf, "%s %s", buf, buf);
group->material = material = glmFindMaterial(model, buf);
break;
case 'g': /* group */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
#if SINGLE_STRING_GROUP_NAMES
sscanf(buf, "%s", buf);
#else
buf[strlen(buf)-1] = '\0'; /* nuke '\n' */
#endif
group = glmFindGroup(model, buf);
group->material = material;
break;
case 'f': /* face */
v = n = t = 0;
fscanf(file, "%s", buf);
/* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
if (strstr(buf, "//")) {
/* v//n */
sscanf(buf, "%d//%d", &v, &n);
T(numtriangles).vindices[0] = v;
T(numtriangles).nindices[0] = n;
fscanf(file, "%d//%d", &v, &n);
T(numtriangles).vindices[1] = v;
T(numtriangles).nindices[1] = n;
fscanf(file, "%d//%d", &v, &n);
T(numtriangles).vindices[2] = v;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d//%d", &v, &n) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
T(numtriangles).vindices[2] = v;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
} else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) {
/* v/t/n */
T(numtriangles).vindices[0] = v;
T(numtriangles).tindices[0] = t;
T(numtriangles).nindices[0] = n;
fscanf(file, "%d/%d/%d", &v, &t, &n);
T(numtriangles).vindices[1] = v;
T(numtriangles).tindices[1] = t;
T(numtriangles).nindices[1] = n;
fscanf(file, "%d/%d/%d", &v, &t, &n);
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
T(numtriangles).nindices[2] = n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
} else if (sscanf(buf, "%d/%d", &v, &t) == 2) {
/* v/t */
T(numtriangles).vindices[0] = v;
T(numtriangles).tindices[0] = t;
fscanf(file, "%d/%d", &v, &t);
T(numtriangles).vindices[1] = v;
T(numtriangles).tindices[1] = t;
fscanf(file, "%d/%d", &v, &t);
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d/%d", &v, &t) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
T(numtriangles).vindices[2] = v;
T(numtriangles).tindices[2] = t;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
} else {
/* v */
sscanf(buf, "%d", &v);
T(numtriangles).vindices[0] = v;
fscanf(file, "%d", &v);
T(numtriangles).vindices[1] = v;
fscanf(file, "%d", &v);
T(numtriangles).vindices[2] = v;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d", &v) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).vindices[2] = v;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
}
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
}
#if 0
/* announce the memory requirements */
printf(" Memory: %d bytes\n",
numvertices * 3*sizeof(GLfloat) +
numnormals * 3*sizeof(GLfloat) * (numnormals ? 1 : 0) +
numtexcoords * 3*sizeof(GLfloat) * (numtexcoords ? 1 : 0) +
numtriangles * sizeof(GLMtriangle));
#endif
}
/* glmUnitize: "unitize" a model by translating it to the origin and
* scaling it to fit in a unit cube around the origin (-1 to 1 in all
* dimensions).
* Returns the scalefactor used.
*
* model - properly initialized GLMmodel structure
*/
GLfloat
glmUnitize(GLMmodel* model)
{
GLuint i;
GLfloat maxx, minx, maxy, miny, maxz, minz;
GLfloat cx, cy, cz, w, h, d;
GLfloat scale;
assert(model);
assert(model->vertices);
/* get the max/mins */
maxx = minx = model->vertices[3 + 0];
maxy = miny = model->vertices[3 + 1];
maxz = minz = model->vertices[3 + 2];
for (i = 1; i <= model->numvertices; i++) {
if (maxx < model->vertices[3 * i + 0])
maxx = model->vertices[3 * i + 0];
if (minx > model->vertices[3 * i + 0])
minx = model->vertices[3 * i + 0];
if (maxy < model->vertices[3 * i + 1])
maxy = model->vertices[3 * i + 1];
if (miny > model->vertices[3 * i + 1])
miny = model->vertices[3 * i + 1];
if (maxz < model->vertices[3 * i + 2])
maxz = model->vertices[3 * i + 2];
if (minz > model->vertices[3 * i + 2])
minz = model->vertices[3 * i + 2];
}
/* calculate model width, height, and depth */
w = glmAbs(maxx) + glmAbs(minx);
h = glmAbs(maxy) + glmAbs(miny);
d = glmAbs(maxz) + glmAbs(minz);
/* calculate center of the model */
cx = (maxx + minx) / 2.0;
cy = (maxy + miny) / 2.0;
cz = (maxz + minz) / 2.0;
/* calculate unitizing scale factor */
scale = 2.0 / glmMax(glmMax(w, h), d);
/* translate around center then scale */
for (i = 1; i <= model->numvertices; i++) {
model->vertices[3 * i + 0] -= cx;
model->vertices[3 * i + 1] -= cy;
model->vertices[3 * i + 2] -= cz;
model->vertices[3 * i + 0] *= scale;
model->vertices[3 * i + 1] *= scale;
model->vertices[3 * i + 2] *= scale;
}
return scale;
}
/* glmDimensions: Calculates the dimensions (width, height, depth) of
* a model.
*
* model - initialized GLMmodel structure
* dimensions - array of 3 GLfloats (GLfloat dimensions[3])
*/
GLvoid
glmDimensions(GLMmodel* model, GLfloat* dimensions)
{
GLuint i;
GLfloat maxx, minx, maxy, miny, maxz, minz;
assert(model);
assert(model->vertices);
assert(dimensions);
/* get the max/mins */
maxx = minx = model->vertices[3 + 0];
maxy = miny = model->vertices[3 + 1];
maxz = minz = model->vertices[3 + 2];
for (i = 1; i <= model->numvertices; i++) {
if (maxx < model->vertices[3 * i + 0])
maxx = model->vertices[3 * i + 0];
if (minx > model->vertices[3 * i + 0])
minx = model->vertices[3 * i + 0];
if (maxy < model->vertices[3 * i + 1])
maxy = model->vertices[3 * i + 1];
if (miny > model->vertices[3 * i + 1])
miny = model->vertices[3 * i + 1];
if (maxz < model->vertices[3 * i + 2])
maxz = model->vertices[3 * i + 2];
if (minz > model->vertices[3 * i + 2])
minz = model->vertices[3 * i + 2];
}
/* calculate model width, height, and depth */
dimensions[0] = glmAbs(maxx) + glmAbs(minx);
dimensions[1] = glmAbs(maxy) + glmAbs(miny);
dimensions[2] = glmAbs(maxz) + glmAbs(minz);
}
/* glmScale: Scales a model by a given amount.
*
* model - properly initialized GLMmodel structure
* scale - scalefactor (0.5 = half as large, 2.0 = twice as large)
*/
GLvoid
glmScale(GLMmodel* model, GLfloat scale)
{
GLuint i;
for (i = 1; i <= model->numvertices; i++) {
model->vertices[3 * i + 0] *= scale;
model->vertices[3 * i + 1] *= scale;
model->vertices[3 * i + 2] *= scale;
}
}
/* glmReverseWinding: Reverse the polygon winding for all polygons in
* this model. Default winding is counter-clockwise. Also changes
* the direction of the normals.
*
* model - properly initialized GLMmodel structure
*/
GLvoid
glmReverseWinding(GLMmodel* model)
{
GLuint i, swap;
assert(model);
for (i = 0; i < model->numtriangles; i++) {
swap = T(i).vindices[0];
T(i).vindices[0] = T(i).vindices[2];
T(i).vindices[2] = swap;
if (model->numnormals) {
swap = T(i).nindices[0];
T(i).nindices[0] = T(i).nindices[2];
T(i).nindices[2] = swap;
}
if (model->numtexcoords) {
swap = T(i).tindices[0];
T(i).tindices[0] = T(i).tindices[2];
T(i).tindices[2] = swap;
}
}
/* reverse facet normals */
for (i = 1; i <= model->numfacetnorms; i++) {
model->facetnorms[3 * i + 0] = -model->facetnorms[3 * i + 0];
model->facetnorms[3 * i + 1] = -model->facetnorms[3 * i + 1];
model->facetnorms[3 * i + 2] = -model->facetnorms[3 * i + 2];
}
/* reverse vertex normals */
for (i = 1; i <= model->numnormals; i++) {
model->normals[3 * i + 0] = -model->normals[3 * i + 0];
model->normals[3 * i + 1] = -model->normals[3 * i + 1];
model->normals[3 * i + 2] = -model->normals[3 * i + 2];
}
}
/* glmFacetNormals: Generates facet normals for a model (by taking the
* cross product of the two vectors derived from the sides of each
* triangle). Assumes a counter-clockwise winding.
*
* model - initialized GLMmodel structure
*/
GLvoid
glmFacetNormals(GLMmodel* model)
{
GLuint i;
GLfloat u[3];
GLfloat v[3];
assert(model);
assert(model->vertices);
/* clobber any old facetnormals */
if (model->facetnorms)
free(model->facetnorms);
/* allocate memory for the new facet normals */
model->numfacetnorms = model->numtriangles;
model->facetnorms = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numfacetnorms + 1));
for (i = 0; i < model->numtriangles; i++) {
model->triangles[i].findex = i+1;
u[0] = model->vertices[3 * T(i).vindices[1] + 0] -
model->vertices[3 * T(i).vindices[0] + 0];
u[1] = model->vertices[3 * T(i).vindices[1] + 1] -
model->vertices[3 * T(i).vindices[0] + 1];
u[2] = model->vertices[3 * T(i).vindices[1] + 2] -
model->vertices[3 * T(i).vindices[0] + 2];
v[0] = model->vertices[3 * T(i).vindices[2] + 0] -
model->vertices[3 * T(i).vindices[0] + 0];
v[1] = model->vertices[3 * T(i).vindices[2] + 1] -
model->vertices[3 * T(i).vindices[0] + 1];
v[2] = model->vertices[3 * T(i).vindices[2] + 2] -
model->vertices[3 * T(i).vindices[0] + 2];
glmCross(u, v, &model->facetnorms[3 * (i+1)]);
glmNormalize(&model->facetnorms[3 * (i+1)]);
}
}
/* glmVertexNormals: Generates smooth vertex normals for a model.
* First builds a list of all the triangles each vertex is in. Then
* loops through each vertex in the the list averaging all the facet
* normals of the triangles each vertex is in. Finally, sets the
* normal index in the triangle for the vertex to the generated smooth
* normal. If the dot product of a facet normal and the facet normal
* associated with the first triangle in the list of triangles the
* current vertex is in is greater than the cosine of the angle
* parameter to the function, that facet normal is not added into the
* average normal calculation and the corresponding vertex is given
* the facet normal. This tends to preserve hard edges. The angle to
* use depends on the model, but 90 degrees is usually a good start.
*
* model - initialized GLMmodel structure
* angle - maximum angle (in degrees) to smooth across
*/
GLvoid
glmVertexNormals(GLMmodel* model, GLfloat angle)
{
GLMnode* node;
GLMnode* tail;
GLMnode** members;
GLfloat* normals;
GLuint numnormals;
GLfloat average[3];
GLfloat dot, cos_angle;
GLuint i, avg;
assert(model);
assert(model->facetnorms);
/* calculate the cosine of the angle (in degrees) */
cos_angle = cos(angle * M_PI / 180.0);
/* nuke any previous normals */
if (model->normals)
free(model->normals);
/* allocate space for new normals */
model->numnormals = model->numtriangles * 3; /* 3 normals per triangle */
model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1));
/* allocate a structure that will hold a linked list of triangle
indices for each vertex */
members = (GLMnode**)malloc(sizeof(GLMnode*) * (model->numvertices + 1));
for (i = 1; i <= model->numvertices; i++)
members[i] = NULL;
/* for every triangle, create a node for each vertex in it */
for (i = 0; i < model->numtriangles; i++) {
node = (GLMnode*)malloc(sizeof(GLMnode));
node->index = i;
node->next = members[T(i).vindices[0]];
members[T(i).vindices[0]] = node;
node = (GLMnode*)malloc(sizeof(GLMnode));
node->index = i;
node->next = members[T(i).vindices[1]];
members[T(i).vindices[1]] = node;
node = (GLMnode*)malloc(sizeof(GLMnode));
node->index = i;
node->next = members[T(i).vindices[2]];
members[T(i).vindices[2]] = node;
}
/* calculate the average normal for each vertex */
numnormals = 1;
for (i = 1; i <= model->numvertices; i++) {
/* calculate an average normal for this vertex by averaging the
facet normal of every triangle this vertex is in */
node = members[i];
//Change made in this file (I put this two lines in commentary)
//if (!node)
// fprintf(stderr, "glmVertexNormals(): vertex w/o a triangle\n");
average[0] = 0.0; average[1] = 0.0; average[2] = 0.0;
avg = 0;
while (node) {
/* only average if the dot product of the angle between the two
facet normals is greater than the cosine of the threshold
angle -- or, said another way, the angle between the two
facet normals is less than (or equal to) the threshold angle */
dot = glmDot(&model->facetnorms[3 * T(node->index).findex],
&model->facetnorms[3 * T(members[i]->index).findex]);
if (dot > cos_angle) {
node->averaged = GL_TRUE;
average[0] += model->facetnorms[3 * T(node->index).findex + 0];
average[1] += model->facetnorms[3 * T(node->index).findex + 1];
average[2] += model->facetnorms[3 * T(node->index).findex + 2];
avg = 1; /* we averaged at least one normal! */
} else {
node->averaged = GL_FALSE;
}
node = node->next;
}
if (avg) {
/* normalize the averaged normal */
glmNormalize(average);
/* add the normal to the vertex normals list */
model->normals[3 * numnormals + 0] = average[0];
model->normals[3 * numnormals + 1] = average[1];
model->normals[3 * numnormals + 2] = average[2];
avg = numnormals;
numnormals++;
}
/* set the normal of this vertex in each triangle it is in */
node = members[i];
while (node) {
if (node->averaged) {
/* if this node was averaged, use the average normal */
if (T(node->index).vindices[0] == i)
T(node->index).nindices[0] = avg;
else if (T(node->index).vindices[1] == i)
T(node->index).nindices[1] = avg;
else if (T(node->index).vindices[2] == i)
T(node->index).nindices[2] = avg;
} else {
/* if this node wasn't averaged, use the facet normal */
model->normals[3 * numnormals + 0] =
model->facetnorms[3 * T(node->index).findex + 0];
model->normals[3 * numnormals + 1] =
model->facetnorms[3 * T(node->index).findex + 1];
model->normals[3 * numnormals + 2] =
model->facetnorms[3 * T(node->index).findex + 2];
if (T(node->index).vindices[0] == i)
T(node->index).nindices[0] = numnormals;
else if (T(node->index).vindices[1] == i)
T(node->index).nindices[1] = numnormals;
else if (T(node->index).vindices[2] == i)
T(node->index).nindices[2] = numnormals;
numnormals++;
}
node = node->next;
}
}
model->numnormals = numnormals - 1;
/* free the member information */
for (i = 1; i <= model->numvertices; i++) {
node = members[i];
while (node) {
tail = node;
node = node->next;
free(tail);
}
}
free(members);
/* pack the normals array (we previously allocated the maximum
number of normals that could possibly be created (numtriangles *
3), so get rid of some of them (usually alot unless none of the
facet normals were averaged)) */
normals = model->normals;
model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1));
for (i = 1; i <= model->numnormals; i++) {
model->normals[3 * i + 0] = normals[3 * i + 0];
model->normals[3 * i + 1] = normals[3 * i + 1];
model->normals[3 * i + 2] = normals[3 * i + 2];
}
free(normals);
}
/* glmLinearTexture: Generates texture coordinates according to a
* linear projection of the texture map. It generates these by
* linearly mapping the vertices onto a square.
*
* model - pointer to initialized GLMmodel structure
*/
GLvoid
glmLinearTexture(GLMmodel* model)
{
GLMgroup *group;
GLfloat dimensions[3];
GLfloat x, y, scalefactor;
GLuint i;
assert(model);
if (model->texcoords)
free(model->texcoords);
model->numtexcoords = model->numvertices;
model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1));
glmDimensions(model, dimensions);
scalefactor = 2.0 /
glmAbs(glmMax(glmMax(dimensions[0], dimensions[1]), dimensions[2]));
/* do the calculations */
for(i = 1; i <= model->numvertices; i++) {
x = model->vertices[3 * i + 0] * scalefactor;
y = model->vertices[3 * i + 2] * scalefactor;
model->texcoords[2 * i + 0] = (x + 1.0) / 2.0;
model->texcoords[2 * i + 1] = (y + 1.0) / 2.0;
}
/* go through and put texture coordinate indices in all the triangles */
group = model->groups;
while(group) {
for(i = 0; i < group->numtriangles; i++) {
T(group->triangles[i]).tindices[0] = T(group->triangles[i]).vindices[0];
T(group->triangles[i]).tindices[1] = T(group->triangles[i]).vindices[1];
T(group->triangles[i]).tindices[2] = T(group->triangles[i]).vindices[2];
}
group = group->next;
}
#if 0
printf("glmLinearTexture(): generated %d linear texture coordinates\n",
model->numtexcoords);
#endif
}
/* glmSpheremapTexture: Generates texture coordinates according to a
* spherical projection of the texture map. Sometimes referred to as
* spheremap, or reflection map texture coordinates. It generates
* these by using the normal to calculate where that vertex would map
* onto a sphere. Since it is impossible to map something flat
* perfectly onto something spherical, there is distortion at the
* poles. This particular implementation causes the poles along the X
* axis to be distorted.
*
* model - pointer to initialized GLMmodel structure
*/
GLvoid
glmSpheremapTexture(GLMmodel* model)
{
GLMgroup* group;
GLfloat theta, phi, rho, x, y, z, r;
GLuint i;
assert(model);
assert(model->normals);
if (model->texcoords)
free(model->texcoords);
model->numtexcoords = model->numnormals;
model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1));
for (i = 1; i <= model->numnormals; i++) {
z = model->normals[3 * i + 0]; /* re-arrange for pole distortion */
y = model->normals[3 * i + 1];
x = model->normals[3 * i + 2];
r = sqrt((x * x) + (y * y));
rho = sqrt((r * r) + (z * z));
if(r == 0.0) {
theta = 0.0;
phi = 0.0;
} else {
if(z == 0.0)
phi = 3.14159265 / 2.0;
else
phi = acos(z / rho);
if(y == 0.0)
theta = 3.141592365 / 2.0;
else
theta = asin(y / r) + (3.14159265 / 2.0);
}
model->texcoords[2 * i + 0] = theta / 3.14159265;
model->texcoords[2 * i + 1] = phi / 3.14159265;
}
/* go through and put texcoord indices in all the triangles */
group = model->groups;
while(group) {
for (i = 0; i < group->numtriangles; i++) {
T(group->triangles[i]).tindices[0] = T(group->triangles[i]).nindices[0];
T(group->triangles[i]).tindices[1] = T(group->triangles[i]).nindices[1];
T(group->triangles[i]).tindices[2] = T(group->triangles[i]).nindices[2];
}
group = group->next;
}
}
/* glmDelete: Deletes a GLMmodel structure.
*
* model - initialized GLMmodel structure
*/
GLvoid
glmDelete(GLMmodel* model)
{
GLMgroup* group;
GLuint i;
assert(model);
if (model->pathname) free(model->pathname);
if (model->mtllibname) free(model->mtllibname);
if (model->vertices) free(model->vertices);
if (model->normals) free(model->normals);
if (model->texcoords) free(model->texcoords);
if (model->facetnorms) free(model->facetnorms);
if (model->triangles) free(model->triangles);
if (model->materials) {
for (i = 0; i < model->nummaterials; i++)
free(model->materials[i].name);
}
free(model->materials);
while(model->groups) {
group = model->groups;
model->groups = model->groups->next;
free(group->name);
free(group->triangles);
free(group);
}
free(model);
}
/* glmReadOBJ: Reads a model description from a Wavefront .OBJ file.
* Returns a pointer to the created object which should be free'd with
* glmDelete().
*
* filename - name of the file containing the Wavefront .OBJ format data.
*/
GLMmodel*
glmReadOBJ(char* filename)
{
GLMmodel* model;
FILE* file;
/* open the file */
file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "glmReadOBJ() failed: can't open data file \"%s\".\n",
filename);
exit(1);
}
/* allocate a new model */
model = (GLMmodel*)malloc(sizeof(GLMmodel));
model->pathname = strdup(filename);
model->mtllibname = NULL;
model->numvertices = 0;
model->vertices = NULL;
model->numnormals = 0;
model->normals = NULL;
model->numtexcoords = 0;
model->texcoords = NULL;
model->numfacetnorms = 0;
model->facetnorms = NULL;
model->numtriangles = 0;
model->triangles = NULL;
model->nummaterials = 0;
model->materials = NULL;
model->numgroups = 0;
model->groups = NULL;
model->position[0] = 0.0;
model->position[1] = 0.0;
model->position[2] = 0.0;
/* make a first pass through the file to get a count of the number
of vertices, normals, texcoords & triangles */
glmFirstPass(model, file);
/* allocate memory */
model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numvertices + 1));
model->triangles = (GLMtriangle*)malloc(sizeof(GLMtriangle) *
model->numtriangles);
if (model->numnormals) {
model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numnormals + 1));
}
if (model->numtexcoords) {
model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
2 * (model->numtexcoords + 1));
}
/* rewind to beginning of file and read in the data this pass */
rewind(file);
glmSecondPass(model, file);
/* close the file */
fclose(file);
return model;
}
/* glmWriteOBJ: Writes a model description in Wavefront .OBJ format to
* a file.
*
* model - initialized GLMmodel structure
* filename - name of the file to write the Wavefront .OBJ format data to
* mode - a bitwise or of values describing what is written to the file
* GLM_NONE - render with only vertices
* GLM_FLAT - render with facet normals
* GLM_SMOOTH - render with vertex normals
* GLM_TEXTURE - render with texture coords
* GLM_COLOR - render with colors (color material)
* GLM_MATERIAL - render with materials
* GLM_COLOR and GLM_MATERIAL should not both be specified.
* GLM_FLAT and GLM_SMOOTH should not both be specified.
*/
GLvoid
glmWriteOBJ(GLMmodel* model, char* filename, GLuint mode)
{
GLuint i;
FILE* file;
GLMgroup* group;
assert(model);
/* do a bit of warning */
if (mode & GLM_FLAT && !model->facetnorms) {
printf("glmWriteOBJ() warning: flat normal output requested "
"with no facet normals defined.\n");
mode &= ~GLM_FLAT;
}
if (mode & GLM_SMOOTH && !model->normals) {
printf("glmWriteOBJ() warning: smooth normal output requested "
"with no normals defined.\n");
mode &= ~GLM_SMOOTH;
}
if (mode & GLM_TEXTURE && !model->texcoords) {
printf("glmWriteOBJ() warning: texture coordinate output requested "
"with no texture coordinates defined.\n");
mode &= ~GLM_TEXTURE;
}
if (mode & GLM_FLAT && mode & GLM_SMOOTH) {
printf("glmWriteOBJ() warning: flat normal output requested "
"and smooth normal output requested (using smooth).\n");
mode &= ~GLM_FLAT;
}
if (mode & GLM_COLOR && !model->materials) {
printf("glmWriteOBJ() warning: color output requested "
"with no colors (materials) defined.\n");
mode &= ~GLM_COLOR;
}
if (mode & GLM_MATERIAL && !model->materials) {
printf("glmWriteOBJ() warning: material output requested "
"with no materials defined.\n");
mode &= ~GLM_MATERIAL;
}
if (mode & GLM_COLOR && mode & GLM_MATERIAL) {
printf("glmDraw() warning: color and material output requested "
"outputting only materials.\n");
mode &= ~GLM_COLOR;
}
/* open the file */
file = fopen(filename, "w");
if (!file) {
fprintf(stderr, "glmWriteOBJ() failed: can't open file \"%s\" to write.\n",
filename);
exit(1);
}
/* spit out a header */
fprintf(file, "# \n");
fprintf(file, "# Wavefront OBJ generated by GLM library\n");
fprintf(file, "# \n");
fprintf(file, "# GLM library\n");
fprintf(file, "# Nate Robins\n");
fprintf(file, "# [email protected]\n");
fprintf(file, "# http://www.pobox.com/~ndr\n");
fprintf(file, "# \n");
if (mode & GLM_MATERIAL && model->mtllibname) {
fprintf(file, "\nmtllib %s\n\n", model->mtllibname);
glmWriteMTL(model, filename, model->mtllibname);
}
/* spit out the vertices */
fprintf(file, "\n");
fprintf(file, "# %d vertices\n", model->numvertices);
for (i = 1; i <= model->numvertices; i++) {
fprintf(file, "v %f %f %f\n",
model->vertices[3 * i + 0],
model->vertices[3 * i + 1],
model->vertices[3 * i + 2]);
}
/* spit out the smooth/flat normals */
if (mode & GLM_SMOOTH) {
fprintf(file, "\n");
fprintf(file, "# %d normals\n", model->numnormals);
for (i = 1; i <= model->numnormals; i++) {
fprintf(file, "vn %f %f %f\n",
model->normals[3 * i + 0],
model->normals[3 * i + 1],
model->normals[3 * i + 2]);
}
} else if (mode & GLM_FLAT) {
fprintf(file, "\n");
fprintf(file, "# %d normals\n", model->numfacetnorms);
for (i = 1; i <= model->numnormals; i++) {
fprintf(file, "vn %f %f %f\n",
model->facetnorms[3 * i + 0],
model->facetnorms[3 * i + 1],
model->facetnorms[3 * i + 2]);
}
}
/* spit out the texture coordinates */
if (mode & GLM_TEXTURE) {
fprintf(file, "\n");
fprintf(file, "# %d texcoords\n", model->texcoords);
for (i = 1; i <= model->numtexcoords; i++) {
fprintf(file, "vt %f %f\n",
model->texcoords[2 * i + 0],
model->texcoords[2 * i + 1]);
}
}
fprintf(file, "\n");
fprintf(file, "# %d groups\n", model->numgroups);
fprintf(file, "# %d faces (triangles)\n", model->numtriangles);
fprintf(file, "\n");
group = model->groups;
while(group) {
fprintf(file, "g %s\n", group->name);
if (mode & GLM_MATERIAL)
fprintf(file, "usemtl %s\n", model->materials[group->material].name);
for (i = 0; i < group->numtriangles; i++) {
if (mode & GLM_SMOOTH && mode & GLM_TEXTURE) {
fprintf(file, "f %d/%d/%d %d/%d/%d %d/%d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).nindices[0],
T(group->triangles[i]).tindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).nindices[1],
T(group->triangles[i]).tindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).nindices[2],
T(group->triangles[i]).tindices[2]);
} else if (mode & GLM_FLAT && mode & GLM_TEXTURE) {
fprintf(file, "f %d/%d %d/%d %d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).findex);
} else if (mode & GLM_TEXTURE) {
fprintf(file, "f %d/%d %d/%d %d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).tindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).tindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).tindices[2]);
} else if (mode & GLM_SMOOTH) {
fprintf(file, "f %d//%d %d//%d %d//%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).nindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).nindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).nindices[2]);
} else if (mode & GLM_FLAT) {
fprintf(file, "f %d//%d %d//%d %d//%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).findex);
} else {
fprintf(file, "f %d %d %d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).vindices[2]);
}
}
fprintf(file, "\n");
group = group->next;
}
fclose(file);
}
/* glmDraw: Renders the model to the current OpenGL context using the
* mode specified.
*
* model - initialized GLMmodel structure
* mode - a bitwise OR of values describing what is to be rendered.
* GLM_NONE - render with only vertices
* GLM_FLAT - render with facet normals
* GLM_SMOOTH - render with vertex normals
* GLM_TEXTURE - render with texture coords
* GLM_COLOR - render with colors (color material)
* GLM_MATERIAL - render with materials
* GLM_COLOR and GLM_MATERIAL should not both be specified.
* GLM_FLAT and GLM_SMOOTH should not both be specified.
*/
GLvoid
glmDraw(GLMmodel* model, GLuint mode)
{
static GLuint i;
static GLMgroup* group;
static GLMtriangle* triangle;
static GLMmaterial* material;
assert(model);
assert(model->vertices);
/* do a bit of warning */
if (mode & GLM_FLAT && !model->facetnorms) {
printf("glmDraw() warning: flat render mode requested "
"with no facet normals defined.\n");
mode &= ~GLM_FLAT;
}
if (mode & GLM_SMOOTH && !model->normals) {
printf("glmDraw() warning: smooth render mode requested "
"with no normals defined.\n");
mode &= ~GLM_SMOOTH;
}
if (mode & GLM_TEXTURE && !model->texcoords) {
printf("glmDraw() warning: texture render mode requested "
"with no texture coordinates defined.\n");
mode &= ~GLM_TEXTURE;
}
if (mode & GLM_FLAT && mode & GLM_SMOOTH) {
printf("glmDraw() warning: flat render mode requested "
"and smooth render mode requested (using smooth).\n");
mode &= ~GLM_FLAT;
}
if (mode & GLM_COLOR && !model->materials) {
printf("glmDraw() warning: color render mode requested "
"with no materials defined.\n");
mode &= ~GLM_COLOR;
}
if (mode & GLM_MATERIAL && !model->materials) {
printf("glmDraw() warning: material render mode requested "
"with no materials defined.\n");
mode &= ~GLM_MATERIAL;
}
if (mode & GLM_COLOR && mode & GLM_MATERIAL) {
printf("glmDraw() warning: color and material render mode requested "
"using only material mode.\n");
mode &= ~GLM_COLOR;
}
if (mode & GLM_COLOR)
glEnable(GL_COLOR_MATERIAL);
else if (mode & GLM_MATERIAL)
glDisable(GL_COLOR_MATERIAL);
/* perhaps this loop should be unrolled into material, color, flat,
smooth, etc. loops? since most cpu's have good branch prediction
schemes (and these branches will always go one way), probably
wouldn't gain too much? */
group = model->groups;
while (group) {
if (mode & GLM_MATERIAL) {
material = &model->materials[group->material];
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, material->ambient);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material->diffuse);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material->specular);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, material->shininess);
}
if (mode & GLM_COLOR) {
material = &model->materials[group->material];
glColor3fv(material->diffuse);
}
glBegin(GL_TRIANGLES);
for (i = 0; i < group->numtriangles; i++) {
triangle = &T(group->triangles[i]);
if (mode & GLM_FLAT)
glNormal3fv(&model->facetnorms[3 * triangle->findex]);
if (mode & GLM_SMOOTH)
glNormal3fv(&model->normals[3 * triangle->nindices[0]]);
if (mode & GLM_TEXTURE)
glTexCoord2fv(&model->texcoords[2 * triangle->tindices[0]]);
glVertex3fv(&model->vertices[3 * triangle->vindices[0]]);
if (mode & GLM_SMOOTH)
glNormal3fv(&model->normals[3 * triangle->nindices[1]]);
if (mode & GLM_TEXTURE)
glTexCoord2fv(&model->texcoords[2 * triangle->tindices[1]]);
glVertex3fv(&model->vertices[3 * triangle->vindices[1]]);
if (mode & GLM_SMOOTH)
glNormal3fv(&model->normals[3 * triangle->nindices[2]]);
if (mode & GLM_TEXTURE)
glTexCoord2fv(&model->texcoords[2 * triangle->tindices[2]]);
glVertex3fv(&model->vertices[3 * triangle->vindices[2]]);
}
glEnd();
group = group->next;
}
}
/* glmList: Generates and returns a display list for the model using
* the mode specified.
*
* model - initialized GLMmodel structure
* mode - a bitwise OR of values describing what is to be rendered.
* GLM_NONE - render with only vertices
* GLM_FLAT - render with facet normals
* GLM_SMOOTH - render with vertex normals
* GLM_TEXTURE - render with texture coords
* GLM_COLOR - render with colors (color material)
* GLM_MATERIAL - render with materials
* GLM_COLOR and GLM_MATERIAL should not both be specified.
* GLM_FLAT and GLM_SMOOTH should not both be specified. */
GLuint
glmList(GLMmodel* model, GLuint mode)
{
GLuint list;
list = glGenLists(1);
glNewList(list, GL_COMPILE);
glmDraw(model, mode);
glEndList();
return list;
}
/* glmWeld: eliminate (weld) vectors that are within an epsilon of
* each other.
*
* model - initialized GLMmodel structure
* epsilon - maximum difference between vertices
* ( 0.00001 is a good start for a unitized model)
*
*/
GLuint
glmWeld(GLMmodel* model, GLfloat epsilon)
{
GLfloat* vectors;
GLfloat* copies;
GLuint numvectors;
GLuint i, welded;
/* vertices */
numvectors = model->numvertices;
vectors = model->vertices;
copies = glmWeldVectors(vectors, &numvectors, epsilon);
welded = model->numvertices - numvectors - 1;
for (i = 0; i < model->numtriangles; i++) {
T(i).vindices[0] = (GLuint)vectors[3 * T(i).vindices[0] + 0];
T(i).vindices[1] = (GLuint)vectors[3 * T(i).vindices[1] + 0];
T(i).vindices[2] = (GLuint)vectors[3 * T(i).vindices[2] + 0];
}
/* free space for old vertices */
free(vectors);
/* allocate space for the new vertices */
model->numvertices = numvectors;
model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numvertices + 1));
/* copy the optimized vertices into the actual vertex list */
for (i = 1; i <= model->numvertices; i++) {
model->vertices[3 * i + 0] = copies[3 * i + 0];
model->vertices[3 * i + 1] = copies[3 * i + 1];
model->vertices[3 * i + 2] = copies[3 * i + 2];
}
free(copies);
return welded;
}
#if 0
/* normals */
if (model->numnormals) {
numvectors = model->numnormals;
vectors = model->normals;
copies = glmOptimizeVectors(vectors, &numvectors);
printf("glmOptimize(): %d redundant normals.\n",
model->numnormals - numvectors);
for (i = 0; i < model->numtriangles; i++) {
T(i).nindices[0] = (GLuint)vectors[3 * T(i).nindices[0] + 0];
T(i).nindices[1] = (GLuint)vectors[3 * T(i).nindices[1] + 0];
T(i).nindices[2] = (GLuint)vectors[3 * T(i).nindices[2] + 0];
}
/* free space for old normals */
free(vectors);
/* allocate space for the new normals */
model->numnormals = numvectors;
model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numnormals + 1));
/* copy the optimized vertices into the actual vertex list */
for (i = 1; i <= model->numnormals; i++) {
model->normals[3 * i + 0] = copies[3 * i + 0];
model->normals[3 * i + 1] = copies[3 * i + 1];
model->normals[3 * i + 2] = copies[3 * i + 2];
}
free(copies);
}
/* texcoords */
if (model->numtexcoords) {
numvectors = model->numtexcoords;
vectors = model->texcoords;
copies = glmOptimizeVectors(vectors, &numvectors);
printf("glmOptimize(): %d redundant texcoords.\n",
model->numtexcoords - numvectors);
for (i = 0; i < model->numtriangles; i++) {
for (j = 0; j < 3; j++) {
T(i).tindices[j] = (GLuint)vectors[3 * T(i).tindices[j] + 0];
}
}
/* free space for old texcoords */
free(vectors);
/* allocate space for the new texcoords */
model->numtexcoords = numvectors;
model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
2 * (model->numtexcoords + 1));
/* copy the optimized vertices into the actual vertex list */
for (i = 1; i <= model->numtexcoords; i++) {
model->texcoords[2 * i + 0] = copies[2 * i + 0];
model->texcoords[2 * i + 1] = copies[2 * i + 1];
}
free(copies);
}
#endif
#if 0
/* look for unused vertices */
/* look for unused normals */
/* look for unused texcoords */
for (i = 1; i <= model->numvertices; i++) {
for (j = 0; j < model->numtriangles; i++) {
if (T(j).vindices[0] == i ||
T(j).vindices[1] == i ||
T(j).vindices[1] == i)
break;
}
}
#endif
| [
"emanspace@db629c75-4b32-85d7-0afe-a27431d4d09a"
]
| [
[
[
1,
1845
]
]
]
|
bc3120f220863613d159d7006f1d301243beb898 | 723202e673511cf9f243177d964dfeba51cb06a3 | /10/oot_Mozg/INC/SlavePlayer.h | 1560f867984a93dd419caee410cbcca39f6d9e91 | []
| no_license | aeremenok/a-team-777 | c2ffe04b408a266f62c523fb8d68c87689f2a2e9 | 0945efbe00c3695c9cc3dbcdb9177ff6f1e9f50b | refs/heads/master | 2020-12-24T16:50:12.178873 | 2009-06-16T14:55:41 | 2009-06-16T14:55:41 | 32,388,114 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 755 | h | // **************************************************************************
//! \file SlavePlayer.h
//! \brief Класс реализующий ведомого игрока
//! \author Bessonov A.V.
//! \date 17.May.2008 - 17.May.2008
// **************************************************************************
#ifndef __SLAVEPLAYER_H
#define __SLAVEPLAYER_H
#include <string>
#include "Player.h"
// ==========================================================================
namespace Game
{
class SlavePlayer : public Player
{
public:
bool ifMain () const; //!< Возвращает false
};
}//end of namespace Game
// ==========================================================================
#endif
| [
"scorpion1105@9273621a-9230-0410-b1c6-9ffd80c20a0c"
]
| [
[
[
1,
26
]
]
]
|
e9e311b4fa1e247dca549a3621e0ba5b8a1d44e3 | 6253ab92ce2e85b4db9393aa630bde24655bd9b4 | /Common/time/car_timestamp_sender.h | 5cabe29c3bb937e43404edf3b77811f58541b556 | []
| no_license | Aand1/cornell-urban-challenge | 94fd4df18fd4b6cc6e12d30ed8eed280826d4aed | 779daae8703fe68e7c6256932883de32a309a119 | refs/heads/master | 2021-01-18T11:57:48.267384 | 2008-10-01T06:43:18 | 2008-10-01T06:43:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | h | #ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifdef __cplusplus_cli
#pragma managed(push,off)
#endif
#include <winsock2.h>
#include <windows.h>
#include <Mmsystem.h>
#include <exception>
using namespace std;
#include "../coords/dpvector2.h"
#include "../coords/dpmatrix2.h"
#include "timestamp.h"
#include "car_timestamp.h"
#ifndef _CAR_TIMESTAMP_SENDER_H
#define _CAR_TIMESTAMP_SENDER_H
_MM_ALIGN16 class car_timestamp_sender {
private:
const static double sigma_b;
const static double sigma_d;
const static double r;
WSADATA wsadata;
bool wsa_init;
SOCKET sock;
HANDLE thread;
bool running;
bool init_wsa();
bool init_socket();
bool init_thread();
void cleanup_wsa();
void cleanup_socket();
void cleanup_thread();
static DWORD WINAPI send_thread(LPVOID lpparam);
public:
car_timestamp_sender();
~car_timestamp_sender();
};
#ifdef __cplusplus_cli
#pragma managed(pop)
#endif
#endif | [
"anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5"
]
| [
[
[
1,
61
]
]
]
|
be88dae50a67176adebf880946765df7b848f51e | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Scada/SysCADMarshal/SysCADMarshalView.h | b360b68793957112ac8cd743a86b11138ff3ad47 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,948 | h | // SysCADMarshalView.h : interface of the CSysCADMarshalView class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_SYSCADMARSHALVIEW_H__4E5472AC_B358_48BD_85D7_09527AAE6600__INCLUDED_)
#define AFX_SYSCADMARSHALVIEW_H__4E5472AC_B358_48BD_85D7_09527AAE6600__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CSysCADMarshalView : public CView
{
protected: // create from serialization only
CSysCADMarshalView();
DECLARE_DYNCREATE(CSysCADMarshalView)
// Attributes
public:
CSysCADMarshalDoc* GetDocument();
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSysCADMarshalView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CSysCADMarshalView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CSysCADMarshalView)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in SysCADMarshalView.cpp
inline CSysCADMarshalDoc* CSysCADMarshalView::GetDocument()
{ return (CSysCADMarshalDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SYSCADMARSHALVIEW_H__4E5472AC_B358_48BD_85D7_09527AAE6600__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
65
]
]
]
|
b377948a0319ff0f7d57411c7125922155294966 | b67d58bd5bfe13b32bebe83dec22904243a52223 | /FlashDBSimDll_Sample/BufferManagerGroup.cpp | 009fa90fd74789910afeb0a231bd4f90ae001c73 | []
| no_license | maheshdharhari/flash-sim | b8929efc83a65ee6d5e782b835106ca36228c6c8 | d04eb0e34bb44e7356f5c1b0e1f1af6097339225 | refs/heads/master | 2021-01-10T07:48:37.820361 | 2010-05-22T09:19:20 | 2010-05-22T09:19:20 | 43,440,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,648 | cpp | #pragma managed(off)
#include "StdAfx.h"
#include "BufferManagerGroup.h"
#include "IBufferManager.h"
#include "IBlockDevice.h"
using namespace std;
using namespace std::tr1;
void BufferManagerGroup::Add(shared_ptr<IBufferManager> pbuf)
{
mgrs_.push_back(pbuf);
}
void BufferManagerGroup::Read(size_t pageid, void *result)
{
MgrsType::iterator it, itend = mgrs_.end();
for (it=mgrs_.begin(); it!=itend; ++it)
(*it)->Read(pageid, result);
}
void BufferManagerGroup::Write(size_t pageid, const void *data)
{
MgrsType::iterator it, itend = mgrs_.end();
for (it=mgrs_.begin(); it!=itend; ++it)
(*it)->Write(pageid, data);
}
void BufferManagerGroup::Flush()
{
MgrsType::iterator it, itend = mgrs_.end();
for (it=mgrs_.begin(); it!=itend; ++it)
(*it)->Flush();
}
int BufferManagerGroup::GetMgrCount() const
{
return mgrs_.size();
}
int BufferManagerGroup::GetReadCount() const
{
return mgrs_[0]->GetReadCount();
}
int BufferManagerGroup::GetWriteCount() const
{
return mgrs_[0]->GetWriteCount();
}
int BufferManagerGroup::GetDevReadCount(size_t index) const
{
return mgrs_[index]->GetDevice()->GetReadCount();
}
int BufferManagerGroup::GetDevWriteCount(size_t index) const
{
return mgrs_[index]->GetDevice()->GetWriteCount();
}
int BufferManagerGroup::GetDevCost(size_t index) const
{
return mgrs_[index]->GetDevice()->GetTotalCost();
}
std::tr1::shared_ptr<IBlockDevice> BufferManagerGroup::GetDevice()
{
throw logic_error("No device");
}
std::tr1::shared_ptr<const IBlockDevice> BufferManagerGroup::GetDevice() const
{
throw logic_error("No device");
}
| [
"hiYoungCat@9895585c-9ddb-11de-bf4a-bd5be0e2b6d7"
]
| [
[
[
1,
70
]
]
]
|
fdbc9e82e6d688b7f33291dc28ff336fc37a8c59 | 0f40e36dc65b58cc3c04022cf215c77ae31965a8 | /src/apps/wiseml/examples/wiseml_example_processor_factory.cpp | 45bcf6abc3d483544a4f3f371e4f0b8cfaf65e75 | [
"MIT",
"BSD-3-Clause"
]
| permissive | venkatarajasekhar/shawn-1 | 08e6cd4cf9f39a8962c1514aa17b294565e849f8 | d36c90dd88f8460e89731c873bb71fb97da85e82 | refs/heads/master | 2020-06-26T18:19:01.247491 | 2010-10-26T17:40:48 | 2010-10-26T17:40:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,381 | cpp | /************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004-2010 by the SwarmNet (www.swarmnet.de) project **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the BSD License. Refer to the shawn-licence.txt **
** file in the root of the Shawn source tree for further details. **
************************************************************************/
#include "_apps_enable_cmake.h"
#ifdef ENABLE_WISEML
#ifdef ENABLE_EXAMPLES
#include "apps/wiseml/examples/wiseml_example_processor_factory.h"
#include "apps/wiseml/examples/wiseml_example_processor.h"
#include "sys/processors/processor_keeper.h"
#include "sys/simulation/simulation_controller.h"
#include <iostream>
using namespace std;
using namespace shawn;
namespace wiseml
{
// ----------------------------------------------------------------------
void
WisemlExampleProcessorFactory::
register_factory( SimulationController& sc )
throw()
{
sc.processor_keeper_w().add( new WisemlExampleProcessorFactory );
}
// ----------------------------------------------------------------------
WisemlExampleProcessorFactory::
WisemlExampleProcessorFactory()
{
//cout << "WisemlExampleProcessorFactory ctor" << &auto_reg_ << endl;
}
// ----------------------------------------------------------------------
WisemlExampleProcessorFactory::
~WisemlExampleProcessorFactory()
{
//cout << "WisemlExampleProcessorFactory dtor" << endl;
}
// ----------------------------------------------------------------------
std::string
WisemlExampleProcessorFactory::
name( void )
const throw()
{
return "wiseml_example";
}
// ----------------------------------------------------------------------
std::string
WisemlExampleProcessorFactory::
description( void )
const throw()
{
return "WiseML sensor demo processor";
}
// ----------------------------------------------------------------------
shawn::Processor*
WisemlExampleProcessorFactory::
create( void )
throw()
{
return new WisemlExampleProcessor;
}
}
#endif
#endif
| [
"[email protected]"
]
| [
[
[
1,
77
]
]
]
|
020be381d6931d503f93397949c2d24b61f6a26f | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/gil/test/performance.cpp | b50f8fefefe8768e947195421580d4d71642cbe4 | [
"BSL-1.0"
]
| permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,627 | cpp | /*
Copyright 2005-2007 Adobe Systems Incorporated
Use, modification and distribution are 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).
See http://opensource.adobe.com/gil for most recent version including documentation.
*/
/*************************************************************************************************/
/// \file
/// \brief GIL performance test suite
/// \date 2007 \n Last updated on February 12, 2007
///
/// Available tests:
/// fill_pixels() on rgb8_image_t with rgb8_pixel_t
/// fill_pixels() on rgb8_planar_image_t with rgb8_pixel_t
/// fill_pixels() on rgb8_image_t with bgr8_pixel_t
/// fill_pixels() on rgb8_planar_image_t with bgr8_pixel_t
/// for_each_pixel() on rgb8_image_t
/// for_each_pixel() on rgb8_planar_t
/// copy_pixels() between rgb8_image_t and rgb8_image_t
/// copy_pixels() between rgb8_image_t and bgr8_image_t
/// copy_pixels() between rgb8_planar_image_t and rgb8_planar_image_t
/// copy_pixels() between rgb8_image_t and rgb8_planar_image_t
/// copy_pixels() between rgb8_planar_image_t and rgb8_image_t
/// transform_pixels() between rgb8_image_t and rgb8_image_t
/// transform_pixels() between rgb8_planar_image_t and rgb8_planar_image_t
/// transform_pixels() between rgb8_planar_image_t and rgb8_image_t
/// transform_pixels() between rgb8_image_t and rgb8_planar_image_t
#include <cstddef>
#include <ctime>
#include <iostream>
#include <boost/gil/pixel.hpp>
#include <boost/gil/planar_pixel_iterator.hpp>
#include <boost/gil/planar_pixel_reference.hpp>
#include <boost/gil/iterator_from_2d.hpp>
#include <boost/gil/step_iterator.hpp>
#include <boost/gil/rgb.hpp>
#include <boost/gil/image_view.hpp>
#include <boost/gil/image.hpp>
#include <boost/gil/typedefs.hpp>
#include <boost/gil/algorithm.hpp>
using namespace boost::gil;
// returns time in milliseconds per call
template <typename Op>
double measure_time(Op op, std::size_t num_loops) {
clock_t begin=clock();
for (std::size_t ii=0; ii<num_loops; ++ii) op();
return double(clock()-begin)/double(num_loops);
}
// image dimension
std::size_t width=1000, height=400;
// macros for standard GIL views
#define RGB_VIEW(T) image_view<memory_based_2d_locator<memory_based_step_iterator<pixel<T,rgb_layout_t>*> > >
#define BGR_VIEW(T) image_view<memory_based_2d_locator<memory_based_step_iterator<pixel<T,bgr_layout_t>*> > >
#define RGB_PLANAR_VIEW(T) image_view<memory_based_2d_locator<memory_based_step_iterator<planar_pixel_iterator<T*,rgb_t> > > >
template <typename View, typename P>
struct fill_gil_t {
View _v;
P _p;
fill_gil_t(const View& v_in,const P& p_in) : _v(v_in), _p(p_in) {}
void operator()() const {fill_pixels(_v,_p);}
};
template <typename View, typename P> struct fill_nongil_t;
template <typename T, typename P>
struct fill_nongil_t<RGB_VIEW(T), P> {
typedef RGB_VIEW(T) View;
View _v;
P _p;
fill_nongil_t(const View& v_in,const P& p_in) : _v(v_in), _p(p_in) {}
void operator()() const {
T* first=(T*)_v.row_begin(0);
T* last=first+_v.size()*3;
while(first!=last) {
first[0]=at_c<0>(_p);
first[1]=at_c<1>(_p);
first[2]=at_c<2>(_p);
first+=3;
}
}
};
template <typename T1, typename T2>
struct fill_nongil_t<RGB_VIEW(T1), pixel<T2,bgr_layout_t> > {
typedef RGB_VIEW(T1) View;
typedef pixel<T2,bgr_layout_t> P;
View _v;
P _p;
fill_nongil_t(const View& v_in,const P& p_in) : _v(v_in), _p(p_in) {}
void operator()() const {
T1* first=(T1*)_v.row_begin(0);
T1* last=first+_v.size()*3;
while(first!=last) {
first[0]=at_c<2>(_p);
first[1]=at_c<1>(_p);
first[2]=at_c<0>(_p);
first+=3;
}
}
};
template <typename T1, typename T2>
struct fill_nongil_t<RGB_PLANAR_VIEW(T1), pixel<T2,rgb_layout_t> > {
typedef RGB_PLANAR_VIEW(T1) View;
typedef pixel<T2,rgb_layout_t> P;
View _v;
P _p;
fill_nongil_t(const View& v_in,const P& p_in) : _v(v_in), _p(p_in) {}
void operator()() const {
std::size_t size=_v.size();
T1* first;
first=(T1*)at_c<0>(_v.row_begin(0));
std::fill(first,first+size,at_c<0>(_p));
first=(T1*)at_c<1>(_v.row_begin(0));
std::fill(first,first+size,at_c<1>(_p));
first=(T1*)at_c<2>(_v.row_begin(0));
std::fill(first,first+size,at_c<2>(_p));
}
};
template <typename T1, typename T2>
struct fill_nongil_t<RGB_PLANAR_VIEW(T1), pixel<T2,bgr_layout_t> > {
typedef RGB_PLANAR_VIEW(T1) View;
typedef pixel<T2,bgr_layout_t> P;
View _v;
P _p;
fill_nongil_t(const View& v_in,const P& p_in) : _v(v_in), _p(p_in) {}
void operator()() const {
std::size_t size=_v.size();
T1* first;
first=(T1*)at_c<0>(_v.row_begin(0));
std::fill(first,first+size,at_c<2>(_p));
first=(T1*)at_c<1>(_v.row_begin(0));
std::fill(first,first+size,at_c<1>(_p));
first=(T1*)at_c<2>(_v.row_begin(0));
std::fill(first,first+size,at_c<1>(_p));
}
};
template <typename View, typename P>
void test_fill(std::size_t trials) {
image<typename View::value_type, is_planar<View>::value> im(width,height);
std::cout << "GIL: "<< measure_time(fill_gil_t<View,P>(view(im),P()),trials) << std::endl;
std::cout << "Non-GIL: "<< measure_time(fill_nongil_t<View,P>(view(im),P()),trials) << std::endl;
};
template <typename T>
struct rgb_fr_t {
void operator()(pixel<T,rgb_layout_t>& p) const {p[0]=0;p[1]=1;p[2]=2;}
void operator()(const planar_pixel_reference<T&,rgb_t>& p) const {p[0]=0;p[1]=1;p[2]=2;}
};
template <typename View, typename F>
struct for_each_gil_t {
View _v;
F _f;
for_each_gil_t(const View& v_in,const F& f_in) : _v(v_in), _f(f_in) {}
void operator()() const {for_each_pixel(_v,_f);}
};
template <typename View, typename F> struct for_each_nongil_t;
template <typename T, typename T2>
struct for_each_nongil_t<RGB_VIEW(T), rgb_fr_t<T2> > {
typedef RGB_VIEW(T) View;
typedef rgb_fr_t<T2> F;
View _v;
F _f;
for_each_nongil_t(const View& v_in,const F& f_in) : _v(v_in), _f(f_in) {}
void operator()() const {
T* first=(T*)_v.row_begin(0);
T* last=first+_v.size()*3;
while(first!=last) {
first[0]=0;
first[1]=1;
first[2]=2;
first+=3;
}
}
};
template <typename T1, typename T2>
struct for_each_nongil_t<RGB_PLANAR_VIEW(T1), rgb_fr_t<T2> > {
typedef RGB_PLANAR_VIEW(T1) View;
typedef rgb_fr_t<T2> F;
View _v;
F _f;
for_each_nongil_t(const View& v_in,const F& f_in) : _v(v_in), _f(f_in) {}
void operator()() const {
T1 *first0, *first1, *first2, *last0;
first0=(T1*)at_c<0>(_v.row_begin(0));
first1=(T1*)at_c<1>(_v.row_begin(0));
first2=(T1*)at_c<2>(_v.row_begin(0));
last0=first0+_v.size();
while(first0!=last0) {
*first0++=0;
*first1++=1;
*first2++=2;
}
}
};
template <typename View, typename F>
void test_for_each(std::size_t trials) {
image<typename View::value_type, is_planar<View>::value> im(width,height);
std::cout << "GIL: "<<measure_time(for_each_gil_t<View,F>(view(im),F()),trials) << std::endl;
std::cout << "Non-GIL: "<<measure_time(for_each_nongil_t<View,F>(view(im),F()),trials) << std::endl;
}
// copy
template <typename View1, typename View2>
struct copy_gil_t {
View1 _v1;
View2 _v2;
copy_gil_t(const View1& v1_in,const View2& v2_in) : _v1(v1_in), _v2(v2_in) {}
void operator()() const {copy_pixels(_v1,_v2);}
};
template <typename View1, typename View2> struct copy_nongil_t;
template <typename T1, typename T2>
struct copy_nongil_t<RGB_VIEW(T1),RGB_VIEW(T2)> {
typedef RGB_VIEW(T1) View1;
typedef RGB_VIEW(T2) View2;
View1 _v1;
View2 _v2;
copy_nongil_t(const View1& v1_in,const View2& v2_in) : _v1(v1_in), _v2(v2_in) {}
void operator()() const {
T1* first1=(T1*)_v1.row_begin(0);
T1* last1=first1+_v1.size()*3;
T2* first2=(T2*)_v2.row_begin(0);
std::copy(first1,last1,first2);
}
};
template <typename T1, typename T2>
struct copy_nongil_t<RGB_VIEW(T1),BGR_VIEW(T2)> {
typedef RGB_VIEW(T1) View1;
typedef BGR_VIEW(T2) View2;
View1 _v1;
View2 _v2;
copy_nongil_t(const View1& v1_in,const View2& v2_in) : _v1(v1_in), _v2(v2_in) {}
void operator()() const {
T1* first1=(T1*)_v1.row_begin(0);
T1* last1=first1+_v1.size()*3;
T2* first2=(T2*)_v2.row_begin(0);
while(first1!=last1) {
first2[2]=first1[0];
first2[1]=first1[1];
first2[0]=first1[2];
first1+=3; first2+=3;
}
}
};
template <typename T1, typename T2>
struct copy_nongil_t<RGB_PLANAR_VIEW(T1),RGB_PLANAR_VIEW(T2)> {
typedef RGB_PLANAR_VIEW(T1) View1;
typedef RGB_PLANAR_VIEW(T2) View2;
View1 _v1;
View2 _v2;
copy_nongil_t(const View1& v1_in,const View2& v2_in) : _v1(v1_in), _v2(v2_in) {}
void operator()() const {
std::size_t size=_v1.size();
T1* first10=(T1*)at_c<0>(_v1.row_begin(0));
T1* first11=(T1*)at_c<1>(_v1.row_begin(0));
T1* first12=(T1*)at_c<2>(_v1.row_begin(0));
T2* first20=(T2*)at_c<0>(_v2.row_begin(0));
T2* first21=(T2*)at_c<1>(_v2.row_begin(0));
T2* first22=(T2*)at_c<2>(_v2.row_begin(0));
std::copy(first10,first10+size,first20);
std::copy(first11,first11+size,first21);
std::copy(first12,first12+size,first22);
}
};
template <typename T1, typename T2>
struct copy_nongil_t<RGB_VIEW(T1),RGB_PLANAR_VIEW(T2)> {
typedef RGB_VIEW(T1) View1;
typedef RGB_PLANAR_VIEW(T2) View2;
View1 _v1;
View2 _v2;
copy_nongil_t(const View1& v1_in,const View2& v2_in) : _v1(v1_in), _v2(v2_in) {}
void operator()() const {
T1* first=(T1*)_v1.row_begin(0);
T1* last=first+_v1.size()*3;
T2* first0=(T2*)at_c<0>(_v2.row_begin(0));
T2* first1=(T2*)at_c<1>(_v2.row_begin(0));
T2* first2=(T2*)at_c<2>(_v2.row_begin(0));
while(first!=last) {
*first0++=first[0];
*first1++=first[1];
*first2++=first[2];
first+=3;
}
}
};
template <typename T1, typename T2>
struct copy_nongil_t<RGB_PLANAR_VIEW(T1),RGB_VIEW(T2)> {
typedef RGB_PLANAR_VIEW(T1) View1;
typedef RGB_VIEW(T2) View2;
View1 _v1;
View2 _v2;
copy_nongil_t(const View1& v1_in,const View2& v2_in) : _v1(v1_in), _v2(v2_in) {}
void operator()() const {
T1* first=(T1*)_v2.row_begin(0);
T1* last=first+_v2.size()*3;
T2* first0=(T2*)at_c<0>(_v1.row_begin(0));
T2* first1=(T2*)at_c<1>(_v1.row_begin(0));
T2* first2=(T2*)at_c<2>(_v1.row_begin(0));
while(first!=last) {
first[0]=*first0++;
first[1]=*first1++;
first[2]=*first2++;
first+=3;
}
}
};
template <typename View1, typename View2>
void test_copy(std::size_t trials) {
image<typename View1::value_type, is_planar<View1>::value> im1(width,height);
image<typename View2::value_type, is_planar<View2>::value> im2(width,height);
std::cout << "GIL: " <<measure_time(copy_gil_t<View1,View2>(view(im1),view(im2)),trials) << std::endl;
std::cout << "Non-GIL: "<<measure_time(copy_nongil_t<View1,View2>(view(im1),view(im2)),trials) << std::endl;
}
// transform()
template <typename T,typename Pixel>
struct bgr_to_rgb_t {
pixel<T,rgb_layout_t> operator()(const Pixel& p) const {
return pixel<T,rgb_layout_t>(T(get_color(p,blue_t())*0.1f),
T(get_color(p,green_t())*0.2f),
T(get_color(p,red_t())*0.3f));
}
};
template <typename View1, typename View2, typename F>
struct transform_gil_t {
View1 _v1;
View2 _v2;
F _f;
transform_gil_t(const View1& v1_in,const View2& v2_in,const F& f_in) : _v1(v1_in),_v2(v2_in),_f(f_in) {}
void operator()() const {transform_pixels(_v1,_v2,_f);}
};
template <typename View1, typename View2, typename F> struct transform_nongil_t;
template <typename T1, typename T2, typename F>
struct transform_nongil_t<RGB_VIEW(T1),RGB_VIEW(T2),F> {
typedef RGB_VIEW(T1) View1;
typedef RGB_VIEW(T2) View2;
View1 _v1;
View2 _v2;
F _f;
transform_nongil_t(const View1& v1_in,const View2& v2_in,const F& f_in) : _v1(v1_in),_v2(v2_in),_f(f_in) {}
void operator()() const {
T1* first1=(T1*)_v1.row_begin(0);
T2* first2=(T1*)_v2.row_begin(0);
T1* last1=first1+_v1.size()*3;
while(first1!=last1) {
first2[0]=T2(first1[2]*0.1f);
first2[1]=T2(first1[1]*0.2f);
first2[2]=T2(first1[0]*0.3f);
first1+=3; first2+=3;
}
}
};
template <typename T1, typename T2, typename F>
struct transform_nongil_t<RGB_PLANAR_VIEW(T1),RGB_PLANAR_VIEW(T2),F> {
typedef RGB_PLANAR_VIEW(T1) View1;
typedef RGB_PLANAR_VIEW(T2) View2;
View1 _v1;
View2 _v2;
F _f;
transform_nongil_t(const View1& v1_in,const View2& v2_in,const F& f_in) : _v1(v1_in),_v2(v2_in),_f(f_in) {}
void operator()() const {
T1* first10=(T1*)at_c<0>(_v1.row_begin(0));
T1* first11=(T1*)at_c<1>(_v1.row_begin(0));
T1* first12=(T1*)at_c<2>(_v1.row_begin(0));
T1* first20=(T2*)at_c<0>(_v2.row_begin(0));
T1* first21=(T2*)at_c<1>(_v2.row_begin(0));
T1* first22=(T2*)at_c<2>(_v2.row_begin(0));
T1* last10=first10+_v1.size();
while(first10!=last10) {
*first20++=T2(*first12++*0.1f);
*first21++=T2(*first11++*0.2f);
*first22++=T2(*first10++*0.3f);
}
}
};
template <typename T1, typename T2, typename F>
struct transform_nongil_t<RGB_VIEW(T1),RGB_PLANAR_VIEW(T2),F> {
typedef RGB_VIEW(T1) View1;
typedef RGB_PLANAR_VIEW(T2) View2;
View1 _v1;
View2 _v2;
F _f;
transform_nongil_t(const View1& v1_in,const View2& v2_in,const F& f_in) : _v1(v1_in),_v2(v2_in),_f(f_in) {}
void operator()() const {
T1* first1=(T1*)_v1.row_begin(0);
T1* last1=first1+_v1.size()*3;
T1* first20=(T2*)at_c<0>(_v2.row_begin(0));
T1* first21=(T2*)at_c<1>(_v2.row_begin(0));
T1* first22=(T2*)at_c<2>(_v2.row_begin(0));
while(first1!=last1) {
*first20++=T2(first1[2]*0.1f);
*first21++=T2(first1[1]*0.2f);
*first22++=T2(first1[0]*0.3f);
first1+=3;
}
}
};
template <typename T1, typename T2, typename F>
struct transform_nongil_t<RGB_PLANAR_VIEW(T1),RGB_VIEW(T2),F> {
typedef RGB_PLANAR_VIEW(T1) View1;
typedef RGB_VIEW(T2) View2;
View1 _v1;
View2 _v2;
F _f;
transform_nongil_t(const View1& v1_in,const View2& v2_in,const F& f_in) : _v1(v1_in),_v2(v2_in),_f(f_in) {}
void operator()() const {
T1* first10=(T1*)at_c<0>(_v1.row_begin(0));
T1* first11=(T1*)at_c<1>(_v1.row_begin(0));
T1* first12=(T1*)at_c<2>(_v1.row_begin(0));
T2* first2=(T1*)_v2.row_begin(0);
T1* last2=first2+_v1.size()*3;
while(first2!=last2) {
first2[0]=T2(*first12++*0.1f);
first2[1]=T2(*first11++*0.2f);
first2[2]=T2(*first10++*0.3f);
first2+=3;
}
}
};
template <typename View1, typename View2, typename F>
void test_transform(std::size_t trials) {
image<typename View1::value_type, is_planar<View1>::value> im1(width,height);
image<typename View2::value_type, is_planar<View2>::value> im2(width,height);
std::cout << "GIL: " <<measure_time(transform_gil_t<View1,View2,F>(view(im1),view(im2),F()),trials) << std::endl;
std::cout << "Non-GIL: "<<measure_time(transform_nongil_t<View1,View2,F>(view(im1),view(im2),F()),trials) << std::endl;
}
int main() {
#ifdef NDEBUG
std::size_t num_trials=1000;
#else
std::size_t num_trials=1;
#endif
// fill()
std::cout<<"test fill_pixels() on rgb8_image_t with rgb8_pixel_t"<<std::endl;
test_fill<rgb8_view_t,rgb8_pixel_t>(num_trials);
std::cout<<std::endl;
std::cout<<"test fill_pixels() on rgb8_planar_image_t with rgb8_pixel_t"<<std::endl;
test_fill<rgb8_planar_view_t,rgb8_pixel_t>(num_trials);
std::cout<<std::endl;
std::cout<<"test fill_pixels() on rgb8_image_t with bgr8_pixel_t"<<std::endl;
test_fill<rgb8_view_t,bgr8_pixel_t>(num_trials);
std::cout<<std::endl;
std::cout<<"test fill_pixels() on rgb8_planar_image_t with bgr8_pixel_t"<<std::endl;
test_fill<rgb8_planar_view_t,bgr8_pixel_t>(num_trials);
std::cout<<std::endl;
// for_each()
std::cout<<"test for_each_pixel() on rgb8_image_t"<<std::endl;
test_for_each<rgb8_view_t,rgb_fr_t<bits8> >(num_trials);
std::cout<<std::endl;
std::cout<<"test for_each_pixel() on rgb8_planar_image_t"<<std::endl;
test_for_each<rgb8_planar_view_t,rgb_fr_t<bits8> >(num_trials);
std::cout<<std::endl;
// copy()
std::cout<<"test copy_pixels() between rgb8_image_t and rgb8_image_t"<<std::endl;
test_copy<rgb8_view_t,rgb8_view_t>(num_trials);
std::cout<<std::endl;
std::cout<<"test copy_pixels() between rgb8_image_t and bgr8_image_t"<<std::endl;
test_copy<rgb8_view_t,bgr8_view_t>(num_trials);
std::cout<<std::endl;
std::cout<<"test copy_pixels() between rgb8_planar_image_t and rgb8_planar_image_t"<<std::endl;
test_copy<rgb8_planar_view_t,rgb8_planar_view_t>(num_trials);
std::cout<<std::endl;
std::cout<<"test copy_pixels() between rgb8_image_t and rgb8_planar_image_t"<<std::endl;
test_copy<rgb8_view_t,rgb8_planar_view_t>(num_trials);
std::cout<<std::endl;
std::cout<<"test copy_pixels() between rgb8_planar_image_t and rgb8_image_t"<<std::endl;
test_copy<rgb8_planar_view_t,rgb8_view_t>(num_trials);
std::cout<<std::endl;
// transform()
std::cout<<"test transform_pixels() between rgb8_image_t and rgb8_image_t"<<std::endl;
test_transform<rgb8_view_t,rgb8_view_t,bgr_to_rgb_t<bits8,pixel<bits8,rgb_layout_t> > >(num_trials);
std::cout<<std::endl;
std::cout<<"test transform_pixels() between rgb8_planar_image_t and rgb8_planar_image_t"<<std::endl;
test_transform<rgb8_planar_view_t,rgb8_planar_view_t,bgr_to_rgb_t<bits8,planar_pixel_reference<bits8,rgb_t> > >(num_trials);
std::cout<<std::endl;
std::cout<<"test transform_pixels() between rgb8_image_t and rgb8_planar_image_t"<<std::endl;
test_transform<rgb8_view_t,rgb8_planar_view_t,bgr_to_rgb_t<bits8,pixel<bits8,rgb_layout_t> > >(num_trials);
std::cout<<std::endl;
std::cout<<"test transform_pixels() between rgb8_planar_image_t and rgb8_image_t"<<std::endl;
test_transform<rgb8_planar_view_t,rgb8_view_t,bgr_to_rgb_t<bits8,planar_pixel_reference<bits8,rgb_t> > >(num_trials);
std::cout<<std::endl;
return 0;
}
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
511
]
]
]
|
7f510e73ac23015993f4fd8fa982466e52df130a | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SETools/SEManagedFramework/SEManagedRendering/SEManagedImage.cpp | 0a1b1778fc8cc65a5b3befb6546347da401a1bbb | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,245 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEManagedFrameworkPCH.h"
#include "SEManagedImage.h"
using namespace Swing;
using namespace Swing::Tools::ManagedFramework;
//---------------------------------------------------------------------------
ManagedImage::ManagedImage()
{
}
//---------------------------------------------------------------------------
ManagedImage::ManagedImage(SEImage* pImage)
{
m_pspImage = SE_NEW SEImagePtr;
(*m_pspImage) = pImage;
}
//---------------------------------------------------------------------------
ManagedImage::~ManagedImage()
{
SE_DELETE m_pspImage;
m_pspImage = 0;
}
//---------------------------------------------------------------------------
void ManagedImage::SetName(String^ thName)
{
SE_NULL_ARGUMENT_CHECK(thName, "thName");
SE_NULL_REFERENCE_CHECK(m_pspImage, "Native pointer is null");
const char* acName = ManagedUtility::StringToNativeCharBuffer(thName);
std::string tempName(acName);
ManagedUtility::FreeNativeCharBuffer(acName);
(*m_pspImage)->SetName(tempName);
}
//---------------------------------------------------------------------------
String^ ManagedImage::GetName()
{
SE_NULL_REFERENCE_CHECK(m_pspImage, "Native pointer is null");
return gcnew String((*m_pspImage)->GetName().c_str());
}
//---------------------------------------------------------------------------
int ManagedImage::GetNativeReferences()
{
SE_NULL_REFERENCE_CHECK(m_pspImage, "Native pointer is null");
return (*m_pspImage)->GetReferences();
}
//---------------------------------------------------------------------------
SEImage* ManagedImage::GetNativeImage()
{
SE_NULL_REFERENCE_CHECK(m_pspImage, "Native pointer is null");
return (SEImage*)(*m_pspImage);
}
//---------------------------------------------------------------------------
ManagedImage^ ManagedImage::Find(String^ thName)
{
SE_NULL_ARGUMENT_CHECK(thName, "thName");
const char* acName = ManagedUtility::StringToNativeCharBuffer(thName);
std::string tempName(acName);
ManagedUtility::FreeNativeCharBuffer(acName);
SEImage* pImage = SEImageCatalog::GetActive()->Find(tempName);
return gcnew ManagedImage(pImage);
}
//--------------------------------------------------------------------------- | [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
83
]
]
]
|
c7b8917bdaf3ee2ccbdbc3a1707014be4722556e | 0531b270535a46f315ead3524e60fb70fd6055da | /Source/libkwl/IrcChannel.h | 3130754ea3998870f4f32ba92e56d36d6ae60a01 | []
| no_license | jannispl/kwlbot | e7588283d395ea6d54f6a82d45f2f0577f66fde1 | a5c1ea65c38067747893eeccdae726faeedec0d5 | refs/heads/master | 2021-01-01T19:10:16.324535 | 2010-12-12T22:58:24 | 2010-12-12T22:58:24 | 33,863,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,205 | h | /*
kwlbot IRC bot
File: IrcChannel.h
Purpose: Class which represents a remote IRC channel
*/
class CIrcChannel;
#ifndef _IRCCHANNEL_H
#define _IRCCHANNEL_H
#include "ScriptObject.h"
#include "Bot.h"
#include "IrcUser.h"
#include "Pool.h"
#include "Script.h"
#include <time.h>
#include <map>
/**
* @brief Class which represents a remote IRC channel.
*/
class DLLEXPORT CIrcChannel : public CScriptObject
{
friend class CBot;
public:
CIrcChannel(CBot *pParentBot, const std::string &strName);
~CIrcChannel();
/**
* Gets the channel's name.
* @return The channel's name.
*/
const std::string &GetName();
/**
* Searches the user pool for a certain user.
* @param szName The user's nickname.
* @param bCaseSensitive Search case-sensitively or not (optional)
* @return A pointer to a CIrcUser, or NULL incase the user was not found.
*/
CIrcUser *FindUser(const char *szNickname, bool bCaseSensitive = true);
/**
* Checks if a certain user exists in the user pool.
* @param pUser The user.
* @return True if the given user exists in the user pool, false otherwise.
*/
bool HasUser(CIrcUser *pUser);
/**
* Gets a pointer to the user pool.
* @return A pointer to a CPool<CIrcUser *>.
*/
CPool<CIrcUser *> *GetUsers();
/**
* Gets the parent bot.
* @return The parent bot.
*/
CBot *GetParentBot();
void NewScript(CScript *pScript);
void DeleteScript(CScript *pScript);
v8::Object *GetScriptObject(CScript *pScript);
/**
* Gets the script type of this class.
* @return The script type of this class.
*/
CScriptObject::eScriptType GetType();
typedef struct
{
time_t ullTopicSetDate;
std::string strTopicSetBy;
std::string strTopic;
} TopicInfo;
TopicInfo m_topicInfo;
private:
CBot *m_pParentBot;
std::string m_strName;
/*#ifdef WIN32
template class DLLEXPORT CPool<CIrcUser *>;
#endif*/
CPool<CIrcUser *> m_plIrcUsers;
bool m_bHasDetailedUsers;
std::map<CScript *, v8::Persistent<v8::Object> > m_mapScriptObjects;
#if defined(SERVICE) && IRCD == HYBRID
time_t m_ullChannelStamp;
#endif
};
#endif
| [
"[email protected]@f9c66ffb-4930-c197-0f80-100fa691f586"
]
| [
[
[
1,
103
]
]
]
|
a492e534ce5f1e91badbe72d3da5991cda9864ad | 611fc0940b78862ca89de79a8bbeab991f5f471a | /src/Stage/Haichi.h | 35f9b41a5431e6c4a88bc882f3d24a6383a1ed2c | []
| no_license | LakeIshikawa/splstage2 | df1d8f59319a4e8d9375b9d3379c3548bc520f44 | b4bf7caadf940773a977edd0de8edc610cd2f736 | refs/heads/master | 2021-01-10T21:16:45.430981 | 2010-01-29T08:57:34 | 2010-01-29T08:57:34 | 37,068,575 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,861 | h | #pragma once
#include <list>
#include <vector>
#include "Map.h"
#include "HaichiObj.h"
#include "..\\Object\\AshibaMovable.h"
#include "..\\Object\\Tenbin.h"
using namespace std;
class CheckpointController;
/*
敵の配置データ
*/
class Haichi : public Map
{
public:
Haichi(void);
~Haichi(void);
int Load(string rFname, CheckpointController* checkpointController);
void UnLoad();
void Process();
//! 敵を復活させる
void RestoreTekiAfter( int rPos );
//! 動く足場をゲット
AshibaMovable* GetAshibaMov(int idx);
//! 動く足場の数
int GetAshibaMovNum();
//! 足場をあたりターゲットとして設定する
void SetAshibaTargets( Collidable* rToThisObj );
//! 足場に設定されているターゲットを未設定する
void RemoveAshibaTargets( ICollidable* rRemoveMe );
//! 天秤の数
int GetTenbinNum();
//! 天秤をゲット
Tenbin* GetTenbin(int idx);
//! 生データを参照
int GetData(int rX, int rY);
// ローストデバイス
void OnLostDevice();
void OnRestoredDevice();
private:
// 足場用の特別な処理
bool IsAshiba(int data);
void ProcessAshiba(int data, int x, int y);
list< HaichiObj* > mHaichiListOrig; // mXPx順で並び替えてあるが想定
list< HaichiObj* > mHaichiListTemp; // mXPx順で並び替えてあるが想定
vector< AshibaMovable* > mAshibaMovList; // 動く足場
vector< Ashiba* > mAshibaList; // 動く足場以外の足場
vector< Tenbin* > mTenbinList; // 天秤
int mShutugenStartPoint;
// 設定定数
int SHUTSUGEN_POINTX;
// 後の処理を軽くする
int CHECKPOINT_NO;
int MOVASHIBA_NO;
int MOVASHIBA2_NO;
int MOVASHIBA3_NO;
int ASHIBA_NO;
int ASHIBA2_NO;
int ASHIBA3_NO;
int INVASHIBA3_NO;
int TENBIN_NO;
};
| [
"lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b"
]
| [
[
[
1,
85
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.